strata-python 0.2.1__py3-none-any.whl → 0.2.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
strata_python/settings.py CHANGED
@@ -3,21 +3,30 @@
3
3
  An app declares its settings once (`Setting`: key, default, optional normaliser) and gets the file handling, the override order and the validation:
4
4
 
5
5
  SETTINGS = Settings("myapp", [Setting("data_dir", default=lambda: "/srv/data", normalise=absolute_path),
6
- Setting("greeting", default="Hello", normalise=non_empty)])
6
+ Setting("greeting", default="Hello", normalise=non_empty),
7
+ Setting("workers", default="2", normalise=whole_between(1, 16)),
8
+ ListSetting("source_roots", item=absolute_path)])
7
9
  SETTINGS.get("greeting") # MYAPP_GREETING, else the file, else the default
10
+ SETTINGS.get_int("workers") # typed getters: get_int, get_float, get_bool, get_list
8
11
  SETTINGS.save({"greeting": "Hi"}) # validated, written atomically; None resets to the default
9
12
 
10
- Order of precedence: environment variable (`<APP>_<KEY>`, upper-cased, or the name given), then the file, then the default. The folder holding the file is `~/.<app>`, moved
13
+ Order of precedence: environment variable (`<APP>_<KEY>`, upper-cased, or the name given), then the store, then the default. The folder holding the file is `~/.<app>`, moved
11
14
  with `<APP>_HOME`. A stored or environment value that fails its normaliser is ignored (the default applies) rather than crashing the app at start; only `save` raises.
12
- Values are strings: the file is edited by hand as well as by the app."""
15
+ Values are canonical strings (a normaliser returns the one spelling it accepts), and lists of them: the file is edited by hand as well as by the app.
13
16
 
17
+ Where the values live is a `SettingsStore`: the JSON file by default; `Settings.bind(store)` moves an app onto another one at run time (its database's `settings` table,
18
+ `strata_python.db.settings.TableStore`), copying the file's values in once. The CLI and tests without a database keep the file."""
19
+
20
+ import datetime
14
21
  import json
22
+ import math
15
23
  import os
24
+ import re
16
25
  import tempfile
17
26
  import threading
18
27
  from collections.abc import Callable, Mapping, Sequence
19
28
  from dataclasses import dataclass
20
- from typing import Any, cast
29
+ from typing import Any, Protocol, cast
21
30
 
22
31
  from strata_python.oslib import file_lock
23
32
 
@@ -38,6 +47,73 @@ def absolute_path(value: str) -> str:
38
47
  return os.path.abspath(p)
39
48
 
40
49
 
50
+ def number_between(lo: float, hi: float) -> Callable[[str], str]:
51
+ """Normaliser: a finite number from `lo` to `hi` (GB of memory, a budget in dollars), written the shortest way (`"8"`, `"8.5"`)."""
52
+
53
+ def normalise(value: str) -> str:
54
+ try:
55
+ x = float(value.strip())
56
+ except ValueError:
57
+ raise ValueError("must be a number") from None
58
+ if not math.isfinite(x) or not lo <= x <= hi:
59
+ raise ValueError(f"must be a number from {_num(lo)} to {_num(hi)}")
60
+ return _num(x)
61
+
62
+ return normalise
63
+
64
+
65
+ def whole_between(lo: int, hi: int) -> Callable[[str], str]:
66
+ """Normaliser: a whole number from `lo` to `hi` (job slots, a port)."""
67
+
68
+ def normalise(value: str) -> str:
69
+ try:
70
+ x = int(value.strip())
71
+ except ValueError:
72
+ raise ValueError("must be a whole number") from None
73
+ if not lo <= x <= hi:
74
+ raise ValueError(f"must be a whole number from {lo} to {hi}")
75
+ return str(x)
76
+
77
+ return normalise
78
+
79
+
80
+ _DATE = re.compile(r"\d{4}-\d{2}-\d{2}")
81
+
82
+
83
+ def iso_date(allow_blank: bool = True) -> Callable[[str], str]:
84
+ """Normaliser: a `YYYY-MM-DD` date; with `allow_blank`, `""` is a value too (no date: the setting is cleared but not reset)."""
85
+
86
+ def normalise(value: str) -> str:
87
+ v = value.strip()
88
+ if not v and allow_blank:
89
+ return ""
90
+ try:
91
+ if not _DATE.fullmatch(v):
92
+ raise ValueError
93
+ return datetime.date.fromisoformat(v).isoformat()
94
+ except ValueError:
95
+ raise ValueError("must be a date, YYYY-MM-DD") from None
96
+
97
+ return normalise
98
+
99
+
100
+ _TRUE, _FALSE = {"1", "true", "yes", "on"}, {"0", "false", "no", "off"}
101
+
102
+
103
+ def boolean(value: str) -> str:
104
+ """Normaliser: `true` or `false` (also accepts 1/0, yes/no, on/off, in any case)."""
105
+ v = value.strip().lower()
106
+ if v in _TRUE:
107
+ return "true"
108
+ if v in _FALSE:
109
+ return "false"
110
+ raise ValueError("must be true or false")
111
+
112
+
113
+ def _num(x: float) -> str:
114
+ return str(int(x)) if float(x).is_integer() and abs(x) < 1e15 else repr(float(x))
115
+
116
+
41
117
  def _identity(value: str) -> str:
42
118
  return value
43
119
 
@@ -53,15 +129,117 @@ class Setting:
53
129
  d = self.default
54
130
  return d if isinstance(d, str) else d()
55
131
 
132
+ def parse(self, raw: object) -> str:
133
+ """A stored, environment or saved value as its canonical string; ValueError when it is not acceptable."""
134
+ if not isinstance(raw, str):
135
+ raise ValueError("must be text") # str(5) would pass a hand-edited number off as a deliberate string
136
+ return self.normalise(raw)
137
+
138
+
139
+ def _no_list() -> list[str]:
140
+ return []
141
+
142
+
143
+ @dataclass(frozen=True)
144
+ class ListSetting:
145
+ """A setting that is a list of strings (folders to scan, names to enable). The file holds a JSON list (a string there is split, so hand edits work); the
146
+ environment value is split on `sep` (`os.pathsep` by default, for folders; give `sep=","` for names). `item` normalises each entry, and blank entries are
147
+ dropped. `get_list` returns the list and `all()` (so GET /api/settings) the list as JSON; `get` and `strata set` show it joined by `sep`, and `save` takes a
148
+ list or a joined string."""
149
+
150
+ key: str
151
+ default: Sequence[str] | Callable[[], Sequence[str]] = _no_list
152
+ item: Callable[[str], str] = _identity
153
+ sep: str = os.pathsep
154
+ env: str | None = None
155
+
156
+ def default_value(self) -> list[str]:
157
+ d = self.default
158
+ return list(cast("Sequence[str]", d) if isinstance(d, Sequence) else d())
159
+
160
+ def parse(self, raw: object) -> list[str]:
161
+ if isinstance(raw, str):
162
+ items: list[object] = list(raw.split(self.sep))
163
+ elif isinstance(raw, list | tuple):
164
+ items = list(cast("Sequence[object]", raw))
165
+ else:
166
+ raise ValueError("must be a list")
167
+ out: list[str] = []
168
+ for i in items:
169
+ if not isinstance(i, str):
170
+ raise ValueError("must be a list of text")
171
+ if i.strip():
172
+ out.append(self.item(i.strip()))
173
+ return out
174
+
175
+
176
+ AnySetting = Setting | ListSetting
177
+ Value = str | list[str]
178
+
179
+ IMPORTED = "_imported_from_file" # the marker bind() leaves in a store it copied the file into; not a setting
180
+
181
+
182
+ class SettingsStore(Protocol):
183
+ """Where the values live. `load` returns every stored value; `update` applies changes (already validated; None removes a key) as one atomic step, so two
184
+ saves of different keys never lose one, and returns what is stored afterwards."""
185
+
186
+ def load(self) -> dict[str, object]: ...
187
+
188
+ def update(self, changes: Mapping[str, object]) -> dict[str, object]: ...
189
+
190
+
191
+ class JsonFileStore:
192
+ """The default store: one JSON object in a file, written atomically under a lock (across threads and processes). `path` is called each time, so a
193
+ variable that moves the folder (`<APP>_HOME`) takes effect without a restart."""
194
+
195
+ def __init__(self, path: str | Callable[[], str]) -> None:
196
+ self._path = path
197
+ self._thread_lock = threading.Lock() # file_lock alone does not exclude threads on every platform
198
+
199
+ def path(self) -> str:
200
+ p = self._path
201
+ return p if isinstance(p, str) else p()
202
+
203
+ def load(self) -> dict[str, object]:
204
+ """The file's contents ({} when it is missing, unreadable or not a JSON object)."""
205
+ try:
206
+ with open(self.path(), encoding="utf8") as f:
207
+ d = json.load(f)
208
+ except (OSError, ValueError):
209
+ return {}
210
+ return cast("dict[str, object]", d) if isinstance(d, dict) else {}
211
+
212
+ def update(self, changes: Mapping[str, object]) -> dict[str, object]:
213
+ path = self.path()
214
+ folder = os.path.dirname(path)
215
+ os.makedirs(folder, exist_ok=True)
216
+ # The whole read-merge-write is one critical section, across threads (the server's PUT handlers run in a pool) and processes (the CLI `set` beside a running server);
217
+ # otherwise two saves of different keys lose one update.
218
+ with self._thread_lock, open(path + ".lock", "a+") as lock, file_lock(lock):
219
+ d = self.load()
220
+ for k, v in changes.items():
221
+ if v is None:
222
+ d.pop(k, None)
223
+ else:
224
+ d[k] = v
225
+ fd, tmp = tempfile.mkstemp(dir=folder, prefix="settings.", suffix=".tmp")
226
+ with os.fdopen(fd, "w", encoding="utf8") as f:
227
+ json.dump(d, f, indent=1)
228
+ os.replace(tmp, path) # atomic: a reader never sees half a file
229
+ return d
230
+
56
231
 
