strata-python 0.2.5__py3-none-any.whl → 0.2.6__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/cli.py +45 -2
- strata_python/contracts.py +9 -0
- strata_python/db/__init__.py +7 -1
- strata_python/db/cli.py +23 -9
- strata_python/db/config.py +28 -4
- strata_python/db/engine.py +4 -0
- strata_python/db/project.py +58 -7
- strata_python/db/web.py +103 -0
- strata_python/public_check.py +122 -19
- strata_python/settings.py +99 -25
- strata_python/testing.py +13 -0
- strata_python/web.py +10 -1
- {strata_python-0.2.5.dist-info → strata_python-0.2.6.dist-info}/METADATA +27 -8
- {strata_python-0.2.5.dist-info → strata_python-0.2.6.dist-info}/RECORD +17 -16
- {strata_python-0.2.5.dist-info → strata_python-0.2.6.dist-info}/WHEEL +0 -0
- {strata_python-0.2.5.dist-info → strata_python-0.2.6.dist-info}/entry_points.txt +0 -0
- {strata_python-0.2.5.dist-info → strata_python-0.2.6.dist-info}/licenses/LICENSE +0 -0
strata_python/cli.py
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
checks=[Check("ffmpeg", program("ffmpeg"))])
|
|
6
6
|
add_set(sub, SETTINGS)
|
|
7
7
|
add_serve(sub, lambda host, port: web.serve(create_app(), ["--host", host, "--port", str(port)]), default_port=8360)
|
|
8
|
+
add_openapi(sub, create_app) # myapp openapi [-o web/openapi.json | -] [--check]
|
|
8
9
|
args = parser.parse_args(argv); return args.fn(args)
|
|
9
10
|
|
|
10
11
|
Each command sets `fn` on its parser; the handler returns the exit code."""
|
|
@@ -15,10 +16,14 @@ import shutil
|
|
|
15
16
|
import sys
|
|
16
17
|
from collections.abc import Callable, Iterable
|
|
17
18
|
from dataclasses import dataclass
|
|
18
|
-
from
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import TYPE_CHECKING, Any, Literal
|
|
19
21
|
|
|
20
22
|
from strata_python.settings import Settings
|
|
21
23
|
|
|
24
|
+
if TYPE_CHECKING:
|
|
25
|
+
from fastapi import FastAPI
|
|
26
|
+
|
|
22
27
|
Sub = Any # argparse's subparsers object is a private generic type; only add_parser is used
|
|
23
28
|
|
|
24
29
|
Status = Literal["ok", "missing", "slow", "broken"]
|
|
@@ -128,7 +133,8 @@ def add_set(sub: Sub, settings: Settings) -> None:
|
|
|
128
133
|
settings.save({args.key: None if args.value == "default" else args.value})
|
|
129
134
|
except ValueError as e:
|
|
130
135
|
sys.exit(str(e))
|
|
131
|
-
|
|
136
|
+
allowed = settings.allowed(args.key)
|
|
137
|
+
print(f"{args.key} = {settings.get(args.key)}" + (f" (one of: {', '.join(allowed)})" if allowed else ""))
|
|
132
138
|
return 0
|
|
133
139
|
|
|
134
140
|
p = sub.add_parser("set", help=f'show or change a setting ({", ".join(settings.keys)}); value "default" resets it')
|
|
@@ -148,3 +154,40 @@ def add_serve(sub: Sub, run: Callable[[str, int], None], *, default_port: int) -
|
|
|
148
154
|
p.add_argument("--host", default="127.0.0.1")
|
|
149
155
|
p.add_argument("--port", type=int, default=default_port)
|
|
150
156
|
p.set_defaults(fn=cmd_serve)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def add_openapi(sub: Sub, create_app: "Callable[[], FastAPI]", *, default: Path = Path("web/openapi.json")) -> None:
|
|
160
|
+
"""`openapi [-o PATH|-] [--check]`: write the app's schema (`web.openapi_text`) to `default`, another path or
|
|
161
|
+
stdout, for strata-react's `strata-api-types`, which reads the file so CI needs no server. `--check` writes
|
|
162
|
+
nothing and exits 1 when the file differs, so a Python-only CI job can gate it too. The app is built only when
|
|
163
|
+
the command runs, so `create_app` may be slow."""
|
|
164
|
+
|
|
165
|
+
def cmd_openapi(args: argparse.Namespace) -> int:
|
|
166
|
+
from strata_python import web # here, so the app's other commands do not import FastAPI
|
|
167
|
+
|
|
168
|
+
text = web.openapi_text(create_app())
|
|
169
|
+
out: str = args.output
|
|
170
|
+
if out == "-":
|
|
171
|
+
if args.check:
|
|
172
|
+
sys.exit("--check compares a file; give -o PATH")
|
|
173
|
+
sys.stdout.write(text)
|
|
174
|
+
return 0
|
|
175
|
+
path = Path(out)
|
|
176
|
+
if args.check:
|
|
177
|
+
current = path.read_text(encoding="utf-8") if path.is_file() else None
|
|
178
|
+
if current == text:
|
|
179
|
+
return 0
|
|
180
|
+
print(
|
|
181
|
+
f"{path} is {'missing' if current is None else 'out of date'}: run the openapi command", file=sys.stderr
|
|
182
|
+
)
|
|
183
|
+
return 1
|
|
184
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
185
|
+
with open(path, "w", encoding="utf-8", newline="\n") as f: # LF on Windows too, or the check never agrees
|
|
186
|
+
f.write(text)
|
|
187
|
+
print(f"wrote {path}")
|
|
188
|
+
return 0
|
|
189
|
+
|
|
190
|
+
p = sub.add_parser("openapi", help=f"write the API schema for the web app's types (default {default.as_posix()})")
|
|
191
|
+
p.add_argument("-o", "--output", default=str(default), help='file to write, or "-" for stdout')
|
|
192
|
+
p.add_argument("--check", action="store_true", help="write nothing; exit 1 if the file differs")
|
|
193
|
+
p.set_defaults(fn=cmd_openapi)
|
strata_python/contracts.py
CHANGED
|
@@ -13,6 +13,7 @@ generated from it instead of copied.
|
|
|
13
13
|
Page[T] one page of a list: items, the cursor for the next page (None at the end), the total when it is known
|
|
14
14
|
FileRef a file by content and place: sha256, size, mtime, root, rel (the path under that root)
|
|
15
15
|
Judgment one pairwise choice by a person or a model: a, b, the winner (a, b or tie), who, when, undone when
|
|
16
|
+
ApiModel a base for an app's own response shapes: a field with a default is still required in the schema
|
|
16
17
|
|
|
17
18
|
Times are timezone-aware datetimes, sent as ISO 8601 with their offset: the apps had both ISO text and float epochs,
|
|
18
19
|
and only one of those reads correctly in a browser. Use `utc(epoch)` to turn a stored float into one."""
|
|
@@ -30,6 +31,14 @@ def utc(epoch: float | None) -> datetime.datetime | None:
|
|
|
30
31
|
return None if epoch is None else datetime.datetime.fromtimestamp(epoch, datetime.UTC)
|
|
31
32
|
|
|
32
33
|
|
|
34
|
+
class ApiModel(BaseModel):
|
|
35
|
+
"""A base for an app's own response models. pydantic marks a field with a default as optional in the schema, so
|
|
36
|
+
the generated TypeScript gets a `?` though the server always sends it; this config makes the response schema
|
|
37
|
+
say what is sent. Use it for responses: a request body built on it has an `-Input` and an `-Output` schema."""
|
|
38
|
+
|
|
39
|
+
model_config = ConfigDict(json_schema_serialization_defaults_required=True)
|
|
40
|
+
|
|
41
|
+
|
|
33
42
|
class Health(BaseModel):
|
|
34
43
|
"""What `GET /api/health` answers. Extra fields are the app's own (strata-models adds `gpu`)."""
|
|
35
44
|
|
strata_python/db/__init__.py
CHANGED
|
@@ -19,7 +19,8 @@ extra: `strata-python[db]`.
|
|
|
19
19
|
s.add(Note(text="hi")); s.commit()
|
|
20
20
|
|
|
21
21
|
Migrations: `strata-db revision -m "..."` (autogenerate), `strata-db migrate`, `strata-db check`; or in code
|
|
22
|
-
`Project.load(__file__).upgrade(engine)`
|
|
22
|
+
`Project.load(__file__).upgrade(engine)` (or `.open()`, connect and migrate) at service start; a FastAPI server
|
|
23
|
+
uses `strata_python.db.web.add_database` and its `DbSession` dependency. Tests: the plugin's `db_session` / `db_engine` / `db_url`
|
|
23
24
|
/ `db_env` fixtures and `strata_python.db.testing`. See the README.
|
|
24
25
|
|
|
25
26
|
The names load on first use: the pytest plugin imports `strata_python.db.guard` in every app with strata-python
|
|
@@ -35,6 +36,9 @@ if TYPE_CHECKING:
|
|
|
35
36
|
from .config import (
|
|
36
37
|
DatabaseNotConfigured as DatabaseNotConfigured,
|
|
37
38
|
)
|
|
39
|
+
from .config import (
|
|
40
|
+
local_url as local_url,
|
|
41
|
+
)
|
|
38
42
|
from .config import (
|
|
39
43
|
normalise_url as normalise_url,
|
|
40
44
|
)
|
|
@@ -74,6 +78,7 @@ _WHERE = {
|
|
|
74
78
|
"DatabaseNotConfigured": "config",
|
|
75
79
|
"normalise_url": "config",
|
|
76
80
|
"resolve_url": "config",
|
|
81
|
+
"local_url": "config",
|
|
77
82
|
"url_for": "config",
|
|
78
83
|
"connect": "engine",
|
|
79
84
|
"session": "engine",
|
|
@@ -93,6 +98,7 @@ __all__ = [ # noqa: RUF022 (grouped as _WHERE is)
|
|
|
93
98
|
"DatabaseNotConfigured",
|
|
94
99
|
"normalise_url",
|
|
95
100
|
"resolve_url",
|
|
101
|
+
"local_url",
|
|
96
102
|
"url_for",
|
|
97
103
|
"connect",
|
|
98
104
|
"session",
|
strata_python/db/cli.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""strata-db: the app-facing command line (run from anywhere inside the app's repo; also `python -m strata_python.db`).
|
|
2
2
|
|
|
3
|
-
strata-db init --app NAME --models pkg.models:Base [--engine portable|postgres]
|
|
3
|
+
strata-db init --app NAME --models pkg.models:Base [--engine portable|postgres] [--package src/pkg]
|
|
4
4
|
add [tool.strata-db] to pyproject.toml and create migrations/
|
|
5
5
|
strata-db new-app [NAME] on the shared server: owner role NAME (NOLOGIN, you are a member) and schema NAME in
|
|
6
6
|
the shared database, owned by it, no USAGE for PUBLIC (other app roles cannot see it).
|
|
@@ -33,7 +33,7 @@ from . import migrations as m
|
|
|
33
33
|
from .config import normalise_url, resolve_url, shared_database
|
|
34
34
|
from .engine import connect
|
|
35
35
|
from .guard import LIVE, LiveDatabaseRefused, allow_live
|
|
36
|
-
from .project import TABLE, Project
|
|
36
|
+
from .project import FILE, TABLE, Project
|
|
37
37
|
from .scratch import live_admin_url, pg_available, scratch_database
|
|
38
38
|
from .testing import scratch_engine
|
|
39
39
|
|
|
@@ -41,18 +41,29 @@ NAME = re.compile(r"[a-z][a-z0-9_]*") # role and schema names: nothing that nee
|
|
|
41
41
|
|
|
42
42
|
|
|
43
43
|
def cmd_init(a: argparse.Namespace) -> None:
|
|
44
|
+
"""Write the declaration: into pyproject.toml, or with --package into the package's strata-db.toml (migrations
|
|
45
|
+
beside it, so an installed wheel carries both) with a pointer to it in pyproject.toml."""
|
|
44
46
|
pp = Path.cwd() / "pyproject.toml"
|
|
45
47
|
body = pp.read_text(encoding="utf-8") if pp.exists() else f'[project]\nname = "{a.app}"\nversion = "0.1.0"\n'
|
|
46
48
|
if f"[tool.{TABLE}]" in body:
|
|
47
49
|
sys.exit(f"{pp} already has [tool.{TABLE}]")
|
|
48
|
-
|
|
49
|
-
body.rstrip("\n") + f'\n\n[tool.{TABLE}]\napp = "{a.app}"\nmodels = "{a.models}"\nmigrations = "migrations"\n'
|
|
50
|
-
)
|
|
50
|
+
keys = f'app = "{a.app}"\nmodels = "{a.models}"\nmigrations = "migrations"\n'
|
|
51
51
|
if a.engine != "portable":
|
|
52
|
-
|
|
52
|
+
keys += f'engine = "{a.engine}"\n'
|
|
53
|
+
if a.package:
|
|
54
|
+
pkg = Path(a.package)
|
|
55
|
+
if not (Path.cwd() / pkg / "__init__.py").is_file():
|
|
56
|
+
sys.exit(f"{pkg} is not a package folder (no __init__.py)")
|
|
57
|
+
(Path.cwd() / pkg / FILE).write_text(keys, encoding="utf-8")
|
|
58
|
+
(Path.cwd() / pkg / "migrations").mkdir(exist_ok=True)
|
|
59
|
+
body = body.rstrip("\n") + f'\n\n[tool.{TABLE}]\nfile = "{(pkg / FILE).as_posix()}"\n'
|
|
60
|
+
where = f"{(pkg / FILE).as_posix()} (pointed to from {pp.name}); {(pkg / 'migrations').as_posix()}/ ready"
|
|
61
|
+
else:
|
|
62
|
+
body = body.rstrip("\n") + f"\n\n[tool.{TABLE}]\n{keys}"
|
|
63
|
+
(Path.cwd() / "migrations").mkdir(exist_ok=True)
|
|
64
|
+
where = f"[tool.{TABLE}] to {pp}; migrations/ ready"
|
|
53
65
|
pp.write_text(body, encoding="utf-8")
|
|
54
|
-
(
|
|
55
|
-
print(f"wrote [tool.{TABLE}] to {pp}; migrations/ ready. Next: strata-db revision -m 'initial'")
|
|
66
|
+
print(f"wrote {where}. Next: strata-db revision -m 'initial'")
|
|
56
67
|
|
|
57
68
|
|
|
58
69
|
def cmd_new_app(a: argparse.Namespace) -> None:
|
|
@@ -103,7 +114,9 @@ def cmd_revision(a: argparse.Namespace) -> None:
|
|
|
103
114
|
path = m.revision(eng, p.migrations_dir, p.metadata, a.message, autogenerate=not a.empty)
|
|
104
115
|
eng.dispose()
|
|
105
116
|
if path:
|
|
106
|
-
|
|
117
|
+
shown = Path(path).resolve()
|
|
118
|
+
shown = shown.relative_to(Path.cwd().resolve()) if shown.is_relative_to(Path.cwd().resolve()) else shown
|
|
119
|
+
print(f"wrote {shown.as_posix()}: review it, then commit it")
|
|
107
120
|
else:
|
|
108
121
|
print("no changes: the models match the migrations")
|
|
109
122
|
|
|
@@ -162,6 +175,7 @@ def main(argv: list[str] | None = None) -> None:
|
|
|
162
175
|
s.add_argument("--app", required=True)
|
|
163
176
|
s.add_argument("--models", required=True)
|
|
164
177
|
s.add_argument("--engine", choices=["portable", "postgres"], default="portable")
|
|
178
|
+
s.add_argument("--package", metavar="DIR", help="declare in DIR/strata-db.toml, so an installed wheel has it")
|
|
165
179
|
s.set_defaults(f=cmd_init)
|
|
166
180
|
s = sub.add_parser("new-app", help="role and schema on the shared server")
|
|
167
181
|
s.add_argument("name", nargs="?")
|
strata_python/db/config.py
CHANGED
|
@@ -12,6 +12,9 @@ has no schemas.
|
|
|
12
12
|
|
|
13
13
|
The shared database has no built-in name: the name is the owner's, and this package is public (AGENTS.md rule 4).
|
|
14
14
|
|
|
15
|
+
An app that should still work before it is given a database (a checkout, a new deployment) passes a `default`, usually
|
|
16
|
+
`local_url(SETTINGS)`: a SQLite file in its settings folder. It is used only when nothing above is set.
|
|
17
|
+
|
|
15
18
|
A real Postgres database is opt-in (see `strata_python.db.guard`): url_for() and connect() refuse one unless the
|
|
16
19
|
process has `STRATA_DB_LIVE=1`, and refuse it always during tests.
|
|
17
20
|
"""
|
|
@@ -20,6 +23,10 @@ from __future__ import annotations
|
|
|
20
23
|
|
|
21
24
|
import os
|
|
22
25
|
import re
|
|
26
|
+
from typing import TYPE_CHECKING
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from strata_python.settings import Settings
|
|
23
30
|
|
|
24
31
|
URL = "STRATA_DB_URL"
|
|
25
32
|
DATABASE = "STRATA_DB_DATABASE"
|
|
@@ -67,19 +74,36 @@ def with_search_path(url: str, schema: str) -> str:
|
|
|
67
74
|
return url + ("&" if "?" in url else "?") + f"options=-csearch_path%3D{schema}"
|
|
68
75
|
|
|
69
76
|
|
|
70
|
-
def
|
|
71
|
-
"""
|
|
77
|
+
def local_url(home: Settings | str | os.PathLike[str], name: str | None = None) -> str:
|
|
78
|
+
"""A SQLite file for an app with no database configured: `<home>/<name>.db`, where home is a folder or the app's
|
|
79
|
+
`Settings` (its folder, `<APP>_HOME` or `~/.<app>`, and its name). `connect` makes the folder."""
|
|
80
|
+
from strata_python.settings import Settings
|
|
81
|
+
|
|
82
|
+
if isinstance(home, Settings):
|
|
83
|
+
folder, name = home.home(), name or home.app
|
|
84
|
+
else:
|
|
85
|
+
folder = os.fspath(home)
|
|
86
|
+
if not name:
|
|
87
|
+
raise ValueError("local_url(folder) needs the app name")
|
|
88
|
+
return normalise_url(os.path.join(folder, f"{name}.db"))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def resolve_url(app: str, schema: str | None = None, *, default: str | None = None) -> str:
|
|
92
|
+
"""Where `app`'s data is (see the module docstring), without the live-database check. `default` (a URL or a
|
|
93
|
+
path) is used when nothing is configured, instead of raising DatabaseNotConfigured."""
|
|
72
94
|
for var in (URL, env_name(app)):
|
|
73
95
|
if value := os.environ.get(var):
|
|
74
96
|
return with_search_path(normalise_url(value), schema or app)
|
|
97
|
+
if default is not None and not shared_database():
|
|
98
|
+
return with_search_path(normalise_url(default), schema or app) # as an environment URL (review finding)
|
|
75
99
|
return schema_url(schema or app)
|
|
76
100
|
|
|
77
101
|
|
|
78
|
-
def url_for(app: str, schema: str | None = None) -> str:
|
|
102
|
+
def url_for(app: str, schema: str | None = None, *, default: str | None = None) -> str:
|
|
79
103
|
"""resolve_url(), refused (guard.LiveDatabaseRefused) when it is a real Postgres database and the process has
|
|
80
104
|
not opted in with `STRATA_DB_LIVE=1`, or is running tests."""
|
|
81
105
|
from .guard import check_url
|
|
82
106
|
|
|
83
|
-
url = resolve_url(app, schema)
|
|
107
|
+
url = resolve_url(app, schema, default=default)
|
|
84
108
|
check_url(url, f"url_for({app!r})")
|
|
85
109
|
return url
|
strata_python/db/engine.py
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import os
|
|
5
6
|
import re
|
|
6
7
|
import sqlite3
|
|
7
8
|
from collections.abc import Generator
|
|
@@ -27,6 +28,9 @@ def connect(app_or_url: str, **kw: Any) -> Engine:
|
|
|
27
28
|
engine = create_engine(url, **kw)
|
|
28
29
|
if engine.dialect.name == "sqlite":
|
|
29
30
|
sqlite_pragmas(engine)
|
|
31
|
+
file = engine.url.database
|
|
32
|
+
if file and file != ":memory:" and not file.startswith("file:"):
|
|
33
|
+
os.makedirs(os.path.dirname(os.path.abspath(file)), exist_ok=True) # a fallback in a folder not made yet
|
|
30
34
|
return engine
|
|
31
35
|
|
|
32
36
|
|
strata_python/db/project.py
CHANGED
|
@@ -7,6 +7,16 @@ models = "notes.models:Base" # module:attribute with .metadata (a Base or
|
|
|
7
7
|
migrations = "migrations" # folder of Alembic revisions, relative to pyproject.toml
|
|
8
8
|
engine = "portable" # or "postgres": uses Postgres-only features; tests and autogenerate then
|
|
9
9
|
# need Postgres (strata-db and the pytest plugin follow this)
|
|
10
|
+
|
|
11
|
+
An app installed as a wheel (a service run from `uv tool install`) has no pyproject.toml beside its code, so the same
|
|
12
|
+
keys can live in the package instead, in a `strata-db.toml` (top level, no table header) next to the migrations:
|
|
13
|
+
|
|
14
|
+
[tool.strata-db] # pyproject.toml: only where the declaration is
|
|
15
|
+
file = "src/notes/strata-db.toml"
|
|
16
|
+
|
|
17
|
+
`migrations` is then relative to that file, so the folder ships inside the package, and `Project.load(__file__)` at
|
|
18
|
+
service start finds the file by walking up from the module, in a checkout and in site-packages alike. strata-db and
|
|
19
|
+
the pytest plugin follow the pointer, so all three read one declaration.
|
|
10
20
|
"""
|
|
11
21
|
|
|
12
22
|
from __future__ import annotations
|
|
@@ -24,22 +34,46 @@ if TYPE_CHECKING:
|
|
|
24
34
|
from sqlalchemy.engine import Engine
|
|
25
35
|
|
|
26
36
|
TABLE = "strata-db"
|
|
37
|
+
FILE = "strata-db.toml"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _read(f: Path) -> dict[str, Any]:
|
|
41
|
+
return tomllib.loads(f.read_text(encoding="utf-8"))
|
|
27
42
|
|
|
28
43
|
|
|
29
44
|
def find_table(start: str | os.PathLike[str] | None = None) -> tuple[Path, dict[str, Any]] | None:
|
|
30
|
-
"""The nearest
|
|
31
|
-
|
|
45
|
+
"""The nearest declaration, from start (default: cwd) upwards: a `strata-db.toml`, or a pyproject.toml with
|
|
46
|
+
[tool.strata-db] (followed to the file its `file` key names). Returns the folder paths are relative to and the
|
|
47
|
+
keys. Standard library only, so the pytest plugin can ask without loading SQLAlchemy."""
|
|
32
48
|
p = Path(start or os.getcwd()).resolve()
|
|
33
49
|
for d in [p, *p.parents] if p.is_dir() else [p.parent, *p.parent.parents]:
|
|
50
|
+
if (d / FILE).is_file():
|
|
51
|
+
return d, _read(d / FILE)
|
|
34
52
|
f = d / "pyproject.toml"
|
|
35
53
|
if not f.is_file():
|
|
36
54
|
continue
|
|
37
|
-
cfg = cast("dict[str, Any]",
|
|
55
|
+
cfg = cast("dict[str, Any] | None", cast("dict[str, Any]", _read(f).get("tool", {})).get(TABLE))
|
|
56
|
+
if cfg and "file" in cfg:
|
|
57
|
+
target = (d / str(cfg["file"])).resolve()
|
|
58
|
+
if not target.is_file():
|
|
59
|
+
raise FileNotFoundError(f"{f}: [tool.{TABLE}] file = {cfg['file']!r} does not exist")
|
|
60
|
+
return target.parent, _read(target)
|
|
38
61
|
if cfg:
|
|
39
|
-
return d,
|
|
62
|
+
return d, cfg
|
|
40
63
|
return None
|
|
41
64
|
|
|
42
65
|
|
|
66
|
+
def _import_roots(root: Path) -> list[Path]:
|
|
67
|
+
"""Folders to put on sys.path so the models import when the app is not installed (a test run from its checkout):
|
|
68
|
+
`src` and the project folder, or for a declaration inside a package, the folder above its top package."""
|
|
69
|
+
if (root / "__init__.py").is_file():
|
|
70
|
+
top = root
|
|
71
|
+
while (top.parent / "__init__.py").is_file():
|
|
72
|
+
top = top.parent
|
|
73
|
+
return [top.parent]
|
|
74
|
+
return [root / "src", root]
|
|
75
|
+
|
|
76
|
+
|
|
43
77
|
@dataclass
|
|
44
78
|
class Project:
|
|
45
79
|
root: Path
|
|
@@ -54,12 +88,13 @@ class Project:
|
|
|
54
88
|
|
|
55
89
|
@classmethod
|
|
56
90
|
def load(cls, start: str | os.PathLike[str] | None = None) -> Project:
|
|
57
|
-
"""
|
|
91
|
+
"""The nearest declaration from start (default: cwd) upwards: a `strata-db.toml`, or a pyproject.toml with
|
|
92
|
+
[tool.strata-db] (see the module notes). Pass `__file__` in the service, so an installed wheel finds it too."""
|
|
58
93
|
found = find_table(start)
|
|
59
94
|
if found is None:
|
|
60
95
|
p = Path(start or os.getcwd()).resolve()
|
|
61
96
|
raise FileNotFoundError(
|
|
62
|
-
f"no pyproject.toml with [tool.{TABLE}] in {p} or above (strata-db init writes one)"
|
|
97
|
+
f"no {FILE} or pyproject.toml with [tool.{TABLE}] in {p} or above (strata-db init writes one)"
|
|
63
98
|
)
|
|
64
99
|
d, cfg = found
|
|
65
100
|
return cls(
|
|
@@ -75,7 +110,7 @@ class Project:
|
|
|
75
110
|
def metadata(self) -> MetaData:
|
|
76
111
|
from sqlalchemy import MetaData
|
|
77
112
|
|
|
78
|
-
for extra in (self.root
|
|
113
|
+
for extra in _import_roots(self.root): # the app need not be installed (a test run from its checkout)
|
|
79
114
|
if extra.is_dir() and str(extra) not in sys.path:
|
|
80
115
|
sys.path.insert(0, str(extra))
|
|
81
116
|
mod, _, attr = self.models.partition(":")
|
|
@@ -91,6 +126,22 @@ class Project:
|
|
|
91
126
|
|
|
92
127
|
return url_for(self.app, self.schema)
|
|
93
128
|
|
|
129
|
+
def open(self, url: str | None = None, *, default: str | None = None) -> Engine:
|
|
130
|
+
"""An engine on the app's database, migrated to head: `url`, else `url()` with `default` (a URL or path,
|
|
131
|
+
such as `config.local_url(SETTINGS)`) when nothing is configured. Call once and keep the engine."""
|
|
132
|
+
from .config import normalise_url, url_for, with_search_path
|
|
133
|
+
from .engine import connect
|
|
134
|
+
|
|
135
|
+
# a Postgres URL without a search_path would query public while upgrade() migrated the app's schema
|
|
136
|
+
given = with_search_path(normalise_url(url), self.schema) if url else None
|
|
137
|
+
engine = connect(given or url_for(self.app, self.schema, default=default))
|
|
138
|
+
try:
|
|
139
|
+
self.upgrade(engine)
|
|
140
|
+
except BaseException:
|
|
141
|
+
engine.dispose()
|
|
142
|
+
raise
|
|
143
|
+
return engine
|
|
144
|
+
|
|
94
145
|
def upgrade(self, engine: Engine, revision: str = "head") -> None:
|
|
95
146
|
"""Migrate to head (safe at every start). On Postgres: in the app's schema, as the app's role."""
|
|
96
147
|
from .migrations import upgrade
|
strata_python/db/web.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""A FastAPI server's records: one engine per app, opened and migrated on the first request that needs it, a session
|
|
2
|
+
per request, and the engine disposed when the server stops.
|
|
3
|
+
|
|
4
|
+
from strata_python.db.web import DbSession, add_database
|
|
5
|
+
|
|
6
|
+
app = web.base_app("notes", __version__, SETTINGS)
|
|
7
|
+
add_database(app, Project.load(__file__), default=lambda: local_url(SETTINGS))
|
|
8
|
+
|
|
9
|
+
@app.get("/api/notes")
|
|
10
|
+
def notes(db: DbSession) -> list[NoteOut]:
|
|
11
|
+
return [NoteOut.of(n) for n in db.scalars(select(Note))]
|
|
12
|
+
|
|
13
|
+
Every app with records behind its server wrote this glue (flashtap's `learners/db.py` and `_records`, issue #39). The
|
|
14
|
+
engine is lazy so a server nobody records on never creates a database and its other routes never wait for a
|
|
15
|
+
migration; `default` (a URL, a path, or a function giving one, read when the engine opens) keeps a checkout or a
|
|
16
|
+
deployment with no database configured working on a local SQLite file. Needs the `[db]` extra."""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import contextlib
|
|
21
|
+
import threading
|
|
22
|
+
from collections.abc import AsyncGenerator, Callable, Iterator
|
|
23
|
+
from typing import TYPE_CHECKING, Annotated, Any
|
|
24
|
+
|
|
25
|
+
from fastapi import Depends, FastAPI, Request
|
|
26
|
+
from sqlalchemy.orm import Session
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from sqlalchemy.engine import Engine
|
|
30
|
+
|
|
31
|
+
from .project import Project
|
|
32
|
+
|
|
33
|
+
STATE = "strata_db" # the attribute on app.state
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Database:
|
|
37
|
+
"""The app's engine, opened once on first use (thread-safe: sync routes run in a pool) and disposed by `close`."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, project: Project, url: str | None = None, default: str | Callable[[], str] | None = None):
|
|
40
|
+
self.project, self.url, self.default = project, url, default
|
|
41
|
+
self._engine: Engine | None = None
|
|
42
|
+
self._lock = threading.Lock()
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def opened(self) -> bool:
|
|
46
|
+
return self._engine is not None
|
|
47
|
+
|
|
48
|
+
def engine(self) -> Engine:
|
|
49
|
+
"""The migrated engine, opened on the first call. A failure (a bad URL, a migration that fails) is raised to
|
|
50
|
+
that request and tried again on the next one, so a fixed configuration needs no restart."""
|
|
51
|
+
if self._engine is None:
|
|
52
|
+
with self._lock:
|
|
53
|
+
if self._engine is None:
|
|
54
|
+
d = self.default
|
|
55
|
+
default = d if d is None or isinstance(d, str) else d()
|
|
56
|
+
self._engine = self.project.open(self.url, default=default)
|
|
57
|
+
return self._engine
|
|
58
|
+
|
|
59
|
+
def close(self) -> None:
|
|
60
|
+
with self._lock:
|
|
61
|
+
if self._engine is not None:
|
|
62
|
+
self._engine.dispose()
|
|
63
|
+
self._engine = None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def add_database(
|
|
67
|
+
app: FastAPI, project: Project, *, url: str | None = None, default: str | Callable[[], str] | None = None
|
|
68
|
+
) -> Database:
|
|
69
|
+
"""Hold the app's database on `app.state` for `DbSession`, and dispose it when the server stops (wrapping the
|
|
70
|
+
app's own lifespan, which still runs). `url` overrides the configured one (a test); `default` is used when
|
|
71
|
+
nothing is configured (see `config.local_url`). Returns the `Database`, also reachable as `database(app)`."""
|
|
72
|
+
holder = Database(project, url, default)
|
|
73
|
+
setattr(app.state, STATE, holder)
|
|
74
|
+
inner = app.router.lifespan_context
|
|
75
|
+
|
|
76
|
+
@contextlib.asynccontextmanager
|
|
77
|
+
async def lifespan(a: Any) -> AsyncGenerator[Any]:
|
|
78
|
+
try:
|
|
79
|
+
async with inner(a) as state:
|
|
80
|
+
yield state
|
|
81
|
+
finally:
|
|
82
|
+
holder.close()
|
|
83
|
+
|
|
84
|
+
app.router.lifespan_context = lifespan
|
|
85
|
+
return holder
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def database(app: FastAPI) -> Database:
|
|
89
|
+
"""The `Database` `add_database` put on the app (RuntimeError, naming the call, when there is none)."""
|
|
90
|
+
holder = getattr(app.state, STATE, None)
|
|
91
|
+
if not isinstance(holder, Database):
|
|
92
|
+
raise RuntimeError("no database on this app: call strata_python.db.web.add_database(app, project) first")
|
|
93
|
+
return holder
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def db_session(request: Request) -> Iterator[Session]:
|
|
97
|
+
"""A Session on the app's database for one request, closed afterwards (commit yourself: `db.commit()`)."""
|
|
98
|
+
with Session(database(request.app).engine()) as s:
|
|
99
|
+
yield s
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
DbSession = Annotated[Session, Depends(db_session)]
|
|
103
|
+
"""A route parameter typed `DbSession` gets a session for that request."""
|
strata_python/public_check.py
CHANGED
|
@@ -13,6 +13,16 @@ False positives left after that are silenced in the repo, where a reviewer sees
|
|
|
13
13
|
`pkg-1.0/web/package-lock.json` matches too). An excluded file skips the built-in patterns only.
|
|
14
14
|
- `strata-public-check: ignore` anywhere on a line skips the built-in patterns on that line. Never the owner's
|
|
15
15
|
`STRATA_PUBLIC_DENY` patterns: a name the owner listed is never one to publish.
|
|
16
|
+
|
|
17
|
+
Patterns about the *shape* of a detail (an age, a birth date) are safe to publish and belong with the code, so every
|
|
18
|
+
contributor and every local run gets them: `[tool.strata-public-check] deny = ["\\bdate of birth\\b"]`, each a
|
|
19
|
+
case-insensitive regex or a `{pattern = "...", kind = "age"}` table naming what it reports. They behave like the
|
|
20
|
+
built-in ones (an exclude and the ignore comment skip them, and the match is printed), unlike the owner's secret ones.
|
|
21
|
+
|
|
22
|
+
What is read: source and config text by suffix (Python, TypeScript and JavaScript, CSS, HTML, MDX, SVG, Markdown,
|
|
23
|
+
TOML, JSON, YAML...) and files with no suffix unless they look binary. In a git checkout only the files git would
|
|
24
|
+
commit are read (`git ls-files -co --exclude-standard`), so tool output such as `.coverage`, a SQLite file full of
|
|
25
|
+
absolute paths, is never scanned on a local run.
|
|
16
26
|
"""
|
|
17
27
|
|
|
18
28
|
from __future__ import annotations
|
|
@@ -21,6 +31,8 @@ import argparse
|
|
|
21
31
|
import io
|
|
22
32
|
import os
|
|
23
33
|
import re
|
|
34
|
+
import shutil
|
|
35
|
+
import subprocess
|
|
24
36
|
import sys
|
|
25
37
|
import tarfile
|
|
26
38
|
import tomllib
|
|
@@ -52,14 +64,25 @@ BUILT_IN: dict[str, re.Pattern[str]] = {
|
|
|
52
64
|
"home folder path": re.compile(r"(?:/home/|/Users/|[A-Za-z]:\\+Users\\+)(?P<user>[A-Za-z0-9._-]+)"),
|
|
53
65
|
}
|
|
54
66
|
|
|
55
|
-
# Text files only: a binary (an image, a compiled extension) is skipped rather than decoded into noise.
|
|
56
|
-
|
|
67
|
+
# Text files only: a binary (an image, a compiled extension) is skipped rather than decoded into noise. Every strata app
|
|
68
|
+
# with a web front end keeps most of its code, stories and mock fixtures in the web suffixes (issue #37).
|
|
69
|
+
TEXT_SUFFIXES = {
|
|
70
|
+
*(".py", ".pyi", ".md", ".txt", ".toml", ".cfg", ".ini", ".json", ".yml", ".yaml", ".typed", ".sh", ""),
|
|
71
|
+
*(".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs", ".mdx", ".css", ".html", ".svg", ".vue"),
|
|
72
|
+
}
|
|
73
|
+
TEXT_NAMES = {".env.example"} # a template of the settings an app reads, committed on purpose
|
|
57
74
|
SKIP_PARTS = {
|
|
58
75
|
"__pycache__",
|
|
59
76
|
"node_modules",
|
|
60
77
|
"dist",
|
|
61
78
|
"build",
|
|
79
|
+
"storybook-static",
|
|
80
|
+
"baselines", # strata-visual's screenshots
|
|
62
81
|
} # and hidden folders (.git, .venv, caches), but not .github
|
|
82
|
+
# A file with no suffix is read only when it looks like text: no NUL byte in its start, so `.coverage` (SQLite) or a
|
|
83
|
+
# compiled tool is skipped even outside a git checkout.
|
|
84
|
+
SNIFF = 8192
|
|
85
|
+
DENY_KIND = f"matches [tool.{TABLE}] deny pattern"
|
|
63
86
|
|
|
64
87
|
|
|
65
88
|
@dataclass(frozen=True)
|
|
@@ -80,12 +103,19 @@ def deny_patterns(env: str | None = None) -> list[re.Pattern[str]]:
|
|
|
80
103
|
|
|
81
104
|
|
|
82
105
|
def scan_text(
|
|
83
|
-
where: str,
|
|
106
|
+
where: str,
|
|
107
|
+
text: str,
|
|
108
|
+
extra: Iterable[re.Pattern[str]] = (),
|
|
109
|
+
*,
|
|
110
|
+
built_in: bool = True,
|
|
111
|
+
repo: Iterable[tuple[str, re.Pattern[str]]] = (),
|
|
84
112
|
) -> Iterator[Finding]:
|
|
85
|
-
"""Findings in one file's text. `
|
|
113
|
+
"""Findings in one file's text. `repo` is `(kind, pattern)` pairs from the repo's `deny`, checked like the built-in
|
|
114
|
+
patterns; `built_in=False` (an excluded file) checks only the owner's patterns."""
|
|
86
115
|
extra = list(extra)
|
|
116
|
+
patterns = [*BUILT_IN.items(), *repo]
|
|
87
117
|
for number, line in enumerate(text.splitlines(), 1):
|
|
88
|
-
for kind, pattern in
|
|
118
|
+
for kind, pattern in patterns if built_in and IGNORE not in line else ():
|
|
89
119
|
for match in pattern.finditer(line):
|
|
90
120
|
if kind == "home folder path" and match.group("user").lower() in PLACEHOLDER_USERS:
|
|
91
121
|
continue
|
|
@@ -101,26 +131,88 @@ def excluded(name: str, patterns: Iterable[str]) -> bool:
|
|
|
101
131
|
return any(fnmatchcase(name, p) or fnmatchcase(name, "*/" + p) for p in patterns)
|
|
102
132
|
|
|
103
133
|
|
|
104
|
-
def
|
|
105
|
-
"""`exclude` from `[tool.strata-public-check]` in root's (default: the current folder's) pyproject.toml."""
|
|
134
|
+
def _config(root: Path | None) -> dict[str, Any]:
|
|
106
135
|
f = (root or Path()) / "pyproject.toml"
|
|
107
136
|
if not f.is_file():
|
|
108
|
-
return
|
|
137
|
+
return {}
|
|
109
138
|
tool = cast("dict[str, Any]", tomllib.loads(f.read_text(encoding="utf-8")).get("tool", {}))
|
|
110
|
-
return
|
|
139
|
+
return cast("dict[str, Any]", tool.get(TABLE, {}))
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def config_excludes(root: Path | None = None) -> list[str]:
|
|
143
|
+
"""`exclude` from `[tool.strata-public-check]` in root's (default: the current folder's) pyproject.toml."""
|
|
144
|
+
return [str(p) for p in _config(root).get("exclude", [])]
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def config_deny(root: Path | None = None) -> list[tuple[str, re.Pattern[str]]]:
|
|
148
|
+
"""`deny` from `[tool.strata-public-check]`: `(kind, pattern)` pairs, each a regex string or a `{pattern, kind}`
|
|
149
|
+
table, compiled case-insensitive. A bad regex or entry raises ValueError naming it."""
|
|
150
|
+
out: list[tuple[str, re.Pattern[str]]] = []
|
|
151
|
+
for entry in cast("list[Any]", _config(root).get("deny", [])):
|
|
152
|
+
if isinstance(entry, str):
|
|
153
|
+
raw, kind = entry, DENY_KIND
|
|
154
|
+
elif isinstance(entry, dict) and isinstance(cast("dict[str, Any]", entry).get("pattern"), str):
|
|
155
|
+
table = cast("dict[str, Any]", entry)
|
|
156
|
+
raw, kind = str(table["pattern"]), str(table.get("kind", DENY_KIND))
|
|
157
|
+
else:
|
|
158
|
+
raise ValueError(f'[tool.{TABLE}] deny: {entry!r} is neither a regex nor {{pattern = "...", kind = "..."}}')
|
|
159
|
+
try:
|
|
160
|
+
out.append((kind, re.compile(raw, re.IGNORECASE)))
|
|
161
|
+
except re.error as e:
|
|
162
|
+
raise ValueError(f"[tool.{TABLE}] deny: {raw!r} is not a valid regex: {e}") from e
|
|
163
|
+
return out
|
|
111
164
|
|
|
112
165
|
|
|
113
166
|
def _is_text(name: str) -> bool:
|
|
114
167
|
path = Path(name)
|
|
115
168
|
hidden = any(part.startswith(".") and part != ".github" for part in path.parts[:-1])
|
|
116
|
-
|
|
169
|
+
readable = path.suffix in TEXT_SUFFIXES or path.name in TEXT_NAMES
|
|
170
|
+
return readable and not hidden and not (set(path.parts) & SKIP_PARTS)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _looks_binary(name: str, data: bytes) -> bool:
|
|
174
|
+
"""A file with no suffix whose start holds a NUL byte (SQLite's `.coverage`, an executable) is not text."""
|
|
175
|
+
return not Path(name).suffix and b"\0" in data[:SNIFF]
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _git(folder: Path, *args: str) -> subprocess.CompletedProcess[bytes] | None:
|
|
179
|
+
git = shutil.which("git")
|
|
180
|
+
if git is None:
|
|
181
|
+
return None
|
|
182
|
+
try:
|
|
183
|
+
return subprocess.run([git, "-C", str(folder), *args], capture_output=True, check=False) # noqa: S603 - git on PATH, fixed arguments
|
|
184
|
+
except OSError:
|
|
185
|
+
return None
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _git_files(folder: Path) -> list[str] | None:
|
|
189
|
+
"""The files git would commit under `folder` (tracked, plus untracked ones not ignored), or None when git is not
|
|
190
|
+
installed, the folder is not in a checkout, or the folder is itself ignored (`strata-public-check dist` asks for
|
|
191
|
+
the built files, which a checkout ignores), so the caller walks the folder instead."""
|
|
192
|
+
listed = _git(folder, "ls-files", "-co", "--exclude-standard", "-z")
|
|
193
|
+
if listed is None or listed.returncode != 0:
|
|
194
|
+
return None
|
|
195
|
+
ignored = _git(folder.resolve().parent, "check-ignore", "-q", folder.resolve().name)
|
|
196
|
+
if ignored is not None and ignored.returncode == 0:
|
|
197
|
+
return None
|
|
198
|
+
return sorted({name for name in listed.stdout.decode("utf-8", "surrogateescape").split("\0") if name})
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _files(folder: Path) -> Iterator[tuple[str, Path]]:
|
|
202
|
+
names = _git_files(folder)
|
|
203
|
+
if names is None:
|
|
204
|
+
for file in sorted(folder.rglob("*")):
|
|
205
|
+
yield file.relative_to(folder).as_posix(), file
|
|
206
|
+
else:
|
|
207
|
+
for name in names:
|
|
208
|
+
yield name, folder / name
|
|
117
209
|
|
|
118
210
|
|
|
119
211
|
def _members(path: Path) -> Iterator[tuple[str, bytes]]:
|
|
120
212
|
if path.is_dir():
|
|
121
|
-
for file in
|
|
122
|
-
|
|
123
|
-
if
|
|
213
|
+
for relative, file in _files(path):
|
|
214
|
+
# a tracked file deleted from the work tree is listed by git but gone; a symlink to a folder is not a file
|
|
215
|
+
if _is_text(relative) and file.is_file():
|
|
124
216
|
yield relative, file.read_bytes()
|
|
125
217
|
elif path.name.endswith((".tar.gz", ".tgz")):
|
|
126
218
|
with tarfile.open(path) as archive:
|
|
@@ -137,19 +229,25 @@ def _members(path: Path) -> Iterator[tuple[str, bytes]]:
|
|
|
137
229
|
yield path.as_posix(), path.read_bytes()
|
|
138
230
|
|
|
139
231
|
|
|
140
|
-
def scan(
|
|
141
|
-
|
|
142
|
-
extra
|
|
232
|
+
def scan(
|
|
233
|
+
paths: Iterable[Path],
|
|
234
|
+
extra: Iterable[re.Pattern[str]] = (),
|
|
235
|
+
exclude: Iterable[str] = (),
|
|
236
|
+
repo: Iterable[tuple[str, re.Pattern[str]]] = (),
|
|
237
|
+
) -> list[Finding]:
|
|
238
|
+
"""Every finding in the given folders, files, sdists (.tar.gz) and wheels (.whl), less the excluded files.
|
|
239
|
+
`extra` is the owner's secret patterns, `repo` the `(kind, pattern)` pairs from the repo's `deny`."""
|
|
240
|
+
extra, exclude, repo = list(extra), list(exclude), list(repo)
|
|
143
241
|
findings: list[Finding] = []
|
|
144
242
|
for path in paths:
|
|
145
243
|
for where, data in _members(path):
|
|
146
244
|
skip = excluded(where, exclude)
|
|
147
|
-
if skip and not extra:
|
|
245
|
+
if (skip and not extra) or _looks_binary(where, data):
|
|
148
246
|
continue
|
|
149
247
|
text = io.TextIOWrapper(io.BytesIO(data), encoding="utf-8", errors="replace").read()
|
|
150
248
|
# an excluded file is still checked against the owner's patterns: an exclude is for false positives of the
|
|
151
249
|
# built-in ones, and a name the owner listed is never one to publish (review finding)
|
|
152
|
-
findings.extend(scan_text(where, text, extra, built_in=not skip))
|
|
250
|
+
findings.extend(scan_text(where, text, extra, built_in=not skip, repo=repo))
|
|
153
251
|
return findings
|
|
154
252
|
|
|
155
253
|
|
|
@@ -166,7 +264,12 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
166
264
|
help=f"skip matching files, as well as [tool.{TABLE}] exclude in ./pyproject.toml",
|
|
167
265
|
)
|
|
168
266
|
args = parser.parse_args(argv)
|
|
169
|
-
|
|
267
|
+
try:
|
|
268
|
+
repo = config_deny()
|
|
269
|
+
except ValueError as e:
|
|
270
|
+
print(e, file=sys.stderr)
|
|
271
|
+
return 2
|
|
272
|
+
findings = scan(args.paths, deny_patterns(), [*config_excludes(), *args.exclude], repo)
|
|
170
273
|
for finding in findings:
|
|
171
274
|
print(finding, file=sys.stderr)
|
|
172
275
|
if findings:
|
strata_python/settings.py
CHANGED
|
@@ -5,6 +5,7 @@ An app declares its settings once (`Setting`: key, default, optional normaliser)
|
|
|
5
5
|
SETTINGS = Settings("myapp", [Setting("data_dir", default=lambda: "/srv/data", normalise=absolute_path),
|
|
6
6
|
Setting("greeting", default="Hello", normalise=non_empty),
|
|
7
7
|
Setting("workers", default="2", normalise=whole_between(1, 16)),
|
|
8
|
+
Setting("mode", default="mixed", choices=["mixed", "review", "new"]),
|
|
8
9
|
ListSetting("source_roots", item=absolute_path)])
|
|
9
10
|
SETTINGS.get("greeting") # MYAPP_GREETING, else the file, else the default
|
|
10
11
|
SETTINGS.get_int("workers") # typed getters: get_int, get_float, get_bool, get_list
|
|
@@ -14,6 +15,11 @@ Order of precedence: environment variable (`<APP>_<KEY>`, upper-cased, or the na
|
|
|
14
15
|
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.
|
|
15
16
|
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.
|
|
16
17
|
|
|
18
|
+
`Settings.model()` describes them for `/api/openapi.json`: a setting with `choices` (or `normalise=one_of(...)`) is a
|
|
19
|
+
`Literal` of them, so the schema has an `enum` and the web app's generated type is the union. `Settings(...,
|
|
20
|
+
numbers=True)` also sends `whole_between` and `number_between` settings as JSON numbers with their range in the schema.
|
|
21
|
+
It is off by default because it changes what `GET /api/settings` sends, so an app turns it on with its web app.
|
|
22
|
+
|
|
17
23
|
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
24
|
`strata_python.db.settings.TableStore`), copying the file's values in once. The CLI and tests without a database keep the file."""
|
|
19
25
|
|
|
@@ -26,7 +32,7 @@ import tempfile
|
|
|
26
32
|
import threading
|
|
27
33
|
from collections.abc import Callable, Mapping, Sequence
|
|
28
34
|
from dataclasses import dataclass
|
|
29
|
-
from typing import Any, Protocol, cast
|
|
35
|
+
from typing import Any, Literal, Protocol, cast
|
|
30
36
|
|
|
31
37
|
from strata_python.oslib import file_lock
|
|
32
38
|
|
|
@@ -47,34 +53,61 @@ def absolute_path(value: str) -> str:
|
|
|
47
53
|
return os.path.abspath(p)
|
|
48
54
|
|
|
49
55
|
|
|
50
|
-
|
|
51
|
-
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class number_between: # lower case: used as a normaliser function, and was one before it carried its range
|
|
58
|
+
"""Normaliser: a finite number from `lo` to `hi` (GB of memory, a budget in dollars), written the shortest way
|
|
59
|
+
(`"8"`, `"8.5"`). Its range is visible, so `Settings(numbers=True)` puts it in the schema."""
|
|
52
60
|
|
|
53
|
-
|
|
61
|
+
lo: float
|
|
62
|
+
hi: float
|
|
63
|
+
|
|
64
|
+
def __call__(self, value: str) -> str:
|
|
54
65
|
try:
|
|
55
66
|
x = float(value.strip())
|
|
56
67
|
except ValueError:
|
|
57
68
|
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)}")
|
|
69
|
+
if not math.isfinite(x) or not self.lo <= x <= self.hi:
|
|
70
|
+
raise ValueError(f"must be a number from {_num(self.lo)} to {_num(self.hi)}")
|
|
60
71
|
return _num(x)
|
|
61
72
|
|
|
62
|
-
return normalise
|
|
63
73
|
|
|
74
|
+
@dataclass(frozen=True)
|
|
75
|
+
class whole_between: # lower case: as number_between
|
|
76
|
+
"""Normaliser: a whole number from `lo` to `hi` (job slots, a port). Its range is visible, so
|
|
77
|
+
`Settings(numbers=True)` puts it in the schema."""
|
|
64
78
|
|
|
65
|
-
|
|
66
|
-
|
|
79
|
+
lo: int
|
|
80
|
+
hi: int
|
|
67
81
|
|
|
68
|
-
def
|
|
82
|
+
def __call__(self, value: str) -> str:
|
|
69
83
|
try:
|
|
70
84
|
x = int(value.strip())
|
|
71
85
|
except ValueError:
|
|
72
86
|
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}")
|
|
87
|
+
if not self.lo <= x <= self.hi:
|
|
88
|
+
raise ValueError(f"must be a whole number from {self.lo} to {self.hi}")
|
|
75
89
|
return str(x)
|
|
76
90
|
|
|
77
|
-
|
|
91
|
+
|
|
92
|
+
@dataclass(frozen=True)
|
|
93
|
+
class one_of: # lower case: as number_between
|
|
94
|
+
"""Normaliser: one of `choices`, matched without regard to case and surrounding space and returned as the choice
|
|
95
|
+
is spelled; anything else is refused with the list. `Setting(choices=...)` is the short form. `Settings.model()`
|
|
96
|
+
sees the choices and types the setting as a `Literal` of them."""
|
|
97
|
+
|
|
98
|
+
choices: tuple[str, ...]
|
|
99
|
+
|
|
100
|
+
def __init__(self, choices: Sequence[str]) -> None:
|
|
101
|
+
if not choices:
|
|
102
|
+
raise ValueError("one_of needs at least one choice")
|
|
103
|
+
object.__setattr__(self, "choices", tuple(choices))
|
|
104
|
+
|
|
105
|
+
def __call__(self, value: str) -> str:
|
|
106
|
+
v = value.strip().casefold()
|
|
107
|
+
for choice in self.choices:
|
|
108
|
+
if choice.casefold() == v:
|
|
109
|
+
return choice
|
|
110
|
+
raise ValueError(f"must be one of {', '.join(self.choices)}")
|
|
78
111
|
|
|
79
112
|
|
|
80
113
|
_DATE = re.compile(r"\d{4}-\d{2}-\d{2}")
|
|
@@ -120,10 +153,18 @@ def _identity(value: str) -> str:
|
|
|
120
153
|
|
|
121
154
|
@dataclass(frozen=True)
|
|
122
155
|
class Setting:
|
|
156
|
+
"""One setting. `normalise` turns a value into its one spelling or raises ValueError; `choices` limits it to a
|
|
157
|
+
fixed set (`one_of`, applied after `normalise`), which `set` shows and the API schema types as an enum."""
|
|
158
|
+
|
|
123
159
|
key: str
|
|
124
160
|
default: str | Callable[[], str]
|
|
125
161
|
normalise: Callable[[str], str] = _identity
|
|
126
162
|
env: str | None = None # environment variable; default `<APP>_<KEY>`
|
|
163
|
+
choices: Sequence[str] | None = None
|
|
164
|
+
|
|
165
|
+
def __post_init__(self) -> None:
|
|
166
|
+
if self.choices is not None:
|
|
167
|
+
object.__setattr__(self, "choices", one_of(self.choices).choices) # a tuple, and refuses an empty list
|
|
127
168
|
|
|
128
169
|
def default_value(self) -> str:
|
|
129
170
|
d = self.default
|
|
@@ -133,7 +174,15 @@ class Setting:
|
|
|
133
174
|
"""A stored, environment or saved value as its canonical string; ValueError when it is not acceptable."""
|
|
134
175
|
if not isinstance(raw, str):
|
|
135
176
|
raise ValueError("must be text") # str(5) would pass a hand-edited number off as a deliberate string
|
|
136
|
-
|
|
177
|
+
v = self.normalise(raw)
|
|
178
|
+
return v if self.choices is None else one_of(self.choices)(v)
|
|
179
|
+
|
|
180
|
+
def allowed(self) -> tuple[str, ...] | None:
|
|
181
|
+
"""The fixed set of values, from `choices` or a `one_of` normaliser, else None."""
|
|
182
|
+
if self.choices is not None:
|
|
183
|
+
return tuple(self.choices)
|
|
184
|
+
n = self.normalise
|
|
185
|
+
return n.choices if isinstance(n, one_of) else None
|
|
137
186
|
|
|
138
187
|
|
|
139
188
|
def _no_list() -> list[str]:
|
|
@@ -231,11 +280,19 @@ class JsonFileStore:
|
|
|
231
280
|
|
|
232
281
|
class Settings:
|
|
233
282
|
def __init__(
|
|
234
|
-
self,
|
|
283
|
+
self,
|
|
284
|
+
app: str,
|
|
285
|
+
settings: Sequence[AnySetting],
|
|
286
|
+
*,
|
|
287
|
+
prefix: str | None = None,
|
|
288
|
+
store: SettingsStore | None = None,
|
|
289
|
+
numbers: bool = False,
|
|
235
290
|
) -> None:
|
|
236
291
|
"""`prefix` names the environment variables (`<PREFIX>_HOME`, `<PREFIX>_<KEY>`); default the upper-cased app name with `-` as `_`.
|
|
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).
|
|
292
|
+
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).
|
|
293
|
+
`numbers=True` makes `model()` type `whole_between`/`number_between` settings as numbers (see the module notes)."""
|
|
238
294
|
self.app = app
|
|
295
|
+
self.numbers = numbers
|
|
239
296
|
self.prefix = prefix or app.upper().replace("-", "_")
|
|
240
297
|
self._by_key: dict[str, AnySetting] = {s.key: s for s in settings}
|
|
241
298
|
self.file = JsonFileStore(self.path)
|
|
@@ -308,6 +365,11 @@ class Settings:
|
|
|
308
365
|
s = self._by_key[key]
|
|
309
366
|
return s.sep.join(v) if isinstance(s, ListSetting) and isinstance(v, list) else cast("str", v)
|
|
310
367
|
|
|
368
|
+
def allowed(self, key: str) -> tuple[str, ...] | None:
|
|
369
|
+
"""The values setting `key` may take, when it has a fixed set (`choices` or `one_of`), else None."""
|
|
370
|
+
s = self._by_key[key]
|
|
371
|
+
return s.allowed() if isinstance(s, Setting) else None
|
|
372
|
+
|
|
311
373
|
def get_list(self, key: str) -> list[str]:
|
|
312
374
|
s = self._by_key[key]
|
|
313
375
|
if not isinstance(s, ListSetting):
|
|
@@ -327,18 +389,30 @@ class Settings:
|
|
|
327
389
|
return {k: self.value(k) for k in self._by_key}
|
|
328
390
|
|
|
329
391
|
def model(self) -> type[Any]:
|
|
330
|
-
"""The settings as a pydantic model
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
a
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
}
|
|
392
|
+
"""The settings as a pydantic model, named `<App>Settings`: a field per setting, `str` (a `Literal` of its
|
|
393
|
+
choices when it has them; with `numbers=True`, `int` or `float` with its range for `whole_between` and
|
|
394
|
+
`number_between`), or `list[str]` for a `ListSetting`. `web.base_app` declares it as the settings routes'
|
|
395
|
+
response, so `/api/openapi.json` describes each setting and a web app's types can be generated from it. Built
|
|
396
|
+
on each call; pydantic is imported here, so a CLI that only reads settings does not load it."""
|
|
397
|
+
from pydantic import Field, create_model
|
|
398
|
+
|
|
399
|
+
fields: dict[str, Any] = {k: self._field(s, Field) for k, s in self._by_key.items()}
|
|
339
400
|
name = "".join(p.capitalize() for p in re.split(r"[^0-9A-Za-z]+", self.app) if p) + "Settings"
|
|
340
401
|
return create_model(name, **fields)
|
|
341
402
|
|
|
403
|
+
def _field(self, s: AnySetting, field: Callable[..., Any]) -> tuple[Any, Any]:
|
|
404
|
+
if isinstance(s, ListSetting):
|
|
405
|
+
return list[str], ...
|
|
406
|
+
allowed = s.allowed()
|
|
407
|
+
if allowed is not None:
|
|
408
|
+
return Literal[allowed], ... # pyright: ignore[reportInvalidTypeForm] - a Literal built at run time # ty: ignore[invalid-type-form]
|
|
409
|
+
n = s.normalise
|
|
410
|
+
if self.numbers and isinstance(n, whole_between):
|
|
411
|
+
return int, field(..., ge=n.lo, le=n.hi)
|
|
412
|
+
if self.numbers and isinstance(n, number_between):
|
|
413
|
+
return float, field(..., ge=n.lo, le=n.hi)
|
|
414
|
+
return str, ...
|
|
415
|
+
|
|
342
416
|
def folder(self, key: str) -> str:
|
|
343
417
|
"""The setting `key` as a folder that exists (created when asked for)."""
|
|
344
418
|
p = self.get(key)
|
strata_python/testing.py
CHANGED
|
@@ -15,6 +15,7 @@ Testing policy).
|
|
|
15
15
|
FakeRun `subprocess.run` / `check_output`; `.returns` maps a command-line substring to stdout, `.code` fails
|
|
16
16
|
Sleeper `time.sleep` that returns at once and records `.delays`
|
|
17
17
|
run_cli an argparse `main(argv)` in this process -> CliResult; run_module the same as a real `python -m`
|
|
18
|
+
assert_openapi_current the committed schema file equals what the app answers now (cli.add_openapi writes it)
|
|
18
19
|
FakeModels a stand-in strata-models service (jobs, leases, registry) for `strata_python.clients.models`; served
|
|
19
20
|
by the `fake_models` fixture. MODELS_RESULTS holds one reply per role in the service's shapes.
|
|
20
21
|
"""
|
|
@@ -301,6 +302,18 @@ for _role in ("text", "judge-text", "judge-vision", "judge-audio"):
|
|
|
301
302
|
MODELS_RESULTS[_role] = MODELS_RESULTS["vision-language"]
|
|
302
303
|
|
|
303
304
|
|
|
305
|
+
def assert_openapi_current(create_app: Callable[[], Any], path: str | os.PathLike[str]) -> None:
|
|
306
|
+
"""Fail, with the command to run, when the committed OpenAPI file at `path` is not what `create_app()` answers
|
|
307
|
+
now: the unit test every app with generated web types writes."""
|
|
308
|
+
from strata_python.web import openapi_text # FastAPI only when asked
|
|
309
|
+
|
|
310
|
+
file = Path(path)
|
|
311
|
+
current = file.read_text(encoding="utf-8") if file.is_file() else None
|
|
312
|
+
if current != openapi_text(create_app()):
|
|
313
|
+
state = "missing" if current is None else "out of date"
|
|
314
|
+
raise AssertionError(f"{file} is {state}: run the app's `openapi` command and commit the file")
|
|
315
|
+
|
|
316
|
+
|
|
304
317
|
class FakeModels:
|
|
305
318
|
"""A stand-in strata-models service for an app's tests, over real HTTP: the `fake_models` fixture serves `.app` on
|
|
306
319
|
a loopback port and points `STRATA_MODELS_URL` at it, so the app's own calls through `strata_python.clients.models`
|
strata_python/web.py
CHANGED
|
@@ -13,6 +13,7 @@ assets are relative (Vite `base: './'`)."""
|
|
|
13
13
|
import argparse
|
|
14
14
|
import concurrent.futures
|
|
15
15
|
import datetime
|
|
16
|
+
import json
|
|
16
17
|
import os
|
|
17
18
|
import platform
|
|
18
19
|
import shutil
|
|
@@ -82,7 +83,8 @@ def base_app(
|
|
|
82
83
|
return settings.all()
|
|
83
84
|
|
|
84
85
|
@app.put("/api/settings", response_model=shape)
|
|
85
|
-
|
|
86
|
+
# numbers too: with Settings(numbers=True) the web app sends back the numbers GET gave it; save() takes str(n)
|
|
87
|
+
def put_settings(changes: dict[str, str | int | float | list[str] | None]) -> dict[str, str | list[str]]: # pyright: ignore[reportUnusedFunction]
|
|
86
88
|
try:
|
|
87
89
|
settings.save(changes)
|
|
88
90
|
except (KeyError, ValueError) as e:
|
|
@@ -92,6 +94,13 @@ def base_app(
|
|
|
92
94
|
return app
|
|
93
95
|
|
|
94
96
|
|
|
97
|
+
def openapi_text(app: FastAPI) -> str:
|
|
98
|
+
"""The app's OpenAPI schema as the text an app commits for strata-react's `strata-api-types`: sorted keys, indent 1,
|
|
99
|
+
non-ASCII kept, a final newline, so two runs and a git diff compare like with like. Nothing in it comes from the
|
|
100
|
+
machine or the moment; `base_app`'s version is in `info.version`, so a release changes the file as it should."""
|
|
101
|
+
return json.dumps(app.openapi(), indent=1, sort_keys=True, ensure_ascii=False) + "\n"
|
|
102
|
+
|
|
103
|
+
|
|
95
104
|
def source_commit(path: str) -> str | None:
|
|
96
105
|
"""The git commit of the checkout that holds `path` (pass `__file__`), read from `.git` without running git, or
|
|
97
106
|
None outside a checkout (an installed wheel). A worktree's `.git` file and packed refs are followed."""
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: strata-python
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.6
|
|
4
4
|
Summary: Common code for Python web server apps: OS helpers, settings, FastAPI serving, CLI commands, test fixtures and the strata-check gate
|
|
5
5
|
Project-URL: Homepage, https://github.com/jburnhams/strata-python
|
|
6
6
|
Project-URL: Source, https://github.com/jburnhams/strata-python
|
|
@@ -53,9 +53,9 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
|
|
|
53
53
|
|---|---|
|
|
54
54
|
| `strata_python.oslib` | Cross-platform file locks, process liveness (`pid_alive`), `kill_tree`, `lower_priority`, `detached_kwargs`, `load_average`, `start_supervised`/`watch_supervisor`/`kill_group` (a child in its own process group that dies with its parent), `venv_python`, `cli_command(module)` |
|
|
55
55
|
| `strata_python.settings` | `Settings` / `Setting` / `ListSetting`: one JSON file in `~/.<app>` with `<APP>_*` environment overrides, validation (`absolute_path`, `non_empty`, `number_between`, `whole_between`, `iso_date`, `boolean`), typed getters, atomic saves, and `bind(store)` to keep them elsewhere (`strata_python.db.settings.TableStore`) |
|
|
56
|
-
| `strata_python.web` | `base_app` (health with the app's own fields and `commit` + typed settings routes), `add_error_handlers` (exceptions to `ErrorBody` responses), `add_system` (`GET /api/system`: folders, disks, services), `source_commit`, `add_web` (built web app or stand-in page at every non-API path), `with_base` (reverse-proxy-safe `<base href>`), `static_file` (path-safe), `serve` |
|
|
57
|
-
| `strata_python.cli` | `add_doctor` (imports, labels, optional modules and the app's own `Check`s), `add_set`, `add_serve` for the app's argparse subcommands |
|
|
58
|
-
| `strata_python.contracts` | The shapes the apps' APIs share, as pydantic models for `response_model`: `Health`, `SystemInfo`, `ErrorBody`, `Task` (with `TaskState`), `Progress`, `Page[T]`, `FileRef`, `Judgment` |
|
|
56
|
+
| `strata_python.web` | `base_app` (health with the app's own fields and `commit` + typed settings routes), `add_error_handlers` (exceptions to `ErrorBody` responses), `add_system` (`GET /api/system`: folders, disks, services), `source_commit`, `add_web` (built web app or stand-in page at every non-API path), `with_base` (reverse-proxy-safe `<base href>`), `static_file` (path-safe), `serve`, `openapi_text` (the schema as stable text) |
|
|
57
|
+
| `strata_python.cli` | `add_doctor` (imports, labels, optional modules and the app's own `Check`s), `add_set`, `add_serve`, `add_openapi` (the schema file for strata-react's `strata-api-types`) for the app's argparse subcommands |
|
|
58
|
+
| `strata_python.contracts` | The shapes the apps' APIs share, as pydantic models for `response_model`: `Health`, `SystemInfo`, `ErrorBody`, `Task` (with `TaskState`), `Progress`, `Page[T]`, `FileRef`, `Judgment`; `ApiModel`, a base for the app's own responses whose defaulted fields stay required in the schema |
|
|
59
59
|
| `strata_python.client` | `ServiceClient`, the standard-library base for calling a strata service: JSON calls, `Rejected` (4xx, with the reason and payload) and `Unavailable` (down or 5xx), retried reads, a long-poll `wait`, `available()`, and `env_url` |
|
|
60
60
|
| `strata_python.tasks` | Work outside a request: `next_state`/`backoff_s`/`RetryLater` (when to retry), `report_progress` and `ProgressReporter` (throttled), `SingleFlight` (one run per key, `Conflict` on a second), `StatusFile` and `Detached` (a process that outlives the server), `Ticker` (a loop that survives its errors), and with the `[db]` extra `tasks.queue` (`Queue`, `Worker`, `jobs_table`: durable jobs with retry, dedupe, resources, cancel and crash recovery) |
|
|
61
61
|
| `strata_python.files` | Atomic writes (`atomic_path` keeps the extension for ffmpeg, `atomic_open`, `write_json_atomic`, `write_text_atomic`, `write_bytes_atomic`), `read_json(path, default)`, `sha256`/`sha256_hex`, `quick_fingerprint` (size and both ends), `stat_key` (a cache key that follows the file), `inside(root, path)` (refuses `..` and links out), and `DiskCache` (values on disk with an age; `json(key, fetch, max_age_s)`) |
|
|
@@ -66,11 +66,11 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
|
|
|
66
66
|
| `strata_python.clients.models` | The strata-models client, standard library only: `run`, `submit`, `wait`, `role_model`, `gpu_lease`, a shortcut for every role the service runs (`faces`, `face_kind`, `transcribe`, `ocr`, `speak`, `denoise_audio`, `audio_quality`, `generate_image`, `embed`, `enhance_video`, and `ask` for the language models) and a typed result for each |
|
|
67
67
|
| `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
|
|
68
68
|
| pytest plugin | Loaded automatically: hermetic home and data folders (`strata_env` adds the app's own variables), a no-network guard, `http_server` and `live_app`, the `fake_urlopen`, `fake_popen`, `fake_run` and `no_sleep` fixtures, `fake_models` (a stand-in strata-models), and the `integration` marker on everything under `tests/integration` |
|
|
69
|
-
| `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) `FakeModels`,
|
|
70
|
-
| `strata_python.db` (extra `[db]`) | The shared database: `connect("myapp")` (the app's schema of one shared Postgres, or a SQLite path), a declarative base with the shared `NAMING_CONVENTION` for typed models, Alembic migrations with no per-app `env.py`, the live-database guard, the `strata-db` command,
|
|
69
|
+
| `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) `FakeModels`, the CLI runners `run_cli(main, *args)` and `run_module("myapp", *args, src=...)`, and `assert_openapi_current(create_app, path)` |
|
|
70
|
+
| `strata_python.db` (extra `[db]`) | The shared database: `connect("myapp")` (the app's schema of one shared Postgres, or a SQLite path), a declarative base with the shared `NAMING_CONVENTION` for typed models, Alembic migrations with no per-app `env.py`, the live-database guard, the `strata-db` command, the `db_*` fixtures (SQLite by default, a throwaway Postgres with `--pg`), and `strata_python.db.web` (`add_database`, `DbSession`) for a server's records |
|
|
71
71
|
| `strata_python.pages` (extra `[pdf]`) | A scanned page described as blocks, lines, styled spans and figures in scan pixels, drawn as a PDF with real embedded fonts (`render`), and read back as pixels at the scan's dpi (`rasterise`) and as text (`read_text`): for rebuilding scanned books, and for scoring a rebuild with the renderer that prints it |
|
|
72
72
|
| `strata-check` | The one gate: lockfile, ruff, `ruff format`, pyright strict, ty, unit tests with coverage |
|
|
73
|
-
| `strata-public-check` | Fails on email addresses, private IPv4 addresses, home-folder paths and the
|
|
73
|
+
| `strata-public-check` | Fails on email addresses, private IPv4 addresses, home-folder paths, the repo's own `[tool.strata-public-check] deny` regexes and the owner's `STRATA_PUBLIC_DENY` ones in a tree, sdist or wheel; run before anything public is published. Reads Python, web source (`.ts`, `.tsx`, `.js`, `.css`, `.html`, `.mdx`, `.svg`...) and config text; in a git checkout only what git would commit, so tool output such as `.coverage` is skipped. Silence a false positive with `[tool.strata-public-check] exclude = ["web/package-lock.json"]` (or `--exclude`), or `strata-public-check: ignore` on the line (never applies to `STRATA_PUBLIC_DENY`) |
|
|
74
74
|
|
|
75
75
|
## Move an app onto it
|
|
76
76
|
|
|
@@ -135,6 +135,7 @@ SETTINGS = Settings(
|
|
|
135
135
|
Setting("data_dir", default=lambda: "/srv/myapp", normalise=absolute_path),
|
|
136
136
|
Setting("greeting", default="Hello", normalise=non_empty),
|
|
137
137
|
Setting("workers", default="2", normalise=whole_between(1, 16)),
|
|
138
|
+
Setting("mode", default="mixed", choices=["mixed", "review", "new"]), # an enum in the API schema
|
|
138
139
|
ListSetting("source_roots", item=absolute_path, env="MYAPP_SOURCES"), # MYAPP_SOURCES split on os.pathsep
|
|
139
140
|
],
|
|
140
141
|
prefix="MYAPP", # only if the app already runs with other variable names
|
|
@@ -147,6 +148,8 @@ SETTINGS.folder("data_dir") # the value as a folder, created if missing
|
|
|
147
148
|
|
|
148
149
|
Values are canonical strings, and lists of them. Normalisers for the common kinds give one spelling each: `number_between(lo, hi)`, `whole_between(lo, hi)`, `iso_date(allow_blank=True)` and `boolean`, read back with `get_float`, `get_int` and `get_bool`. A `ListSetting` is a JSON list in the file (a string there is split, so a hand edit works), split on `sep` in the environment (`os.pathsep` by default, `sep=","` for names), with `item` normalising each entry. `get_list` returns it, and `all()` and `GET /api/settings` return it as JSON. `get` and `set` show it joined, and `save` takes a list or a joined string.
|
|
149
150
|
|
|
151
|
+
A setting that takes one of a fixed set has `choices=[m.value for m in Mode]` (or `normalise=one_of(...)`): a value is matched without regard to case and stored as the choice is spelled, anything else is refused with the list, `set` shows the choices, and the schema in `/api/openapi.json` has an `enum`, so the web app's generated type needs no narrowing by hand. `Settings(..., numbers=True)` also sends `whole_between` and `number_between` settings as JSON numbers, with `minimum` and `maximum` in the schema; it changes what `GET /api/settings` sends, so turn it on with the web app's change. `PUT /api/settings` takes numbers either way.
|
|
152
|
+
|
|
150
153
|
To keep the values in the app's database instead of the file, add the table to the models and bind at service start, after the migrations. The file's values are copied in the first time, and the CLI and tests without a database keep using the file:
|
|
151
154
|
|
|
152
155
|
```python
|
|
@@ -208,6 +211,8 @@ def main(argv=None):
|
|
|
208
211
|
return args.fn(args)
|
|
209
212
|
```
|
|
210
213
|
|
|
214
|
+
An app with a web front end on strata-react adds `cli.add_openapi(sub, create_app)`: `myapp openapi` writes `web/openapi.json` (or `-o PATH`, `-o -` for stdout) for `strata-api-types`, in a stable form (sorted keys, indent 1, a final newline, nothing from the machine), and `myapp openapi --check` exits 1 when the committed file is out of date. Its unit test is `strata_python.testing.assert_openapi_current(create_app, "web/openapi.json")`. Build response models on `contracts.ApiModel` so a field with a default is not optional (`?`) in the generated types.
|
|
215
|
+
|
|
211
216
|
Delete the hand-written `doctor`, `set` and `serve` subparsers. Each app's port belongs in its deploy units, not in this library.
|
|
212
217
|
|
|
213
218
|
A doctor that needs more than imports takes labels, optional modules, checks and its own hint, and prints every app's rows in the same columns:
|
|
@@ -388,7 +393,21 @@ migrations = "migrations" # the app's Alembic revisions, unchanged
|
|
|
388
393
|
```
|
|
389
394
|
- Environment: `STRATA_DB_LIVE=1` in the service unit (next to the old variable until every app has moved), and `STRATA_DB_DATABASE` naming the shared database. It has no built-in name any more, because that name is the owner's and this package is public; set it once where the services get their environment. `STRATA_DB_URL` and `<APP>_DATABASE_URL` work as before. Tests and CI: `STRATA_DB_TEST_ADMIN_URL`, `STRATA_DB_TEST=postgres`.
|
|
390
395
|
- Commands: `strata-db revision -m "..."`, `strata-db check`, `strata-db migrate --live`, `strata-db current --live`, `strata-db new-app`, `strata-db init` (or `python -m strata_python.db`).
|
|
391
|
-
- At service start (only there): `Project.load(__file__).upgrade(connect("myapp"))
|
|
396
|
+
- At service start (only there): `Project.load(__file__).upgrade(connect("myapp"))`, or `Project.load(__file__).open(default=local_url(SETTINGS))`, which connects and migrates, falling back to `<settings home>/myapp.db` when no database is configured (the folder is made).
|
|
397
|
+
- An app installed as a wheel (a service from `uv tool install`) has no pyproject.toml beside its code. `strata-db init --package src/myapp` declares the keys in `src/myapp/strata-db.toml` instead, with `migrations/` beside it, and puts `[tool.strata-db] file = "src/myapp/strata-db.toml"` in pyproject.toml. Both ship in the wheel, `Project.load(__file__)` finds the file by walking up from the module, and strata-db and the pytest plugin follow the pointer, so there is one declaration and no drift test. To move an existing app, move the keys and the `migrations` folder into the package and leave `file = ...` in the table.
|
|
398
|
+
- A FastAPI server's records:
|
|
399
|
+
|
|
400
|
+
```python
|
|
401
|
+
from strata_python.db import Project, local_url
|
|
402
|
+
from strata_python.db.web import DbSession, add_database
|
|
403
|
+
|
|
404
|
+
add_database(app, Project.load(__file__), default=lambda: local_url(SETTINGS))
|
|
405
|
+
|
|
406
|
+
@app.get("/api/notes")
|
|
407
|
+
def notes(db: DbSession) -> list[NoteOut]: ...
|
|
408
|
+
```
|
|
409
|
+
|
|
410
|
+
The engine is opened and migrated on the first request that needs one (a server nobody records on never creates a database), kept on `app.state` and disposed when the server stops, after the app's own lifespan. A failure to open is that request's error and is tried again on the next. Delete the app's `db.py` fallback, its session dependency and the conftest that disposed the engine.
|
|
392
411
|
- Tests: the plugin is registered with every install and does nothing until the extra is installed and the project has `[tool.strata-db]` (or `strata_db = true` in `[tool.pytest.ini_options]`; `strata_db = false` turns it off). So an app can take a 0.2.x release before it moves its database, even with the old database package still installed. Then `db_session`, `db_engine`, `db_url` (a URL for code that builds its own engine), `db_env` (points the app's own `connect("myapp")` at the test database; make it autouse in `conftest.py` for an app that connects by itself), `db_backend`, `db_project`. Migrations run once into a template and each test gets a copy, so a test costs a file copy. `pytest --pg` (or `--strata-pg`, which no other plugin can take) runs the same tests on a private Postgres the run starts for itself (needs the PostgreSQL server binaries), or on `STRATA_DB_TEST_ADMIN_URL`. Add the standard tests once:
|
|
393
412
|
|
|
394
413
|
```python
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
strata_python/__init__.py,sha256=eF-f5-pwPokTJjoq063Hr78JTnjPkVm-3hQBN9tXqDs,1723
|
|
2
2
|
strata_python/check.py,sha256=lFjXuPjVIWn6dBu2yMKIW-76RloUREijuMHCRsBW4Z8,2932
|
|
3
|
-
strata_python/cli.py,sha256=
|
|
3
|
+
strata_python/cli.py,sha256=guO3aDiSe8Ri4-0aHDLCwUKMiu6rLpnSo7leWzf0Ehw,8170
|
|
4
4
|
strata_python/client.py,sha256=S-cfDQqbO0dJ951TAiFyW2CbkFQkN1OWnUBCYaTO3Lg,7911
|
|
5
|
-
strata_python/contracts.py,sha256=
|
|
5
|
+
strata_python/contracts.py,sha256=DNyCi8pKXrfaRIadJ3DuAH8YUbXh4fVVY5T21sAJf98,6379
|
|
6
6
|
strata_python/files.py,sha256=jJMFnzsigY29f6EcpjEtbBnc-66FCOuw875epYMOSjg,11423
|
|
7
7
|
strata_python/http.py,sha256=dltLx14TqQGuLhFeFoYyNZiOVAXx7ZEeXPQwPjaT2hc,16152
|
|
8
8
|
strata_python/http_server.py,sha256=64uYWy4zFxughOgtvkssGXMJDZ7jhRj1bxUIfnzte8w,4475
|
|
@@ -10,29 +10,30 @@ strata_python/images.py,sha256=nNQ7fQxkpmnTf5iotYlR7VejxCfthXgIpMEGTsLvNVE,4872
|
|
|
10
10
|
strata_python/live.py,sha256=kNY6h6gMxBo9l78UoGUIWjcADeZi4eZuAEp0jqDowEE,1215
|
|
11
11
|
strata_python/media.py,sha256=66Pk1_CTHyApKlWD8LuzS08O3EOx-7dNaj9AkEbNxmw,12647
|
|
12
12
|
strata_python/oslib.py,sha256=vfZDUCNZnTjjjB704eoyNXlPFCz2yVR3puFljE0Z1gE,12137
|
|
13
|
-
strata_python/public_check.py,sha256=
|
|
13
|
+
strata_python/public_check.py,sha256=2N1X15D578QFgN32TUazFDj6SOHtAJhjOgoZNOQu_vU,13398
|
|
14
14
|
strata_python/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
15
15
|
strata_python/pytest_plugin.py,sha256=BaD-XokrX1PMMj0Cqxj9IJTb6EXBp7ozQZ6SSCDumMg,7223
|
|
16
|
-
strata_python/settings.py,sha256=
|
|
16
|
+
strata_python/settings.py,sha256=YeQMJwyqFNX7L3bbgbwRN1hdfzBem9uWxqg_WVswT-A,18688
|
|
17
17
|
strata_python/stats.py,sha256=nc6qXELpMg7eK0xjFo45M1FK7FR3q89be3VCJzExKYc,8354
|
|
18
|
-
strata_python/testing.py,sha256=
|
|
19
|
-
strata_python/web.py,sha256
|
|
18
|
+
strata_python/testing.py,sha256=WvakeIAJtdeOrIDq32WWXfWkfBkMQ2cUU279L0Ebhs0,20888
|
|
19
|
+
strata_python/web.py,sha256=-AWb9Ad2e870zbr4OT1oZS1IpOZ0nd-jdpu4ICOHejE,13528
|
|
20
20
|
strata_python/clients/__init__.py,sha256=xivuysmYG7rbCGProVNvdSs-h4xVFQsuqUY6EwzuJbk,182
|
|
21
21
|
strata_python/clients/models.py,sha256=vxnvINQ_xQRbU848BTnGyjlTcr1-bhv6GAkrCN5ZDuU,30314
|
|
22
|
-
strata_python/db/__init__.py,sha256=
|
|
22
|
+
strata_python/db/__init__.py,sha256=Vx28OmktWBhEM9gj1VxoxNuJDvdtpYoJ3-prrzoBR40,4009
|
|
23
23
|
strata_python/db/__main__.py,sha256=nHCtenRtjL_Ouig4FHh60dax2oILeVdoIIKrxXEc6Ss,106
|
|
24
|
-
strata_python/db/cli.py,sha256=
|
|
25
|
-
strata_python/db/config.py,sha256=
|
|
26
|
-
strata_python/db/engine.py,sha256=
|
|
24
|
+
strata_python/db/cli.py,sha256=kCNHDlFIzECtvExUGBaJ0BK4ZqesGHS7Jjnhh-gWIpI,10896
|
|
25
|
+
strata_python/db/config.py,sha256=1Bjz5T5jOTeeB_6e9I2BJB62aqM8UDjoGd2JsJ7NLaE,5098
|
|
26
|
+
strata_python/db/engine.py,sha256=fcHJeLiIXDxWzXzSkG3HD_QM3VI1VtksSvFfQzR_0O8,2165
|
|
27
27
|
strata_python/db/guard.py,sha256=HyRtDMRgTWFgT9D4gNomA18ErR1mqJbzJgtU7xAqBG8,6722
|
|
28
28
|
strata_python/db/migrations.py,sha256=Hb77afQNjtKS2DD-zmen4BscbAx9DRjLHtcPOdzuaGo,12138
|
|
29
29
|
strata_python/db/models.py,sha256=bWg1xgn-VgDLnFe0Ps_2hiYD5fp-_8W8mCErATS3RQs,3005
|
|
30
|
-
strata_python/db/project.py,sha256=
|
|
30
|
+
strata_python/db/project.py,sha256=JKkjYOWtiVJ5YQdDctLlI2L9nfyk76wMq8SJKJCTdVA,6393
|
|
31
31
|
strata_python/db/pytest_plugin.py,sha256=opJb5AI8Dy8IYqkx6IcZV1KBeMB4DHmnaEKd36h_r9Q,8978
|
|
32
32
|
strata_python/db/scratch.py,sha256=mlb4a1MTevhBS3WWIJOvUiyggLGeBR9NbXi8Jh8Rf2k,5059
|
|
33
33
|
strata_python/db/settings.py,sha256=sg1xDhqYhTzUx8_8-VKJBlpb1qRKKYhujJYZ8KeIbbY,2635
|
|
34
34
|
strata_python/db/testing.py,sha256=U39cwmg_6Dp4XPyc1Z2NWVgSGI_Q93Y--78_7PgEwes,1979
|
|
35
35
|
strata_python/db/testserver.py,sha256=I5__od7FEjNBcYYcJqmzLA_5t1wRqJ85NBukZMebS4Q,8806
|
|
36
|
+
strata_python/db/web.py,sha256=CmSVg7BNuP_uHmG7WsnN0VF7xYKskuyDQBb37EdapYo,4223
|
|
36
37
|
strata_python/db/_alembic/env.py,sha256=gXzRn02h59PB_1RaABkaT6GuyuzPQCZh3Z5ml2JlS34,1125
|
|
37
38
|
strata_python/db/_alembic/script.py.mako,sha256=04kgeBtNMa4cCnG8CfQcKt6P6rnloIfj8wy0u_DBydM,704
|
|
38
39
|
strata_python/pages/__init__.py,sha256=6QsTqJbFiuLCxywt8C0D6nyXRXjpzI1Xoo5u6rK9toQ,665
|
|
@@ -46,8 +47,8 @@ strata_python/tasks/queue.py,sha256=b4in3XnplTlapL_ECTs_WYJcittYj3iKz7q_fQ8_HDY,
|
|
|
46
47
|
strata_python/tasks/retry.py,sha256=NztmOf3Q-rl5y3CZlfP1qcDqPT0jOiIDjMfD-MUkr5s,3995
|
|
47
48
|
strata_python/tasks/status.py,sha256=cZvYghNAGJRlpVIJAtUSb5pW19UbxR6bNQU4etJMYN4,7440
|
|
48
49
|
strata_python/tasks/ticker.py,sha256=V6JLWgAGV5sIGeX1vp4t35omuRvvB6AYWv_lzJAq69Y,2860
|
|
49
|
-
strata_python-0.2.
|
|
50
|
-
strata_python-0.2.
|
|
51
|
-
strata_python-0.2.
|
|
52
|
-
strata_python-0.2.
|
|
53
|
-
strata_python-0.2.
|
|
50
|
+
strata_python-0.2.6.dist-info/METADATA,sha256=dDY27gm38DSVlkMD1G1_GIVYjyYut3TsTEfbb_YAwIM,37541
|
|
51
|
+
strata_python-0.2.6.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
52
|
+
strata_python-0.2.6.dist-info/entry_points.txt,sha256=6RVv-uDumVQ-KY2YdvKwd5R3l6P9WQD4kPtPOKKEM-I,256
|
|
53
|
+
strata_python-0.2.6.dist-info/licenses/LICENSE,sha256=9yVMCPoK7unONyTAiDYjMTt3MZPGJ639nWOwxyNsZGg,1066
|
|
54
|
+
strata_python-0.2.6.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|