strata-python 0.2.2__py3-none-any.whl → 0.2.4__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.
strata_python/web.py CHANGED
@@ -1,6 +1,8 @@
1
1
  """The web side every app shares: health and settings routes, the built web app (or a stand-in page), and the uvicorn runner.
2
2
 
3
3
  app = base_app("myapp", __version__, SETTINGS) # /api/health, GET/PUT /api/settings
4
+ add_error_handlers(app) # ValueError -> 400, KeyError -> 404, ... as ErrorBody
5
+ add_system(app, __version__, folders={"data": SETTINGS.home}, services={"strata-models": MODELS}) # GET /api/system
4
6
  ... app routes under /api ...
5
7
  add_web(app, STATIC, LANDING) # last: assets + the page at every other path
6
8
 
@@ -9,15 +11,23 @@ gets a relative `<base href>` (`with_base`) and one build works at the server's
9
11
  assets are relative (Vite `base: './'`)."""
10
12
 
11
13
  import argparse
14
+ import concurrent.futures
15
+ import datetime
12
16
  import os
17
+ import platform
18
+ import shutil
19
+ import sys
13
20
  from collections.abc import Callable, Mapping, Sequence
14
21
 
15
22
  import uvicorn
16
- from fastapi import FastAPI, HTTPException
17
- from fastapi.responses import FileResponse, HTMLResponse
23
+ from fastapi import FastAPI, HTTPException, Request
24
+ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
18
25
  from fastapi.staticfiles import StaticFiles
19
26
 
27
+ from strata_python.client import Rejected, ServiceClient, Unavailable
28
+ from strata_python.contracts import ErrorBody, Folder, ServiceStatus, SystemInfo
20
29
  from strata_python.settings import Settings
30
+ from strata_python.tasks import Conflict
21
31
 
22
32
 
23
33
  def with_base(html: str, path: str) -> str:
@@ -43,10 +53,12 @@ def base_app(
43
53
  *,
44
54
  docs: bool = True,
45
55
  health: Callable[[], Mapping[str, object]] | None = None,
56
+ commit: str | None = None,
46
57
  ) -> FastAPI:
