strata-python 0.2.2__tar.gz → 0.2.4__tar.gz
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-0.2.2 → strata_python-0.2.4}/CHANGELOG.md +21 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/PKG-INFO +47 -9
- {strata_python-0.2.2 → strata_python-0.2.4}/README.md +45 -7
- {strata_python-0.2.2 → strata_python-0.2.4}/pyproject.toml +2 -2
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/__init__.py +5 -1
- strata_python-0.2.4/src/strata_python/client.py +184 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/clients/models.py +5 -2
- strata_python-0.2.4/src/strata_python/contracts.py +149 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/oslib.py +140 -5
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/pages/render.py +10 -2
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/pytest_plugin.py +10 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/settings.py +13 -0
- strata_python-0.2.4/src/strata_python/tasks/__init__.py +37 -0
- strata_python-0.2.4/src/strata_python/tasks/child.py +236 -0
- strata_python-0.2.4/src/strata_python/tasks/flight.py +146 -0
- strata_python-0.2.4/src/strata_python/tasks/progress.py +92 -0
- strata_python-0.2.4/src/strata_python/tasks/queue.py +716 -0
- strata_python-0.2.4/src/strata_python/tasks/retry.py +101 -0
- strata_python-0.2.4/src/strata_python/tasks/status.py +188 -0
- strata_python-0.2.4/src/strata_python/tasks/ticker.py +85 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/testing.py +164 -0
- strata_python-0.2.4/src/strata_python/web.py +260 -0
- strata_python-0.2.4/tests/unit/job_handlers.py +68 -0
- strata_python-0.2.4/tests/unit/test_client.py +132 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/tests/unit/test_clients_models.py +34 -136
- strata_python-0.2.4/tests/unit/test_contracts.py +47 -0
- strata_python-0.2.4/tests/unit/test_oslib.py +251 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/tests/unit/test_pages.py +22 -0
- strata_python-0.2.4/tests/unit/test_queue.py +515 -0
- strata_python-0.2.4/tests/unit/test_tasks.py +284 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/tests/unit/test_testing.py +35 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/tests/unit/test_web.py +126 -0
- strata_python-0.2.2/src/strata_python/web.py +0 -107
- strata_python-0.2.2/tests/unit/test_oslib.py +0 -120
- {strata_python-0.2.2 → strata_python-0.2.4}/.gitignore +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/LICENSE +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/check.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/cli.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/clients/__init__.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/db/__init__.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/db/__main__.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/db/_alembic/env.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/db/_alembic/script.py.mako +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/db/cli.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/db/config.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/db/engine.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/db/guard.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/db/migrations.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/db/models.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/db/project.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/db/pytest_plugin.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/db/scratch.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/db/settings.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/db/testing.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/db/testserver.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/http_server.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/live.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/pages/__init__.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/pages/model.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/public_check.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/src/strata_python/py.typed +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/tests/conftest.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/tests/integration/test_db_cli.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/tests/integration/test_serve.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/tests/integration/test_strata_check.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/tests/unit/test_check.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/tests/unit/test_cli.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/tests/unit/test_db.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/tests/unit/test_http_server.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/tests/unit/test_live.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/tests/unit/test_package.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/tests/unit/test_plugin.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/tests/unit/test_public_check.py +0 -0
- {strata_python-0.2.2 → strata_python-0.2.4}/tests/unit/test_settings.py +0 -0
|
@@ -4,10 +4,30 @@ What each release adds or changes for an app that depends on strata-python, newe
|
|
|
4
4
|
|
|
5
5
|
## Unreleased
|
|
6
6
|
|
|
7
|
+
## 0.2.4 (2026-11-23)
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
|
|
11
|
+
- `oslib.lower_priority(nice)` sets the nice value to `nice` (never lower than the current one) instead of adding it, so `lower_priority(19)` gives 19 from a process that starts below 0. An app that worked around it with its own `setpriority` can drop that.
|
|
12
|
+
- `pages.render.rasterise(pdf, dpi=page.dpi)` comes back exactly the scan's size: the page's points times `dpi / 72`, rounded. pdfium rounded up, so some sizes came back a pixel wider or taller. An app that padded or cropped the raster to the scan's size can drop that.
|
|
13
|
+
|
|
14
|
+
## 0.2.3 (2026-11-14)
|
|
15
|
+
|
|
7
16
|
## 0.2.2 (2026-11-14)
|
|
8
17
|
|
|
9
18
|
### Added
|
|
10
19
|
|
|
20
|
+
- `strata_python.contracts`: the shapes the apps' APIs share, as pydantic models to declare as a route's `response_model` (so `/api/openapi.json` describes them and a web app's types can be generated): `Health`, `SystemInfo` (with `Folder`, `ServiceStatus`), `ErrorBody`, `Task` with `TaskState` and `FINISHED`, `Progress`, `Page[T]` (cursor paging), `FileRef`, `Judgment`, and `utc(epoch)`. Times are aware datetimes, sent as ISO 8601.
|
|
21
|
+
- `strata_python.client.ServiceClient(base_url, app=...)`: the standard-library base for calling a strata service: `get`/`post`/`put`/`delete` returning parsed JSON, `Rejected` for a 4xx (`.status`, `.detail`, `.payload`) and `Unavailable` for an outage or a 5xx, reads retried with a doubling pause (POSTs never), `wait(path, done)` long-polling with `?wait=`, `health()` and `available()`, and `env_url("MYAPP_URL", default)` reading the URL on each call. `X-Strata-App` and the User-Agent name the calling app. `clients.models.Unavailable` is now a `client.Unavailable`.
|
|
22
|
+
- `web.add_error_handlers(app, {MyError: 423})`: the app's exceptions answered as `ErrorBody` responses (`{detail, payload}`); the defaults map `ValueError` to 400, `PermissionError` 403, `KeyError` and `FileNotFoundError` 404, `tasks.Conflict` 409, `client.Rejected` 502 and `client.Unavailable` 503. Delete the app's `guard()`.
|
|
23
|
+
- `web.add_system(app, version, commit=, folders=, services=, extra=)`: `GET /api/system` as a `SystemInfo` (version, commit, Python, platform, start time, each folder with its disk's free and total bytes, each service's health probed in parallel). Delete the app's own route.
|
|
24
|
+
- `base_app(..., commit=web.source_commit(__file__))`: `/api/health` answers `commit`, read from `.git` without running git (worktrees and packed refs included).
|
|
25
|
+
- `Settings.model()`: the settings as a pydantic model (`<App>Settings`), which `base_app` declares as the settings routes' response, so `/api/openapi.json` now names each setting and its type.
|
|
26
|
+
- `strata_python.tasks`: `next_state`, `backoff_s`, `RetryLater` and `PROGRAMMING_ERRORS` (retry rules: bugs fail at once, outside failures back off, progress resets the count); `report_progress` with `ProgressReporter` and `reporting` (throttled to one write a second, stage changes and the last step always written); `SingleFlight` and `Flight` (one in-process run per key, `Conflict` on a second start, cooperative `stopping`); `StatusFile` and `Detached` (a process outside the server's session, its state in an atomic JSON file that reads `died` when its pid is gone; the child finds the file in `STRATA_STATUS_FILE`; writes and merges hold `StatusFile.locked()` across processes, so none is lost); `Ticker` (a function every N seconds that survives its own errors and stops at once); `write_json_atomic`.
|
|
27
|
+
- `oslib.stdin_from_devnull()` (an empty stdin for the process and its tools; returns the old one) and `oslib.stdout_to_stderr()` (moves stdout for the process and the tools it starts, the Win32 handle too, and returns the old one). `oslib.start_supervised`, `watch_supervisor`, `terminate_own_group` and `kill_group`: listory's per-job process groups. A child started with a lifeline on its stdin ends its whole group when the parent dies; `kill_group` stops it and every tool it started. Replaces listory's `job_process`, `start_job`, `watch_supervisor`, `terminate_job_group` and `kill_job`.
|
|
28
|
+
- `strata_python.tasks.queue` (needs `[db]`): a durable job queue in the app's own database, SQLite or Postgres. `jobs_table(metadata)` for the app's models; `Queue(engine, table)` with `enqueue` (priority, `delay_s`, `dedupe`, `resources`, `timeout_s`, `domain`), `claim`, `heartbeat`, `report`, `finish`, `fail` (the `tasks.retry` rules; `on_fail(conn, job, error)` runs in the transaction that fails a job for good), `cancel`, `retry`, `get`, `page` (`Page[Task]`, newest first, cursor paging), `counts`, `recover` (jobs whose worker died are retried; each claim carries a token, so a slow worker whose job was claimed again cannot write over the new attempt), `prune`, and `step(handlers)` for tests; `Worker(queue, handlers, concurrency=)` runs them on threads with heartbeats, cooperative cancel and timeouts, and releases running jobs back to the queue on `stop()`. By default jobs run in a job process per worker thread (`tasks.child`), kept between jobs so a quick job costs well under a millisecond more than on a thread: cancel, timeout and `stop()` kill the job and the tools it started (the next job gets a new process), and jobs die with the server. Handlers must be module-level functions (checked when the `Worker` is made); `max_jobs=N` replaces a process after N jobs, `isolate=False` keeps handlers on threads, and `lower_priority=True` runs the processes at idle priority. Replaces an app's own queue and its job dicts that must survive a restart.
|
|
29
|
+
- `oslib.detached_kwargs()` (Popen arguments for a process outside this one's session or console) and `oslib.load_average()`.
|
|
30
|
+
- The `fake_models` fixture and `strata_python.testing.FakeModels`: a stand-in strata-models on a real loopback port with `STRATA_MODELS_URL` pointing at it, so an app's own `strata_python.clients.models` calls run in its tests without the service or a GPU. Script `fake_models.results[role]` (a reply or a function of the params; `MODELS_RESULTS` has one in the service's shape per role), `.fail(error, role=...)`, `.busy` (leases stay queued), `.down` (503s), and assert on `.jobs`, `.leases`, `.heartbeats`, `.released`. Delete the app's own stand-in.
|
|
11
31
|
- `strata_python.pages` and the `[pdf]` extra (ReportLab, pypdfium2, Pillow): a scanned page described as blocks, lines, styled spans and figures in scan pixels (`Page`, `Block`, `Line`, `Span`, `Figure`, JSON with `to_dict`/`from_dict`), drawn as a PDF with real, embedded fonts by `pages.render.render(page, fonts)`, and read back with `rasterise(pdf, page, dpi)` (greyscale pixels at the scan's size) and `read_text(pdf)`. A span takes a font matcher's per-word fit as it is (`x`, `baseline_y`, `size_pt`, `tracking_em`, `hscale`, `stroke_em`); small capitals are synthesised unless the face is a small-caps cut; the same input gives the same bytes. For apps that rebuild scanned books, and for scoring a rebuild against the scan with the very renderer that prints it.
|
|
12
32
|
- `strata_python.clients.models`: the strata-models client, standard library only, with the same functions as `strata_models_client` (`run`, `submit`, `wait`, `wait_job`, `faces`, `transcribe`, `ocr`, `speak`, `role_model`, `acquire`, `gpu_lease`, `Unavailable`, `JobFailed`), now typed, plus a shortcut for each of the other roles the service runs (`ask` for `vision-language`, `text` and the judges; `generate_image`, `embed`, `face_kind`, `denoise_audio`, `audio_quality`, `enhance_video`) and a result shape for every role (`OcrPage`, `Transcript`, `Faces`, `Speech`, `Answer`, `GeneratedImage`, `Embeddings`, `FaceKinds`, `CleanAudio`, `AudioQuality`, `EnhancedVideo`; `.from_json`, with everything the service sent in `.raw`). `ROLES` lists them. To move: replace `import strata_models_client as sm` with `from strata_python.clients import models as sm` and drop the client's path or git dependency.
|
|
13
33
|
- Typed settings: normalisers `number_between(lo, hi)`, `whole_between(lo, hi)`, `iso_date(allow_blank=True)` and `boolean`, and getters `get_int`, `get_float`, `get_bool`. Replace an app's own range and date normalisers and its `int(SETTINGS.get(...))` calls.
|
|
@@ -25,6 +45,7 @@ What each release adds or changes for an app that depends on strata-python, newe
|
|
|
25
45
|
|
|
26
46
|
### Fixed
|
|
27
47
|
|
|
48
|
+
- The `[pdf]` extra needs Pillow 13 (`pillow>=13,<14`): 12.x has eight published advisories, most of them in PDF parsing, and `uv audit` fails an app that locks it. Run `uv lock --upgrade-package pillow`.
|
|
28
49
|
- `strata-public-check` no longer reads three-part versions (`10.4.2` in package.json and package-lock.json) as private IPv4 addresses: only a whole four-part address counts. An app with a web front end can now run it in CI.
|
|
29
50
|
- The db pytest plugin no longer stops an app's tests from running when the old database package is installed too ("option names {'--pg'} already added"). It now switches on only for an app that uses `strata_python.db`: the db extra installed and a `[tool.strata-db]` table in pyproject.toml, or `strata_db = true` in `[tool.pytest.ini_options]` (`strata_db = false` turns it off). SQLAlchemy and Alembic brought in by another package no longer switch on its guard. Until it is on it adds no `--pg`; once on, `--pg` is ours unless another plugin has it, and `--strata-pg` always works. Drop the old database package once the app has moved to `strata_python.db`.
|
|
30
51
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: strata-python
|
|
3
|
-
Version: 0.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,>=
|
|
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.
|
|
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
|
|
|
@@ -4,14 +4,17 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
|
|
|
4
4
|
|
|
5
5
|
| Module | What it gives an app |
|
|
6
6
|
|---|---|
|
|
7
|
-
| `strata_python.oslib` | Cross-platform file locks, process liveness (`pid_alive`), `kill_tree`, `lower_priority`, `venv_python`, `cli_command(module)` |
|
|
7
|
+
| `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)` |
|
|
8
8
|
| `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`) |
|
|
9
|
-
| `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` |
|
|
9
|
+
| `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` |
|
|
10
10
|
| `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 |
|
|
11
|
+
| `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` |
|
|
12
|
+
| `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` |
|
|
13
|
+
| `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) |
|
|
11
14
|
| `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 |
|
|
12
15
|
| `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
|
|
13
|
-
| 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` |
|
|
14
|
-
| `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=...)` |
|
|
16
|
+
| 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` |
|
|
17
|
+
| `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=...)` |
|
|
15
18
|
| `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`) |
|
|
16
19
|
| `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 |
|
|
17
20
|
| `strata-check` | The one gate: lockfile, ruff, `ruff format`, pyright strict, ty, unit tests with coverage |
|
|
@@ -114,6 +117,18 @@ def create_app():
|
|
|
114
117
|
return app
|
|
115
118
|
```
|
|
116
119
|
|
|
120
|
+
Two more that replace code most servers carry:
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
web.add_error_handlers(app) # ValueError 400, PermissionError 403, KeyError and FileNotFoundError 404,
|
|
124
|
+
# tasks.Conflict 409, client.Rejected 502, client.Unavailable 503: {detail, payload}
|
|
125
|
+
web.add_system(app, __version__, commit=web.source_commit(__file__),
|
|
126
|
+
folders={"data": lambda: SETTINGS.get("data_dir")},
|
|
127
|
+
services={"strata-models": "http://127.0.0.1:8366"}) # GET /api/system, a SystemInfo
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
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`.
|
|
131
|
+
|
|
117
132
|
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.
|
|
118
133
|
|
|
119
134
|
### 5. The CLI
|
|
@@ -167,11 +182,33 @@ with sm.gpu_lease("strata-stills", vram_gb=4):
|
|
|
167
182
|
run_my_own_cuda_code()
|
|
168
183
|
```
|
|
169
184
|
|
|
170
|
-
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.
|
|
185
|
+
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.
|
|
171
186
|
|
|
172
187
|
### 6. OS helpers
|
|
173
188
|
|
|
174
|
-
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.
|
|
189
|
+
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.
|
|
190
|
+
|
|
191
|
+
### 6b. Background work
|
|
192
|
+
|
|
193
|
+
Replace the app's job dicts and loops with `strata_python.tasks`:
|
|
194
|
+
|
|
195
|
+
- 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.
|
|
196
|
+
- 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.
|
|
197
|
+
- A loop every N seconds is `Ticker(every_s, fn, name=...)`. Delete the hand-written `while not stop.wait(...)` threads.
|
|
198
|
+
- 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.
|
|
199
|
+
- 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:
|
|
200
|
+
|
|
201
|
+
```python
|
|
202
|
+
from strata_python.tasks.queue import Job, Queue, Worker
|
|
203
|
+
|
|
204
|
+
QUEUE = Queue(engine, JOBS, on_fail=cascade) # on_fail(conn, job, error), in the failing transaction
|
|
205
|
+
QUEUE.enqueue("ocr", {"page": 3}, domain="book:12", dedupe=True, resources=["gpu"], timeout_s=600)
|
|
206
|
+
WORKER = Worker(QUEUE, {"ocr": ocr_page}, concurrency=2).start() # a job process per thread, reused; recovers dead workers' jobs
|
|
207
|
+
QUEUE.page(state="running", after=cursor) # Page[Task] for GET /api/jobs
|
|
208
|
+
QUEUE.cancel(job_id); QUEUE.retry(job_id); QUEUE.prune(older_than_s=30 * 86400)
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
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.
|
|
175
212
|
|
|
176
213
|
### 7. Tests
|
|
177
214
|
|
|
@@ -229,8 +266,9 @@ What every test gets:
|
|
|
229
266
|
| `fake_popen` | Code that starts a long-running process: nothing starts; `fake_popen.instances[-1].cmd` and `.kw`; set `.returncode = 0` to finish it |
|
|
230
267
|
| `fake_run` | Code that runs a program: `fake_run.returns["ffprobe"] = b"..."`, `fake_run.code = 1`, then `fake_run.calls` |
|
|
231
268
|
| `no_sleep` | Retries and backoff without waiting: `no_sleep.delays` |
|
|
269
|
+
| `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"]` |
|
|
232
270
|
|
|
233
|
-
`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.
|
|
271
|
+
`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.
|
|
234
272
|
|
|
235
273
|
### 8. Database (apps with one)
|
|
236
274
|
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "strata-python"
|
|
7
|
-
version = "0.2.
|
|
7
|
+
version = "0.2.4" # the single source of truth: `strata_python.__version__` reads it back with importlib.metadata
|
|
8
8
|
description = "Common code for Python web server apps: OS helpers, settings, FastAPI serving, CLI commands, test fixtures and the strata-check gate"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
@@ -60,7 +60,7 @@ db = [
|
|
|
60
60
|
pdf = [
|
|
61
61
|
"reportlab>=4.2,<6",
|
|
62
62
|
"pypdfium2>=4.30,<6",
|
|
63
|
-
"pillow>=
|
|
63
|
+
"pillow>=13,<14", # 13.0.0 fixes eight advisories, most in PDF parsing, which this extra exists for
|
|
64
64
|
]
|
|
65
65
|
|
|
66
66
|
[project.urls]
|
|
@@ -2,8 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
oslib file locks, process liveness and termination, priority, how to start a CLI (POSIX and Windows)
|
|
4
4
|
settings one JSON settings file per app with environment overrides and validation
|
|
5
|
-
web reverse-proxy-safe page serving, health and
|
|
5
|
+
web reverse-proxy-safe page serving, health, settings and system routes, error handlers, static files, the uvicorn runner
|
|
6
6
|
cli argparse commands every app has: doctor, set, serve
|
|
7
|
+
contracts the shapes the apps' APIs share (Health, SystemInfo, ErrorBody, Task, Progress, Page, FileRef, Judgment)
|
|
8
|
+
client ServiceClient: the standard-library base for calling a strata service
|
|
9
|
+
clients one typed client per strata service (models)
|
|
10
|
+
tasks retry rules, progress reporting, SingleFlight, StatusFile and Detached, Ticker; a durable queue with [db]
|
|
7
11
|
http_server a real scripted HTTP server on loopback for tests of outbound requests
|
|
8
12
|
live run a FastAPI app on a real loopback port for tests
|
|
9
13
|
testing the fakes for HTTP, subprocesses and sleep, and CLI runners, shared by every app's tests
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""A typed base for calling another strata service's HTTP API: standard library only, so it runs in any venv.
|
|
2
|
+
|
|
3
|
+
The models client, the 360 and models self-CLIs and the homepage probes each wrote the same urllib wrapper: build a
|
|
4
|
+
JSON request, map a refusal to one error and an outage to another, poll until a row finishes. This is that once.
|
|
5
|
+
|
|
6
|
+
MODELS = ServiceClient(env_url("STRATA_MODELS_URL", "http://127.0.0.1:8366"), app="strata-scan")
|
|
7
|
+
MODELS.get("/api/registry") # parsed JSON
|
|
8
|
+
MODELS.post("/api/jobs", {"role": "ocr", ...})
|
|
9
|
+
MODELS.wait(f"/api/jobs/{jid}", lambda row: row["status"] in FINISHED, timeout=600) # long-polls with ?wait=
|
|
10
|
+
MODELS.available() # GET /api/health answered ok
|
|
11
|
+
|
|
12
|
+
Errors: `Rejected` when the service answered 4xx (it understood and said no: `.status`, `.detail`, `.payload`, the
|
|
13
|
+
`ErrorBody` shape), `Unavailable` when it could not be asked or answered 5xx. Reads (GET, PUT, DELETE, HEAD: the
|
|
14
|
+
idempotent methods) are retried `retries` times on `Unavailable`, with a doubling pause; a POST is not, since a
|
|
15
|
+
retried POST can do the work twice.
|
|
16
|
+
|
|
17
|
+
The URL is read on every call, so `env_url` picks up a changed environment variable (a test's stand-in service) and
|
|
18
|
+
no URL is fixed at import. `app` is sent as `X-Strata-App` and in the User-Agent, so the service can say who asked."""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import time
|
|
25
|
+
import urllib.error
|
|
26
|
+
import urllib.parse
|
|
27
|
+
import urllib.request
|
|
28
|
+
from collections.abc import Callable, Mapping
|
|
29
|
+
from typing import Any, cast
|
|
30
|
+
|
|
31
|
+
Json = dict[str, Any]
|
|
32
|
+
IDEMPOTENT = frozenset({"GET", "HEAD", "PUT", "DELETE"})
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Unavailable(RuntimeError):
|
|
36
|
+
"""The service could not be asked (not running, not reachable) or failed while answering (5xx)."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Rejected(RuntimeError):
|
|
40
|
+
"""The service answered 4xx: the request was understood and refused. `.detail` is its reason, `.payload` what it
|
|
41
|
+
sent with it (an `ErrorBody` payload, or the whole body when it was not one)."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, status: int, detail: str, payload: Any = None) -> None:
|
|
44
|
+
super().__init__(detail)
|
|
45
|
+
self.status = status
|
|
46
|
+
self.detail = detail
|
|
47
|
+
self.payload = payload
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def env_url(var: str, default: str) -> Callable[[], str]:
|
|
51
|
+
"""The service URL from environment variable `var`, read on each call, else `default`."""
|
|
52
|
+
return lambda: os.environ.get(var) or default
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ServiceClient:
|
|
56
|
+
def __init__(
|
|
57
|
+
self,
|
|
58
|
+
base_url: str | Callable[[], str],
|
|
59
|
+
*,
|
|
60
|
+
app: str | None = None,
|
|
61
|
+
timeout: float = 30,
|
|
62
|
+
retries: int = 2,
|
|
63
|
+
backoff_s: float = 0.5,
|
|
64
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
65
|
+
) -> None:
|
|
66
|
+
self._base = base_url
|
|
67
|
+
self.app = app
|
|
68
|
+
self.timeout = timeout
|
|
69
|
+
self.retries = retries
|
|
70
|
+
self.backoff_s = backoff_s
|
|
71
|
+
self._sleep = sleep
|
|
72
|
+
|
|
73
|
+
def url(self) -> str:
|
|
74
|
+
b = self._base
|
|
75
|
+
return (b if isinstance(b, str) else b()).rstrip("/")
|
|
76
|
+
|
|
77
|
+
def call(
|
|
78
|
+
self,
|
|
79
|
+
method: str,
|
|
80
|
+
path: str,
|
|
81
|
+
body: object = None,
|
|
82
|
+
*,
|
|
83
|
+
params: Mapping[str, object] | None = None,
|
|
84
|
+
timeout: float | None = None,
|
|
85
|
+
) -> Any:
|
|
86
|
+
"""Send one request and return the parsed JSON answer (None for an empty body)."""
|
|
87
|
+
method = method.upper()
|
|
88
|
+
attempts = 1 + (self.retries if method in IDEMPOTENT else 0)
|
|
89
|
+
for attempt in range(attempts):
|
|
90
|
+
try:
|
|
91
|
+
return self._once(method, path, body, params, self.timeout if timeout is None else timeout)
|
|
92
|
+
except Unavailable:
|
|
93
|
+
if attempt == attempts - 1:
|
|
94
|
+
raise
|
|
95
|
+
self._sleep(self.backoff_s * 2**attempt)
|
|
96
|
+
raise AssertionError("unreachable") # pragma: no cover - the loop returns or raises
|
|
97
|
+
|
|
98
|
+
def _once(self, method: str, path: str, body: object, params: Mapping[str, object] | None, timeout: float) -> Any:
|
|
99
|
+
url = self.url() + path
|
|
100
|
+
if params:
|
|
101
|
+
url += ("&" if "?" in url else "?") + urllib.parse.urlencode({k: str(v) for k, v in params.items()})
|
|
102
|
+
data = None if body is None else json.dumps(body).encode()
|
|
103
|
+
headers = {"Accept": "application/json"}
|
|
104
|
+
if data is not None:
|
|
105
|
+
headers["Content-Type"] = "application/json"
|
|
106
|
+
if self.app:
|
|
107
|
+
headers["X-Strata-App"] = self.app
|
|
108
|
+
headers["User-Agent"] = f"{self.app} (strata-python)"
|
|
109
|
+
req = urllib.request.Request(url, data=data, method=method, headers=headers) # noqa: S310 - the service's own URL
|
|
110
|
+
try:
|
|
111
|
+
with urllib.request.urlopen(req, timeout=timeout) as r: # noqa: S310
|
|
112
|
+
raw = r.read()
|
|
113
|
+
except urllib.error.HTTPError as e:
|
|
114
|
+
answer = _parse(e.read())
|
|
115
|
+
detail, payload = _reason(answer, e)
|
|
116
|
+
if 400 <= e.code < 500:
|
|
117
|
+
raise Rejected(e.code, detail, payload) from None
|
|
118
|
+
raise Unavailable(f"{self.url()} answered {e.code}: {detail}") from None
|
|
119
|
+
except (urllib.error.URLError, OSError) as e:
|
|
120
|
+
raise Unavailable(f"{self.url()} is not reachable: {getattr(e, 'reason', e)}") from None
|
|
121
|
+
return _parse(raw) if raw else None
|
|
122
|
+
|
|
123
|
+
def get(self, path: str, **kw: Any) -> Any:
|
|
124
|
+
return self.call("GET", path, **kw)
|
|
125
|
+
|
|
126
|
+
def post(self, path: str, body: object = None, **kw: Any) -> Any:
|
|
127
|
+
return self.call("POST", path, body, **kw)
|
|
128
|
+
|
|
129
|
+
def put(self, path: str, body: object = None, **kw: Any) -> Any:
|
|
130
|
+
return self.call("PUT", path, body, **kw)
|
|
131
|
+
|
|
132
|
+
def delete(self, path: str, **kw: Any) -> Any:
|
|
133
|
+
return self.call("DELETE", path, **kw)
|
|
134
|
+
|
|
135
|
+
def health(self, timeout: float = 2.0) -> Json:
|
|
136
|
+
"""`GET /api/health`, once (no retries: a probe wants the answer now)."""
|
|
137
|
+
return cast("Json", self._once("GET", "/api/health", None, None, timeout) or {})
|
|
138
|
+
|
|
139
|
+
def available(self, timeout: float = 2.0) -> bool:
|
|
140
|
+
"""Is the service up and saying it is ok?"""
|
|
141
|
+
try:
|
|
142
|
+
return bool(self.health(timeout).get("ok"))
|
|
143
|
+
except (Unavailable, Rejected):
|
|
144
|
+
return False
|
|
145
|
+
|
|
146
|
+
def wait(
|
|
147
|
+
self,
|
|
148
|
+
path: str,
|
|
149
|
+
done: Callable[[Json], bool],
|
|
150
|
+
*,
|
|
151
|
+
timeout: float | None = None,
|
|
152
|
+
poll_s: float = 30,
|
|
153
|
+
clock: Callable[[], float] = time.monotonic,
|
|
154
|
+
) -> Json:
|
|
155
|
+
"""Long-poll `path?wait=<s>` until `done(row)`; TimeoutError (with the last row's state) after `timeout`.
|
|
156
|
+
The service holds each request up to `wait` seconds and answers early when the row changes, so this costs one
|
|
157
|
+
request per change, not one per second."""
|
|
158
|
+
end = None if timeout is None else clock() + timeout
|
|
159
|
+
while True:
|
|
160
|
+
step = poll_s if end is None else max(min(poll_s, end - clock()), 0)
|
|
161
|
+
row = cast("Json", self.get(path, params={"wait": f"{step:.1f}"}, timeout=step + 15))
|
|
162
|
+
if done(row):
|
|
163
|
+
return row
|
|
164
|
+
if end is not None and clock() >= end:
|
|
165
|
+
raise TimeoutError(
|
|
166
|
+
f"{path} did not finish in {timeout} s (last: {row.get('status') or row.get('state')})"
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _parse(raw: bytes) -> Any:
|
|
171
|
+
try:
|
|
172
|
+
return json.loads(raw)
|
|
173
|
+
except ValueError:
|
|
174
|
+
return raw.decode(errors="replace").strip() or None
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _reason(answer: Any, e: urllib.error.HTTPError) -> tuple[str, Any]:
|
|
178
|
+
"""The reason and payload in an error answer: `ErrorBody` ({detail, payload}), FastAPI's {detail}, or plain text."""
|
|
179
|
+
if isinstance(answer, dict):
|
|
180
|
+
d = cast("Json", answer)
|
|
181
|
+
detail = d.get("detail")
|
|
182
|
+
text = detail if isinstance(detail, str) else json.dumps(detail) if detail is not None else str(e.reason)
|
|
183
|
+
return text, d.get("payload", d if set(d) - {"detail"} else None)
|
|
184
|
+
return (answer if isinstance(answer, str) and answer else str(e.reason)), None
|
|
@@ -38,14 +38,17 @@ from collections.abc import Generator, Mapping, Sequence
|
|
|
38
38
|
from dataclasses import dataclass, field
|
|
39
39
|
from typing import Any, Literal, cast
|
|
40
40
|
|
|
41
|
+
from strata_python import client
|
|
42
|
+
|
|
41
43
|
Json = dict[str, Any]
|
|
42
44
|
Priority = Literal["high", "normal", "low"]
|
|
43
45
|
POLL_S = 30 # one long-poll request waits this long at most
|
|
44
46
|
DEFAULT_URL = "http://127.0.0.1:8366"
|
|
45
47
|
|
|
46
48
|
|
|
47
|
-
class Unavailable(
|
|
48
|
-
"""The service is not running (or not reachable).
|
|
49
|
+
class Unavailable(client.Unavailable):
|
|
50
|
+
"""The service is not running (or not reachable). A `strata_python.client.Unavailable`, so an app's
|
|
51
|
+
`web.add_error_handlers` answers it as 503 like any other service outage."""
|
|
49
52
|
|
|
50
53
|
|
|
51
54
|
class JobFailed(RuntimeError):
|