python-corekit 0.1.0__py3-none-any.whl → 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. corekit/api/__init__.py +18 -3
  2. corekit/api/application.py +237 -0
  3. corekit/api/lifespan.py +210 -0
  4. corekit/api/middleware.py +93 -0
  5. corekit/api/routers.py +109 -1
  6. corekit/concurrency/worker.py +65 -65
  7. corekit/config/settings.py +3 -3
  8. corekit/connections/sql/__init__.py +31 -3
  9. corekit/connections/sql/connection.py +19 -0
  10. corekit/connections/sql/migration/__init__.py +5 -5
  11. corekit/connections/sql/migration/base.py +3 -3
  12. corekit/connections/sql/migration/operations.py +66 -42
  13. corekit/connections/sql/migration/registry.py +2 -2
  14. corekit/connections/sql/operations/__init__.py +24 -0
  15. corekit/connections/sql/operations/base.py +102 -0
  16. corekit/connections/sql/operations/statements.py +150 -0
  17. corekit/connections/sql/query.py +4 -62
  18. corekit/connections/sql/table.py +30 -4
  19. corekit/constants.py +45 -45
  20. corekit/crypto/constants.py +4 -4
  21. corekit/data/__init__.py +8 -0
  22. corekit/data/expressions/__init__.py +10 -2
  23. corekit/data/expressions/comparison.py +184 -104
  24. corekit/data/expressions/expression.py +103 -98
  25. corekit/data/expressions/operator.py +54 -0
  26. corekit/data/expressions/target.py +21 -0
  27. corekit/data/record.py +147 -147
  28. corekit/data/stats.py +159 -157
  29. corekit/decorators/__init__.py +2 -2
  30. corekit/decorators/exception_handling.py +2 -1
  31. corekit/etl/connection.py +44 -44
  32. corekit/events/websocket.py +3 -2
  33. corekit/exceptions/__init__.py +18 -0
  34. corekit/http/__init__.py +13 -0
  35. corekit/jobs/__init__.py +26 -0
  36. corekit/jobs/registry.py +87 -0
  37. corekit/jobs/runner.py +69 -0
  38. corekit/jobs/task.py +152 -0
  39. corekit/observability/__init__.py +5 -3
  40. corekit/observability/request_context.py +135 -0
  41. corekit/registry/__init__.py +11 -6
  42. corekit/registry/ordered.py +86 -0
  43. corekit/schemas/__init__.py +10 -0
  44. corekit/schemas/enum.py +49 -49
  45. corekit/schemas/models/arbitrary.py +11 -11
  46. corekit/schemas/pydantic/fields.py +35 -35
  47. corekit/schemas/types.py +40 -40
  48. corekit/serialization/__init__.py +22 -0
  49. corekit/serialization/serializer.py +1 -1
  50. corekit/utils/__init__.py +59 -5
  51. corekit/utils/coercion.py +118 -0
  52. corekit/utils/collections.py +115 -0
  53. corekit/utils/ids.py +61 -5
  54. corekit/utils/payload.py +100 -0
  55. corekit/utils/raise_exc.py +8 -8
  56. corekit/utils/text.py +56 -0
  57. corekit/utils/time.py +74 -21
  58. corekit/utils/validators.py +15 -15
  59. corekit/utils/void.py +8 -8
  60. {python_corekit-0.1.0.dist-info → python_corekit-0.2.0.dist-info}/METADATA +105 -100
  61. {python_corekit-0.1.0.dist-info → python_corekit-0.2.0.dist-info}/RECORD +64 -46
  62. {python_corekit-0.1.0.dist-info → python_corekit-0.2.0.dist-info}/WHEEL +0 -0
  63. {python_corekit-0.1.0.dist-info → python_corekit-0.2.0.dist-info}/licenses/LICENSE +0 -0
  64. {python_corekit-0.1.0.dist-info → python_corekit-0.2.0.dist-info}/top_level.txt +0 -0
