strata-python 0.2.5__tar.gz → 0.2.7__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.5 → strata_python-0.2.7}/CHANGELOG.md +27 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/PKG-INFO +30 -8
- {strata_python-0.2.5 → strata_python-0.2.7}/README.md +29 -7
- {strata_python-0.2.5 → strata_python-0.2.7}/pyproject.toml +1 -1
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/cli.py +45 -2
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/contracts.py +19 -8
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/db/__init__.py +7 -1
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/db/cli.py +23 -9
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/db/config.py +28 -4
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/db/engine.py +4 -0
- strata_python-0.2.7/src/strata_python/db/project.py +149 -0
- strata_python-0.2.7/src/strata_python/db/web.py +103 -0
- strata_python-0.2.7/src/strata_python/mediatime.py +232 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/public_check.py +122 -19
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/settings.py +99 -25
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/testing.py +13 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/web.py +50 -7
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_cli.py +65 -0
- strata_python-0.2.7/tests/unit/test_contracts.py +97 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_db.py +151 -0
- strata_python-0.2.7/tests/unit/test_mediatime.py +124 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_public_check.py +83 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_settings.py +24 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_web.py +98 -0
- strata_python-0.2.5/src/strata_python/db/project.py +0 -98
- strata_python-0.2.5/tests/unit/test_contracts.py +0 -47
- {strata_python-0.2.5 → strata_python-0.2.7}/.gitignore +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/LICENSE +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/__init__.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/check.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/client.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/clients/__init__.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/clients/models.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/db/__main__.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/db/_alembic/env.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/db/_alembic/script.py.mako +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/db/guard.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/db/migrations.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/db/models.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/db/pytest_plugin.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/db/scratch.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/db/settings.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/db/testing.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/db/testserver.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/files.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/http.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/http_server.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/images.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/live.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/media.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/oslib.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/pages/__init__.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/pages/model.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/pages/render.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/py.typed +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/pytest_plugin.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/stats.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/tasks/__init__.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/tasks/child.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/tasks/flight.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/tasks/progress.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/tasks/queue.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/tasks/retry.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/tasks/status.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/src/strata_python/tasks/ticker.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/conftest.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/integration/test_db_cli.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/integration/test_serve.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/integration/test_strata_check.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/job_handlers.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_check.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_client.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_clients_models.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_files.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_http.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_http_server.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_images.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_live.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_media.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_oslib.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_package.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_pages.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_plugin.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_queue.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_stats.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_tasks.py +0 -0
- {strata_python-0.2.5 → strata_python-0.2.7}/tests/unit/test_testing.py +0 -0
|
@@ -4,6 +4,33 @@ 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.7 (2026-11-23)
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- `strata_python.mediatime`: exact time for media. `rational(...)` (seconds as a `Fraction` from an int, "p/q" or decimal text, a Decimal, or a float by its shortest repr), `Rate` (`parse("30000/1001")`, `frame_at`, `time_of`, `snap`), `Span` (half-open `[start, end)`: `duration`, `in`, `&`, `overlaps` (an empty span overlaps nothing), `shift`, `frames(rate)`), `Piece` and `TimeMap` (an edit's output time to its sources and back: `sequence(ranges)`, `to_source(t)`, `to_output(source, t)`), all with exact JSON (`text`, `to_json`, `from_json`).
|
|
12
|
+
- `web.add_system(..., extra_model=AppNumbers)` (or `extra` annotated `-> AppNumbers`, which may return the model): the route's response is `<App>SystemInfo`, `SystemInfo` plus the app's fields, so they are in `/api/openapi.json` and the generated types (#46). Replace the hand-written `Schema<'SystemInfo'> & {...}` with `Schema<'<App>SystemInfo'>`. Without a model, `extra` works as before.
|
|
13
|
+
|
|
14
|
+
### Changed
|
|
15
|
+
|
|
16
|
+
- The response contracts (`Page`, `Health`, `SystemInfo`, `Folder`, `ServiceStatus`, `ErrorBody`, `Task`, `Progress`) are built on `ApiModel`, so a field with a default is required in the response schema: `Page.next` is `string | null` in the generated types, not `next?` (#45). Drop the app's `page.next ?? null` and similar fill-ins. An app that takes one of them as a request body gets `-Input` and `-Output` schemas for it.
|
|
17
|
+
|
|
18
|
+
## 0.2.6 (2026-11-23)
|
|
19
|
+
|
|
20
|
+
### Added
|
|
21
|
+
|
|
22
|
+
- `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.
|
|
23
|
+
- `[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.
|
|
24
|
+
- `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).
|
|
25
|
+
- `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).
|
|
26
|
+
- `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).
|
|
27
|
+
- `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).
|
|
28
|
+
|
|
29
|
+
### Changed
|
|
30
|
+
|
|
31
|
+
- `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).
|
|
32
|
+
- `whole_between` and `number_between` are now small callable classes with `lo`/`hi` (they used to be closures); calling them is unchanged.
|
|
33
|
+
|
|
7
34
|
## 0.2.5 (2026-11-23)
|
|
8
35
|
|
|
9
36
|
### Added
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: strata-python
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.7
|
|
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
|
|
@@ -53,24 +53,25 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
|
|
|
53
53
|
|---|---|
|
|
54
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)` |
|
|
55
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`) |
|
|
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` |
|
|
57
|
-
| `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 |
|
|
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` |
|
|
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 |
|
|
59
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` |
|
|
60
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
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
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
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.mediatime` | Exact time for media: `rational` seconds (Fraction), `Rate` (`frame_at`, `time_of`, `snap`), half-open `Span`, and `TimeMap` from an edit's output time to its sources and back, with exact JSON |
|
|
64
65
|
| `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
66
|
| `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` |
|
|
66
67
|
| `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 |
|
|
67
68
|
| `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
|
|
68
69
|
| 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` |
|
|
69
|
-
| `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) `FakeModels`,
|
|
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,
|
|
70
|
+
| `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)` |
|
|
71
|
+
| `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 |
|
|
71
72
|
| `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 |
|
|
72
73
|
| `strata-check` | The one gate: lockfile, ruff, `ruff format`, pyright strict, ty, unit tests with coverage |
|
|
73
|
-
| `strata-public-check` | Fails on email addresses, private IPv4 addresses, home-folder paths and the
|
|
74
|
+
| `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`) |
|
|
74
75
|
|
|
75
76
|
## Move an app onto it
|
|
76
77
|
|
|
@@ -135,6 +136,7 @@ SETTINGS = Settings(
|
|
|
135
136
|
Setting("data_dir", default=lambda: "/srv/myapp", normalise=absolute_path),
|
|
136
137
|
Setting("greeting", default="Hello", normalise=non_empty),
|
|
137
138
|
Setting("workers", default="2", normalise=whole_between(1, 16)),
|
|
139
|
+
Setting("mode", default="mixed", choices=["mixed", "review", "new"]), # an enum in the API schema
|
|
138
140
|
ListSetting("source_roots", item=absolute_path, env="MYAPP_SOURCES"), # MYAPP_SOURCES split on os.pathsep
|
|
139
141
|
],
|
|
140
142
|
prefix="MYAPP", # only if the app already runs with other variable names
|
|
@@ -147,6 +149,8 @@ SETTINGS.folder("data_dir") # the value as a folder, created if missing
|
|
|
147
149
|
|
|
148
150
|
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.
|
|
149
151
|
|
|
152
|
+
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.
|
|
153
|
+
|
|
150
154
|
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:
|
|
151
155
|
|
|
152
156
|
```python
|
|
@@ -183,6 +187,8 @@ web.add_system(
|
|
|
183
187
|
) # GET /api/system, a SystemInfo
|
|
184
188
|
```
|
|
185
189
|
|
|
190
|
+
The app's own `/api/system` fields go in `extra=`, a function returning a mapping or a model. Give their model (`extra_model=AppNumbers`, or annotate the function `-> AppNumbers`) and the route's response is `<App>SystemInfo`, `SystemInfo` plus those fields, so the web app's type is `Schema<'MyappSystemInfo'>` with nothing added by hand.
|
|
191
|
+
|
|
186
192
|
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`.
|
|
187
193
|
|
|
188
194
|
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.
|
|
@@ -208,6 +214,8 @@ def main(argv=None):
|
|
|
208
214
|
return args.fn(args)
|
|
209
215
|
```
|
|
210
216
|
|
|
217
|
+
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.
|
|
218
|
+
|
|
211
219
|
Delete the hand-written `doctor`, `set` and `serve` subparsers. Each app's port belongs in its deploy units, not in this library.
|
|
212
220
|
|
|
213
221
|
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:
|
|
@@ -388,7 +396,21 @@ migrations = "migrations" # the app's Alembic revisions, unchanged
|
|
|
388
396
|
```
|
|
389
397
|
- 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`.
|
|
390
398
|
- 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`).
|
|
391
|
-
- At service start (only there): `Project.load(__file__).upgrade(connect("myapp"))
|
|
399
|
+
- 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).
|
|
400
|
+
- 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.
|
|
401
|
+
- A FastAPI server's records:
|
|
402
|
+
|
|
403
|
+
```python
|
|
404
|
+
from strata_python.db import Project, local_url
|
|
405
|
+
from strata_python.db.web import DbSession, add_database
|
|
406
|
+
|
|
407
|
+
add_database(app, Project.load(__file__), default=lambda: local_url(SETTINGS))
|
|
408
|
+
|
|
409
|
+
@app.get("/api/notes")
|
|
410
|
+
def notes(db: DbSession) -> list[NoteOut]: ...
|
|
411
|
+
```
|
|
412
|
+
|
|
413
|
+
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.
|
|
392
414
|
- 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:
|
|
393
415
|
|
|
394
416
|
```python
|
|
@@ -6,24 +6,25 @@ 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
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
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
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.mediatime` | Exact time for media: `rational` seconds (Fraction), `Rate` (`frame_at`, `time_of`, `snap`), half-open `Span`, and `TimeMap` from an edit's output time to its sources and back, with exact JSON |
|
|
17
18
|
| `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
19
|
| `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` |
|
|
19
20
|
| `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 |
|
|
20
21
|
| `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
|
|
21
22
|
| 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` |
|
|
22
|
-
| `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) `FakeModels`,
|
|
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,
|
|
23
|
+
| `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)` |
|
|
24
|
+
| `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 |
|
|
24
25
|
| `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 |
|
|
25
26
|
| `strata-check` | The one gate: lockfile, ruff, `ruff format`, pyright strict, ty, unit tests with coverage |
|
|
26
|
-
| `strata-public-check` | Fails on email addresses, private IPv4 addresses, home-folder paths and the
|
|
27
|
+
| `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`) |
|
|
27
28
|
|
|
28
29
|
## Move an app onto it
|
|
29
30
|
|
|
@@ -88,6 +89,7 @@ SETTINGS = Settings(
|
|
|
88
89
|
Setting("data_dir", default=lambda: "/srv/myapp", normalise=absolute_path),
|
|
89
90
|
Setting("greeting", default="Hello", normalise=non_empty),
|
|
90
91
|
Setting("workers", default="2", normalise=whole_between(1, 16)),
|
|
92
|
+
Setting("mode", default="mixed", choices=["mixed", "review", "new"]), # an enum in the API schema
|
|
91
93
|
ListSetting("source_roots", item=absolute_path, env="MYAPP_SOURCES"), # MYAPP_SOURCES split on os.pathsep
|
|
92
94
|
],
|
|
93
95
|
prefix="MYAPP", # only if the app already runs with other variable names
|
|
@@ -100,6 +102,8 @@ SETTINGS.folder("data_dir") # the value as a folder, created if missing
|
|
|
100
102
|
|
|
101
103
|
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.
|
|
102
104
|
|
|
105
|
+
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.
|
|
106
|
+
|
|
103
107
|
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:
|
|
104
108
|
|
|
105
109
|
```python
|
|
@@ -136,6 +140,8 @@ web.add_system(
|
|
|
136
140
|
) # GET /api/system, a SystemInfo
|
|
137
141
|
```
|
|
138
142
|
|
|
143
|
+
The app's own `/api/system` fields go in `extra=`, a function returning a mapping or a model. Give their model (`extra_model=AppNumbers`, or annotate the function `-> AppNumbers`) and the route's response is `<App>SystemInfo`, `SystemInfo` plus those fields, so the web app's type is `Schema<'MyappSystemInfo'>` with nothing added by hand.
|
|
144
|
+
|
|
139
145
|
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`.
|
|
140
146
|
|
|
141
147
|
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.
|
|
@@ -161,6 +167,8 @@ def main(argv=None):
|
|
|
161
167
|
return args.fn(args)
|
|
162
168
|
```
|
|
163
169
|
|
|
170
|
+
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.
|
|
171
|
+
|
|
164
172
|
Delete the hand-written `doctor`, `set` and `serve` subparsers. Each app's port belongs in its deploy units, not in this library.
|
|
165
173
|
|
|
166
174
|
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:
|
|
@@ -341,7 +349,21 @@ migrations = "migrations" # the app's Alembic revisions, unchanged
|
|
|
341
349
|
```
|
|
342
350
|
- 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`.
|
|
343
351
|
- 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`).
|
|
344
|
-
- At service start (only there): `Project.load(__file__).upgrade(connect("myapp"))
|
|
352
|
+
- 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).
|
|
353
|
+
- 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.
|
|
354
|
+
- A FastAPI server's records:
|
|
355
|
+
|
|
356
|
+
```python
|
|
357
|
+
from strata_python.db import Project, local_url
|
|
358
|
+
from strata_python.db.web import DbSession, add_database
|
|
359
|
+
|
|
360
|
+
add_database(app, Project.load(__file__), default=lambda: local_url(SETTINGS))
|
|
361
|
+
|
|
362
|
+
@app.get("/api/notes")
|
|
363
|
+
def notes(db: DbSession) -> list[NoteOut]: ...
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
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.
|
|
345
367
|
- 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:
|
|
346
368
|
|
|
347
369
|
```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.7" # 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"
|
|
@@ -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,7 +31,17 @@ 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
|
|
|
33
|
-
class
|
|
34
|
+
class ApiModel(BaseModel):
|
|
35
|
+
"""The base of the response shapes here, and for an app's own. pydantic marks a field with a default as optional in
|
|
36
|
+
the schema, so the generated TypeScript gets a `?` though the server always sends it; this config makes the
|
|
37
|
+
response schema say what is sent (`Page.next` is `string | null`, not `next?`). Use it for responses: a request
|
|
38
|
+
body built on it has an `-Input` and an `-Output` schema. `FileRef` and `Judgment` stay on `BaseModel`, since an
|
|
39
|
+
app may take them as a request body."""
|
|
40
|
+
|
|
41
|
+
model_config = ConfigDict(json_schema_serialization_defaults_required=True)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Health(ApiModel):
|
|
34
45
|
"""What `GET /api/health` answers. Extra fields are the app's own (strata-models adds `gpu`)."""
|
|
35
46
|
|
|
36
47
|
model_config = ConfigDict(extra="allow")
|
|
@@ -39,7 +50,7 @@ class Health(BaseModel):
|
|
|
39
50
|
commit: str | None = None # the source commit the server runs, so a probe can tell a stale deploy
|
|
40
51
|
|
|
41
52
|
|
|
42
|
-
class Folder(
|
|
53
|
+
class Folder(ApiModel):
|
|
43
54
|
"""A folder the app uses, and the disk it is on (None when the folder does not exist yet)."""
|
|
44
55
|
|
|
45
56
|
name: str
|
|
@@ -49,7 +60,7 @@ class Folder(BaseModel):
|
|
|
49
60
|
total_bytes: int | None = None
|
|
50
61
|
|
|
51
62
|
|
|
52
|
-
class ServiceStatus(
|
|
63
|
+
class ServiceStatus(ApiModel):
|
|
53
64
|
"""Another strata service this app calls, as its health endpoint answered just now."""
|
|
54
65
|
|
|
55
66
|
name: str
|
|
@@ -59,7 +70,7 @@ class ServiceStatus(BaseModel):
|
|
|
59
70
|
detail: str | None = None # why it is not ok: not reachable, or what it answered
|
|
60
71
|
|
|
61
72
|
|
|
62
|
-
class SystemInfo(
|
|
73
|
+
class SystemInfo(ApiModel):
|
|
63
74
|
"""What `GET /api/system` answers: what is running, where its data is, and whether its services answer."""
|
|
64
75
|
|
|
65
76
|
model_config = ConfigDict(extra="allow")
|
|
@@ -72,7 +83,7 @@ class SystemInfo(BaseModel):
|
|
|
72
83
|
services: list[ServiceStatus] = Field(default_factory=lambda: [])
|
|
73
84
|
|
|
74
85
|
|
|
75
|
-
class ErrorBody(
|
|
86
|
+
class ErrorBody(ApiModel):
|
|
76
87
|
"""The body of every error the app answers. `detail` is what FastAPI already uses, so clients that read it keep
|
|
77
88
|
working; `payload` carries what the error wants the client to have (the job row of a refused job)."""
|
|
78
89
|
|
|
@@ -84,7 +95,7 @@ TaskState = Literal["queued", "running", "done", "failed", "cancelled"]
|
|
|
84
95
|
FINISHED: frozenset[str] = frozenset({"done", "failed", "cancelled"})
|
|
85
96
|
|
|
86
97
|
|
|
87
|
-
class Progress(
|
|
98
|
+
class Progress(ApiModel):
|
|
88
99
|
"""How far a task has got. `total` None means not known yet; `text` is the line a person reads ("Page 3 of 40")."""
|
|
89
100
|
|
|
90
101
|
done: float = 0
|
|
@@ -98,7 +109,7 @@ class Progress(BaseModel):
|
|
|
98
109
|
return None if not self.total else min(max(self.done / self.total, 0.0), 1.0)
|
|
99
110
|
|
|
100
111
|
|
|
101
|
-
class Task(
|
|
112
|
+
class Task(ApiModel):
|
|
102
113
|
"""A job or task row as an API answers it."""
|
|
103
114
|
|
|
104
115
|
id: int | str
|
|
@@ -117,7 +128,7 @@ class Task(BaseModel):
|
|
|
117
128
|
T = TypeVar("T")
|
|
118
129
|
|
|
119
130
|
|
|
120
|
-
class Page(
|
|
131
|
+
class Page(ApiModel, Generic[T]): # Generic, not `Page[T]`: Python 3.11 is supported
|
|
121
132
|
"""One page of a list. `next` is an opaque cursor (pass it back as `after`), None on the last page; a cursor, not an
|
|
122
133
|
offset, so rows added while a person pages through do not repeat or vanish."""
|
|
123
134
|
|
|
@@ -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",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""strata-db: the app-facing command line (run from anywhere inside the app's repo; also `python -m strata_python.db`).
|
|
2
2
|
|
|
3
|
-
strata-db init --app NAME --models pkg.models:Base [--engine portable|postgres]
|
|
3
|
+
strata-db init --app NAME --models pkg.models:Base [--engine portable|postgres] [--package src/pkg]
|
|
4
4
|
add [tool.strata-db] to pyproject.toml and create migrations/
|
|
5
5
|
strata-db new-app [NAME] on the shared server: owner role NAME (NOLOGIN, you are a member) and schema NAME in
|
|
6
6
|
the shared database, owned by it, no USAGE for PUBLIC (other app roles cannot see it).
|
|
@@ -33,7 +33,7 @@ from . import migrations as m
|
|
|
33
33
|
from .config import normalise_url, resolve_url, shared_database
|
|
34
34
|
from .engine import connect
|
|
35
35
|
from .guard import LIVE, LiveDatabaseRefused, allow_live
|
|
36
|
-
from .project import TABLE, Project
|
|
36
|
+
from .project import FILE, TABLE, Project
|
|
37
37
|
from .scratch import live_admin_url, pg_available, scratch_database
|
|
38
38
|
from .testing import scratch_engine
|
|
39
39
|
|
|
@@ -41,18 +41,29 @@ NAME = re.compile(r"[a-z][a-z0-9_]*") # role and schema names: nothing that nee
|
|
|
41
41
|
|
|
42
42
|
|
|
43
43
|
def cmd_init(a: argparse.Namespace) -> None:
|
|
44
|
+
"""Write the declaration: into pyproject.toml, or with --package into the package's strata-db.toml (migrations
|
|
45
|
+
beside it, so an installed wheel carries both) with a pointer to it in pyproject.toml."""
|
|
44
46
|
pp = Path.cwd() / "pyproject.toml"
|
|
45
47
|
body = pp.read_text(encoding="utf-8") if pp.exists() else f'[project]\nname = "{a.app}"\nversion = "0.1.0"\n'
|
|
46
48
|
if f"[tool.{TABLE}]" in body:
|
|
47
49
|
sys.exit(f"{pp} already has [tool.{TABLE}]")
|
|
48
|
-
|
|
49
|
-
body.rstrip("\n") + f'\n\n[tool.{TABLE}]\napp = "{a.app}"\nmodels = "{a.models}"\nmigrations = "migrations"\n'
|
|
50
|
-
)
|
|
50
|
+
keys = f'app = "{a.app}"\nmodels = "{a.models}"\nmigrations = "migrations"\n'
|
|
51
51
|
if a.engine != "portable":
|
|
52
|
-
|
|
52
|
+
keys += f'engine = "{a.engine}"\n'
|
|
53
|
+
if a.package:
|
|
54
|
+
pkg = Path(a.package)
|
|
55
|
+
if not (Path.cwd() / pkg / "__init__.py").is_file():
|
|
56
|
+
sys.exit(f"{pkg} is not a package folder (no __init__.py)")
|
|
57
|
+
(Path.cwd() / pkg / FILE).write_text(keys, encoding="utf-8")
|
|
58
|
+
(Path.cwd() / pkg / "migrations").mkdir(exist_ok=True)
|
|
59
|
+
body = body.rstrip("\n") + f'\n\n[tool.{TABLE}]\nfile = "{(pkg / FILE).as_posix()}"\n'
|
|
60
|
+
where = f"{(pkg / FILE).as_posix()} (pointed to from {pp.name}); {(pkg / 'migrations').as_posix()}/ ready"
|
|
61
|
+
else:
|
|
62
|
+
body = body.rstrip("\n") + f"\n\n[tool.{TABLE}]\n{keys}"
|
|
63
|
+
(Path.cwd() / "migrations").mkdir(exist_ok=True)
|
|
64
|
+
where = f"[tool.{TABLE}] to {pp}; migrations/ ready"
|
|
53
65
|
pp.write_text(body, encoding="utf-8")
|
|
54
|
-
(
|
|
55
|
-
print(f"wrote [tool.{TABLE}] to {pp}; migrations/ ready. Next: strata-db revision -m 'initial'")
|
|
66
|
+
print(f"wrote {where}. Next: strata-db revision -m 'initial'")
|
|
56
67
|
|
|
57
68
|
|
|
58
69
|
def cmd_new_app(a: argparse.Namespace) -> None:
|
|
@@ -103,7 +114,9 @@ def cmd_revision(a: argparse.Namespace) -> None:
|
|
|
103
114
|
path = m.revision(eng, p.migrations_dir, p.metadata, a.message, autogenerate=not a.empty)
|
|
104
115
|
eng.dispose()
|
|
105
116
|
if path:
|
|
106
|
-
|
|
117
|
+
shown = Path(path).resolve()
|
|
118
|
+
shown = shown.relative_to(Path.cwd().resolve()) if shown.is_relative_to(Path.cwd().resolve()) else shown
|
|
119
|
+
print(f"wrote {shown.as_posix()}: review it, then commit it")
|
|
107
120
|
else:
|
|
108
121
|
print("no changes: the models match the migrations")
|
|
109
122
|
|
|
@@ -162,6 +175,7 @@ def main(argv: list[str] | None = None) -> None:
|
|
|
162
175
|
s.add_argument("--app", required=True)
|
|
163
176
|
s.add_argument("--models", required=True)
|
|
164
177
|
s.add_argument("--engine", choices=["portable", "postgres"], default="portable")
|
|
178
|
+
s.add_argument("--package", metavar="DIR", help="declare in DIR/strata-db.toml, so an installed wheel has it")
|
|
165
179
|
s.set_defaults(f=cmd_init)
|
|
166
180
|
s = sub.add_parser("new-app", help="role and schema on the shared server")
|
|
167
181
|
s.add_argument("name", nargs="?")
|
|
@@ -12,6 +12,9 @@ has no schemas.
|
|
|
12
12
|
|
|
13
13
|
The shared database has no built-in name: the name is the owner's, and this package is public (AGENTS.md rule 4).
|
|
14
14
|
|
|
15
|
+
An app that should still work before it is given a database (a checkout, a new deployment) passes a `default`, usually
|
|
16
|
+
`local_url(SETTINGS)`: a SQLite file in its settings folder. It is used only when nothing above is set.
|
|
17
|
+
|
|
15
18
|
A real Postgres database is opt-in (see `strata_python.db.guard`): url_for() and connect() refuse one unless the
|
|
16
19
|
process has `STRATA_DB_LIVE=1`, and refuse it always during tests.
|
|
17
20
|
"""
|
|
@@ -20,6 +23,10 @@ from __future__ import annotations
|
|
|
20
23
|
|
|
21
24
|
import os
|
|
22
25
|
import re
|
|
26
|
+
from typing import TYPE_CHECKING
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from strata_python.settings import Settings
|
|
23
30
|
|
|
24
31
|
URL = "STRATA_DB_URL"
|
|
25
32
|
DATABASE = "STRATA_DB_DATABASE"
|
|
@@ -67,19 +74,36 @@ def with_search_path(url: str, schema: str) -> str:
|
|
|
67
74
|
return url + ("&" if "?" in url else "?") + f"options=-csearch_path%3D{schema}"
|
|
68
75
|
|
|
69
76
|
|
|
70
|
-
def
|
|
71
|
-
"""
|
|
77
|
+
def local_url(home: Settings | str | os.PathLike[str], name: str | None = None) -> str:
|
|
78
|
+
"""A SQLite file for an app with no database configured: `<home>/<name>.db`, where home is a folder or the app's
|
|
79
|
+
`Settings` (its folder, `<APP>_HOME` or `~/.<app>`, and its name). `connect` makes the folder."""
|
|
80
|
+
from strata_python.settings import Settings
|
|
81
|
+
|
|
82
|
+
if isinstance(home, Settings):
|
|
83
|
+
folder, name = home.home(), name or home.app
|
|
84
|
+
else:
|
|
85
|
+
folder = os.fspath(home)
|
|
86
|
+
if not name:
|
|
87
|
+
raise ValueError("local_url(folder) needs the app name")
|
|
88
|
+
return normalise_url(os.path.join(folder, f"{name}.db"))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def resolve_url(app: str, schema: str | None = None, *, default: str | None = None) -> str:
|
|
92
|
+
"""Where `app`'s data is (see the module docstring), without the live-database check. `default` (a URL or a
|
|
93
|
+
path) is used when nothing is configured, instead of raising DatabaseNotConfigured."""
|
|
72
94
|
for var in (URL, env_name(app)):
|
|
73
95
|
if value := os.environ.get(var):
|
|
74
96
|
return with_search_path(normalise_url(value), schema or app)
|
|
97
|
+
if default is not None and not shared_database():
|
|
98
|
+
return with_search_path(normalise_url(default), schema or app) # as an environment URL (review finding)
|
|
75
99
|
return schema_url(schema or app)
|
|
76
100
|
|
|
77
101
|
|
|
78
|
-
def url_for(app: str, schema: str | None = None) -> str:
|
|
102
|
+
def url_for(app: str, schema: str | None = None, *, default: str | None = None) -> str:
|
|
79
103
|
"""resolve_url(), refused (guard.LiveDatabaseRefused) when it is a real Postgres database and the process has
|
|
80
104
|
not opted in with `STRATA_DB_LIVE=1`, or is running tests."""
|
|
81
105
|
from .guard import check_url
|
|
82
106
|
|
|
83
|
-
url = resolve_url(app, schema)
|
|
107
|
+
url = resolve_url(app, schema, default=default)
|
|
84
108
|
check_url(url, f"url_for({app!r})")
|
|
85
109
|
return url
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import os
|
|
5
6
|
import re
|
|
6
7
|
import sqlite3
|
|
7
8
|
from collections.abc import Generator
|
|
@@ -27,6 +28,9 @@ def connect(app_or_url: str, **kw: Any) -> Engine:
|
|
|
27
28
|
engine = create_engine(url, **kw)
|
|
28
29
|
if engine.dialect.name == "sqlite":
|
|
29
30
|
sqlite_pragmas(engine)
|
|
31
|
+
file = engine.url.database
|
|
32
|
+
if file and file != ":memory:" and not file.startswith("file:"):
|
|
33
|
+
os.makedirs(os.path.dirname(os.path.abspath(file)), exist_ok=True) # a fallback in a folder not made yet
|
|
30
34
|
return engine
|
|
31
35
|
|
|
32
36
|
|