47
58
  """A FastAPI app with `GET /api/health` and, given settings, `GET`/`PUT /api/settings` (a PUT with an unknown key or a value that fails validation is a 400 and changes nothing).
48
59
  `health` adds the app's own fields to the health response after `ok` and `version` (strata-models' `gpu`); it is called on every request, so keep it cheap,
49
- and it may set `ok` to false for a service that is up but cannot do its work."""
60
+ and it may set `ok` to false for a service that is up but cannot do its work. `commit` (`source_commit(__file__)`) is
61
+ answered as `commit`, so a probe can tell which source a server runs without reading files beside it."""
50
62
  app = FastAPI(
51
63
  title=title,
52
64
  docs_url="/api/docs" if docs else None,
@@ -55,15 +67,21 @@ def base_app(
55
67
 
56
68
  @app.get("/api/health")
57
69
  def get_health() -> dict[str, object]: # pyright: ignore[reportUnusedFunction]
58
- return {"ok": True, "version": version, **(health() if health else {})}
70
+ return {
71
+ "ok": True,
72
+ "version": version,
73
+ **({"commit": commit} if commit else {}),
74
+ **(health() if health else {}),
75
+ }
59
76
 
60
77
  if settings is not None:
78
+ shape = settings.model() # the settings as a typed object in /api/openapi.json, for the web app's types
61
79
 
62
- @app.get("/api/settings")
80
+ @app.get("/api/settings", response_model=shape)
63
81
  def get_settings() -> dict[str, str | list[str]]: # pyright: ignore[reportUnusedFunction]
64
82
  return settings.all()
65
83
 
66
- @app.put("/api/settings")
84
+ @app.put("/api/settings", response_model=shape)
67
85
  def put_settings(changes: dict[str, str | list[str] | None]) -> dict[str, str | list[str]]: # pyright: ignore[reportUnusedFunction]
68
86
  try:
69
87
  settings.save(changes)
@@ -74,6 +92,141 @@ def base_app(
74
92
  return app
75
93
 
76
94
 
95
+ def source_commit(path: str) -> str | None:
96
+ """The git commit of the checkout that holds `path` (pass `__file__`), read from `.git` without running git, or
97
+ None outside a checkout (an installed wheel). A worktree's `.git` file and packed refs are followed."""
98
+ d = os.path.abspath(path if os.path.isdir(path) else os.path.dirname(path))
99
+ while True:
100
+ dot = os.path.join(d, ".git")
101
+ if os.path.exists(dot):
102
+ return _read_head(dot)
103
+ parent = os.path.dirname(d)
104
+ if parent == d:
105
+ return None
106
+ d = parent
107
+
108
+
109
+ def _read_head(dot: str) -> str | None:
110
+ try:
111
+ if os.path.isfile(dot): # a worktree or submodule: "gitdir: <path>"
112
+ with open(dot, encoding="utf8") as f:
113
+ dot = os.path.join(os.path.dirname(dot), f.read().split(":", 1)[1].strip())
114
+ with open(os.path.join(dot, "HEAD"), encoding="utf8") as f:
115
+ head = f.read().strip()
116
+ if not head.startswith("ref:"):
117
+ return head or None # detached
118
+ ref = head.split(":", 1)[1].strip()
119
+ common = dot
120
+ if os.path.exists(os.path.join(dot, "commondir")): # a worktree keeps its branches in the main .git
121
+ with open(os.path.join(dot, "commondir"), encoding="utf8") as f:
122
+ common = os.path.normpath(os.path.join(dot, f.read().strip()))
123
+ for base in (dot, common):
124
+ loose = os.path.join(base, *ref.split("/"))
125
+ if os.path.isfile(loose):
126
+ with open(loose, encoding="utf8") as f:
127
+ return f.read().strip() or None
128
+ with open(os.path.join(common, "packed-refs"), encoding="utf8") as f:
129
+ for line in f:
130
+ sha, _, name = line.strip().partition(" ")
131
+ if name == ref:
132
+ return sha
133
+ except (OSError, IndexError):
134
+ return None
135
+ return None
136
+
137
+
138
+ ErrorMap = Mapping[type[Exception], int]
139
+ DEFAULT_ERRORS: ErrorMap = {
140
+ ValueError: 400, # a request the app cannot use (pydantic's ValidationError is one too)
141
+ PermissionError: 403,
142
+ FileNotFoundError: 404,
143
+ KeyError: 404, # an id the app does not know
144
+ Conflict: 409, # tasks.SingleFlight: that job is already running
145
+ Rejected: 502, # a service this app called refused: the request is fine, the dependency said no
146
+ Unavailable: 503, # a service this app needs is down
147
+ }
148
+
149
+
150
+ def add_error_handlers(app: FastAPI, errors: ErrorMap | None = None, *, defaults: bool = True) -> None:
151
+ """Answer the app's own exceptions as HTTP errors with an `ErrorBody` ({detail, payload}), instead of a
152
+ `try/except` and `HTTPException` in every route (the `guard()` five servers wrote). `errors` maps an exception
153
+ class to a status and is added to `DEFAULT_ERRORS` (pass `defaults=False` for only yours); a subclass takes the
154
+ closest mapped class. An exception's `.payload`, when it has one, is sent as `payload`."""
155
+ table = {**(DEFAULT_ERRORS if defaults else {}), **(errors or {})}
156
+
157
+ def handler(status: int) -> Callable[[Request, Exception], JSONResponse]:
158
+ def answer(request: Request, e: Exception) -> JSONResponse:
159
+ detail = str(e.args[0]) if isinstance(e, KeyError) and e.args else str(e) or type(e).__name__
160
+ body = ErrorBody(detail=detail, payload=getattr(e, "payload", None))
161
+ return JSONResponse(body.model_dump(mode="json"), status_code=status)
162
+
163
+ return answer
164
+
165
+ for cls, status in table.items():
166
+ app.add_exception_handler(cls, handler(status)) # pyright: ignore[reportArgumentType] - Starlette types the handler's exception as Exception
167
+
168
+
169
+ def _folder(name: str, path: str) -> Folder:
170
+ probe = path
171
+ while not os.path.exists(probe) and os.path.dirname(probe) != probe:
172
+ probe = os.path.dirname(probe) # the disk a missing folder will be on
173
+ try:
174
+ usage = shutil.disk_usage(probe)
175
+ free, total = usage.free, usage.total
176
+ except OSError:
177
+ free = total = None
178
+ return Folder(name=name, path=path, exists=os.path.isdir(path), free_bytes=free, total_bytes=total)
179
+
180
+
181
+ def _service(name: str, client: ServiceClient) -> ServiceStatus:
182
+ try:
183
+ h = client.health()
184
+ except (Unavailable, Rejected) as e:
185
+ return ServiceStatus(name=name, url=client.url(), ok=False, detail=str(e))
186
+ version = h.get("version")
187
+ return ServiceStatus(
188
+ name=name,
189
+ url=client.url(),
190
+ ok=bool(h.get("ok")),
191
+ version=None if version is None else str(version),
192
+ detail=None if h.get("ok") else "answered, but not ok",
193
+ )
194
+
195
+
196
+ def add_system(
197
+ app: FastAPI,
198
+ version: str,
199
+ *,
200
+ commit: str | None = None,
201
+ folders: Mapping[str, str | Callable[[], str]] | None = None,
202
+ services: Mapping[str, ServiceClient | str] | None = None,
203
+ extra: Callable[[], Mapping[str, object]] | None = None,
204
+ ) -> None:
205
+ """`GET /api/system`, a `SystemInfo`: the version and commit, Python and platform, when the server started, each
206
+ named folder with its disk's free and total space, and each service this app calls with what its health endpoint
207
+ answers now (probed in parallel, 2 s each). A folder is a path or a function giving one (a setting read on each
208
+ request); a service is a `ServiceClient` or a base URL. `extra` adds the app's own fields (a queue length)."""
209
+ started = datetime.datetime.now(datetime.UTC)
210
+ clients = {k: v if isinstance(v, ServiceClient) else ServiceClient(v) for k, v in (services or {}).items()}
211
+
212
+ @app.get("/api/system", response_model=SystemInfo)
213
+ def get_system() -> SystemInfo: # pyright: ignore[reportUnusedFunction]
214
+ paths = {k: v if isinstance(v, str) else v() for k, v in (folders or {}).items()}
215
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max(len(clients), 1)) as pool:
216
+ probes = [pool.submit(_service, k, c) for k, c in clients.items()]
217
+ statuses = [p.result() for p in probes]
218
+ return SystemInfo(
219
+ version=version,
220
+ commit=commit,
221
+ python=sys.version.split()[0],
222
+ platform=platform.platform(terse=True),
223
+ started_at=started,
224
+ folders=[_folder(k, p) for k, p in paths.items()],
225
+ services=statuses,
226
+ **(extra() if extra else {}),
227
+ )
228
+
229
+
77
230
  def add_web(app: FastAPI, static: str, landing: str | None = None) -> None:
78
231
  """Serve the built web app: `static/assets` at /assets, files directly in `static` (favicon and the like) at their name, and `static/index.html` (else the plain `landing` page)
79
232
  at every other path outside /api, so a reload or a shared link opens that screen (the app routes in the browser). Call it after the app's own routes: the catch-all is registered here."""
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: strata-python
3
- Version: 0.2.2
3
+ Version: 0.2.4
4
4
  Summary: Common code for Python web server apps: OS helpers, settings, FastAPI serving, CLI commands, test fixtures and the strata-check gate
5
5
  Project-URL: Homepage, https://github.com/jburnhams/strata-python
6
6
  Project-URL: Source, https://github.com/jburnhams/strata-python
@@ -38,7 +38,7 @@ Requires-Dist: pytest-xdist<4,>=3; extra == 'dev'
38
38
  Requires-Dist: ruff<0.18,>=0.17; extra == 'dev'
39
39
  Requires-Dist: ty<0.1,>=0.0.99; extra == 'dev'
40
40
  Provides-Extra: pdf
41
- Requires-Dist: pillow<14,>=10; extra == 'pdf'
41
+ Requires-Dist: pillow<14,>=13; extra == 'pdf'
42
42
  Requires-Dist: pypdfium2<6,>=4.30; extra == 'pdf'
43
43
  Requires-Dist: reportlab<6,>=4.2; extra == 'pdf'
44
44
  Description-Content-Type: text/markdown
@@ -49,14 +49,17 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
49
49
 
50
50
  | Module | What it gives an app |
51
51
  |---|---|