corekit/utils/text.py ADDED
@@ -0,0 +1,56 @@
1
+ """
2
+ String assembly helpers.
3
+
4
+ Small formatters for turning collections into text a human will read -- log
5
+ lines, notification bodies, error messages -- plus filename sanitization.
6
+ """
7
+
8
+ import re
9
+ from typing import Any, Literal
10
+
11
+ __all__ = ["join_lines", "list_to_english", "sanitize_filename"]
12
+
13
+ FALLBACK_FILENAME = "unnamed"
14
+ _UNSAFE_CHARS = re.compile(r"[^a-z0-9\-]")
15
+ _REPEATED_HYPHENS = re.compile(r"-{2,}")
16
+
17
+
18
+ def join_lines(*items: Any, prefix: str = "") -> str:
19
+ """
20
+ Join items with newlines, optionally prefixing each one.
21
+ """
22
+ return "\n".join(f"{prefix}{item}" for item in items)
23
+
24
+
25
+ def list_to_english(items: list[str], ending: Literal["and", "or"] | None = None) -> str:
26
+ """
27
+ Join items into a readable list: ``"a, b, and c"``.
28
+
29
+ Without ``ending`` the final item is joined with a plain comma, which suits
30
+ a bare enumeration; pass ``"and"`` or ``"or"`` for prose.
31
+ """
32
+ if not items:
33
+ return ""
34
+
35
+ if len(items) == 1:
36
+ return items[0]
37
+
38
+ buffer = ", ".join(items[:-1])
39
+ last = items[-1]
40
+
41
+ if ending is None:
42
+ return f"{buffer}, {last}"
43
+ return f"{buffer}, {ending} {last}"
44
+
45
+
46
+ def sanitize_filename(raw: str, fallback: str = FALLBACK_FILENAME) -> str:
47
+ """
48
+ Reduce a string to lowercase kebab-case safe for use as a filename stem.
49
+
50
+ Everything outside ``a-z0-9-`` becomes a hyphen, runs collapse, and the
51
+ result is trimmed. A string with nothing usable in it returns ``fallback``
52
+ rather than the empty string, which would produce a nameless file.
53
+ """
54
+ cleaned = _UNSAFE_CHARS.sub("-", raw.strip().lower())
55
+ cleaned = _REPEATED_HYPHENS.sub("-", cleaned).strip("-")
56
+ return cleaned or fallback
corekit/utils/time.py CHANGED
@@ -1,21 +1,74 @@
1
- from datetime import UTC, datetime, timedelta
2
-
3
-
4
- def time_now() -> datetime:
5
- """
6
- Helper for getting the current UTC time
7
- """
8
- return datetime.now(UTC)
9
-
10
-
11
- def timedelta_now(delta_seconds: int | None = None, add_time: bool = False, **kwargs) -> datetime:
12
- """
13
- Helper for getting a quick timedelta
14
- """
15
- if delta_seconds is not None:
16
- kwargs = {"seconds": delta_seconds}
17
-
18
- delta = timedelta(**kwargs)
19
- if add_time:
20
- return time_now() + delta
21
- return time_now() - delta
1
+ """
2
+ Timezone-aware time helpers.
3
+
4
+ Every function returns UTC. Naive datetimes are the usual source of "works on
5
+ my machine" time bugs, so nothing here produces one.
6
+ """
7
+
8
+ import re
9
+ from datetime import UTC, datetime, timedelta
10
+ from typing import Any
11
+
12
+ __all__ = ["isoformat_now", "parse_docker_timestamp", "time_now", "timedelta_now", "timestamp_now"]
13
+
14
+ # Docker reports nanosecond precision; fromisoformat accepts at most microseconds.
15
+ _DOCKER_TS_PATTERN = re.compile(r"(\.\d{6})\d*")
16
+
17
+ # Docker's zero value for "this never happened".
18
+ _DOCKER_ZERO_TIME = "0001-01-01"
19
+
20
+
21
+ def time_now() -> datetime:
22
+ """
23
+ Return the current UTC time, timezone-aware.
24
+ """
25
+ return datetime.now(UTC)
26
+
27
+
28
+ def isoformat_now() -> str:
29
+ """
30
+ Return the current UTC time as an ISO 8601 string.
31
+ """
32
+ return time_now().isoformat()
33
+
34
+
35
+ def timestamp_now() -> float:
36
+ """
37
+ Return the current UTC time as a Unix timestamp.
38
+ """
39
+ return time_now().timestamp()
40
+
41
+
42
+ def timedelta_now(delta_seconds: int | None = None, add_time: bool = False, **kwargs: Any) -> datetime:
43
+ """
44
+ Return a time offset from now, in the past by default.
45
+
46
+ Pass ``delta_seconds`` for the common case, or any ``timedelta`` keyword
47
+ (``days``, ``hours``, ...) for the rest. ``add_time`` moves forward instead
48
+ of back.
49
+ """
50
+ if delta_seconds is not None:
51
+ kwargs = {"seconds": delta_seconds}
52
+
53
+ delta = timedelta(**kwargs)
54
+ if add_time:
55
+ return time_now() + delta
56
+ return time_now() - delta
57
+
58
+
59
+ def parse_docker_timestamp(value: str | None) -> float | None:
60
+ """
61
+ Parse a docker API timestamp into a Unix timestamp, or ``None``.
62
+
63
+ Docker emits nanosecond-precision ISO 8601 (a container's ``State.StartedAt``,
64
+ for instance), which ``fromisoformat`` rejects. Returns ``None`` for empty
65
+ input, docker's zero timestamp, and anything unparseable, so a caller can
66
+ treat "no such time" and "bad time" the same way.
67
+ """
68
+ if not value or value.startswith(_DOCKER_ZERO_TIME):
69
+ return None
70
+ try:
71
+ trimmed = _DOCKER_TS_PATTERN.sub(r"\1", value.replace("Z", "+00:00"))
72
+ return datetime.fromisoformat(trimmed).timestamp()
73
+ except ValueError:
74
+ return None
@@ -1,15 +1,15 @@
1
- from typing import Any
2
-
3
-
4
- def true_validator(*args: Any, **kwargs: Any) -> bool:
5
- """
6
- Generic placeholder validator function that always returns True
7
- """
8
- return True
9
-
10
-
11
- def false_validator(*args: Any, **kwargs: Any) -> bool:
12
- """
13
- Generic placeholder validator function that always returns False
14
- """
15
- return False
1
+ from typing import Any
2
+
3
+
4
+ def true_validator(*args: Any, **kwargs: Any) -> bool:
5
+ """
6
+ Generic placeholder validator function that always returns True
7
+ """
8
+ return True
9
+
10
+
11
+ def false_validator(*args: Any, **kwargs: Any) -> bool:
12
+ """
13
+ Generic placeholder validator function that always returns False
14
+ """
15
+ return False
corekit/utils/void.py CHANGED
@@ -1,8 +1,8 @@
1
- from typing import Any
2
-
3
-
4
- def void(ex: Exception, *args: Any, **kwargs: Any) -> None:
5
- """
6
- Generic callback function that does nothing and returns nothing
7
- """
8
- pass
1
+ from typing import Any
2
+
3
+
4
+ def void(ex: Exception, *args: Any, **kwargs: Any) -> None:
5
+ """
6
+ Generic callback function that does nothing and returns nothing
7
+ """
8
+ pass
@@ -1,12 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-corekit
3
- Version: 0.1.0
4
- Summary: Shared foundations for Python projects: logging, benchmarking, registries, FastAPI routers/handlers, data stores, and ETL
3
+ Version: 0.2.0
4
+ Summary: Shared foundations for Python projects: logging, benchmarking, registries, FastAPI application and routers, SQL statements and migrations, background tasks, and ETL
5
5
  Author: Steven Jacobsen