57
232
  class Settings:
58
- def __init__(self, app: str, settings: Sequence[Setting], *, prefix: str | None = None) -> None:
233
+ def __init__(
234
+ self, app: str, settings: Sequence[AnySetting], *, prefix: str | None = None, store: SettingsStore | None = None
235
+ ) -> None:
59
236
  """`prefix` names the environment variables (`<PREFIX>_HOME`, `<PREFIX>_<KEY>`); default the upper-cased app name with `-` as `_`.
60
- Give it when an app's variables already have a short form that deployed services use."""
237
+ Give it when an app's variables already have a short form that deployed services use. `store` is where values live (default: the JSON file)."""
61
238
  self.app = app
62
239
  self.prefix = prefix or app.upper().replace("-", "_")
63
- self._by_key = {s.key: s for s in settings}
64
- self._thread_lock = threading.Lock() # file_lock alone does not exclude threads on every platform
240
+ self._by_key: dict[str, AnySetting] = {s.key: s for s in settings}
241
+ self.file = JsonFileStore(self.path)
242
+ self.store: SettingsStore = store or self.file
65
243
 
66
244
  @property
67
245
  def keys(self) -> tuple[str, ...]:
@@ -77,53 +255,76 @@ class Settings:
77
255
  def env_name(self, key: str) -> str:
78
256
  return self._by_key[key].env or f"{self.prefix}_{key.upper()}"
79
257
 
258
+ def bind(self, store: SettingsStore, *, import_file: bool = True) -> None:
259
+ """Keep the values in `store` from now on. The first time a store is bound (it has no import marker), the file's valid values are copied into it,
260
+ with the marker, so moving an app onto its database keeps what its people set. Two processes binding a new store at once both copy the same values."""
261
+ if import_file and IMPORTED not in store.load():
262
+ values: dict[str, object] = {}
263
+ for k, raw in self.file.load().items():
264
+ s = self._by_key.get(k)
265
+ if s is not None:
266
+ try:
267
+ values[k] = s.parse(raw)
268
+ except ValueError:
269
+ continue # a bad value would be ignored by get() too; it is not carried over
270
+ store.update({**values, IMPORTED: self.file.path()})
271
+ self.store = store
272
+
80
273
  def load(self) -> dict[str, Any]:
81
- """The raw file contents ({} when it is missing, unreadable or not a JSON object)."""
82
- try:
83
- with open(self.path(), encoding="utf8") as f:
84
- d = json.load(f)
85
- except (OSError, ValueError):
86
- return {}
87
- return cast("dict[str, Any]", d) if isinstance(d, dict) else {}
274
+ """The raw stored values (for the file: its contents; {} when it is missing, unreadable or not a JSON object)."""
275
+ return self.store.load()
88
276
 
89
277
  def save(self, changes: Mapping[str, object]) -> dict[str, Any]:
90
- """Merge `changes` into the file and return the saved contents. Unknown keys raise KeyError, a value its normaliser refuses raises ValueError
91
- (naming the key), and None removes the setting. All changes are checked before any is written."""
278
+ """Merge `changes` into the store and return what is stored. Unknown keys raise KeyError, a value its normaliser refuses raises ValueError
279
+ (naming the key), and None removes the setting. All changes are checked before any is written. A list setting takes a list or a joined string."""
92
280
  for k in changes:
93
281
  if k not in self._by_key:
94
282
  raise KeyError(f"unknown setting {k!r}")
95
- os.makedirs(self.home(), exist_ok=True)
96
- # The whole read-merge-write is one critical section, across threads (the server's PUT handlers run in a pool) and processes (the CLI `set` beside a running server);
97
- # otherwise two saves of different keys lose one update.
98
- with self._thread_lock, open(self.path() + ".lock", "a+") as lock, file_lock(lock):
99
- d = self.load()
100
- for k, v in changes.items():
101
- if v is None:
102
- d.pop(k, None)
103
- continue
104
- try:
105
- d[k] = self._by_key[k].normalise(str(v))
106
- except ValueError as e:
107
- raise ValueError(f"{k}: {e}") from e
108
- fd, tmp = tempfile.mkstemp(dir=self.home(), prefix="settings.", suffix=".tmp")
109
- with os.fdopen(fd, "w", encoding="utf8") as f:
110
- json.dump(d, f, indent=1)
111
- os.replace(tmp, self.path()) # atomic: a reader never sees half a file
112
- return d
283
+ clean: dict[str, object] = {}
284
+ for k, v in changes.items():
285
+ s = self._by_key[k]
286
+ try:
287
+ clean[k] = (
288
+ None if v is None else s.parse(v if isinstance(s, ListSetting) or isinstance(v, str) else str(v))
289
+ )
290
+ except ValueError as e:
291
+ raise ValueError(f"{k}: {e}") from e
292
+ return self.store.update(clean)
113
293
 
114
- def get(self, key: str) -> str:
294
+ def value(self, key: str) -> Value:
295
+ """The setting's value: a string, or a list of strings for a `ListSetting`."""
115
296
  s = self._by_key[key]
116
- stored = self.load().get(key)
117
- for raw in (os.environ.get(self.env_name(key)), stored if isinstance(stored, str) else None):
297
+ for raw in (os.environ.get(self.env_name(key)), self.load().get(key)):
118
298
  if raw is not None: # "" is a value; the normaliser decides whether it is acceptable
119
299
  try:
120
- return s.normalise(raw)
300
+ return s.parse(raw)
121
301
  except ValueError:
122
302
  continue
123
- return s.normalise(s.default_value())
303
+ return s.parse(s.default_value())
304
+
305
+ def get(self, key: str) -> str:
306
+ """The value as a string (a list setting joined by its separator)."""
307
+ v = self.value(key)
308
+ s = self._by_key[key]
309
+ return s.sep.join(v) if isinstance(s, ListSetting) and isinstance(v, list) else cast("str", v)
310
+
311
+ def get_list(self, key: str) -> list[str]:
312
+ s = self._by_key[key]
313
+ if not isinstance(s, ListSetting):
314
+ raise TypeError(f"{key!r} is not a ListSetting")
315
+ return cast("list[str]", self.value(key))
316
+
317
+ def get_int(self, key: str) -> int:
318
+ return int(self.get(key))
319
+
320
+ def get_float(self, key: str) -> float:
321
+ return float(self.get(key))
322
+
323
+ def get_bool(self, key: str) -> bool:
324
+ return boolean(self.get(key)) == "true"
124
325
 