52
- | `strata_python.oslib` | Cross-platform file locks, process liveness (`pid_alive`), `kill_tree`, `lower_priority`, `venv_python`, `cli_command(module)` |
52
+ | `strata_python.oslib` | Cross-platform file locks, process liveness (`pid_alive`), `kill_tree`, `lower_priority`, `detached_kwargs`, `load_average`, `start_supervised`/`watch_supervisor`/`kill_group` (a child in its own process group that dies with its parent), `venv_python`, `cli_command(module)` |
53
53
  | `strata_python.settings` | `Settings` / `Setting` / `ListSetting`: one JSON file in `~/.<app>` with `<APP>_*` environment overrides, validation (`absolute_path`, `non_empty`, `number_between`, `whole_between`, `iso_date`, `boolean`), typed getters, atomic saves, and `bind(store)` to keep them elsewhere (`strata_python.db.settings.TableStore`) |
54
- | `strata_python.web` | `base_app` (health with the app's own fields + settings routes), `add_web` (built web app or stand-in page at every non-API path), `with_base` (reverse-proxy-safe `<base href>`), `static_file` (path-safe), `serve` |
54
+ | `strata_python.web` | `base_app` (health with the app's own fields and `commit` + typed settings routes), `add_error_handlers` (exceptions to `ErrorBody` responses), `add_system` (`GET /api/system`: folders, disks, services), `source_commit`, `add_web` (built web app or stand-in page at every non-API path), `with_base` (reverse-proxy-safe `<base href>`), `static_file` (path-safe), `serve` |
55
55
  | `strata_python.cli` | `add_doctor` (imports, labels, optional modules and the app's own `Check`s), `add_set`, `add_serve` for the app's argparse subcommands |
56
+ | `strata_python.contracts` | The shapes the apps' APIs share, as pydantic models for `response_model`: `Health`, `SystemInfo`, `ErrorBody`, `Task` (with `TaskState`), `Progress`, `Page[T]`, `FileRef`, `Judgment` |
57
+ | `strata_python.client` | `ServiceClient`, the standard-library base for calling a strata service: JSON calls, `Rejected` (4xx, with the reason and payload) and `Unavailable` (down or 5xx), retried reads, a long-poll `wait`, `available()`, and `env_url` |
58
+ | `strata_python.tasks` | Work outside a request: `next_state`/`backoff_s`/`RetryLater` (when to retry), `report_progress` and `ProgressReporter` (throttled), `SingleFlight` (one run per key, `Conflict` on a second), `StatusFile` and `Detached` (a process that outlives the server), `Ticker` (a loop that survives its errors), and with the `[db]` extra `tasks.queue` (`Queue`, `Worker`, `jobs_table`: durable jobs with retry, dedupe, resources, cancel and crash recovery) |
56
59
  | `strata_python.clients.models` | The strata-models client, standard library only: `run`, `submit`, `wait`, `role_model`, `gpu_lease`, a shortcut for every role the service runs (`faces`, `face_kind`, `transcribe`, `ocr`, `speak`, `denoise_audio`, `audio_quality`, `generate_image`, `embed`, `enhance_video`, and `ask` for the language models) and a typed result for each |
57
60
  | `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
58
- | pytest plugin | Loaded automatically: hermetic home and data folders (`strata_env` adds the app's own variables), a no-network guard, `http_server` and `live_app`, the `fake_urlopen`, `fake_popen`, `fake_run` and `no_sleep` fixtures, and the `integration` marker on everything under `tests/integration` |
59
- | `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) and the CLI runners `run_cli(main, *args)` and `run_module("myapp", *args, src=...)` |
61
+ | pytest plugin | Loaded automatically: hermetic home and data folders (`strata_env` adds the app's own variables), a no-network guard, `http_server` and `live_app`, the `fake_urlopen`, `fake_popen`, `fake_run` and `no_sleep` fixtures, `fake_models` (a stand-in strata-models), and the `integration` marker on everything under `tests/integration` |
62
+ | `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) `FakeModels`, and the CLI runners `run_cli(main, *args)` and `run_module("myapp", *args, src=...)` |
60
63
  | `strata_python.db` (extra `[db]`) | The shared database: `connect("myapp")` (the app's schema of one shared Postgres, or a SQLite path), a declarative base with the shared `NAMING_CONVENTION` for typed models, Alembic migrations with no per-app `env.py`, the live-database guard, the `strata-db` command, and the `db_*` fixtures (SQLite by default, a throwaway Postgres with `--pg`) |
61
64
  | `strata_python.pages` (extra `[pdf]`) | A scanned page described as blocks, lines, styled spans and figures in scan pixels, drawn as a PDF with real embedded fonts (`render`), and read back as pixels at the scan's dpi (`rasterise`) and as text (`read_text`): for rebuilding scanned books, and for scoring a rebuild with the renderer that prints it |
62
65
  | `strata-check` | The one gate: lockfile, ruff, `ruff format`, pyright strict, ty, unit tests with coverage |
@@ -159,6 +162,18 @@ def create_app():
159
162
  return app
160
163
  ```
161
164
 
165
+ Two more that replace code most servers carry:
166
+
167
+ ```python
168
+ web.add_error_handlers(app) # ValueError 400, PermissionError 403, KeyError and FileNotFoundError 404,
169
+ # tasks.Conflict 409, client.Rejected 502, client.Unavailable 503: {detail, payload}
170
+ web.add_system(app, __version__, commit=web.source_commit(__file__),
171
+ folders={"data": lambda: SETTINGS.get("data_dir")},
172
+ services={"strata-models": "http://127.0.0.1:8366"}) # GET /api/system, a SystemInfo
173
+ ```
174
+
175
+ Delete the app's `guard()` (or each route's `try/except` raising `HTTPException`), passing its own exceptions as `add_error_handlers(app, {BookLocked: 423})`, and its `/api/system` route. Give `base_app` the same `commit=` so `/api/health` says which source the server runs. Declare a route's answer with a shape from `strata_python.contracts` (`response_model=Page[Task]`) where the app already returns that shape, so the web app's types can come from `/api/openapi.json`.
176
+
162
177
  Delete the app's own `/api/health` and `/api/settings` routes, its `/assets` mount, SPA fallback, `with_base` and `static_file` copies and its `uvicorn.run` wrapper. `web.serve(app, argv, default_port=...)` replaces the last of these. For health fields of the app's own, pass `health=lambda: {"gpu": gpu_name()}`: they follow `ok` and `version`, and may set `ok` to false. It runs on every request, so keep it cheap.
163
178
 
164
179
  ### 5. The CLI
@@ -212,11 +227,33 @@ with sm.gpu_lease("strata-stills", vram_gb=4):
212
227
  run_my_own_cuda_code()
213
228
  ```
214
229
 
215
- The shortcuts still return the service's JSON, so existing code keeps working, and the result classes keep all of it in `.raw`. There is one shortcut for every role the service runs (`sm.ROLES`): `faces`, `face_kind`, `transcribe` (also `role="transcribe-fast"`), `ocr`, `speak`, `denoise_audio`, `audio_quality`, `generate_image`, `embed` and `enhance_video`, plus `ask` for the language-model roles (`vision-language`, `text`, and the judges). Each has a result class (`Answer`, `GeneratedImage`, `Embeddings`, `FaceKinds`, `CleanAudio`, `AudioQuality`, `EnhancedVideo` and the four above). The roles `models.toml` lists without a runtime yet (sound-events, speaker-embedding, detect-people, upscale, denoise, nsfw) have none: `run(role, params, app)` reaches them once the service serves them.
230
+ The shortcuts still return the service's JSON, so existing code keeps working, and the result classes keep all of it in `.raw`. There is one shortcut for every role the service runs (`sm.ROLES`): `faces`, `face_kind`, `transcribe` (also `role="transcribe-fast"`), `ocr`, `speak`, `denoise_audio`, `audio_quality`, `generate_image`, `embed` and `enhance_video`, plus `ask` for the language-model roles (`vision-language`, `text`, and the judges). Each has a result class (`Answer`, `GeneratedImage`, `Embeddings`, `FaceKinds`, `CleanAudio`, `AudioQuality`, `EnhancedVideo` and the four above). In tests, the `fake_models` fixture (section 7) stands in for the service, so the app's tests need neither the service nor a GPU. The roles `models.toml` lists without a runtime yet (sound-events, speaker-embedding, detect-people, upscale, denoise, nsfw) have none: `run(role, params, app)` reaches them once the service serves them.
216
231
 
217
232
  ### 6. OS helpers
218
233
 
219
- Delete the app's `oslib.py` and import from `strata_python.oslib`: `file_lock(f)`, `pid_alive(pid)`, `kill_tree(pid, sig)`, `lower_priority(nice, io=False)` (`io=True` for idle disk priority too; drop the app's `ionice` helper), `venv_python(venv)` and `cli_command(module)`. `cli_command` now takes the module name (`cli_command("myapp")`). Local `alive(pid)`, `_alive` and `lower_priority()` copies go too. Helpers this library does not have yet (process-group supervision, load average) stay in the app until they move here, and the app's file says so.
234
+ Delete the app's `oslib.py` and import from `strata_python.oslib`: `file_lock(f)`, `pid_alive(pid)`, `kill_tree(pid, sig)`, `lower_priority(nice, io=False)` (`io=True` for idle disk priority too; drop the app's `ionice` helper), `venv_python(venv)` and `cli_command(module)`. `cli_command` now takes the module name (`cli_command("myapp")`). Local `alive(pid)`, `_alive` and `lower_priority()` copies go too. `detached_kwargs()` starts a process outside the server's session and `load_average()` replaces 360's copy. listory's `job_process`, `start_job`, `watch_supervisor`, `terminate_job_group` and `kill_job` are `start_supervised(cmd, env=)`, `watch_supervisor()`, `terminate_own_group()` and `kill_group(proc)`; with the queue's `Worker` an app needs none of them directly.
235
+
236
+ ### 6b. Background work
237
+
238
+ Replace the app's job dicts and loops with `strata_python.tasks`:
239
+
240
+ - An in-process run per key ("scan this folder") is `SingleFlight`: `FLIGHTS.start(key, fn)` raises `Conflict` (a 409 with `add_error_handlers`) when that key is running; `fn(flight)` checks `flight.stopping`; `FLIGHTS.get(key).as_json()` is the status. Delete the app's `*_JOBS` dicts, their locks and their stop flags.
241
+ - Work that must outlive a restart is `Detached(cmd, status_path, log)`: `start()`, `read()`, `stop()`. The child writes its own progress and end state with `StatusFile.from_env().update(...)`. Delete the app's `write_status` copies and its pid bookkeeping.
242
+ - A loop every N seconds is `Ticker(every_s, fn, name=...)`. Delete the hand-written `while not stop.wait(...)` threads.
243
+ - Progress from deep inside a task is `report_progress(done, total, text)`; the runner binds a `ProgressReporter` (at most one write a second). Retry rules are `next_state(attempts, error, progressed=...)`: delete the app's own backoff.
244
+ - Jobs that must survive a restart, retry and be listed are the durable queue (with the db extra). Add `JOBS = jobs_table(Base.metadata)` to the models and a revision, then:
245
+
246
+ ```python
247
+ from strata_python.tasks.queue import Job, Queue, Worker
248
+
249
+ QUEUE = Queue(engine, JOBS, on_fail=cascade) # on_fail(conn, job, error), in the failing transaction
250
+ QUEUE.enqueue("ocr", {"page": 3}, domain="book:12", dedupe=True, resources=["gpu"], timeout_s=600)
251
+ WORKER = Worker(QUEUE, {"ocr": ocr_page}, concurrency=2).start() # a job process per thread, reused; recovers dead workers' jobs
252
+ QUEUE.page(state="running", after=cursor) # Page[Task] for GET /api/jobs
253
+ QUEUE.cancel(job_id); QUEUE.retry(job_id); QUEUE.prune(older_than_s=30 * 86400)
254
+ ```
255
+
256
+ A handler is a module-level `fn(job) -> result` that reads `job.options` and reports progress. By default jobs run in job processes (`python -m strata_python.tasks.child`, one per worker thread, kept between jobs and importing the handlers by name), so a cancel, a timeout or `WORKER.stop()` kills the job and every tool it started, and jobs die with the server; a quick job costs about half a millisecond more than on a thread (3.5 ms against 2.9 ms a job on SQLite), since only a kill starts a new process. `max_jobs=N` replaces a process after N jobs, for code that leaks. The worker checks at start-up that every handler can be imported. `Worker(lower_priority=True)` runs the jobs at idle CPU and disk priority. `Worker(isolate=False)` runs handlers on the server's threads instead, where they return early when `job.stopping`. In tests, `QUEUE.step(handlers)` claims and runs one job in the test's own thread.
220
257
 
221
258
  ### 7. Tests
222
259
 
@@ -274,8 +311,9 @@ What every test gets:
274
311
  | `fake_popen` | Code that starts a long-running process: nothing starts; `fake_popen.instances[-1].cmd` and `.kw`; set `.returncode = 0` to finish it |
275
312
  | `fake_run` | Code that runs a program: `fake_run.returns["ffprobe"] = b"..."`, `fake_run.code = 1`, then `fake_run.calls` |
276
313
  | `no_sleep` | Retries and backoff without waiting: `no_sleep.delays` |
314
+ | `fake_models` | An app that calls strata-models: a stand-in service on a real port with `STRATA_MODELS_URL` set, so `strata_python.clients.models` runs unchanged. `fake_models.results["ocr"] = {...}` (or a function of the params), `.fail("CUDA out of memory", role="faces")`, `.busy = True` (leases wait), `.down = True` (503s), then `.jobs[0]["params"]` |
277
315
 
278
- `strata_python.testing` holds the classes behind them (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) for a test that needs one directly. Prefer the real thing: `http_server` over `fake_urlopen`, the actual program over `fake_run`. A fake is for a true external edge where speed matters.
316
+ `strata_python.testing` holds the classes behind them (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`, `FakeModels` and its example replies `MODELS_RESULTS`) for a test that needs one directly. Prefer the real thing: `http_server` over `fake_urlopen`, the actual program over `fake_run`. A fake is for a true external edge where speed matters.
279
317
 
280
318
  ### 8. Database (apps with one)
281
319
 
@@ -1,17 +1,19 @@
1
- strata_python/__init__.py,sha256=R8RMrmyXpaCez3TMEsuKoPxCR0cQxFZxgHf-UVPymSg,1321
1
+ strata_python/__init__.py,sha256=eF-f5-pwPokTJjoq063Hr78JTnjPkVm-3hQBN9tXqDs,1723
2
2
  strata_python/check.py,sha256=lFjXuPjVIWn6dBu2yMKIW-76RloUREijuMHCRsBW4Z8,2932
3
3
  strata_python/cli.py,sha256=KKcFNjLsNXygeSUvzbaznZ8sTTW1ADkgsovJcyd3Sjc,5991
4
+ strata_python/client.py,sha256=S-cfDQqbO0dJ951TAiFyW2CbkFQkN1OWnUBCYaTO3Lg,7911
5
+ strata_python/contracts.py,sha256=g72b9GQt_ZeiShYXhMJzy4hppDz6t124Ik7lEnnM_HA,5813
4
6
  strata_python/http_server.py,sha256=64uYWy4zFxughOgtvkssGXMJDZ7jhRj1bxUIfnzte8w,4475
5
7
  strata_python/live.py,sha256=kNY6h6gMxBo9l78UoGUIWjcADeZi4eZuAEp0jqDowEE,1215
6
- strata_python/oslib.py,sha256=seDkRBgDEZYqcaZWOF0heGKDd93IHJI_nFPLmOeYcsA,6380
8
+ strata_python/oslib.py,sha256=vfZDUCNZnTjjjB704eoyNXlPFCz2yVR3puFljE0Z1gE,12137
7
9
  strata_python/public_check.py,sha256=A0JusSWnwXtaA3sKsRoa4ocM5MNx38Nc49-dymd__3Q,8398
8
10
  strata_python/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
- strata_python/pytest_plugin.py,sha256=vinyCpDC9KeM_NM37lTN6F1ou0pfHlsn4C3j0Y_4Fg8,6718
10
- strata_python/settings.py,sha256=9y0zGhmGsBoUaH4zkbQ6RETiH-oLL2IKlmhwml3AkCk,14108
11
- strata_python/testing.py,sha256=-4mread8_FHMkcGvbajGtRyoP88fyeG3pAh1LlVr_w4,10372
12
- strata_python/web.py,sha256=7A2G7M0kPjeBr5Dfu6RMZqRX3JjWg0wJx8IeCT47Xcw,5618
11
+ strata_python/pytest_plugin.py,sha256=BaD-XokrX1PMMj0Cqxj9IJTb6EXBp7ozQZ6SSCDumMg,7223
12
+ strata_python/settings.py,sha256=zozaBZetHToxy0XSj4jmRcvgeC8jxW6v3qt8IMrjDwQ,14896
13
+ strata_python/testing.py,sha256=SXIUtWgbqjHPdXhjbtzC6Voo7QhL0nexnY9mSp8euUs,20107
14
+ strata_python/web.py,sha256=Ur7Tt_wLC-qJtPse1U1gDAvyTcIFSpEVg4MFhlzW3c8,12897
13
15
  strata_python/clients/__init__.py,sha256=xivuysmYG7rbCGProVNvdSs-h4xVFQsuqUY6EwzuJbk,182
14
- strata_python/clients/models.py,sha256=rcIKizebN1BEWWpwwqUWBCZBq8zcnV2g7XO9StsLmW8,30146
16
+ strata_python/clients/models.py,sha256=vxnvINQ_xQRbU848BTnGyjlTcr1-bhv6GAkrCN5ZDuU,30314
15
17
  strata_python/db/__init__.py,sha256=ELfBNyONSF9vfl-Tw0a-X0rT3w1h1O_t_QLz1ZQTEwo,3775
16
18
  strata_python/db/__main__.py,sha256=nHCtenRtjL_Ouig4FHh60dax2oILeVdoIIKrxXEc6Ss,106
17
19
  strata_python/db/cli.py,sha256=PCIh0QQuxOH9ybgtFr-8U1p5IY2E4EdOQF1RchKgXrw,9848
@@ -30,9 +32,17 @@ strata_python/db/_alembic/env.py,sha256=gXzRn02h59PB_1RaABkaT6GuyuzPQCZh3Z5ml2Jl
30
32
  strata_python/db/_alembic/script.py.mako,sha256=04kgeBtNMa4cCnG8CfQcKt6P6rnloIfj8wy0u_DBydM,704
31
33
  strata_python/pages/__init__.py,sha256=6QsTqJbFiuLCxywt8C0D6nyXRXjpzI1Xoo5u6rK9toQ,665
32
34
  strata_python/pages/model.py,sha256=8Skz3eishAZiNHIHzScI0g60wGpH6jZ3vNc0LpMZ4q4,9821
33
- strata_python/pages/render.py,sha256=69317W03K0AVxGpelpzrNsnEP5y0oIp5aFodlnhckdE,11760
34
- strata_python-0.2.2.dist-info/METADATA,sha256=lP9ckCGlC4IMVYlbL5mBGaWRRrtRJjCOMzBdyWP-t2o,23333
35
- strata_python-0.2.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
36
- strata_python-0.2.2.dist-info/entry_points.txt,sha256=6RVv-uDumVQ-KY2YdvKwd5R3l6P9WQD4kPtPOKKEM-I,256
37
- strata_python-0.2.2.dist-info/licenses/LICENSE,sha256=9yVMCPoK7unONyTAiDYjMTt3MZPGJ639nWOwxyNsZGg,1066
38
- strata_python-0.2.2.dist-info/RECORD,,
35
+ strata_python/pages/render.py,sha256=Q3_xliHCkDoGKXNLT3KksaYtfNnm0T2-p-7FhOu6loQ,12421
36
+ strata_python/tasks/__init__.py,sha256=q1fIMbB1nD5xrmM6awllA3axrchWJP9Qo0OiudUPj18,1530
37
+ strata_python/tasks/child.py,sha256=1ZpQwlFx0bbNXD5UKmPrlcEogCf-MrPGSOSK8TpqllA,11133
38
+ strata_python/tasks/flight.py,sha256=FjWl7M1Y1qV5Mcr3Qwu6H464sobzpYEjQAKcz_GjPH4,5704
39
+ strata_python/tasks/progress.py,sha256=AqfrrDA-ZBkha98ex0kQIzwk45TiTe_pX1FhYyi2u2I,3636
40
+ strata_python/tasks/queue.py,sha256=b4in3XnplTlapL_ECTs_WYJcittYj3iKz7q_fQ8_HDY,32188
41
+ strata_python/tasks/retry.py,sha256=NztmOf3Q-rl5y3CZlfP1qcDqPT0jOiIDjMfD-MUkr5s,3995
42
+ strata_python/tasks/status.py,sha256=a6QF5u8BzoVJ1S2tynbYzdlkx1TuFlyEUmzxSdIxOiY,7979
43
+ strata_python/tasks/ticker.py,sha256=V6JLWgAGV5sIGeX1vp4t35omuRvvB6AYWv_lzJAq69Y,2860
44
+ strata_python-0.2.4.dist-info/METADATA,sha256=9MqWkBTQJWbxVbQ1zLi3hSkk82k4IbWK61EmNTQg71c,29135
45
+ strata_python-0.2.4.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
46
+ strata_python-0.2.4.dist-info/entry_points.txt,sha256=6RVv-uDumVQ-KY2YdvKwd5R3l6P9WQD4kPtPOKKEM-I,256
47
+ strata_python-0.2.4.dist-info/licenses/LICENSE,sha256=9yVMCPoK7unONyTAiDYjMTt3MZPGJ639nWOwxyNsZGg,1066
48
+ strata_python-0.2.4.dist-info/RECORD,,