6
6
  License-Expression: MIT
7
7
  Project-URL: Homepage, https://github.com/stevejaker/corekit
8
8
  Project-URL: Issues, https://github.com/stevejaker/corekit/issues
9
- Keywords: fastapi,etl,homelab,logging,benchmarking
9
+ Keywords: fastapi,etl,logging,benchmarking,sqlmodel,migrations
10
10
  Classifier: Development Status :: 3 - Alpha
11
11
  Classifier: Intended Audience :: Developers
12
12
  Classifier: Programming Language :: Python :: 3.11
@@ -36,8 +36,8 @@ Dynamic: license-file
36
36
  # corekit
37
37
 
38
38
  Shared foundations for Python projects: structured logging, benchmarking,
39
- registries, FastAPI routers with built-in handlers, an in-memory record store,
40
- and ETL scaffolding.
39
+ registries, a FastAPI application with routers and handlers, SQL statements and
40
+ migrations, background tasks, an in-memory record store, and ETL scaffolding.
41
41
 
42
42
  Requires Python 3.11+.
43
43
 
@@ -47,17 +47,15 @@ Requires Python 3.11+.
47
47
  pip install python-corekit
48
48
  ```
49
49
 
50
- No credentials, no SSH key, no token — which means a project that depends on
51
- corekit can be cloned and built by anyone, including inside a Docker build.
50
+ The distribution is `python-corekit`; the import is `corekit`.
52
51
 
53
52
  Every dependency corekit needs is installed with it. There are no optional
54
53
  extras to remember, and no import that fails because something was left out.
55
54
 
56
- The distribution is `python-corekit`; the import is `corekit`. Pin a compatible
57
- release rather than tracking whatever is newest:
55
+ Pin a compatible release rather than tracking whatever is newest:
58
56
 
59
57
  ```
