strata-python 0.2.4__tar.gz → 0.2.6__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.4 → strata_python-0.2.6}/CHANGELOG.md +30 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/PKG-INFO +84 -21
- {strata_python-0.2.4 → strata_python-0.2.6}/README.md +81 -20
- {strata_python-0.2.4 → strata_python-0.2.6}/pyproject.toml +6 -2
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/cli.py +45 -2
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/contracts.py +9 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/db/__init__.py +7 -1
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/db/cli.py +23 -9
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/db/config.py +28 -4
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/db/engine.py +4 -0
- strata_python-0.2.6/src/strata_python/db/project.py +149 -0
- strata_python-0.2.6/src/strata_python/db/web.py +103 -0
- strata_python-0.2.6/src/strata_python/files.py +247 -0
- strata_python-0.2.6/src/strata_python/http.py +326 -0
- strata_python-0.2.6/src/strata_python/images.py +107 -0
- strata_python-0.2.6/src/strata_python/media.py +323 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/public_check.py +122 -19
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/settings.py +99 -25
- strata_python-0.2.6/src/strata_python/stats.py +196 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/tasks/__init__.py +2 -1
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/tasks/status.py +1 -16
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/testing.py +13 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/web.py +10 -1
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/unit/test_cli.py +65 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/unit/test_contracts.py +14 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/unit/test_db.py +151 -0
- strata_python-0.2.6/tests/unit/test_files.py +259 -0
- strata_python-0.2.6/tests/unit/test_http.py +333 -0
- strata_python-0.2.6/tests/unit/test_images.py +132 -0
- strata_python-0.2.6/tests/unit/test_media.py +165 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/unit/test_public_check.py +83 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/unit/test_settings.py +24 -0
- strata_python-0.2.6/tests/unit/test_stats.py +116 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/unit/test_web.py +40 -0
- strata_python-0.2.4/src/strata_python/db/project.py +0 -98
- {strata_python-0.2.4 → strata_python-0.2.6}/.gitignore +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/LICENSE +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/__init__.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/check.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/client.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/clients/__init__.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/clients/models.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/db/__main__.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/db/_alembic/env.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/db/_alembic/script.py.mako +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/db/guard.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/db/migrations.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/db/models.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/db/pytest_plugin.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/db/scratch.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/db/settings.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/db/testing.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/db/testserver.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/http_server.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/live.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/oslib.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/pages/__init__.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/pages/model.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/pages/render.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/py.typed +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/pytest_plugin.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/tasks/child.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/tasks/flight.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/tasks/progress.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/tasks/queue.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/tasks/retry.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/src/strata_python/tasks/ticker.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/conftest.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/integration/test_db_cli.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/integration/test_serve.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/integration/test_strata_check.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/unit/job_handlers.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/unit/test_check.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/unit/test_client.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/unit/test_clients_models.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/unit/test_http_server.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/unit/test_live.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/unit/test_oslib.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/unit/test_package.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/unit/test_pages.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/unit/test_plugin.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/unit/test_queue.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/unit/test_tasks.py +0 -0
- {strata_python-0.2.4 → strata_python-0.2.6}/tests/unit/test_testing.py +0 -0
|
@@ -4,6 +4,36 @@ 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.6 (2026-11-23)
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- `strata-public-check` reads web source (`.ts`, `.tsx`, `.mts`, `.cts`, `.js`, `.jsx`, `.mjs`, `.cjs`, `.mdx`, `.css`, `.html`, `.svg`, `.vue`, `.env.example`) and skips `storybook-static/` and `baselines/` (#37). Remove the app's own privacy scan of its front end.
|
|
12
|
+
- `[tool.strata-public-check] deny = ["\\bdate of birth\\b", {pattern = "...", kind = "age"}]`: case-insensitive patterns committed in the repo, reported under their kind with the match shown, skipped by an exclude and by `strata-public-check: ignore` like the built-in ones (#38). A bad entry exits 2.
|
|
13
|
+
- `cli.add_openapi(sub, create_app)`: `myapp openapi [-o PATH|-] [--check]` writes `web/openapi.json` for strata-react's `strata-api-types`, via `web.openapi_text(app)` (sorted keys, indent 1, final newline); `testing.assert_openapi_current(create_app, path)` is the unit test; `contracts.ApiModel` keeps defaulted response fields required in the schema (#36).
|
|
14
|
+
- `Setting(..., choices=[...])` and the `one_of(choices)` normaliser: case-insensitive, stored as the choice is spelled, refused with the list; `set` shows the choices and `/api/openapi.json` types the setting as an `enum`. `Settings(..., numbers=True)` sends `whole_between`/`number_between` settings as JSON numbers with `minimum`/`maximum` in the schema (off by default). `PUT /api/settings` takes numbers. `Settings.allowed(key)` (#41).
|
|
15
|
+
- `strata_python.db`: a `strata-db.toml` inside the package (`strata-db init --package src/myapp`, with `[tool.strata-db] file = ...` pointing at it) so `Project.load(__file__)` works from an installed wheel (#40); `local_url(SETTINGS)` and `url_for(app, default=...)` for a SQLite fallback when nothing is configured; `Project.open(url=None, default=...)` connects and migrates; `connect` makes a SQLite file's folder (#39).
|
|
16
|
+
- `strata_python.db.web`: `add_database(app, project, default=...)` opens and migrates the engine on the first request that needs it and disposes it when the server stops; `DbSession` is the per-request session dependency (#39).
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
|
|
20
|
+
- `strata-public-check` on a folder inside a git checkout reads only the files git would commit (`git ls-files -co --exclude-standard`), so ignored tool output such as `.coverage` is not scanned; a folder git ignores (`dist`) is still read in full when named. A file with no suffix that holds a NUL byte is skipped as binary (#37).
|
|
21
|
+
- `whole_between` and `number_between` are now small callable classes with `lo`/`hi` (they used to be closures); calling them is unchanged.
|
|
22
|
+
|
|
23
|
+
## 0.2.5 (2026-11-23)
|
|
24
|
+
|
|
25
|
+
### Added
|
|
26
|
+
|
|
27
|
+
- `strata_python.files`: `atomic_path(path)` (a temp path beside the file, keeping its extension so ffmpeg can write to it, replaced on success and removed on error), `atomic_open`, `write_text_atomic`, `write_bytes_atomic`, `write_json_atomic(path, data, indent=1)`, `read_json(path, default)` (missing or broken file: the default), `sha256`/`sha256_hex`, `quick_fingerprint` (size and both ends of a big file), `stat_key(path, *extra)`, `inside(root, path)` (a path from a request, refused with `ValueError` if it leaves the root) and `DiskCache` (bytes or `json(key, fetch, max_age_s)` on disk with an age). Replace the app's `tmp` + `os.replace` writes, its sha256 helpers and its response caches.
|
|
28
|
+
- `strata_python.http.Http(user_agent, ...)`: the polite client for public web APIs. A gap per host across threads (`min_interval`) and processes (`throttle_file`), 429 and 503 waiting for Retry-After (seconds or a date, capped at `max_wait`), a `cool_down` for a host still saying 429, retries of 5xx and network errors only for idempotent requests (`idempotent=True` for a read sent as POST), `max_bytes`, `https_only`, an optional `DiskCache` (`cache_s=`; 200 and 404 kept), and `observe(reply, attempt)`. Errors come back as a `Reply` (`ok`, `status` 0 when unreachable, `error`, `limited`, `cached`, `json()`, `text()`); `raise_for_status()` and `get_json()` raise `HttpError`. Replace the app's own throttle, Retry-After and cache code.
|
|
29
|
+
- `strata_python.media`: `probe(path)` returns a `Probe` (duration, format, size, bit rate, tags, `streams` as `Stream`, `chapters`, `video`/`audio`, ffprobe's `warnings`, `raw`); `duration(path)`; `ffmpeg(args, input=, timeout=, progress=)` with `-nostdin -hide_banner -v error -y`, raising `MediaError` with the tail of ffmpeg's stderr; `tool(name)` honours `STRATA_FFMPEG` and `STRATA_FFPROBE`; `available()`. Replace the app's ffprobe and ffmpeg wrappers.
|
|
30
|
+
- `strata_python.images` and the `[images]` extra (Pillow): `thumbnail(src, px, cache_dir=, quality=, version=, make=)` returns the path of a cached upright JPEG (keyed on the file, the size, the quality and `version`; never enlarged; one maker per file at a time and `slots` at once); `open_upright`, `flatten`, `jpeg_bytes`. Replace the app's thumbnail cache.
|
|
31
|
+
- `strata_python.stats`: `bradley_terry(votes, side=)` (a `Fit` with `strengths`, the side advantage, `ratings()` on the Elo scale and `p_beats`), `intervals` (bootstrap over votes), `head_to_head`, `votes_from(judgments)`, `wilson`, `mcnemar`, `holm`. Pure Python. Replace the arena's and the evals' copies.
|
|
32
|
+
|
|
33
|
+
### Changed
|
|
34
|
+
|
|
35
|
+
- `tasks.write_json_atomic` is now `files.write_json_atomic` (the same import still works). It also fsyncs before the replace, writes non-ASCII characters as they are instead of `\u` escapes, and takes `indent=`.
|
|
36
|
+
|
|
7
37
|
## 0.2.4 (2026-11-23)
|
|
8
38
|
|
|
9
39
|
### Fixed
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: strata-python
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.6
|
|
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
|
|
@@ -37,6 +37,8 @@ Requires-Dist: pytest-timeout<3,>=2; extra == 'dev'
|
|
|
37
37
|
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
|
+
Provides-Extra: images
|
|
41
|
+
Requires-Dist: pillow<14,>=13; extra == 'images'
|
|
40
42
|
Provides-Extra: pdf
|
|
41
43
|
Requires-Dist: pillow<14,>=13; extra == 'pdf'
|
|
42
44
|
Requires-Dist: pypdfium2<6,>=4.30; extra == 'pdf'
|
|
@@ -51,19 +53,24 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
|
|
|
51
53
|
|---|---|
|
|
52
54
|
| `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
55
|
| `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 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
|
-
| `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` |
|
|
56
|
+
| `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`, `openapi_text` (the schema as stable text) |
|
|
57
|
+
| `strata_python.cli` | `add_doctor` (imports, labels, optional modules and the app's own `Check`s), `add_set`, `add_serve`, `add_openapi` (the schema file for strata-react's `strata-api-types`) for the app's argparse subcommands |
|
|
58
|
+
| `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`; `ApiModel`, a base for the app's own responses whose defaulted fields stay required in the schema |
|
|
57
59
|
| `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
60
|
| `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) |
|
|
61
|
+
| `strata_python.files` | Atomic writes (`atomic_path` keeps the extension for ffmpeg, `atomic_open`, `write_json_atomic`, `write_text_atomic`, `write_bytes_atomic`), `read_json(path, default)`, `sha256`/`sha256_hex`, `quick_fingerprint` (size and both ends), `stat_key` (a cache key that follows the file), `inside(root, path)` (refuses `..` and links out), and `DiskCache` (values on disk with an age; `json(key, fetch, max_age_s)`) |
|
|
62
|
+
| `strata_python.http` | `Http(user_agent, min_interval=...)`, the polite client for other people's APIs: a gap per host across threads (and processes with `throttle_file`), Retry-After as seconds or a date, a cool-down for a host that keeps saying 429, retries that never replay a write, a size cap, an optional `DiskCache`, and errors returned as a `Reply` (`raise_for_status()`, `get_json()` for code that wants exceptions) |
|
|
63
|
+
| `strata_python.media` | `probe(path)` (a typed `Probe`: duration, format, tags, streams, chapters, ffprobe's warnings), `duration`, `ffmpeg(args, progress=...)` raising `MediaError` with ffmpeg's own reason, `available()` |
|
|
64
|
+
| `strata_python.images` (extra `[images]`) | `thumbnail(src, px, cache_dir=...)` (an upright JPEG, made once, keyed on the file, never enlarged, the app's own reader through `make=`), `open_upright`, `flatten` (alpha and 16-bit greys to 8-bit RGB), `jpeg_bytes` |
|
|
65
|
+
| `strata_python.stats` | Pairwise rankings and eval statistics in pure Python: `bradley_terry` (ties, an optional side advantage, Elo-scale `ratings()`), `intervals` (bootstrap), `head_to_head`, `votes_from(judgments)`, `wilson`, `mcnemar`, `holm` |
|
|
59
66
|
| `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 |
|
|
60
67
|
| `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
|
|
61
68
|
| 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`,
|
|
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,
|
|
69
|
+
| `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) `FakeModels`, the CLI runners `run_cli(main, *args)` and `run_module("myapp", *args, src=...)`, and `assert_openapi_current(create_app, path)` |
|
|
70
|
+
| `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, the `db_*` fixtures (SQLite by default, a throwaway Postgres with `--pg`), and `strata_python.db.web` (`add_database`, `DbSession`) for a server's records |
|
|
64
71
|
| `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 |
|
|
65
72
|
| `strata-check` | The one gate: lockfile, ruff, `ruff format`, pyright strict, ty, unit tests with coverage |
|
|
66
|
-
| `strata-public-check` | Fails on email addresses, private IPv4 addresses, home-folder paths and the
|
|
73
|
+
| `strata-public-check` | Fails on email addresses, private IPv4 addresses, home-folder paths, the repo's own `[tool.strata-public-check] deny` regexes and the owner's `STRATA_PUBLIC_DENY` ones in a tree, sdist or wheel; run before anything public is published. Reads Python, web source (`.ts`, `.tsx`, `.js`, `.css`, `.html`, `.mdx`, `.svg`...) and config text; in a git checkout only what git would commit, so tool output such as `.coverage` is skipped. Silence a false positive with `[tool.strata-public-check] exclude = ["web/package-lock.json"]` (or `--exclude`), or `strata-public-check: ignore` on the line (never applies to `STRATA_PUBLIC_DENY`) |
|
|
67
74
|
|
|
68
75
|
## Move an app onto it
|
|
69
76
|
|
|
@@ -128,6 +135,7 @@ SETTINGS = Settings(
|
|
|
128
135
|
Setting("data_dir", default=lambda: "/srv/myapp", normalise=absolute_path),
|
|
129
136
|
Setting("greeting", default="Hello", normalise=non_empty),
|
|
130
137
|
Setting("workers", default="2", normalise=whole_between(1, 16)),
|
|
138
|
+
Setting("mode", default="mixed", choices=["mixed", "review", "new"]), # an enum in the API schema
|
|
131
139
|
ListSetting("source_roots", item=absolute_path, env="MYAPP_SOURCES"), # MYAPP_SOURCES split on os.pathsep
|
|
132
140
|
],
|
|
133
141
|
prefix="MYAPP", # only if the app already runs with other variable names
|
|
@@ -140,13 +148,15 @@ SETTINGS.folder("data_dir") # the value as a folder, created if missing
|
|
|
140
148
|
|
|
141
149
|
Values are canonical strings, and lists of them. Normalisers for the common kinds give one spelling each: `number_between(lo, hi)`, `whole_between(lo, hi)`, `iso_date(allow_blank=True)` and `boolean`, read back with `get_float`, `get_int` and `get_bool`. A `ListSetting` is a JSON list in the file (a string there is split, so a hand edit works), split on `sep` in the environment (`os.pathsep` by default, `sep=","` for names), with `item` normalising each entry. `get_list` returns it, and `all()` and `GET /api/settings` return it as JSON. `get` and `set` show it joined, and `save` takes a list or a joined string.
|
|
142
150
|
|
|
151
|
+
A setting that takes one of a fixed set has `choices=[m.value for m in Mode]` (or `normalise=one_of(...)`): a value is matched without regard to case and stored as the choice is spelled, anything else is refused with the list, `set` shows the choices, and the schema in `/api/openapi.json` has an `enum`, so the web app's generated type needs no narrowing by hand. `Settings(..., numbers=True)` also sends `whole_between` and `number_between` settings as JSON numbers, with `minimum` and `maximum` in the schema; it changes what `GET /api/settings` sends, so turn it on with the web app's change. `PUT /api/settings` takes numbers either way.
|
|
152
|
+
|
|
143
153
|
To keep the values in the app's database instead of the file, add the table to the models and bind at service start, after the migrations. The file's values are copied in the first time, and the CLI and tests without a database keep using the file:
|
|
144
154
|
|
|
145
155
|
```python
|
|
146
156
|
from strata_python.db.settings import TableStore, settings_table
|
|
147
157
|
|
|
148
|
-
SETTINGS_TABLE = settings_table(Base.metadata)
|
|
149
|
-
SETTINGS.bind(TableStore(engine, SETTINGS_TABLE))
|
|
158
|
+
SETTINGS_TABLE = settings_table(Base.metadata) # in models.py, so the migrations create it
|
|
159
|
+
SETTINGS.bind(TableStore(engine, SETTINGS_TABLE)) # any object with load() and update(changes) is a store
|
|
150
160
|
```
|
|
151
161
|
|
|
152
162
|
### 4. The server
|
|
@@ -165,11 +175,15 @@ def create_app():
|
|
|
165
175
|
Two more that replace code most servers carry:
|
|
166
176
|
|
|
167
177
|
```python
|
|
168
|
-
web.add_error_handlers(app)
|
|
169
|
-
|
|
170
|
-
web.add_system(
|
|
171
|
-
|
|
172
|
-
|
|
178
|
+
web.add_error_handlers(app) # ValueError 400, PermissionError 403, KeyError and FileNotFoundError 404,
|
|
179
|
+
# tasks.Conflict 409, client.Rejected 502, client.Unavailable 503: {detail, payload}
|
|
180
|
+
web.add_system(
|
|
181
|
+
app,
|
|
182
|
+
__version__,
|
|
183
|
+
commit=web.source_commit(__file__),
|
|
184
|
+
folders={"data": lambda: SETTINGS.get("data_dir")},
|
|
185
|
+
services={"strata-models": "http://127.0.0.1:8366"},
|
|
186
|
+
) # GET /api/system, a SystemInfo
|
|
173
187
|
```
|
|
174
188
|
|
|
175
189
|
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`.
|
|
@@ -197,6 +211,8 @@ def main(argv=None):
|
|
|
197
211
|
return args.fn(args)
|
|
198
212
|
```
|
|
199
213
|
|
|
214
|
+
An app with a web front end on strata-react adds `cli.add_openapi(sub, create_app)`: `myapp openapi` writes `web/openapi.json` (or `-o PATH`, `-o -` for stdout) for `strata-api-types`, in a stable form (sorted keys, indent 1, a final newline, nothing from the machine), and `myapp openapi --check` exits 1 when the committed file is out of date. Its unit test is `strata_python.testing.assert_openapi_current(create_app, "web/openapi.json")`. Build response models on `contracts.ApiModel` so a field with a default is not optional (`?`) in the generated types.
|
|
215
|
+
|
|
200
216
|
Delete the hand-written `doctor`, `set` and `serve` subparsers. Each app's port belongs in its deploy units, not in this library.
|
|
201
217
|
|
|
202
218
|
A doctor that needs more than imports takes labels, optional modules, checks and its own hint, and prints every app's rows in the same columns:
|
|
@@ -219,9 +235,9 @@ A check returns `(status, text)` with status `ok`, `missing`, `slow` (works, but
|
|
|
219
235
|
Drop the `strata-models-client` path or git dependency and change the import. The functions, their arguments and the exceptions are the same:
|
|
220
236
|
|
|
221
237
|
```python
|
|
222
|
-
from strata_python.clients import models as sm
|
|
238
|
+
from strata_python.clients import models as sm # was: import strata_models_client as sm
|
|
223
239
|
|
|
224
|
-
page = sm.OcrPage.from_json(sm.ocr("/path/page.png", app="strata-scan"))
|
|
240
|
+
page = sm.OcrPage.from_json(sm.ocr("/path/page.png", app="strata-scan")) # typed: page.lines[0].words[0].box
|
|
225
241
|
talk = sm.Transcript.from_json(sm.transcribe("/path/talk.wav", app="strata-360"))
|
|
226
242
|
with sm.gpu_lease("strata-stills", vram_gb=4):
|
|
227
243
|
run_my_own_cuda_code()
|
|
@@ -246,15 +262,48 @@ Replace the app's job dicts and loops with `strata_python.tasks`:
|
|
|
246
262
|
```python
|
|
247
263
|
from strata_python.tasks.queue import Job, Queue, Worker
|
|
248
264
|
|
|
249
|
-
QUEUE = Queue(engine, JOBS, on_fail=cascade)
|
|
265
|
+
QUEUE = Queue(engine, JOBS, on_fail=cascade) # on_fail(conn, job, error), in the failing transaction
|
|
250
266
|
QUEUE.enqueue("ocr", {"page": 3}, domain="book:12", dedupe=True, resources=["gpu"], timeout_s=600)
|
|
251
|
-
WORKER = Worker(
|
|
252
|
-
QUEUE
|
|
253
|
-
|
|
267
|
+
WORKER = Worker(
|
|
268
|
+
QUEUE, {"ocr": ocr_page}, concurrency=2
|
|
269
|
+
).start() # a job process per thread, reused; recovers dead workers' jobs
|
|
270
|
+
QUEUE.page(state="running", after=cursor) # Page[Task] for GET /api/jobs
|
|
271
|
+
QUEUE.cancel(job_id)
|
|
272
|
+
QUEUE.retry(job_id)
|
|
273
|
+
QUEUE.prune(older_than_s=30 * 86400)
|
|
254
274
|
```
|
|
255
275
|
|
|
256
276
|
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.
|
|
257
277
|
|
|
278
|
+
### 6c. Files, web APIs, media, pictures and rankings
|
|
279
|
+
|
|
280
|
+
Each of these replaces code that two to six apps wrote for themselves; move to it when you next touch that code.
|
|
281
|
+
|
|
282
|
+
- **Writes.** Every `tmp = path + ".tmp"; ...; os.replace(tmp, path)` becomes `write_json_atomic(path, data)` (or `write_text_atomic`, `write_bytes_atomic`, `with atomic_open(path, "wb") as f:`). A tool that writes the file itself writes to `with atomic_path(out) as tmp:`; the temp name keeps the extension, so `ffmpeg ... tmp` still picks the format. Reads that tolerate a missing or broken file are `read_json(path, default)`. Delete the app's `_save`, `write_status` and `.part` helpers.
|
|
283
|
+
- **Hashes and keys.** `sha256(path)` (bytes, for a `LargeBinary` column) and `sha256_hex(path)` replace listory's two copies, filecat's and stills' scripts'. `quick_fingerprint(path)` is 360's `clips.fingerprint` idea on SHA-256 (an app that stored the old 12-character SHA-1 keeps its own until it re-keys). A cache that must follow a file's changes keys on `stat_key(path, px, version)`.
|
|
284
|
+
- **Paths from a request.** `files.inside(root, name)` before opening a file a request names; it raises `ValueError` (400 with `add_error_handlers`) for `..`, an absolute path elsewhere, or a link out of the root.
|
|
285
|
+
- **Other people's APIs.** One `Http` per service, at module level so its gap is shared:
|
|
286
|
+
|
|
287
|
+
```python
|
|
288
|
+
from strata_python.files import DiskCache
|
|
289
|
+
from strata_python.http import Http
|
|
290
|
+
|
|
291
|
+
NOMINATIM = Http(
|
|
292
|
+
"myapp/1.0 (reverse geocoding of my own tracks)",
|
|
293
|
+
min_interval=1.1,
|
|
294
|
+
throttle_file=cache_dir / ".nominatim",
|
|
295
|
+
cache=DiskCache(cache_dir),
|
|
296
|
+
)
|
|
297
|
+
reply = NOMINATIM.get(URL, params={"lat": lat, "lon": lon, "format": "json"}, cache_s=30 * 86400)
|
|
298
|
+
if reply.ok:
|
|
299
|
+
place = reply.json() # reply.status == 0 when unreachable; reply.limited when rate limited
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
The User-Agent names the app and what it is for, never a person. Delete the app's `_throttle`, `_retry_after`, `_cool_until`, `_open`/`_get` wrappers and its response cache; listory's `providers.base.Http` keeps its own `emit` through `observe=`. A provider result worth keeping (not an HTTP body) is `DiskCache(...).json(key, fetch, max_age_s)`.
|
|
303
|
+
- **ffprobe and ffmpeg.** `media.probe(path)` replaces every hand-written `ffprobe -show_entries` call; read `info.duration`, `info.audio.sample_rate`, `info.video.fps`, `info.chapters`, `info.tags`, and `info.raw` for anything else. `media.ffmpeg(args)` adds `-nostdin -hide_banner -v error -y` and raises `MediaError` with ffmpeg's last lines; `progress=` reports seconds written. Map `MediaError` in `add_error_handlers` if the app answers it over HTTP. A doctor row is `cli.program("ffmpeg")`.
|
|
304
|
+
- **Thumbnails** (`strata-python[images]`): `images.thumbnail(src, px, cache_dir=settings.thumbs_dir())` returns the cached JPEG's path for a `FileResponse`. An app with its own reader (stills' raw previews, 360's video frames) passes `make=lambda path, px: ...` returning a Pillow image. Bump `version=` when the way a thumbnail is made changes.
|
|
305
|
+
- **Rankings and evals.** `stats.bradley_terry(votes, side=True)` with votes as `(a, b, "a" | "b" | "tie")` (or `stats.votes_from(judgments)`), `.ratings()` for the Elo scale, `stats.intervals(votes)` for how far to trust a gap; `wilson`, `mcnemar` and `holm` for eval write-ups. The numpy bootstraps over items in strata-models' evals stay there until a second app needs them.
|
|
306
|
+
|
|
258
307
|
### 7. Tests
|
|
259
308
|
|
|
260
309
|
The pytest plugin loads itself once strata-python is installed. Configure it in `pyproject.toml`:
|
|
@@ -344,7 +393,21 @@ migrations = "migrations" # the app's Alembic revisions, unchanged
|
|
|
344
393
|
```
|
|
345
394
|
- Environment: `STRATA_DB_LIVE=1` in the service unit (next to the old variable until every app has moved), and `STRATA_DB_DATABASE` naming the shared database. It has no built-in name any more, because that name is the owner's and this package is public; set it once where the services get their environment. `STRATA_DB_URL` and `<APP>_DATABASE_URL` work as before. Tests and CI: `STRATA_DB_TEST_ADMIN_URL`, `STRATA_DB_TEST=postgres`.
|
|
346
395
|
- Commands: `strata-db revision -m "..."`, `strata-db check`, `strata-db migrate --live`, `strata-db current --live`, `strata-db new-app`, `strata-db init` (or `python -m strata_python.db`).
|
|
347
|
-
- At service start (only there): `Project.load(__file__).upgrade(connect("myapp"))
|
|
396
|
+
- At service start (only there): `Project.load(__file__).upgrade(connect("myapp"))`, or `Project.load(__file__).open(default=local_url(SETTINGS))`, which connects and migrates, falling back to `<settings home>/myapp.db` when no database is configured (the folder is made).
|
|
397
|
+
- An app installed as a wheel (a service from `uv tool install`) has no pyproject.toml beside its code. `strata-db init --package src/myapp` declares the keys in `src/myapp/strata-db.toml` instead, with `migrations/` beside it, and puts `[tool.strata-db] file = "src/myapp/strata-db.toml"` in pyproject.toml. Both ship in the wheel, `Project.load(__file__)` finds the file by walking up from the module, and strata-db and the pytest plugin follow the pointer, so there is one declaration and no drift test. To move an existing app, move the keys and the `migrations` folder into the package and leave `file = ...` in the table.
|
|
398
|
+
- A FastAPI server's records:
|
|
399
|
+
|
|
400
|
+
```python
|
|
401
|
+
from strata_python.db import Project, local_url
|
|
402
|
+
from strata_python.db.web import DbSession, add_database
|
|
403
|
+
|
|
404
|
+
add_database(app, Project.load(__file__), default=lambda: local_url(SETTINGS))
|
|
405
|
+
|
|
406
|
+
@app.get("/api/notes")
|
|
407
|
+
def notes(db: DbSession) -> list[NoteOut]: ...
|
|
408
|
+
```
|
|
409
|
+
|
|
410
|
+
The engine is opened and migrated on the first request that needs one (a server nobody records on never creates a database), kept on `app.state` and disposed when the server stops, after the app's own lifespan. A failure to open is that request's error and is tried again on the next. Delete the app's `db.py` fallback, its session dependency and the conftest that disposed the engine.
|
|
348
411
|
- Tests: the plugin is registered with every install and does nothing until the extra is installed and the project has `[tool.strata-db]` (or `strata_db = true` in `[tool.pytest.ini_options]`; `strata_db = false` turns it off). So an app can take a 0.2.x release before it moves its database, even with the old database package still installed. Then `db_session`, `db_engine`, `db_url` (a URL for code that builds its own engine), `db_env` (points the app's own `connect("myapp")` at the test database; make it autouse in `conftest.py` for an app that connects by itself), `db_backend`, `db_project`. Migrations run once into a template and each test gets a copy, so a test costs a file copy. `pytest --pg` (or `--strata-pg`, which no other plugin can take) runs the same tests on a private Postgres the run starts for itself (needs the PostgreSQL server binaries), or on `STRATA_DB_TEST_ADMIN_URL`. Add the standard tests once:
|
|
349
412
|
|
|
350
413
|
```python
|
|
@@ -6,19 +6,24 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
|
|
|
6
6
|
|---|---|
|
|
7
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 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
|
-
| `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` |
|
|
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`, `openapi_text` (the schema as stable text) |
|
|
10
|
+
| `strata_python.cli` | `add_doctor` (imports, labels, optional modules and the app's own `Check`s), `add_set`, `add_serve`, `add_openapi` (the schema file for strata-react's `strata-api-types`) 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`; `ApiModel`, a base for the app's own responses whose defaulted fields stay required in the schema |
|
|
12
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
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) |
|
|
14
|
+
| `strata_python.files` | Atomic writes (`atomic_path` keeps the extension for ffmpeg, `atomic_open`, `write_json_atomic`, `write_text_atomic`, `write_bytes_atomic`), `read_json(path, default)`, `sha256`/`sha256_hex`, `quick_fingerprint` (size and both ends), `stat_key` (a cache key that follows the file), `inside(root, path)` (refuses `..` and links out), and `DiskCache` (values on disk with an age; `json(key, fetch, max_age_s)`) |
|
|
15
|
+
| `strata_python.http` | `Http(user_agent, min_interval=...)`, the polite client for other people's APIs: a gap per host across threads (and processes with `throttle_file`), Retry-After as seconds or a date, a cool-down for a host that keeps saying 429, retries that never replay a write, a size cap, an optional `DiskCache`, and errors returned as a `Reply` (`raise_for_status()`, `get_json()` for code that wants exceptions) |
|
|
16
|
+
| `strata_python.media` | `probe(path)` (a typed `Probe`: duration, format, tags, streams, chapters, ffprobe's warnings), `duration`, `ffmpeg(args, progress=...)` raising `MediaError` with ffmpeg's own reason, `available()` |
|
|
17
|
+
| `strata_python.images` (extra `[images]`) | `thumbnail(src, px, cache_dir=...)` (an upright JPEG, made once, keyed on the file, never enlarged, the app's own reader through `make=`), `open_upright`, `flatten` (alpha and 16-bit greys to 8-bit RGB), `jpeg_bytes` |
|
|
18
|
+
| `strata_python.stats` | Pairwise rankings and eval statistics in pure Python: `bradley_terry` (ties, an optional side advantage, Elo-scale `ratings()`), `intervals` (bootstrap), `head_to_head`, `votes_from(judgments)`, `wilson`, `mcnemar`, `holm` |
|
|
14
19
|
| `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 |
|
|
15
20
|
| `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
|
|
16
21
|
| 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`,
|
|
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,
|
|
22
|
+
| `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) `FakeModels`, the CLI runners `run_cli(main, *args)` and `run_module("myapp", *args, src=...)`, and `assert_openapi_current(create_app, path)` |
|
|
23
|
+
| `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, the `db_*` fixtures (SQLite by default, a throwaway Postgres with `--pg`), and `strata_python.db.web` (`add_database`, `DbSession`) for a server's records |
|
|
19
24
|
| `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 |
|
|
20
25
|
| `strata-check` | The one gate: lockfile, ruff, `ruff format`, pyright strict, ty, unit tests with coverage |
|
|
21
|
-
| `strata-public-check` | Fails on email addresses, private IPv4 addresses, home-folder paths and the
|
|
26
|
+
| `strata-public-check` | Fails on email addresses, private IPv4 addresses, home-folder paths, the repo's own `[tool.strata-public-check] deny` regexes and the owner's `STRATA_PUBLIC_DENY` ones in a tree, sdist or wheel; run before anything public is published. Reads Python, web source (`.ts`, `.tsx`, `.js`, `.css`, `.html`, `.mdx`, `.svg`...) and config text; in a git checkout only what git would commit, so tool output such as `.coverage` is skipped. Silence a false positive with `[tool.strata-public-check] exclude = ["web/package-lock.json"]` (or `--exclude`), or `strata-public-check: ignore` on the line (never applies to `STRATA_PUBLIC_DENY`) |
|
|
22
27
|
|
|
23
28
|
## Move an app onto it
|
|
24
29
|
|
|
@@ -83,6 +88,7 @@ SETTINGS = Settings(
|
|
|
83
88
|
Setting("data_dir", default=lambda: "/srv/myapp", normalise=absolute_path),
|
|
84
89
|
Setting("greeting", default="Hello", normalise=non_empty),
|
|
85
90
|
Setting("workers", default="2", normalise=whole_between(1, 16)),
|
|
91
|
+
Setting("mode", default="mixed", choices=["mixed", "review", "new"]), # an enum in the API schema
|
|
86
92
|
ListSetting("source_roots", item=absolute_path, env="MYAPP_SOURCES"), # MYAPP_SOURCES split on os.pathsep
|
|
87
93
|
],
|
|
88
94
|
prefix="MYAPP", # only if the app already runs with other variable names
|
|
@@ -95,13 +101,15 @@ SETTINGS.folder("data_dir") # the value as a folder, created if missing
|
|
|
95
101
|
|
|
96
102
|
Values are canonical strings, and lists of them. Normalisers for the common kinds give one spelling each: `number_between(lo, hi)`, `whole_between(lo, hi)`, `iso_date(allow_blank=True)` and `boolean`, read back with `get_float`, `get_int` and `get_bool`. A `ListSetting` is a JSON list in the file (a string there is split, so a hand edit works), split on `sep` in the environment (`os.pathsep` by default, `sep=","` for names), with `item` normalising each entry. `get_list` returns it, and `all()` and `GET /api/settings` return it as JSON. `get` and `set` show it joined, and `save` takes a list or a joined string.
|
|
97
103
|
|
|
104
|
+
A setting that takes one of a fixed set has `choices=[m.value for m in Mode]` (or `normalise=one_of(...)`): a value is matched without regard to case and stored as the choice is spelled, anything else is refused with the list, `set` shows the choices, and the schema in `/api/openapi.json` has an `enum`, so the web app's generated type needs no narrowing by hand. `Settings(..., numbers=True)` also sends `whole_between` and `number_between` settings as JSON numbers, with `minimum` and `maximum` in the schema; it changes what `GET /api/settings` sends, so turn it on with the web app's change. `PUT /api/settings` takes numbers either way.
|
|
105
|
+
|
|
98
106
|
To keep the values in the app's database instead of the file, add the table to the models and bind at service start, after the migrations. The file's values are copied in the first time, and the CLI and tests without a database keep using the file:
|
|
99
107
|
|
|
100
108
|
```python
|
|
101
109
|
from strata_python.db.settings import TableStore, settings_table
|
|
102
110
|
|
|
103
|
-
SETTINGS_TABLE = settings_table(Base.metadata)
|
|
104
|
-
SETTINGS.bind(TableStore(engine, SETTINGS_TABLE))
|
|
111
|
+
SETTINGS_TABLE = settings_table(Base.metadata) # in models.py, so the migrations create it
|
|
112
|
+
SETTINGS.bind(TableStore(engine, SETTINGS_TABLE)) # any object with load() and update(changes) is a store
|
|
105
113
|
```
|
|
106
114
|
|
|
107
115
|
### 4. The server
|
|
@@ -120,11 +128,15 @@ def create_app():
|
|
|
120
128
|
Two more that replace code most servers carry:
|
|
121
129
|
|
|
122
130
|
```python
|
|
123
|
-
web.add_error_handlers(app)
|
|
124
|
-
|
|
125
|
-
web.add_system(
|
|
126
|
-
|
|
127
|
-
|
|
131
|
+
web.add_error_handlers(app) # ValueError 400, PermissionError 403, KeyError and FileNotFoundError 404,
|
|
132
|
+
# tasks.Conflict 409, client.Rejected 502, client.Unavailable 503: {detail, payload}
|
|
133
|
+
web.add_system(
|
|
134
|
+
app,
|
|
135
|
+
__version__,
|
|
136
|
+
commit=web.source_commit(__file__),
|
|
137
|
+
folders={"data": lambda: SETTINGS.get("data_dir")},
|
|
138
|
+
services={"strata-models": "http://127.0.0.1:8366"},
|
|
139
|
+
) # GET /api/system, a SystemInfo
|
|
128
140
|
```
|
|
129
141
|
|
|
130
142
|
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`.
|
|
@@ -152,6 +164,8 @@ def main(argv=None):
|
|
|
152
164
|
return args.fn(args)
|
|
153
165
|
```
|
|
154
166
|
|
|
167
|
+
An app with a web front end on strata-react adds `cli.add_openapi(sub, create_app)`: `myapp openapi` writes `web/openapi.json` (or `-o PATH`, `-o -` for stdout) for `strata-api-types`, in a stable form (sorted keys, indent 1, a final newline, nothing from the machine), and `myapp openapi --check` exits 1 when the committed file is out of date. Its unit test is `strata_python.testing.assert_openapi_current(create_app, "web/openapi.json")`. Build response models on `contracts.ApiModel` so a field with a default is not optional (`?`) in the generated types.
|
|
168
|
+
|
|
155
169
|
Delete the hand-written `doctor`, `set` and `serve` subparsers. Each app's port belongs in its deploy units, not in this library.
|
|
156
170
|
|
|
157
171
|
A doctor that needs more than imports takes labels, optional modules, checks and its own hint, and prints every app's rows in the same columns:
|
|
@@ -174,9 +188,9 @@ A check returns `(status, text)` with status `ok`, `missing`, `slow` (works, but
|
|
|
174
188
|
Drop the `strata-models-client` path or git dependency and change the import. The functions, their arguments and the exceptions are the same:
|
|
175
189
|
|
|
176
190
|
```python
|
|
177
|
-
from strata_python.clients import models as sm
|
|
191
|
+
from strata_python.clients import models as sm # was: import strata_models_client as sm
|
|
178
192
|
|
|
179
|
-
page = sm.OcrPage.from_json(sm.ocr("/path/page.png", app="strata-scan"))
|
|
193
|
+
page = sm.OcrPage.from_json(sm.ocr("/path/page.png", app="strata-scan")) # typed: page.lines[0].words[0].box
|
|
180
194
|
talk = sm.Transcript.from_json(sm.transcribe("/path/talk.wav", app="strata-360"))
|
|
181
195
|
with sm.gpu_lease("strata-stills", vram_gb=4):
|
|
182
196
|
run_my_own_cuda_code()
|
|
@@ -201,15 +215,48 @@ Replace the app's job dicts and loops with `strata_python.tasks`:
|
|
|
201
215
|
```python
|
|
202
216
|
from strata_python.tasks.queue import Job, Queue, Worker
|
|
203
217
|
|
|
204
|
-
QUEUE = Queue(engine, JOBS, on_fail=cascade)
|
|
218
|
+
QUEUE = Queue(engine, JOBS, on_fail=cascade) # on_fail(conn, job, error), in the failing transaction
|
|
205
219
|
QUEUE.enqueue("ocr", {"page": 3}, domain="book:12", dedupe=True, resources=["gpu"], timeout_s=600)
|
|
206
|
-
WORKER = Worker(
|
|
207
|
-
QUEUE
|
|
208
|
-
|
|
220
|
+
WORKER = Worker(
|
|
221
|
+
QUEUE, {"ocr": ocr_page}, concurrency=2
|
|
222
|
+
).start() # a job process per thread, reused; recovers dead workers' jobs
|
|
223
|
+
QUEUE.page(state="running", after=cursor) # Page[Task] for GET /api/jobs
|
|
224
|
+
QUEUE.cancel(job_id)
|
|
225
|
+
QUEUE.retry(job_id)
|
|
226
|
+
QUEUE.prune(older_than_s=30 * 86400)
|
|
209
227
|
```
|
|
210
228
|
|
|
211
229
|
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.
|
|
212
230
|
|
|
231
|
+
### 6c. Files, web APIs, media, pictures and rankings
|
|
232
|
+
|
|
233
|
+
Each of these replaces code that two to six apps wrote for themselves; move to it when you next touch that code.
|
|
234
|
+
|
|
235
|
+
- **Writes.** Every `tmp = path + ".tmp"; ...; os.replace(tmp, path)` becomes `write_json_atomic(path, data)` (or `write_text_atomic`, `write_bytes_atomic`, `with atomic_open(path, "wb") as f:`). A tool that writes the file itself writes to `with atomic_path(out) as tmp:`; the temp name keeps the extension, so `ffmpeg ... tmp` still picks the format. Reads that tolerate a missing or broken file are `read_json(path, default)`. Delete the app's `_save`, `write_status` and `.part` helpers.
|
|
236
|
+
- **Hashes and keys.** `sha256(path)` (bytes, for a `LargeBinary` column) and `sha256_hex(path)` replace listory's two copies, filecat's and stills' scripts'. `quick_fingerprint(path)` is 360's `clips.fingerprint` idea on SHA-256 (an app that stored the old 12-character SHA-1 keeps its own until it re-keys). A cache that must follow a file's changes keys on `stat_key(path, px, version)`.
|
|
237
|
+
- **Paths from a request.** `files.inside(root, name)` before opening a file a request names; it raises `ValueError` (400 with `add_error_handlers`) for `..`, an absolute path elsewhere, or a link out of the root.
|
|
238
|
+
- **Other people's APIs.** One `Http` per service, at module level so its gap is shared:
|
|
239
|
+
|
|
240
|
+
```python
|
|
241
|
+
from strata_python.files import DiskCache
|
|
242
|
+
from strata_python.http import Http
|
|
243
|
+
|
|
244
|
+
NOMINATIM = Http(
|
|
245
|
+
"myapp/1.0 (reverse geocoding of my own tracks)",
|
|
246
|
+
min_interval=1.1,
|
|
247
|
+
throttle_file=cache_dir / ".nominatim",
|
|
248
|
+
cache=DiskCache(cache_dir),
|
|
249
|
+
)
|
|
250
|
+
reply = NOMINATIM.get(URL, params={"lat": lat, "lon": lon, "format": "json"}, cache_s=30 * 86400)
|
|
251
|
+
if reply.ok:
|
|
252
|
+
place = reply.json() # reply.status == 0 when unreachable; reply.limited when rate limited
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
The User-Agent names the app and what it is for, never a person. Delete the app's `_throttle`, `_retry_after`, `_cool_until`, `_open`/`_get` wrappers and its response cache; listory's `providers.base.Http` keeps its own `emit` through `observe=`. A provider result worth keeping (not an HTTP body) is `DiskCache(...).json(key, fetch, max_age_s)`.
|
|
256
|
+
- **ffprobe and ffmpeg.** `media.probe(path)` replaces every hand-written `ffprobe -show_entries` call; read `info.duration`, `info.audio.sample_rate`, `info.video.fps`, `info.chapters`, `info.tags`, and `info.raw` for anything else. `media.ffmpeg(args)` adds `-nostdin -hide_banner -v error -y` and raises `MediaError` with ffmpeg's last lines; `progress=` reports seconds written. Map `MediaError` in `add_error_handlers` if the app answers it over HTTP. A doctor row is `cli.program("ffmpeg")`.
|
|
257
|
+
- **Thumbnails** (`strata-python[images]`): `images.thumbnail(src, px, cache_dir=settings.thumbs_dir())` returns the cached JPEG's path for a `FileResponse`. An app with its own reader (stills' raw previews, 360's video frames) passes `make=lambda path, px: ...` returning a Pillow image. Bump `version=` when the way a thumbnail is made changes.
|
|
258
|
+
- **Rankings and evals.** `stats.bradley_terry(votes, side=True)` with votes as `(a, b, "a" | "b" | "tie")` (or `stats.votes_from(judgments)`), `.ratings()` for the Elo scale, `stats.intervals(votes)` for how far to trust a gap; `wilson`, `mcnemar` and `holm` for eval write-ups. The numpy bootstraps over items in strata-models' evals stay there until a second app needs them.
|
|
259
|
+
|
|
213
260
|
### 7. Tests
|
|
214
261
|
|
|
215
262
|
The pytest plugin loads itself once strata-python is installed. Configure it in `pyproject.toml`:
|
|
@@ -299,7 +346,21 @@ migrations = "migrations" # the app's Alembic revisions, unchanged
|
|
|
299
346
|
```
|
|
300
347
|
- Environment: `STRATA_DB_LIVE=1` in the service unit (next to the old variable until every app has moved), and `STRATA_DB_DATABASE` naming the shared database. It has no built-in name any more, because that name is the owner's and this package is public; set it once where the services get their environment. `STRATA_DB_URL` and `<APP>_DATABASE_URL` work as before. Tests and CI: `STRATA_DB_TEST_ADMIN_URL`, `STRATA_DB_TEST=postgres`.
|
|
301
348
|
- Commands: `strata-db revision -m "..."`, `strata-db check`, `strata-db migrate --live`, `strata-db current --live`, `strata-db new-app`, `strata-db init` (or `python -m strata_python.db`).
|
|
302
|
-
- At service start (only there): `Project.load(__file__).upgrade(connect("myapp"))
|
|
349
|
+
- At service start (only there): `Project.load(__file__).upgrade(connect("myapp"))`, or `Project.load(__file__).open(default=local_url(SETTINGS))`, which connects and migrates, falling back to `<settings home>/myapp.db` when no database is configured (the folder is made).
|
|
350
|
+
- An app installed as a wheel (a service from `uv tool install`) has no pyproject.toml beside its code. `strata-db init --package src/myapp` declares the keys in `src/myapp/strata-db.toml` instead, with `migrations/` beside it, and puts `[tool.strata-db] file = "src/myapp/strata-db.toml"` in pyproject.toml. Both ship in the wheel, `Project.load(__file__)` finds the file by walking up from the module, and strata-db and the pytest plugin follow the pointer, so there is one declaration and no drift test. To move an existing app, move the keys and the `migrations` folder into the package and leave `file = ...` in the table.
|
|
351
|
+
- A FastAPI server's records:
|
|
352
|
+
|
|
353
|
+
```python
|
|
354
|
+
from strata_python.db import Project, local_url
|
|
355
|
+
from strata_python.db.web import DbSession, add_database
|
|
356
|
+
|
|
357
|
+
add_database(app, Project.load(__file__), default=lambda: local_url(SETTINGS))
|
|
358
|
+
|
|
359
|
+
@app.get("/api/notes")
|
|
360
|
+
def notes(db: DbSession) -> list[NoteOut]: ...
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
The engine is opened and migrated on the first request that needs one (a server nobody records on never creates a database), kept on `app.state` and disposed when the server stops, after the app's own lifespan. A failure to open is that request's error and is tried again on the next. Delete the app's `db.py` fallback, its session dependency and the conftest that disposed the engine.
|
|
303
364
|
- Tests: the plugin is registered with every install and does nothing until the extra is installed and the project has `[tool.strata-db]` (or `strata_db = true` in `[tool.pytest.ini_options]`; `strata_db = false` turns it off). So an app can take a 0.2.x release before it moves its database, even with the old database package still installed. Then `db_session`, `db_engine`, `db_url` (a URL for code that builds its own engine), `db_env` (points the app's own `connect("myapp")` at the test database; make it autouse in `conftest.py` for an app that connects by itself), `db_backend`, `db_project`. Migrations run once into a template and each test gets a copy, so a test costs a file copy. `pytest --pg` (or `--strata-pg`, which no other plugin can take) runs the same tests on a private Postgres the run starts for itself (needs the PostgreSQL server binaries), or on `STRATA_DB_TEST_ADMIN_URL`. Add the standard tests once:
|
|
304
365
|
|
|
305
366
|
```python
|
|
@@ -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.6" # 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"
|
|
@@ -62,6 +62,10 @@ pdf = [
|
|
|
62
62
|
"pypdfium2>=4.30,<6",
|
|
63
63
|
"pillow>=13,<14", # 13.0.0 fixes eight advisories, most in PDF parsing, which this extra exists for
|
|
64
64
|
]
|
|
65
|
+
# strata_python.images: pictures turned by their EXIF orientation and cached JPEG thumbnails of them.
|
|
66
|
+
images = [
|
|
67
|
+
"pillow>=13,<14",
|
|
68
|
+
]
|
|
65
69
|
|
|
66
70
|
[project.urls]
|
|
67
71
|
Homepage = "https://github.com/jburnhams/strata-python"
|
|
@@ -78,7 +82,7 @@ strata_python = "strata_python.pytest_plugin"
|
|
|
78
82
|
strata_python_db = "strata_python.db.pytest_plugin" # inert unless the db extra is installed and the project has [tool.strata-db]
|
|
79
83
|
|
|
80
84
|
[dependency-groups]
|
|
81
|
-
dev = ["strata-python[dev,db,pdf]"] # the same tools the apps get, and the
|
|
85
|
+
dev = ["strata-python[dev,db,pdf,images]"] # the same tools the apps get, and the extras so their tests run
|
|
82
86
|
|
|
83
87
|
[tool.hatch.build.targets.wheel]
|
|
84
88
|
packages = ["src/strata_python"]
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
checks=[Check("ffmpeg", program("ffmpeg"))])
|
|
6
6
|
add_set(sub, SETTINGS)
|
|
7
7
|
add_serve(sub, lambda host, port: web.serve(create_app(), ["--host", host, "--port", str(port)]), default_port=8360)
|
|
8
|
+
add_openapi(sub, create_app) # myapp openapi [-o web/openapi.json | -] [--check]
|
|
8
9
|
args = parser.parse_args(argv); return args.fn(args)
|
|
9
10
|
|
|
10
11
|
Each command sets `fn` on its parser; the handler returns the exit code."""
|
|
@@ -15,10 +16,14 @@ import shutil
|
|
|
15
16
|
import sys
|
|
16
17
|
from collections.abc import Callable, Iterable
|
|
17
18
|
from dataclasses import dataclass
|
|
18
|
-
from
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import TYPE_CHECKING, Any, Literal
|
|
19
21
|
|
|
20
22
|
from strata_python.settings import Settings
|
|
21
23
|
|
|
24
|
+
if TYPE_CHECKING:
|
|
25
|
+
from fastapi import FastAPI
|
|
26
|
+
|
|
22
27
|
Sub = Any # argparse's subparsers object is a private generic type; only add_parser is used
|
|
23
28
|
|
|
24
29
|
Status = Literal["ok", "missing", "slow", "broken"]
|
|
@@ -128,7 +133,8 @@ def add_set(sub: Sub, settings: Settings) -> None:
|
|
|
128
133
|
settings.save({args.key: None if args.value == "default" else args.value})
|
|
129
134
|
except ValueError as e:
|
|
130
135
|
sys.exit(str(e))
|
|
131
|
-
|
|
136
|
+
allowed = settings.allowed(args.key)
|
|
137
|
+
print(f"{args.key} = {settings.get(args.key)}" + (f" (one of: {', '.join(allowed)})" if allowed else ""))
|
|
132
138
|
return 0
|
|
133
139
|
|
|
134
140
|
p = sub.add_parser("set", help=f'show or change a setting ({", ".join(settings.keys)}); value "default" resets it')
|
|
@@ -148,3 +154,40 @@ def add_serve(sub: Sub, run: Callable[[str, int], None], *, default_port: int) -
|
|
|
148
154
|
p.add_argument("--host", default="127.0.0.1")
|
|
149
155
|
p.add_argument("--port", type=int, default=default_port)
|
|
150
156
|
p.set_defaults(fn=cmd_serve)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def add_openapi(sub: Sub, create_app: "Callable[[], FastAPI]", *, default: Path = Path("web/openapi.json")) -> None:
|
|
160
|
+
"""`openapi [-o PATH|-] [--check]`: write the app's schema (`web.openapi_text`) to `default`, another path or
|
|
161
|
+
stdout, for strata-react's `strata-api-types`, which reads the file so CI needs no server. `--check` writes
|
|
162
|
+
nothing and exits 1 when the file differs, so a Python-only CI job can gate it too. The app is built only when
|
|
163
|
+
the command runs, so `create_app` may be slow."""
|
|
164
|
+
|
|
165
|
+
def cmd_openapi(args: argparse.Namespace) -> int:
|
|
166
|
+
from strata_python import web # here, so the app's other commands do not import FastAPI
|
|
167
|
+
|
|
168
|
+
text = web.openapi_text(create_app())
|
|
169
|
+
out: str = args.output
|
|
170
|
+
if out == "-":
|
|
171
|
+
if args.check:
|
|
172
|
+
sys.exit("--check compares a file; give -o PATH")
|
|
173
|
+
sys.stdout.write(text)
|
|
174
|
+
return 0
|
|
175
|
+
path = Path(out)
|
|
176
|
+
if args.check:
|
|
177
|
+
current = path.read_text(encoding="utf-8") if path.is_file() else None
|
|
178
|
+
if current == text:
|
|
179
|
+
return 0
|
|
180
|
+
print(
|
|
181
|
+
f"{path} is {'missing' if current is None else 'out of date'}: run the openapi command", file=sys.stderr
|
|
182
|
+
)
|
|
183
|
+
return 1
|
|
184
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
185
|
+
with open(path, "w", encoding="utf-8", newline="\n") as f: # LF on Windows too, or the check never agrees
|
|
186
|
+
f.write(text)
|
|
187
|
+
print(f"wrote {path}")
|
|
188
|
+
return 0
|
|
189
|
+
|
|
190
|
+
p = sub.add_parser("openapi", help=f"write the API schema for the web app's types (default {default.as_posix()})")
|
|
191
|
+
p.add_argument("-o", "--output", default=str(default), help='file to write, or "-" for stdout')
|
|
192
|
+
p.add_argument("--check", action="store_true", help="write nothing; exit 1 if the file differs")
|
|
193
|
+
p.set_defaults(fn=cmd_openapi)
|
|
@@ -13,6 +13,7 @@ generated from it instead of copied.
|
|
|
13
13
|
Page[T] one page of a list: items, the cursor for the next page (None at the end), the total when it is known
|
|
14
14
|
FileRef a file by content and place: sha256, size, mtime, root, rel (the path under that root)
|
|
15
15
|
Judgment one pairwise choice by a person or a model: a, b, the winner (a, b or tie), who, when, undone when
|
|
16
|
+
ApiModel a base for an app's own response shapes: a field with a default is still required in the schema
|
|
16
17
|
|
|
17
18
|
Times are timezone-aware datetimes, sent as ISO 8601 with their offset: the apps had both ISO text and float epochs,
|
|
18
19
|
and only one of those reads correctly in a browser. Use `utc(epoch)` to turn a stored float into one."""
|
|
@@ -30,6 +31,14 @@ def utc(epoch: float | None) -> datetime.datetime | None:
|
|
|
30
31
|
return None if epoch is None else datetime.datetime.fromtimestamp(epoch, datetime.UTC)
|
|
31
32
|
|
|
32
33
|
|
|
34
|
+
class ApiModel(BaseModel):
|
|
35
|
+
"""A base for an app's own response models. pydantic marks a field with a default as optional in the schema, so
|
|
36
|
+
the generated TypeScript gets a `?` though the server always sends it; this config makes the response schema
|
|
37
|
+
say what is sent. Use it for responses: a request body built on it has an `-Input` and an `-Output` schema."""
|
|
38
|
+
|
|
39
|
+
model_config = ConfigDict(json_schema_serialization_defaults_required=True)
|
|
40
|
+
|
|
41
|
+
|
|
33
42
|
class Health(BaseModel):
|
|
34
43
|
"""What `GET /api/health` answers. Extra fields are the app's own (strata-models adds `gpu`)."""
|
|
35
44
|
|
|
@@ -19,7 +19,8 @@ extra: `strata-python[db]`.
|
|
|
19
19
|
s.add(Note(text="hi")); s.commit()
|
|
20
20
|
|
|
21
21
|
Migrations: `strata-db revision -m "..."` (autogenerate), `strata-db migrate`, `strata-db check`; or in code
|
|
22
|
-
`Project.load(__file__).upgrade(engine)`
|
|
22
|
+
`Project.load(__file__).upgrade(engine)` (or `.open()`, connect and migrate) at service start; a FastAPI server
|
|
23
|
+
uses `strata_python.db.web.add_database` and its `DbSession` dependency. Tests: the plugin's `db_session` / `db_engine` / `db_url`
|
|
23
24
|
/ `db_env` fixtures and `strata_python.db.testing`. See the README.
|
|
24
25
|
|
|
25
26
|
The names load on first use: the pytest plugin imports `strata_python.db.guard` in every app with strata-python
|
|
@@ -35,6 +36,9 @@ if TYPE_CHECKING:
|
|
|
35
36
|
from .config import (
|
|
36
37
|
DatabaseNotConfigured as DatabaseNotConfigured,
|
|
37
38
|
)
|
|
39
|
+
from .config import (
|
|
40
|
+
local_url as local_url,
|
|
41
|
+
)
|
|
38
42
|
from .config import (
|
|
39
43
|
normalise_url as normalise_url,
|
|
40
44
|
)
|
|
@@ -74,6 +78,7 @@ _WHERE = {
|
|
|
74
78
|
"DatabaseNotConfigured": "config",
|
|
75
79
|
"normalise_url": "config",
|
|
76
80
|
"resolve_url": "config",
|
|
81
|
+
"local_url": "config",
|
|
77
82
|
"url_for": "config",
|
|
78
83
|
"connect": "engine",
|
|
79
84
|
"session": "engine",
|
|
@@ -93,6 +98,7 @@ __all__ = [ # noqa: RUF022 (grouped as _WHERE is)
|
|
|
93
98
|
"DatabaseNotConfigured",
|
|
94
99
|
"normalise_url",
|
|
95
100
|
"resolve_url",
|
|
101
|
+
"local_url",
|
|
96
102
|
"url_for",
|
|
97
103
|
"connect",
|
|
98
104
|
"session",
|