125
- def all(self) -> dict[str, str]:
126
- return {k: self.get(k) for k in self._by_key}
326
+ def all(self) -> dict[str, Value]:
327
+ return {k: self.value(k) for k in self._by_key}
127
328
 
128
329
  def folder(self, key: str) -> str:
129
330
  """The setting `key` as a folder that exists (created when asked for)."""
strata_python/web.py CHANGED
@@ -10,7 +10,7 @@ assets are relative (Vite `base: './'`)."""
10
10
 
11
11
  import argparse
12
12
  import os
13
- from collections.abc import Sequence
13
+ from collections.abc import Callable, Mapping, Sequence
14
14
 
15
15
  import uvicorn
16
16
  from fastapi import FastAPI, HTTPException
@@ -36,8 +36,17 @@ def static_file(static: str, path: str) -> str | None:
36
36
  return full if os.path.dirname(full) == root and os.path.isfile(full) else None
37
37
 
38
38
 
39
- def base_app(title: str, version: str, settings: Settings | None = None, *, docs: bool = True) -> FastAPI:
40
- """A FastAPI app with `GET /api/health` and, given settings, `GET`/`PUT /api/settings` (a PUT with an unknown key or a value that fails validation is a 400 and changes nothing)."""
39
+ def base_app(
40
+ title: str,
41
+ version: str,
42
+ settings: Settings | None = None,
43
+ *,
44
+ docs: bool = True,
45
+ health: Callable[[], Mapping[str, object]] | None = None,
46
+ ) -> FastAPI:
47
+ """A FastAPI app with `GET /api/health` and, given settings, `GET`/`PUT /api/settings` (a PUT with an unknown key or a value that fails validation is a 400 and changes nothing).
48
+ `health` adds the app's own fields to the health response after `ok` and `version` (strata-models' `gpu`); it is called on every request, so keep it cheap,
49
+ and it may set `ok` to false for a service that is up but cannot do its work."""
41
50
  app = FastAPI(
42
51
  title=title,
43
52
  docs_url="/api/docs" if docs else None,
@@ -46,16 +55,16 @@ def base_app(title: str, version: str, settings: Settings | None = None, *, docs
46
55
 
47
56
  @app.get("/api/health")
48
57
  def get_health() -> dict[str, object]: # pyright: ignore[reportUnusedFunction]
49
- return {"ok": True, "version": version}
58
+ return {"ok": True, "version": version, **(health() if health else {})}
50
59
 
51
60
  if settings is not None:
52
61
 
53
62
  @app.get("/api/settings")
54
- def get_settings() -> dict[str, str]: # pyright: ignore[reportUnusedFunction]
63
+ def get_settings() -> dict[str, str | list[str]]: # pyright: ignore[reportUnusedFunction]
55
64
  return settings.all()
56
65
 
57
66
  @app.put("/api/settings")
58
- def put_settings(changes: dict[str, str | None]) -> dict[str, str]: # pyright: ignore[reportUnusedFunction]
67
+ def put_settings(changes: dict[str, str | list[str] | None]) -> dict[str, str | list[str]]: # pyright: ignore[reportUnusedFunction]
59
68
  try:
60
69
  settings.save(changes)
61
70
  except (KeyError, ValueError) as e:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: strata-python
3
- Version: 0.2.1
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`, `add_set`, `add_serve` for the app's argparse subcommands |
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), `make_base()` 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`) |
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", # ~/.myapp/settings.json, moved with MYAPP_HOME
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", # only if the app already runs with other variable names
130
+ prefix="MYAPP", # only if the app already runs with other variable names
123
131
  )
124
132
 
125
- SETTINGS.get("greeting") # MYAPP_GREETING, else the file, else the default
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") # the value as a folder, created if missing
135
+ SETTINGS.folder("data_dir") # the value as a folder, created if missing
128
136
  ```
129
137
 
130
- Values are strings today. An app with int, float or list settings converts at the point of use (`int(SETTINGS.get("workers"))`, `SETTINGS.get("roots").split(os.pathsep)`) until typed settings land here.
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. A route whose reply needs more than `{ok, version}` adds its own route beside them.
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) # myapp set KEY [VALUE|default]
160
- cli.add_serve(sub, lambda host, port: web.serve(create_app(), ["--host", host, "--port", str(port)]), default_port=8000)
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)`, `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.
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`, `make_base`, `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.
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 there. 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` 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:
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
@@ -1,32 +1,38 @@
1
1
  strata_python/__init__.py,sha256=R8RMrmyXpaCez3TMEsuKoPxCR0cQxFZxgHf-UVPymSg,1321
2
2
  strata_python/check.py,sha256=lFjXuPjVIWn6dBu2yMKIW-76RloUREijuMHCRsBW4Z8,2932
3
- strata_python/cli.py,sha256=Vdqq2S2BJpGR3zjyRxqSZX9k65ecWL2SV5Zb7aVqUMY,2856
3
+ strata_python/cli.py,sha256=KKcFNjLsNXygeSUvzbaznZ8sTTW1ADkgsovJcyd3Sjc,5991
4
4
  strata_python/http_server.py,sha256=64uYWy4zFxughOgtvkssGXMJDZ7jhRj1bxUIfnzte8w,4475
5
5
  strata_python/live.py,sha256=kNY6h6gMxBo9l78UoGUIWjcADeZi4eZuAEp0jqDowEE,1215
6
- strata_python/oslib.py,sha256=2YS8Yk5TFgRWNNB9aZQhJlFPZRU1PTW0s0AaTxbNN4g,4206
7
- strata_python/public_check.py,sha256=aCUSdKWakjTQ6Bx1Zx1nMy5YJBWVi3gB3J0dZsIcMtE,5808
6
+ strata_python/oslib.py,sha256=seDkRBgDEZYqcaZWOF0heGKDd93IHJI_nFPLmOeYcsA,6380
7
+ strata_python/public_check.py,sha256=A0JusSWnwXtaA3sKsRoa4ocM5MNx38Nc49-dymd__3Q,8398
8
8
  strata_python/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
9
  strata_python/pytest_plugin.py,sha256=vinyCpDC9KeM_NM37lTN6F1ou0pfHlsn4C3j0Y_4Fg8,6718
10
- strata_python/settings.py,sha256=DzzZr-h39lLTXhi078Ed3dl2BPjteTTChvKN-33kEdI,5888
10
+ strata_python/settings.py,sha256=9y0zGhmGsBoUaH4zkbQ6RETiH-oLL2IKlmhwml3AkCk,14108
11
11
  strata_python/testing.py,sha256=-4mread8_FHMkcGvbajGtRyoP88fyeG3pAh1LlVr_w4,10372
12
- strata_python/web.py,sha256=mhqW0-w0bbYG8O8dBQbKsU8unzKdvmhbsPayTdz4zYQ,5204
13
- strata_python/db/__init__.py,sha256=B1-hXSg9_mV6KdmcGSawib--E_0JzCHgux6mlPMELsY,3536
12
+ strata_python/web.py,sha256=7A2G7M0kPjeBr5Dfu6RMZqRX3JjWg0wJx8IeCT47Xcw,5618
13
+ strata_python/clients/__init__.py,sha256=xivuysmYG7rbCGProVNvdSs-h4xVFQsuqUY6EwzuJbk,182
14
+ strata_python/clients/models.py,sha256=rcIKizebN1BEWWpwwqUWBCZBq8zcnV2g7XO9StsLmW8,30146
15
+ strata_python/db/__init__.py,sha256=ELfBNyONSF9vfl-Tw0a-X0rT3w1h1O_t_QLz1ZQTEwo,3775
14
16
  strata_python/db/__main__.py,sha256=nHCtenRtjL_Ouig4FHh60dax2oILeVdoIIKrxXEc6Ss,106
15
17
  strata_python/db/cli.py,sha256=PCIh0QQuxOH9ybgtFr-8U1p5IY2E4EdOQF1RchKgXrw,9848
16
18
  strata_python/db/config.py,sha256=slUPAjWWBbqLhAxkrcCuPTqUCDhNxCSGkB1lyuYEG9c,3778
17
19
  strata_python/db/engine.py,sha256=PFLSeYqFrwQPVoyP1i5PUk-sZIgFc7qF3yvj9mgj3NA,1929
18
20
  strata_python/db/guard.py,sha256=HyRtDMRgTWFgT9D4gNomA18ErR1mqJbzJgtU7xAqBG8,6722
19
21
  strata_python/db/migrations.py,sha256=Hb77afQNjtKS2DD-zmen4BscbAx9DRjLHtcPOdzuaGo,12138
20
- strata_python/db/models.py,sha256=BtrZZFPV9fFaKAwLfvP8fQ1iIScD90OQe-NUmSfeTSA,2063
21
- strata_python/db/project.py,sha256=og6bzl05BL33a4sylyuhza5N-eAz6CsSj532rJ8W91E,3290
22
- strata_python/db/pytest_plugin.py,sha256=_M4QymlCq-Poaln6w62ykV4Zpb14krwrNnFxc2dIexE,6070
22
+ strata_python/db/models.py,sha256=bWg1xgn-VgDLnFe0Ps_2hiYD5fp-_8W8mCErATS3RQs,3005
23
+ strata_python/db/project.py,sha256=cG5ihJhz4OoOnGPJwmPTFEhaX2o4u-GQYg7Xd0jBAU8,3740
24
+ strata_python/db/pytest_plugin.py,sha256=opJb5AI8Dy8IYqkx6IcZV1KBeMB4DHmnaEKd36h_r9Q,8978
23
25
  strata_python/db/scratch.py,sha256=mlb4a1MTevhBS3WWIJOvUiyggLGeBR9NbXi8Jh8Rf2k,5059
26
+ strata_python/db/settings.py,sha256=sg1xDhqYhTzUx8_8-VKJBlpb1qRKKYhujJYZ8KeIbbY,2635
24
27
  strata_python/db/testing.py,sha256=U39cwmg_6Dp4XPyc1Z2NWVgSGI_Q93Y--78_7PgEwes,1979
25
28
  strata_python/db/testserver.py,sha256=I5__od7FEjNBcYYcJqmzLA_5t1wRqJ85NBukZMebS4Q,8806
26
29
  strata_python/db/_alembic/env.py,sha256=gXzRn02h59PB_1RaABkaT6GuyuzPQCZh3Z5ml2JlS34,1125
27
30
  strata_python/db/_alembic/script.py.mako,sha256=04kgeBtNMa4cCnG8CfQcKt6P6rnloIfj8wy0u_DBydM,704
28
- strata_python-0.2.1.dist-info/METADATA,sha256=q89wuzvLdc1kPZpDQMpAKYSJU4kq_vTiUXm_BZP_pzk,17808
29
- strata_python-0.2.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
30
- strata_python-0.2.1.dist-info/entry_points.txt,sha256=6RVv-uDumVQ-KY2YdvKwd5R3l6P9WQD4kPtPOKKEM-I,256
31
- strata_python-0.2.1.dist-info/licenses/LICENSE,sha256=9yVMCPoK7unONyTAiDYjMTt3MZPGJ639nWOwxyNsZGg,1066
32
- strata_python-0.2.1.dist-info/RECORD,,
31
+ strata_python/pages/__init__.py,sha256=6QsTqJbFiuLCxywt8C0D6nyXRXjpzI1Xoo5u6rK9toQ,665
32
+ strata_python/pages/model.py,sha256=8Skz3eishAZiNHIHzScI0g60wGpH6jZ3vNc0LpMZ4q4,9821
33
+ strata_python/pages/render.py,sha256=69317W03K0AVxGpelpzrNsnEP5y0oIp5aFodlnhckdE,11760
34
+ strata_python-0.2.2.dist-info/METADATA,sha256=lP9ckCGlC4IMVYlbL5mBGaWRRrtRJjCOMzBdyWP-t2o,23333
35
+ strata_python-0.2.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
36
+ strata_python-0.2.2.dist-info/entry_points.txt,sha256=6RVv-uDumVQ-KY2YdvKwd5R3l6P9WQD4kPtPOKKEM-I,256
37
+ strata_python-0.2.2.dist-info/licenses/LICENSE,sha256=9yVMCPoK7unONyTAiDYjMTt3MZPGJ639nWOwxyNsZGg,1066
38
+ strata_python-0.2.2.dist-info/RECORD,,