60
- python-corekit~=0.1.0
58
+ python-corekit~=0.2.0
61
59
  ```
62
60
 
63
61
  Before 1.0, the minor version carries breaking changes.
@@ -90,6 +88,57 @@ class Report(Benchmarkable):
90
88
  self.timing("queried") # logs the time since the previous split
91
89
  ```
92
90
 
91
+ ## Assembling an application
92
+
93
+ `Application` is a plain `FastAPI` subclass — every constructor argument,
94
+ including `lifespan`, passes straight through. What it adds is a short set of
95
+ assembly steps, each of which logs what it did.
96
+
97
+ ```python
98
+ from corekit.api import Application, Lifespan
99
+ from app.backend import routers
100
+
101
+ lifespan = Lifespan()
102
+ lifespan.add("cache", startup=cache.connect, shutdown=cache.disconnect)
103
+
104
+ app = Application(lifespan=lifespan)
105
+ app.discover_routers(routers)
106
+ ```
107
+
108
+ `discover_routers` imports every module under the package so each router can
109
+ register itself. It raises if it finds none: passing a package is a statement
110
+ that routers live there, and an app that silently serves nothing is worse than
111
+ one that refuses to start.
112
+
113
+ Lifespan steps start in the order added and shut down in reverse, the way
114
+ nested `with` blocks unwind. If a step fails on the way up, the steps that
115
+ already started are still torn down. A shutdown hook runs only if its own
116
+ startup completed, so it may assume the state that startup builds — and a hook
117
+ that raises cannot stop the unwind.
118
+
119
+ ### Middleware
120
+
121
+ Middleware order is a security property: a host check that reads a client
122
+ address before the proxy-header layer has rewritten it is checking the proxy,
123
+ not the client. So middleware is never auto-discovered, and corekit installs
124
+ none by default. A stack is declared in one place, outermost first — the order
125
+ a request actually meets the layers.
126
+
127
+ ```python
128
+ from corekit.api import MiddlewareStack
129
+
130
+ stack = (
131
+ MiddlewareStack()
132
+ .add(ProxyHeadersMiddleware, trusted_hosts="*")
133
+ .add(TrustedHostMiddleware, allowed_hosts=HOSTS)
134
+ .add(CORSMiddleware, allow_origins=ORIGINS, allow_credentials=True)
135
+ )
136
+ app.add_middleware_stack(stack)
137
+ ```
138
+
139
+ Reading top to bottom gives the order a request travels, which is the property
140
+ you need when reviewing it.
141
+
93
142
  ## Routers and handlers
94
143
 
95
144
  A router and the handler holding its business logic travel together. Declare the
