strata-python 0.2.1__tar.gz → 0.2.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- strata_python-0.2.2/CHANGELOG.md +63 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/PKG-INFO +78 -18
- {strata_python-0.2.1 → strata_python-0.2.2}/README.md +73 -17
- {strata_python-0.2.1 → strata_python-0.2.2}/pyproject.toml +11 -3
- strata_python-0.2.2/src/strata_python/cli.py +150 -0
- strata_python-0.2.2/src/strata_python/clients/__init__.py +2 -0
- strata_python-0.2.2/src/strata_python/clients/models.py +780 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/db/__init__.py +6 -3
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/db/models.py +15 -3
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/db/project.py +29 -16
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/db/pytest_plugin.py +63 -9
- strata_python-0.2.2/src/strata_python/db/settings.py +63 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/oslib.py +44 -5
- strata_python-0.2.2/src/strata_python/pages/__init__.py +21 -0
- strata_python-0.2.2/src/strata_python/pages/model.py +241 -0
- strata_python-0.2.2/src/strata_python/pages/render.py +273 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/public_check.py +54 -8
- strata_python-0.2.2/src/strata_python/settings.py +333 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/web.py +15 -6
- strata_python-0.2.2/tests/unit/test_cli.py +115 -0
- strata_python-0.2.2/tests/unit/test_clients_models.py +290 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/tests/unit/test_db.py +150 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/tests/unit/test_oslib.py +40 -0
- strata_python-0.2.2/tests/unit/test_pages.py +251 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/tests/unit/test_public_check.py +59 -0
- strata_python-0.2.2/tests/unit/test_settings.py +263 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/tests/unit/test_web.py +27 -1
- strata_python-0.2.1/CHANGELOG.md +0 -39
- strata_python-0.2.1/src/strata_python/cli.py +0 -71
- strata_python-0.2.1/src/strata_python/settings.py +0 -132
- strata_python-0.2.1/tests/unit/test_cli.py +0 -64
- strata_python-0.2.1/tests/unit/test_settings.py +0 -125
- {strata_python-0.2.1 → strata_python-0.2.2}/.gitignore +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/LICENSE +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/__init__.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/check.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/db/__main__.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/db/_alembic/env.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/db/_alembic/script.py.mako +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/db/cli.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/db/config.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/db/engine.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/db/guard.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/db/migrations.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/db/scratch.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/db/testing.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/db/testserver.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/http_server.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/live.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/py.typed +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/pytest_plugin.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/src/strata_python/testing.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/tests/conftest.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/tests/integration/test_db_cli.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/tests/integration/test_serve.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/tests/integration/test_strata_check.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/tests/unit/test_check.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/tests/unit/test_http_server.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/tests/unit/test_live.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/tests/unit/test_package.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/tests/unit/test_plugin.py +0 -0
- {strata_python-0.2.1 → strata_python-0.2.2}/tests/unit/test_testing.py +0 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
What each release adds or changes for an app that depends on strata-python, newest first. Every breaking change says what to do in one line. Versions follow [semver](https://semver.org); while the version is 0.x a minor release may break, so depend on `strata-python>=0.N,<0.N+1`. Why each change was made is in [DEVLOG.md](DEVLOG.md).
|
|
4
|
+
|
|
5
|
+
## Unreleased
|
|
6
|
+
|
|
7
|
+
## 0.2.2 (2026-11-14)
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- `strata_python.pages` and the `[pdf]` extra (ReportLab, pypdfium2, Pillow): a scanned page described as blocks, lines, styled spans and figures in scan pixels (`Page`, `Block`, `Line`, `Span`, `Figure`, JSON with `to_dict`/`from_dict`), drawn as a PDF with real, embedded fonts by `pages.render.render(page, fonts)`, and read back with `rasterise(pdf, page, dpi)` (greyscale pixels at the scan's size) and `read_text(pdf)`. A span takes a font matcher's per-word fit as it is (`x`, `baseline_y`, `size_pt`, `tracking_em`, `hscale`, `stroke_em`); small capitals are synthesised unless the face is a small-caps cut; the same input gives the same bytes. For apps that rebuild scanned books, and for scoring a rebuild against the scan with the very renderer that prints it.
|
|
12
|
+
- `strata_python.clients.models`: the strata-models client, standard library only, with the same functions as `strata_models_client` (`run`, `submit`, `wait`, `wait_job`, `faces`, `transcribe`, `ocr`, `speak`, `role_model`, `acquire`, `gpu_lease`, `Unavailable`, `JobFailed`), now typed, plus a shortcut for each of the other roles the service runs (`ask` for `vision-language`, `text` and the judges; `generate_image`, `embed`, `face_kind`, `denoise_audio`, `audio_quality`, `enhance_video`) and a result shape for every role (`OcrPage`, `Transcript`, `Faces`, `Speech`, `Answer`, `GeneratedImage`, `Embeddings`, `FaceKinds`, `CleanAudio`, `AudioQuality`, `EnhancedVideo`; `.from_json`, with everything the service sent in `.raw`). `ROLES` lists them. To move: replace `import strata_models_client as sm` with `from strata_python.clients import models as sm` and drop the client's path or git dependency.
|
|
13
|
+
- Typed settings: normalisers `number_between(lo, hi)`, `whole_between(lo, hi)`, `iso_date(allow_blank=True)` and `boolean`, and getters `get_int`, `get_float`, `get_bool`. Replace an app's own range and date normalisers and its `int(SETTINGS.get(...))` calls.
|
|
14
|
+
- `ListSetting(key, default=..., item=..., sep=os.pathsep, env=...)`: a list of strings, a JSON list in the file, split on `sep` in the environment, read with `get_list`. `all()`, `GET /api/settings` and `PUT /api/settings` carry it as a JSON list, and `set` shows and takes it joined. An app with a list of folders can now drop its own settings file handling.
|
|
15
|
+
- Settings stores: `Settings(..., store=...)` and `Settings.bind(store)` keep the values in any object with `load()` and `update(changes)`. On the first bind the JSON file's values are copied in once. `strata_python.db.settings` has the table every app shares (`settings_table(Base.metadata)`) and its `TableStore`, on SQLite and Postgres.
|
|
16
|
+
- `cli.add_doctor(..., checks=[...], hint="...")`: imports can be `(label, module)` pairs or `cli.Module(label, module, optional=True)`, and `cli.Check(label, fn)` rows (`fn` returns `(status, text)`; `ok`, `missing`, `slow` or `broken`) cover what an import cannot tell, with `cli.program("ffmpeg")` for a program on the PATH. Every app's rows line up the same. `cli.doctor(...)` runs the same thing directly. Replace an app's own `doctor` with these.
|
|
17
|
+
- `web.base_app(..., health=lambda: {...})` adds the app's own fields to `GET /api/health` after `ok` and `version`; it may set `ok` to false. Replace an app's own health route with it.
|
|
18
|
+
- `oslib.lower_priority(nice, io=True)` also lowers disk priority for batch jobs that read many large files: the idle I/O class on Linux (children inherit it), background mode on Windows, I/O throttling on macOS. Replace the app's own `ionice -c3 -p <pid>` helper with it.
|
|
19
|
+
- `strata-public-check` takes `[tool.strata-public-check] exclude = [...]` in pyproject.toml and `--exclude GLOB` to skip the built-in patterns in matching files (an sdist's copy matches too), and skips the built-in patterns on a line that says `strata-public-check: ignore`. Neither silences `STRATA_PUBLIC_DENY`.
|
|
20
|
+
|
|
21
|
+
### Changed
|
|
22
|
+
|
|
23
|
+
- `Settings.all()` is typed `dict[str, str | list[str]]`, since a `ListSetting` is a list. It is unchanged for an app with only `Setting`s, but its type checker may now ask it to narrow a value it passes on as a `str`.
|
|
24
|
+
- The documented way to declare an app's models base is now the class written out (`class Base(MappedAsDataclass, DeclarativeBase): metadata = MetaData(naming_convention=NAMING_CONVENTION)`, README step 8), because ty rejects `Base = make_base()` as a base class and fails the gate. `make_base()` still works and stays for code that needs a base at run time; an app that uses it for its models should switch.
|
|
25
|
+
|
|
26
|
+
### Fixed
|
|
27
|
+
|
|
28
|
+
- `strata-public-check` no longer reads three-part versions (`10.4.2` in package.json and package-lock.json) as private IPv4 addresses: only a whole four-part address counts. An app with a web front end can now run it in CI.
|
|
29
|
+
- The db pytest plugin no longer stops an app's tests from running when the old database package is installed too ("option names {'--pg'} already added"). It now switches on only for an app that uses `strata_python.db`: the db extra installed and a `[tool.strata-db]` table in pyproject.toml, or `strata_db = true` in `[tool.pytest.ini_options]` (`strata_db = false` turns it off). SQLAlchemy and Alembic brought in by another package no longer switch on its guard. Until it is on it adds no `--pg`; once on, `--pg` is ours unless another plugin has it, and `--strata-pg` always works. Drop the old database package once the app has moved to `strata_python.db`.
|
|
30
|
+
|
|
31
|
+
## 0.2.1 (2026-11-14)
|
|
32
|
+
|
|
33
|
+
### Added
|
|
34
|
+
|
|
35
|
+
- `strata_python.testing`: the test doubles every app copied into `tests/utils/fakes.py` (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, plus `Sleeper`), and CLI runners `run_cli(main, *args, check=True)` and `run_module(module, *args, src=..., check=True)` returning `CliResult(stdout, stderr, code)`. Delete the app's `fakes.py` and import from here.
|
|
36
|
+
- Plugin fixtures `fake_urlopen`, `fake_popen`, `fake_run` and `no_sleep`, so the app's conftest no longer defines them. `fake_popen` gives each test its own `.instances`. `FakeUrlopen.calls` entries are `Call` objects that still answer `call["url"]`.
|
|
37
|
+
- `strata_env = ["KEY=VALUE", ...]` in `[tool.pytest.ini_options]` sets the app's own variables for every test (`{env}` is the isolated folder), for what each app's `isolated_env` copy added.
|
|
38
|
+
- `strata-python[dev]`: ruff, pyright, ty, httpx and the pytest plugins at the versions `strata-check` is tested with. An app's dev group becomes `dev = ["strata-python[dev]"]`; delete those packages from it.
|
|
39
|
+
- `strata-python[db]` and `strata_python.db`: the shared-database code apps took from a git pin of the database package, now typed and released here. `connect`, `session`, `make_base` (the same naming convention, so existing revisions do not drift), `Project` from `[tool.strata-db]`, `upgrade`, `downgrade`, `drift`, `check_migrations`, `lint_revisions`, `stairway`, the live-database guard (`LiveDatabaseRefused`), scratch databases, a private throwaway Postgres for tests (now on Windows too), the `strata-db` command (`init`, `new-app`, `revision`, `migrate`, `check`, `current`; also `python -m strata_python.db`), the fixtures `db_engine`, `db_session`, `db_url`, `db_env`, `db_backend`, `db_project` with `--pg`, and the standard tests in `strata_python.db.testing`. The names are `STRATA_DB_*` (`URL`, `DATABASE`, `LIVE`, `TESTING`, `TEST`, `TEST_ADMIN_URL`, `ADMIN_URL`); throwaway databases are `strata_db_*`. To move: rename the app's table to `[tool.strata-db]`, import from `strata_python.db`, set `STRATA_DB_LIVE=1` and `STRATA_DB_DATABASE` in its service environment, and drop the git dependency (README, step 8).
|
|
40
|
+
- Tests under `tests/integration` get the `integration` marker automatically, and the marker is registered; delete the app's `pytest_collection_modifyitems`. Set `strata_auto_integration = false` to opt out.
|
|
41
|
+
|
|
42
|
+
### Changed
|
|
43
|
+
|
|
44
|
+
- The shared dependencies are capped below their next release that may break (`fastapi<1`, `uvicorn<1`, `pydantic<3`, `pytest<10`), so a breaking upstream release reaches the apps through a strata-python release, not on its own.
|
|
45
|
+
- `FakeRun.check_output` raises `CalledProcessError` when `.code` is set, as the real `check_output` does; the apps' copies returned the output.
|
|
46
|
+
|
|
47
|
+
## 0.2.0 (2026-11-14)
|
|
48
|
+
|
|
49
|
+
The first release on PyPI. Apps tracked a git commit before this.
|
|
50
|
+
|
|
51
|
+
### Changed
|
|
52
|
+
|
|
53
|
+
- **Install from PyPI.** Replace the `[tool.uv.sources] strata-python = { git = ... }` entry with the dependency `strata-python>=0.2,<0.3`, then run `uv lock`.
|
|
54
|
+
|
|
55
|
+
### Added
|
|
56
|
+
|
|
57
|
+
- `strata-public-check`: fails on email addresses, private IPv4 addresses, home-folder paths and the regexes in `STRATA_PUBLIC_DENY`, in a folder, an sdist or a wheel. Run it in a public app's CI.
|
|
58
|
+
- `Settings(..., prefix="MA")` names the environment variables an app already uses (from the pre-PyPI commits; listed here because no earlier release exists).
|
|
59
|
+
- The MIT licence.
|
|
60
|
+
|
|
61
|
+
## Before 0.2.0 (git commits only)
|
|
62
|
+
|
|
63
|
+
`oslib`, `settings`, `web`, `cli`, `http_server`, `live`, the pytest plugin (`isolated_env`, `no_network`, `http_server`, `live_app`) and `strata-check`, taken from python-app-template.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: strata-python
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.2
|
|
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,10 @@ 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: pdf
|
|
41
|
+
Requires-Dist: pillow<14,>=10; extra == 'pdf'
|
|
42
|
+
Requires-Dist: pypdfium2<6,>=4.30; extra == 'pdf'
|
|
43
|
+
Requires-Dist: reportlab<6,>=4.2; extra == 'pdf'
|
|
40
44
|
Description-Content-Type: text/markdown
|
|
41
45
|
|
|
42
46
|
# strata-python
|
|
@@ -46,15 +50,17 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
|
|
|
46
50
|
| Module | What it gives an app |
|
|
47
51
|
|---|---|
|
|
48
52
|
| `strata_python.oslib` | Cross-platform file locks, process liveness (`pid_alive`), `kill_tree`, `lower_priority`, `venv_python`, `cli_command(module)` |
|
|
49
|
-
| `strata_python.settings` | `Settings` / `Setting`: one JSON file in `~/.<app>` with `<APP>_*` environment overrides, validation (`absolute_path`, `non_empty`), atomic saves |
|
|
50
|
-
| `strata_python.web` | `base_app` (health + settings routes), `add_web` (built web app or stand-in page at every non-API path), `with_base` (reverse-proxy-safe `<base href>`), `static_file` (path-safe), `serve` |
|
|
51
|
-
| `strata_python.cli` | `add_doctor
|
|
53
|
+
| `strata_python.settings` | `Settings` / `Setting` / `ListSetting`: one JSON file in `~/.<app>` with `<APP>_*` environment overrides, validation (`absolute_path`, `non_empty`, `number_between`, `whole_between`, `iso_date`, `boolean`), typed getters, atomic saves, and `bind(store)` to keep them elsewhere (`strata_python.db.settings.TableStore`) |
|
|
54
|
+
| `strata_python.web` | `base_app` (health with the app's own fields + settings routes), `add_web` (built web app or stand-in page at every non-API path), `with_base` (reverse-proxy-safe `<base href>`), `static_file` (path-safe), `serve` |
|
|
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.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 |
|
|
52
57
|
| `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
|
|
53
58
|
| pytest plugin | Loaded automatically: hermetic home and data folders (`strata_env` adds the app's own variables), a no-network guard, `http_server` and `live_app`, the `fake_urlopen`, `fake_popen`, `fake_run` and `no_sleep` fixtures, and the `integration` marker on everything under `tests/integration` |
|
|
54
59
|
| `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) and the CLI runners `run_cli(main, *args)` and `run_module("myapp", *args, src=...)` |
|
|
55
|
-
| `strata_python.db` (extra `[db]`) | The shared database: `connect("myapp")` (the app's schema of one shared Postgres, or a SQLite path), `
|
|
60
|
+
| `strata_python.db` (extra `[db]`) | The shared database: `connect("myapp")` (the app's schema of one shared Postgres, or a SQLite path), a declarative base with the shared `NAMING_CONVENTION` for typed models, Alembic migrations with no per-app `env.py`, the live-database guard, the `strata-db` command, and the `db_*` fixtures (SQLite by default, a throwaway Postgres with `--pg`) |
|
|
61
|
+
| `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 |
|
|
56
62
|
| `strata-check` | The one gate: lockfile, ruff, `ruff format`, pyright strict, ty, unit tests with coverage |
|
|
57
|
-
| `strata-public-check` | Fails on email addresses, private IPv4 addresses, home-folder paths and the regexes in `STRATA_PUBLIC_DENY` in a tree, sdist or wheel; run before anything public is published |
|
|
63
|
+
| `strata-public-check` | Fails on email addresses, private IPv4 addresses, home-folder paths and the regexes in `STRATA_PUBLIC_DENY` in a tree, sdist or wheel; run before anything public is published. 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`) |
|
|
58
64
|
|
|
59
65
|
## Move an app onto it
|
|
60
66
|
|
|
@@ -111,23 +117,34 @@ It runs the lockfile check, ruff, `ruff format`, pyright strict, ty and the unit
|
|
|
111
117
|
Replace the app's `settings.py` (its key list, getters, file handling and environment lookups) with a declaration:
|
|
112
118
|
|
|
113
119
|
```python
|
|
114
|
-
from strata_python.settings import Setting, Settings, absolute_path, non_empty
|
|
120
|
+
from strata_python.settings import ListSetting, Setting, Settings, absolute_path, non_empty, whole_between
|
|
115
121
|
|
|
116
122
|
SETTINGS = Settings(
|
|
117
|
-
"myapp",
|
|
123
|
+
"myapp", # ~/.myapp/settings.json, moved with MYAPP_HOME
|
|
118
124
|
[
|
|
119
125
|
Setting("data_dir", default=lambda: "/srv/myapp", normalise=absolute_path),
|
|
120
126
|
Setting("greeting", default="Hello", normalise=non_empty),
|
|
127
|
+
Setting("workers", default="2", normalise=whole_between(1, 16)),
|
|
128
|
+
ListSetting("source_roots", item=absolute_path, env="MYAPP_SOURCES"), # MYAPP_SOURCES split on os.pathsep
|
|
121
129
|
],
|
|
122
|
-
prefix="MYAPP",
|
|
130
|
+
prefix="MYAPP", # only if the app already runs with other variable names
|
|
123
131
|
)
|
|
124
132
|
|
|
125
|
-
SETTINGS.get("greeting")
|
|
133
|
+
SETTINGS.get("greeting") # MYAPP_GREETING, else the file, else the default
|
|
126
134
|
SETTINGS.save({"greeting": "Hi"}) # validated and written atomically; None resets to the default
|
|
127
|
-
SETTINGS.folder("data_dir")
|
|
135
|
+
SETTINGS.folder("data_dir") # the value as a folder, created if missing
|
|
128
136
|
```
|
|
129
137
|
|
|
130
|
-
Values are strings
|
|
138
|
+
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.
|
|
139
|
+
|
|
140
|
+
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:
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
from strata_python.db.settings import TableStore, settings_table
|
|
144
|
+
|
|
145
|
+
SETTINGS_TABLE = settings_table(Base.metadata) # in models.py, so the migrations create it
|
|
146
|
+
SETTINGS.bind(TableStore(engine, SETTINGS_TABLE)) # any object with load() and update(changes) is a store
|
|
147
|
+
```
|
|
131
148
|
|
|
132
149
|
### 4. The server
|
|
133
150
|
|
|
@@ -142,7 +159,7 @@ def create_app():
|
|
|
142
159
|
return app
|
|
143
160
|
```
|
|
144
161
|
|
|
145
|
-
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.
|
|
162
|
+
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.
|
|
146
163
|
|
|
147
164
|
### 5. The CLI
|
|
148
165
|
|
|
@@ -156,8 +173,10 @@ def main(argv=None):
|
|
|
156
173
|
parser = argparse.ArgumentParser(prog="myapp")
|
|
157
174
|
sub = parser.add_subparsers(dest="cmd", required=True)
|
|
158
175
|
cli.add_doctor(sub, "myapp", __version__, ("fastapi", "uvicorn")) # versions, and whether each import works
|
|
159
|
-
cli.add_set(sub, SETTINGS)
|
|
160
|
-
cli.add_serve(
|
|
176
|
+
cli.add_set(sub, SETTINGS) # myapp set KEY [VALUE|default]
|
|
177
|
+
cli.add_serve(
|
|
178
|
+
sub, lambda host, port: web.serve(create_app(), ["--host", host, "--port", str(port)]), default_port=8000
|
|
179
|
+
)
|
|
161
180
|
# ... the app's own subcommands, each with set_defaults(fn=...) ...
|
|
162
181
|
args = parser.parse_args(argv)
|
|
163
182
|
return args.fn(args)
|
|
@@ -165,9 +184,39 @@ def main(argv=None):
|
|
|
165
184
|
|
|
166
185
|
Delete the hand-written `doctor`, `set` and `serve` subparsers. Each app's port belongs in its deploy units, not in this library.
|
|
167
186
|
|
|
187
|
+
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:
|
|
188
|
+
|
|
189
|
+
```python
|
|
190
|
+
cli.add_doctor(
|
|
191
|
+
sub,
|
|
192
|
+
"myapp",
|
|
193
|
+
__version__,
|
|
194
|
+
("fastapi", ("rawpy (DNG decoding)", "rawpy"), cli.Module("ultralytics", optional=True)),
|
|
195
|
+
checks=[cli.Check("ffmpeg", cli.program("ffmpeg", "apt install ffmpeg")), cli.Check("gpu", gpu_check)],
|
|
196
|
+
hint="uv sync (scripts/setup_env)",
|
|
197
|
+
)
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
A check returns `(status, text)` with status `ok`, `missing`, `slow` (works, but not as it should; never fails) or `broken`, and an exception counts as `broken`. Doctor exits 1 when a required module or check is missing or broken. A check that may be missing without that being a fault is `Check(..., optional=True)`.
|
|
201
|
+
|
|
202
|
+
### 5b. The strata-models client (apps that use the model service)
|
|
203
|
+
|
|
204
|
+
Drop the `strata-models-client` path or git dependency and change the import. The functions, their arguments and the exceptions are the same:
|
|
205
|
+
|
|
206
|
+
```python
|
|
207
|
+
from strata_python.clients import models as sm # was: import strata_models_client as sm
|
|
208
|
+
|
|
209
|
+
page = sm.OcrPage.from_json(sm.ocr("/path/page.png", app="strata-scan")) # typed: page.lines[0].words[0].box
|
|
210
|
+
talk = sm.Transcript.from_json(sm.transcribe("/path/talk.wav", app="strata-360"))
|
|
211
|
+
with sm.gpu_lease("strata-stills", vram_gb=4):
|
|
212
|
+
run_my_own_cuda_code()
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
The shortcuts still return the service's JSON, so existing code keeps working, and the result classes keep all of it in `.raw`. There is one shortcut for every role the service runs (`sm.ROLES`): `faces`, `face_kind`, `transcribe` (also `role="transcribe-fast"`), `ocr`, `speak`, `denoise_audio`, `audio_quality`, `generate_image`, `embed` and `enhance_video`, plus `ask` for the language-model roles (`vision-language`, `text`, and the judges). Each has a result class (`Answer`, `GeneratedImage`, `Embeddings`, `FaceKinds`, `CleanAudio`, `AudioQuality`, `EnhancedVideo` and the four above). The roles `models.toml` lists without a runtime yet (sound-events, speaker-embedding, detect-people, upscale, denoise, nsfw) have none: `run(role, params, app)` reaches them once the service serves them.
|
|
216
|
+
|
|
168
217
|
### 6. OS helpers
|
|
169
218
|
|
|
170
|
-
Delete the app's `oslib.py` and import from `strata_python.oslib`: `file_lock(f)`, `pid_alive(pid)`, `kill_tree(pid, sig)`, `lower_priority(nice)
|
|
219
|
+
Delete the app's `oslib.py` and import from `strata_python.oslib`: `file_lock(f)`, `pid_alive(pid)`, `kill_tree(pid, sig)`, `lower_priority(nice, io=False)` (`io=True` for idle disk priority too; drop the app's `ionice` helper), `venv_python(venv)` and `cli_command(module)`. `cli_command` now takes the module name (`cli_command("myapp")`). Local `alive(pid)`, `_alive` and `lower_priority()` copies go too. Helpers this library does not have yet (process-group supervision, load average) stay in the app until they move here, and the app's file says so.
|
|
171
220
|
|
|
172
221
|
### 7. Tests
|
|
173
222
|
|
|
@@ -243,11 +292,22 @@ migrations = "migrations" # the app's Alembic revisions, unchanged
|
|
|
243
292
|
# engine = "postgres" # only for an app that uses Postgres-only features
|
|
244
293
|
```
|
|
245
294
|
|
|
246
|
-
- Imports: the old package's names come from `strata_python.db` (`connect`, `session`, `
|
|
295
|
+
- Imports: the old package's names come from `strata_python.db` (`connect`, `session`, `NAMING_CONVENTION`, `Project`, `upgrade`, `drift`, `check_migrations`, `LiveDatabaseRefused`); the standard tests from `strata_python.db.testing`. The naming convention is byte-identical, so existing revisions and databases do not drift.
|
|
296
|
+
- Models: write the base class out, not `Base = make_base()`, which ty rejects as a base (`unsupported-base`) and so fails the gate:
|
|
297
|
+
|
|
298
|
+
```python
|
|
299
|
+
from sqlalchemy import MetaData
|
|
300
|
+
from sqlalchemy.orm import DeclarativeBase, MappedAsDataclass
|
|
301
|
+
from strata_python.db import NAMING_CONVENTION
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
class Base(MappedAsDataclass, DeclarativeBase):
|
|
305
|
+
metadata = MetaData(naming_convention=NAMING_CONVENTION)
|
|
306
|
+
```
|
|
247
307
|
- 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`.
|
|
248
308
|
- 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`).
|
|
249
309
|
- At service start (only there): `Project.load(__file__).upgrade(connect("myapp"))`.
|
|
250
|
-
- Tests: the plugin is registered with every install and does nothing until the extra is
|
|
310
|
+
- 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:
|
|
251
311
|
|
|
252
312
|
```python
|
|
253
313
|
# tests/unit/test_database.py
|
|
@@ -5,15 +5,17 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
|
|
|
5
5
|
| Module | What it gives an app |
|
|
6
6
|
|---|---|
|
|
7
7
|
| `strata_python.oslib` | Cross-platform file locks, process liveness (`pid_alive`), `kill_tree`, `lower_priority`, `venv_python`, `cli_command(module)` |
|
|
8
|
-
| `strata_python.settings` | `Settings` / `Setting`: one JSON file in `~/.<app>` with `<APP>_*` environment overrides, validation (`absolute_path`, `non_empty`), atomic saves |
|
|
9
|
-
| `strata_python.web` | `base_app` (health + settings routes), `add_web` (built web app or stand-in page at every non-API path), `with_base` (reverse-proxy-safe `<base href>`), `static_file` (path-safe), `serve` |
|
|
10
|
-
| `strata_python.cli` | `add_doctor
|
|
8
|
+
| `strata_python.settings` | `Settings` / `Setting` / `ListSetting`: one JSON file in `~/.<app>` with `<APP>_*` environment overrides, validation (`absolute_path`, `non_empty`, `number_between`, `whole_between`, `iso_date`, `boolean`), typed getters, atomic saves, and `bind(store)` to keep them elsewhere (`strata_python.db.settings.TableStore`) |
|
|
9
|
+
| `strata_python.web` | `base_app` (health with the app's own fields + settings routes), `add_web` (built web app or stand-in page at every non-API path), `with_base` (reverse-proxy-safe `<base href>`), `static_file` (path-safe), `serve` |
|
|
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.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 |
|
|
11
12
|
| `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
|
|
12
13
|
| pytest plugin | Loaded automatically: hermetic home and data folders (`strata_env` adds the app's own variables), a no-network guard, `http_server` and `live_app`, the `fake_urlopen`, `fake_popen`, `fake_run` and `no_sleep` fixtures, and the `integration` marker on everything under `tests/integration` |
|
|
13
14
|
| `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) and the CLI runners `run_cli(main, *args)` and `run_module("myapp", *args, src=...)` |
|
|
14
|
-
| `strata_python.db` (extra `[db]`) | The shared database: `connect("myapp")` (the app's schema of one shared Postgres, or a SQLite path), `
|
|
15
|
+
| `strata_python.db` (extra `[db]`) | The shared database: `connect("myapp")` (the app's schema of one shared Postgres, or a SQLite path), a declarative base with the shared `NAMING_CONVENTION` for typed models, Alembic migrations with no per-app `env.py`, the live-database guard, the `strata-db` command, and the `db_*` fixtures (SQLite by default, a throwaway Postgres with `--pg`) |
|
|
16
|
+
| `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 |
|
|
15
17
|
| `strata-check` | The one gate: lockfile, ruff, `ruff format`, pyright strict, ty, unit tests with coverage |
|
|
16
|
-
| `strata-public-check` | Fails on email addresses, private IPv4 addresses, home-folder paths and the regexes in `STRATA_PUBLIC_DENY` in a tree, sdist or wheel; run before anything public is published |
|
|
18
|
+
| `strata-public-check` | Fails on email addresses, private IPv4 addresses, home-folder paths and the regexes in `STRATA_PUBLIC_DENY` in a tree, sdist or wheel; run before anything public is published. 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`) |
|
|
17
19
|
|
|
18
20
|
## Move an app onto it
|
|
19
21
|
|
|
@@ -70,23 +72,34 @@ It runs the lockfile check, ruff, `ruff format`, pyright strict, ty and the unit
|
|
|
70
72
|
Replace the app's `settings.py` (its key list, getters, file handling and environment lookups) with a declaration:
|
|
71
73
|
|
|
72
74
|
```python
|
|
73
|
-
from strata_python.settings import Setting, Settings, absolute_path, non_empty
|
|
75
|
+
from strata_python.settings import ListSetting, Setting, Settings, absolute_path, non_empty, whole_between
|
|
74
76
|
|
|
75
77
|
SETTINGS = Settings(
|
|
76
|
-
"myapp",
|
|
78
|
+
"myapp", # ~/.myapp/settings.json, moved with MYAPP_HOME
|
|
77
79
|
[
|
|
78
80
|
Setting("data_dir", default=lambda: "/srv/myapp", normalise=absolute_path),
|
|
79
81
|
Setting("greeting", default="Hello", normalise=non_empty),
|
|
82
|
+
Setting("workers", default="2", normalise=whole_between(1, 16)),
|
|
83
|
+
ListSetting("source_roots", item=absolute_path, env="MYAPP_SOURCES"), # MYAPP_SOURCES split on os.pathsep
|
|
80
84
|
],
|
|
81
|
-
prefix="MYAPP",
|
|
85
|
+
prefix="MYAPP", # only if the app already runs with other variable names
|
|
82
86
|
)
|
|
83
87
|
|
|
84
|
-
SETTINGS.get("greeting")
|
|
88
|
+
SETTINGS.get("greeting") # MYAPP_GREETING, else the file, else the default
|
|
85
89
|
SETTINGS.save({"greeting": "Hi"}) # validated and written atomically; None resets to the default
|
|
86
|
-
SETTINGS.folder("data_dir")
|
|
90
|
+
SETTINGS.folder("data_dir") # the value as a folder, created if missing
|
|
87
91
|
```
|
|
88
92
|
|
|
89
|
-
Values are strings
|
|
93
|
+
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.
|
|
94
|
+
|
|
95
|
+
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:
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
from strata_python.db.settings import TableStore, settings_table
|
|
99
|
+
|
|
100
|
+
SETTINGS_TABLE = settings_table(Base.metadata) # in models.py, so the migrations create it
|
|
101
|
+
SETTINGS.bind(TableStore(engine, SETTINGS_TABLE)) # any object with load() and update(changes) is a store
|
|
102
|
+
```
|
|
90
103
|
|
|
91
104
|
### 4. The server
|
|
92
105
|
|
|
@@ -101,7 +114,7 @@ def create_app():
|
|
|
101
114
|
return app
|
|
102
115
|
```
|
|
103
116
|
|
|
104
|
-
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.
|
|
117
|
+
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.
|
|
105
118
|
|
|
106
119
|
### 5. The CLI
|
|
107
120
|
|
|
@@ -115,8 +128,10 @@ def main(argv=None):
|
|
|
115
128
|
parser = argparse.ArgumentParser(prog="myapp")
|
|
116
129
|
sub = parser.add_subparsers(dest="cmd", required=True)
|
|
117
130
|
cli.add_doctor(sub, "myapp", __version__, ("fastapi", "uvicorn")) # versions, and whether each import works
|
|
118
|
-
cli.add_set(sub, SETTINGS)
|
|
119
|
-
cli.add_serve(
|
|
131
|
+
cli.add_set(sub, SETTINGS) # myapp set KEY [VALUE|default]
|
|
132
|
+
cli.add_serve(
|
|
133
|
+
sub, lambda host, port: web.serve(create_app(), ["--host", host, "--port", str(port)]), default_port=8000
|
|
134
|
+
)
|
|
120
135
|
# ... the app's own subcommands, each with set_defaults(fn=...) ...
|
|
121
136
|
args = parser.parse_args(argv)
|
|
122
137
|
return args.fn(args)
|
|
@@ -124,9 +139,39 @@ def main(argv=None):
|
|
|
124
139
|
|
|
125
140
|
Delete the hand-written `doctor`, `set` and `serve` subparsers. Each app's port belongs in its deploy units, not in this library.
|
|
126
141
|
|
|
142
|
+
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:
|
|
143
|
+
|
|
144
|
+
```python
|
|
145
|
+
cli.add_doctor(
|
|
146
|
+
sub,
|
|
147
|
+
"myapp",
|
|
148
|
+
__version__,
|
|
149
|
+
("fastapi", ("rawpy (DNG decoding)", "rawpy"), cli.Module("ultralytics", optional=True)),
|
|
150
|
+
checks=[cli.Check("ffmpeg", cli.program("ffmpeg", "apt install ffmpeg")), cli.Check("gpu", gpu_check)],
|
|
151
|
+
hint="uv sync (scripts/setup_env)",
|
|
152
|
+
)
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
A check returns `(status, text)` with status `ok`, `missing`, `slow` (works, but not as it should; never fails) or `broken`, and an exception counts as `broken`. Doctor exits 1 when a required module or check is missing or broken. A check that may be missing without that being a fault is `Check(..., optional=True)`.
|
|
156
|
+
|
|
157
|
+
### 5b. The strata-models client (apps that use the model service)
|
|
158
|
+
|
|
159
|
+
Drop the `strata-models-client` path or git dependency and change the import. The functions, their arguments and the exceptions are the same:
|
|
160
|
+
|
|
161
|
+
```python
|
|
162
|
+
from strata_python.clients import models as sm # was: import strata_models_client as sm
|
|
163
|
+
|
|
164
|
+
page = sm.OcrPage.from_json(sm.ocr("/path/page.png", app="strata-scan")) # typed: page.lines[0].words[0].box
|
|
165
|
+
talk = sm.Transcript.from_json(sm.transcribe("/path/talk.wav", app="strata-360"))
|
|
166
|
+
with sm.gpu_lease("strata-stills", vram_gb=4):
|
|
167
|
+
run_my_own_cuda_code()
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
The shortcuts still return the service's JSON, so existing code keeps working, and the result classes keep all of it in `.raw`. There is one shortcut for every role the service runs (`sm.ROLES`): `faces`, `face_kind`, `transcribe` (also `role="transcribe-fast"`), `ocr`, `speak`, `denoise_audio`, `audio_quality`, `generate_image`, `embed` and `enhance_video`, plus `ask` for the language-model roles (`vision-language`, `text`, and the judges). Each has a result class (`Answer`, `GeneratedImage`, `Embeddings`, `FaceKinds`, `CleanAudio`, `AudioQuality`, `EnhancedVideo` and the four above). The roles `models.toml` lists without a runtime yet (sound-events, speaker-embedding, detect-people, upscale, denoise, nsfw) have none: `run(role, params, app)` reaches them once the service serves them.
|
|
171
|
+
|
|
127
172
|
### 6. OS helpers
|
|
128
173
|
|
|
129
|
-
Delete the app's `oslib.py` and import from `strata_python.oslib`: `file_lock(f)`, `pid_alive(pid)`, `kill_tree(pid, sig)`, `lower_priority(nice)
|
|
174
|
+
Delete the app's `oslib.py` and import from `strata_python.oslib`: `file_lock(f)`, `pid_alive(pid)`, `kill_tree(pid, sig)`, `lower_priority(nice, io=False)` (`io=True` for idle disk priority too; drop the app's `ionice` helper), `venv_python(venv)` and `cli_command(module)`. `cli_command` now takes the module name (`cli_command("myapp")`). Local `alive(pid)`, `_alive` and `lower_priority()` copies go too. Helpers this library does not have yet (process-group supervision, load average) stay in the app until they move here, and the app's file says so.
|
|
130
175
|
|
|
131
176
|
### 7. Tests
|
|
132
177
|
|
|
@@ -202,11 +247,22 @@ migrations = "migrations" # the app's Alembic revisions, unchanged
|
|
|
202
247
|
# engine = "postgres" # only for an app that uses Postgres-only features
|
|
203
248
|
```
|
|
204
249
|
|
|
205
|
-
- Imports: the old package's names come from `strata_python.db` (`connect`, `session`, `
|
|
250
|
+
- Imports: the old package's names come from `strata_python.db` (`connect`, `session`, `NAMING_CONVENTION`, `Project`, `upgrade`, `drift`, `check_migrations`, `LiveDatabaseRefused`); the standard tests from `strata_python.db.testing`. The naming convention is byte-identical, so existing revisions and databases do not drift.
|
|
251
|
+
- Models: write the base class out, not `Base = make_base()`, which ty rejects as a base (`unsupported-base`) and so fails the gate:
|
|
252
|
+
|
|
253
|
+
```python
|
|
254
|
+
from sqlalchemy import MetaData
|
|
255
|
+
from sqlalchemy.orm import DeclarativeBase, MappedAsDataclass
|
|
256
|
+
from strata_python.db import NAMING_CONVENTION
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
class Base(MappedAsDataclass, DeclarativeBase):
|
|
260
|
+
metadata = MetaData(naming_convention=NAMING_CONVENTION)
|
|
261
|
+
```
|
|
206
262
|
- 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`.
|
|
207
263
|
- 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`).
|
|
208
264
|
- At service start (only there): `Project.load(__file__).upgrade(connect("myapp"))`.
|
|
209
|
-
- Tests: the plugin is registered with every install and does nothing until the extra is
|
|
265
|
+
- 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:
|
|
210
266
|
|
|
211
267
|
```python
|
|
212
268
|
# tests/unit/test_database.py
|
|
@@ -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.2" # 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"
|
|
@@ -55,6 +55,13 @@ db = [
|
|
|
55
55
|
"alembic>=1.13,<2",
|
|
56
56
|
"psycopg[binary]>=3.2,<4",
|
|
57
57
|
]
|
|
58
|
+
# strata_python.pages: a scanned page's description drawn as a PDF with real text, rasterised back for scoring, and the
|
|
59
|
+
# text read back. ReportLab (BSD) writes and pdfium (BSD/Apache) reads: no AGPL library, since this package is MIT.
|
|
60
|
+
pdf = [
|
|
61
|
+
"reportlab>=4.2,<6",
|
|
62
|
+
"pypdfium2>=4.30,<6",
|
|
63
|
+
"pillow>=10,<14",
|
|
64
|
+
]
|
|
58
65
|
|
|
59
66
|
[project.urls]
|
|
60
67
|
Homepage = "https://github.com/jburnhams/strata-python"
|
|
@@ -68,10 +75,10 @@ strata-db = "strata_python.db.cli:main"
|
|
|
68
75
|
|
|
69
76
|
[project.entry-points.pytest11]
|
|
70
77
|
strata_python = "strata_python.pytest_plugin"
|
|
71
|
-
strata_python_db = "strata_python.db.pytest_plugin" # inert unless the db extra is installed
|
|
78
|
+
strata_python_db = "strata_python.db.pytest_plugin" # inert unless the db extra is installed and the project has [tool.strata-db]
|
|
72
79
|
|
|
73
80
|
[dependency-groups]
|
|
74
|
-
dev = ["strata-python[dev,db]"] # the same tools the apps get, and the db
|
|
81
|
+
dev = ["strata-python[dev,db,pdf]"] # the same tools the apps get, and the db and pdf extras so their tests run
|
|
75
82
|
|
|
76
83
|
[tool.hatch.build.targets.wheel]
|
|
77
84
|
packages = ["src/strata_python"]
|
|
@@ -87,6 +94,7 @@ testpaths = ["tests/unit"]
|
|
|
87
94
|
addopts = "-ra --timeout=300 --strict-markers --strict-config -p pytester -p no:strata_python -p no:strata_python_db"
|
|
88
95
|
strata_env_prefix = "DEMO"
|
|
89
96
|
strata_tuning_vars = ["DEMO_TUNE"]
|
|
97
|
+
strata_db = true # this repo has no [tool.strata-db] of its own; its tests need the db plugin and guard on
|
|
90
98
|
markers = ["integration: runs a real server or subprocess end-to-end (tests/integration)"]
|
|
91
99
|
|
|
92
100
|
[tool.coverage.run]
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""The CLI commands every app has, added to the app's own argparse subparsers.
|
|
2
|
+
|
|
3
|
+
sub = parser.add_subparsers(dest="cmd", required=True)
|
|
4
|
+
add_doctor(sub, "myapp", __version__, ("fastapi", ("opencv", "cv2"), Module("ultralytics", optional=True)),
|
|
5
|
+
checks=[Check("ffmpeg", program("ffmpeg"))])
|
|
6
|
+
add_set(sub, SETTINGS)
|
|
7
|
+
add_serve(sub, lambda host, port: web.serve(create_app(), ["--host", host, "--port", str(port)]), default_port=8360)
|
|
8
|
+
args = parser.parse_args(argv); return args.fn(args)
|
|
9
|
+
|
|
10
|
+
Each command sets `fn` on its parser; the handler returns the exit code."""
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import importlib
|
|
14
|
+
import shutil
|
|
15
|
+
import sys
|
|
16
|
+
from collections.abc import Callable, Iterable
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from typing import Any, Literal
|
|
19
|
+
|
|
20
|
+
from strata_python.settings import Settings
|
|
21
|
+
|
|
22
|
+
Sub = Any # argparse's subparsers object is a private generic type; only add_parser is used
|
|
23
|
+
|
|
24
|
+
Status = Literal["ok", "missing", "slow", "broken"]
|
|
25
|
+
"""A doctor row: `ok`; `missing` (not installed or not found); `slow` (works, but not as it should: a CPU fallback,
|
|
26
|
+
cuDNN off), which never fails the run; `broken` (there, but does not work)."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class Module:
|
|
31
|
+
"""A module `doctor` imports: `label` is what a person recognises ("rawpy (DNG decoding)"), `module` the import
|
|
32
|
+
name (default: the label). An `optional` one that is missing is shown with the hint but does not fail the run."""
|
|
33
|
+
|
|
34
|
+
label: str
|
|
35
|
+
module: str = ""
|
|
36
|
+
optional: bool = False
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def name(self) -> str:
|
|
40
|
+
return self.module or self.label
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class Check:
|
|
45
|
+
"""What an import cannot tell (a program on the PATH, whether the GPU runs a kernel): `fn` returns a status and a
|
|
46
|
+
line of text. `missing` or `broken` fails the run unless the check is `optional`; an exception counts as
|
|
47
|
+
`broken`, with the exception as its text."""
|
|
48
|
+
|
|
49
|
+
label: str
|
|
50
|
+
fn: Callable[[], tuple[Status, str]]
|
|
51
|
+
optional: bool = False
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def program(name: str, hint: str = "") -> Callable[[], tuple[Status, str]]:
|
|
55
|
+
"""A check function for a program on the PATH (`ffmpeg`, `exiftool`): `ok` with its path, else `missing`."""
|
|
56
|
+
|
|
57
|
+
def check() -> tuple[Status, str]:
|
|
58
|
+
found = shutil.which(name)
|
|
59
|
+
return ("ok", found) if found else ("missing", hint or "not on the PATH")
|
|
60
|
+
|
|
61
|
+
return check
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _row(status: Status, label: str, text: str, fails: bool) -> str:
|
|
65
|
+
word = status.upper() if fails else status # failing rows shout, so they are found in a long list
|
|
66
|
+
return f" {word:<9}{label}{': ' if text and status != 'ok' else ' '}{text}".rstrip()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def doctor(
|
|
70
|
+
name: str,
|
|
71
|
+
version: str,
|
|
72
|
+
imports: Iterable[str | tuple[str, str] | Module],
|
|
73
|
+
*,
|
|
74
|
+
checks: Iterable[Check] = (),
|
|
75
|
+
hint: str = "uv sync",
|
|
76
|
+
) -> int:
|
|
77
|
+
"""Print the app and Python versions, then one row per module and per check, in the same columns for every app.
|
|
78
|
+
Returns 1 when a required module is missing or a required check is missing or broken, else 0."""
|
|
79
|
+
ok = True
|
|
80
|
+
print(f"{name} {version}, python {sys.version.split()[0]}")
|
|
81
|
+
for item in imports:
|
|
82
|
+
mod = Module(item) if isinstance(item, str) else Module(*item) if isinstance(item, tuple) else item
|
|
83
|
+
try:
|
|
84
|
+
m = importlib.import_module(mod.name)
|
|
85
|
+
print(_row("ok", mod.label, str(getattr(m, "__version__", "")), False))
|
|
86
|
+
except ImportError:
|
|
87
|
+
ok = ok and mod.optional
|
|
88
|
+
print(_row("missing", mod.label, hint, not mod.optional))
|
|
89
|
+
for check in checks:
|
|
90
|
+
try:
|
|
91
|
+
status, text = check.fn()
|
|
92
|
+
except Exception as e: # a check that crashes is a broken row, not a crashed doctor
|
|
93
|
+
status, text = "broken", f"{type(e).__name__}: {e}"
|
|
94
|
+
fails = status in ("missing", "broken") and not check.optional
|
|
95
|
+
ok = ok and not fails
|
|
96
|
+
print(_row(status, check.label, text, fails))
|
|
97
|
+
return 0 if ok else 1
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def add_doctor(
|
|
101
|
+
sub: Sub,
|
|
102
|
+
name: str,
|
|
103
|
+
version: str,
|
|
104
|
+
imports: Iterable[str | tuple[str, str] | Module],
|
|
105
|
+
*,
|
|
106
|
+
checks: Iterable[Check] = (),
|
|
107
|
+
hint: str = "uv sync",
|
|
108
|
+
) -> None:
|
|
109
|
+
"""`doctor`: the app and Python versions, whether each module in `imports` can be imported (a name, a
|
|
110
|
+
`(label, module)` pair or a `Module`), then each of the app's `checks`; `hint` is what a missing module says to
|
|
111
|
+
run. Exit 1 if a required module or check fails (see `doctor`)."""
|
|
112
|
+
mods, chks = tuple(imports), tuple(checks)
|
|
113
|
+
|
|
114
|
+
def cmd_doctor(_args: argparse.Namespace) -> int:
|
|
115
|
+
return doctor(name, version, mods, checks=chks, hint=hint)
|
|
116
|
+
|
|
117
|
+
sub.add_parser("doctor", help="check the environment").set_defaults(fn=cmd_doctor)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def add_set(sub: Sub, settings: Settings) -> None:
|
|
121
|
+
"""`set KEY [VALUE]`: show a setting, change it, or reset it with the value `default`. A bad key or value exits with the message."""
|
|
122
|
+
|
|
123
|
+
def cmd_set(args: argparse.Namespace) -> int:
|
|
124
|
+
if args.key not in settings.keys:
|
|
125
|
+
sys.exit(f"unknown setting {args.key!r} (known: {', '.join(settings.keys)})")
|
|
126
|
+
if args.value is not None:
|
|
127
|
+
try:
|
|
128
|
+
settings.save({args.key: None if args.value == "default" else args.value})
|
|
129
|
+
except ValueError as e:
|
|
130
|
+
sys.exit(str(e))
|
|
131
|
+
print(f"{args.key} = {settings.get(args.key)}")
|
|
132
|
+
return 0
|
|
133
|
+
|
|
134
|
+
p = sub.add_parser("set", help=f'show or change a setting ({", ".join(settings.keys)}); value "default" resets it')
|
|
135
|
+
p.add_argument("key")
|
|
136
|
+
p.add_argument("value", nargs="?")
|
|
137
|
+
p.set_defaults(fn=cmd_set)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def add_serve(sub: Sub, run: Callable[[str, int], None], *, default_port: int) -> None:
|
|
141
|
+
"""`serve [--host] [--port]`: call `run(host, port)`."""
|
|
142
|
+
|
|
143
|
+
def cmd_serve(args: argparse.Namespace) -> int:
|
|
144
|
+
run(args.host, args.port)
|
|
145
|
+
return 0
|
|
146
|
+
|
|
147
|
+
p = sub.add_parser("serve", help="start the web server")
|
|
148
|
+
p.add_argument("--host", default="127.0.0.1")
|
|
149
|
+
p.add_argument("--port", type=int, default=default_port)
|
|
150
|
+
p.set_defaults(fn=cmd_serve)
|