@@ -149,113 +198,67 @@ people.get_record("Ada").age # O(1) lookup by id
149
198
 
150
199
  Stores pickle cleanly, including their dynamically generated record class.
151
200
 
152
- ## Homelab pieces
201
+ ## SQL statements
153
202
 
154
- ### Container control
203
+ Select, insert, update and delete are objects you build and then execute, so a
204
+ statement can be assembled in pieces and passed around before it runs.
155
205
 
156
206
  ```python
157
- from corekit.docker import Watchdog
207
+ from corekit.connections.sql import SQLConnection, Select, Insert, Update, Delete
208
+ from corekit.data import Field
158
209
 
159
- watchdog = Watchdog(enforce_label=True)
160
- watchdog.restart_container_by_name("minecraft")
161
- watchdog.find_and_stop(label="app", value="staging")
162
- ```
210
+ conn = SQLConnection("sqlite:///app.db")
163
211
 
164
- `enforce_label` limits the blast radius: with it on, only containers carrying
165
- the `watchdog=true` label can be started, stopped or paused, so a mistyped name
166
- cannot take down something unrelated. Leave it on unless the watchdog is meant
167
- to control everything on the host.
168
-
169
- ### Reacting to logs
170
-
171
- Describe what to watch for and what to do about it:
172
-
173
- ```yaml
174
- # config.yaml
175
- containers:
176
- - name: "minecraft-.*"
177
- rules:
178
- - name: "out of memory"
179
- pattern: "java.lang.OutOfMemoryError"
180
- severity: critical
181
- send_notification: true
182
- actions:
183
- - type: restart_container
184
- max_restarts: 3
185
- restart_window: 3600
186
- advanced:
187
- ignore_patterns:
188
- - "healthcheck"
189
- rate_limits:
190
- restart_container:
191
- count: 5
192
- period: hour
193
- ```
212
+ conn.execute(Insert(table=User, rows=[{"name": "Ada", "age": 36}]).add(name="Bob", age=17))
194
213
 
195
- ```python
196
- from corekit.log_monitor import LogMonitor
214
+ adults = conn.fetch(Select(table=User).where(User.age >= 18).order_by(User.name).limit(10))
197
215
 
198
- LogMonitor.run("config.yaml")
216
+ conn.execute(Update(table=User).where(User.name == "Bob").set(age=18))
217
+ conn.execute(Delete(table=User).where(User.age < 13))
199
218
  ```
200
219
 
201
- Restarts are capped per container, so a crash loop cannot become a restart loop.
202
-
203
- ### Notifications
220
+ `where` accepts a SQLAlchemy expression or a `corekit.data` one, so the same
221
+ predicate language that filters a `Dataset` also filters a table:
204
222
 
205
223
  ```python
206
- from corekit.notifications import BaseNotificationService, Notification, NotificationType
207
-
208
- class DiscordNotifier(BaseNotificationService):
209
- """
210
- Sends notifications to a Discord channel.
211
- """
212
-
213
- def _send(self, message: str) -> None:
214
- discord.post(message)
215
-
216
- notifier.notify(Notification(message="disk full", type=NotificationType.ERROR))
224
+ Select(table=User).where(Field("age") >= 18)
217
225
  ```
218
226
 
219
- Override `_send`, not `send`. `notify()` formats the message and calls `_send`,
220
- so an override with any other name is silently ignored.
227
+ Update and delete compile to a single statement rather than fetching rows and
228
+ looping, which matters most over a network, where fetch-and-loop pays a round
229
+ trip per row.
221
230
 
222
- ### Real-time updates
231
+ A `Delete` or `Update` with no condition raises rather than running:
223
232
 
224
- Publish from wherever the work happens:
225
-
226
- ```python
227
- from corekit.events import EventPublisher
228
-
229
- publisher = EventPublisher.for_resource("minecraft", "server", "survival")
230
- publisher.publish("backup_finished", {"size": "4.2GB"})
233
+ ```
234
+ Delete on User needs a condition; use truncate to empty a table
231
235
  ```
232
236
 
233
- Stream it to the browser:
237
+ ## Background tasks
234
238
 
235
- ```python
236
- from corekit.api import SSEResponse
237
- from corekit.events import SSEStream
239
+ Tasks describe work and register themselves by name. Nothing here imports a
240
+ queue library, so the same task runs under RQ, Celery, a cron entry, or a test
241
+ with no queue at all.
238
242
 
239
- @router.get("/events")
240
- async def events(channel: str) -> SSEResponse:
241
- return SSEResponse(SSEStream(channel, keepalive_interval=15))
242
- ```
243
+ ```python
244
+ from corekit.jobs import Task, run_task
245
+ from corekit.utils import encode_payload
243
246
 
244
- The browser side is three lines, and reconnects on its own:
247
+ class SendDigest(Task):
248
+ def task_function(self, user: str) -> None:
249
+ ...
245
250
 
246
- ```javascript
247
- const source = new EventSource("/events?channel=minecraft:server:survival");
248
- source.addEventListener("backup_finished", e => console.log(JSON.parse(e.data)));
251
+ # a worker, holding only a name and a JSON string
252
+ run_task("SendDigest", encode_payload(["ada"]))
249
253
  ```
250
254
 
251
- `SSEStream` sends a `connected` frame on subscribe, an optional `initial_state`
252
- so a client arriving late renders immediately, and a comment frame every
253
- `keepalive_interval` seconds so proxies do not close an idle connection. For
254
- WebSockets, `WebSocketBridge` relays the same channel and stops on a terminal
255
- status.
255
+ Arguments cross the queue as JSON, never as a serialized object. `pickle` and
256
+ `dill` execute code while loading, so a queue holding objects turns write
257
+ access to the queue into code execution in a worker. `encode_payload` and
258
+ `decode_payload` live in `corekit.utils`, since crossing a process boundary as
259
+ data is not specific to queues.
256
260
 
257
- Publishing never raises: an event that cannot be delivered should not take down
258
- the operation that produced it. `publish` returns whether it worked.
261
+ `ScheduledTask` adds an `interval` for tasks a scheduler should repeat.
259
262
 
260
263
  ## Parallel work
261
264
 
@@ -371,23 +374,25 @@ Imports go downward only.
371
374
 
372
375
  ```
373
376
  corekit/
374
- config.py constants.py
377
+ config/ settings, sources, loader
378
+ constants.py
375
379
 
376
380
  exceptions/ error types
377
381
 
378
382
  observability/ Loggable, Benchmarkable, Timer
379
- registry/ schemas/ utils/ SmartRegistry, enums and fields, helpers
383
+ registry/ schemas/ utils/ registries, enums and fields, helpers
380
384
  data/ Dataset and its filter expressions
385
+ jobs/ queue-independent background tasks
381
386
  crypto/ files/ serialization/
382
387
  concurrency/ ThreadLocalRegistry, ThreadWorker
383
388
  decorators/
384
389
 
385
390
  connections/ the Connectable lifecycle and @connect
386
- sql/ SQLConnection, queries, migrations
391
+ sql/ SQLConnection, statements, migrations
387
392
  redis/ RedisConnection
388
393
  http/ BaseApiClient, retries, responses
389
394
 
390
- api/ handlers, routers, responses
395
+ api/ Application, lifespan, middleware, routers
391
396
  docker/ notifications/ etl/
392
397
 
393
398
  events/ log_monitor/ built on the capabilities above
@@ -404,13 +409,13 @@ layering deliberately.
404
409
  ## Development
405
410
 
406
411
  ```bash
407
- pip install -e ".[dev,all]"
412
+ pip install -e ".[dev]"
408
413
  pytest
409
414
  ruff format . && ruff check --fix .
410
415
  ```
411
416
 
412
- `tests/test_imports.py` imports every module in the package. Keep it passing:
413
- several modules were broken for months because nothing ever imported them.
417
+ `tests/test_imports.py` imports every module in the package, so a module that
418
+ nothing else happens to import still has to be importable.
414
419
 
415
420
  ## Licence
416
421