strata-python 0.2.0__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/__init__.py +19 -0
- strata_python/check.py +68 -0
- strata_python/cli.py +71 -0
- strata_python/http_server.py +119 -0
- strata_python/live.py +30 -0
- strata_python/oslib.py +117 -0
- strata_python/public_check.py +133 -0
- strata_python/py.typed +0 -0
- strata_python/pytest_plugin.py +80 -0
- strata_python/settings.py +132 -0
- strata_python/web.py +98 -0
- strata_python-0.2.0.dist-info/METADATA +82 -0
- strata_python-0.2.0.dist-info/RECORD +16 -0
- strata_python-0.2.0.dist-info/WHEEL +4 -0
- strata_python-0.2.0.dist-info/entry_points.txt +6 -0
- strata_python-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Common code for the strata Python web server apps (FastAPI + CLI): the parts every app was copying.
|
|
2
|
+
|
|
3
|
+
oslib file locks, process liveness and termination, priority, how to start a CLI (POSIX and Windows)
|
|
4
|
+
settings one JSON settings file per app with environment overrides and validation
|
|
5
|
+
web reverse-proxy-safe page serving, health and settings routes, static files, the uvicorn runner
|
|
6
|
+
cli argparse commands every app has: doctor, set, serve
|
|
7
|
+
http_server a real scripted HTTP server on loopback for tests of outbound requests
|
|
8
|
+
live run a FastAPI app on a real loopback port for tests
|
|
9
|
+
pytest plugin (automatic once installed): hermetic environment, no-network guard, `http_server` and `live_app` fixtures
|
|
10
|
+
check `strata-check`, the one gate: lockfile, ruff, ruff format, pyright, ty, unit tests with coverage
|
|
11
|
+
public_check `strata-public-check`: no email addresses, private addresses, home paths or owner-listed names in what is published
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
__version__ = version("strata-python")
|
|
18
|
+
except PackageNotFoundError: # running from a source tree that was never installed
|
|
19
|
+
__version__ = "0+unknown"
|
strata_python/check.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""`strata-check`: the one gate for an app, run before every commit by hand, by the git hooks and by CI (so they cannot disagree).
|
|
2
|
+
|
|
3
|
+
uv run strata-check # lockfile, ruff lint, ruff format, pyright, ty, then the unit tests with coverage
|
|
4
|
+
uv run strata-check --fast # skip the tests (for a commit hook)
|
|
5
|
+
uv run strata-check --fix # apply safe ruff fixes and formatting first
|
|
6
|
+
|
|
7
|
+
Two type checkers gate: pyright (strict) and ty; when ty is stable and as strict as pyright's strict mode, drop the pyright step. `--fix` never uses ruff's unsafe fixes: they
|
|
8
|
+
rewrite code in ways tests have to catch (see the README). Run it from the project root. Optional configuration in pyproject.toml:
|
|
9
|
+
|
|
10
|
+
[tool.strata-check]
|
|
11
|
+
paths = ["src", "tests", "scripts"] # what ruff checks (only folders that exist are passed); ty checks the first one
|
|
12
|
+
tests = "tests/unit" # what the coverage run covers
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
import tomllib
|
|
19
|
+
from collections.abc import Sequence
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
DEFAULT_PATHS = ("src", "tests", "scripts")
|
|
23
|
+
DEFAULT_TESTS = "tests/unit"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def config(root: str = ".") -> dict[str, Any]:
|
|
27
|
+
try:
|
|
28
|
+
with open(os.path.join(root, "pyproject.toml"), "rb") as f:
|
|
29
|
+
return tomllib.load(f).get("tool", {}).get("strata-check", {})
|
|
30
|
+
except FileNotFoundError:
|
|
31
|
+
return {}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def steps(root: str = ".", *, tests: bool = True) -> list[tuple[str, list[str]]]:
|
|
35
|
+
cfg = config(root)
|
|
36
|
+
paths = [p for p in cfg.get("paths", DEFAULT_PATHS) if os.path.isdir(os.path.join(root, p))]
|
|
37
|
+
out: list[tuple[str, list[str]]] = []
|
|
38
|
+
if os.path.exists(os.path.join(root, "uv.lock")):
|
|
39
|
+
out.append(("lockfile is current", ["uv", "lock", "--check"]))
|
|
40
|
+
out += [
|
|
41
|
+
("ruff lint", ["ruff", "check", *paths]),
|
|
42
|
+
("ruff format", ["ruff", "format", "--check", *paths]),
|
|
43
|
+
("pyright (strict)", ["pyright"]),
|
|
44
|
+
("ty", ["ty", "check", paths[0] if paths else "."]),
|
|
45
|
+
]
|
|
46
|
+
if tests:
|
|
47
|
+
out.append(("unit tests + coverage", ["pytest", cfg.get("tests", DEFAULT_TESTS), "--cov", "-q"]))
|
|
48
|
+
return out
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def run(label: str, cmd: Sequence[str]) -> bool:
|
|
52
|
+
print(f"\n==> {label}: {' '.join(cmd)}", flush=True)
|
|
53
|
+
return subprocess.run(cmd).returncode == 0 # noqa: S603 (fixed commands from this file)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
57
|
+
args = list(sys.argv[1:] if argv is None else argv)
|
|
58
|
+
if "--fix" in args:
|
|
59
|
+
paths = [p for p in config().get("paths", DEFAULT_PATHS) if os.path.isdir(p)]
|
|
60
|
+
run("ruff fix (safe fixes only)", ["ruff", "check", "--fix", *paths])
|
|
61
|
+
run("ruff format", ["ruff", "format", *paths])
|
|
62
|
+
failed = [label for label, cmd in steps(tests="--fast" not in args) if not run(label, cmd)]
|
|
63
|
+
print("\n" + ("FAILED: " + ", ".join(failed) if failed else "all checks passed"))
|
|
64
|
+
return 1 if failed else 0
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
if __name__ == "__main__":
|
|
68
|
+
sys.exit(main())
|
strata_python/cli.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""The CLI commands every app has, added to the app's own argparse subparsers.
|
|
2
|
+
|
|
3
|
+
sub = parser.add_subparsers(dest="cmd", required=True)
|
|
4
|
+
add_doctor(sub, "myapp", __version__, ("fastapi", "uvicorn"))
|
|
5
|
+
add_set(sub, SETTINGS)
|
|
6
|
+
add_serve(sub, lambda host, port: web.serve(create_app(), ["--host", host, "--port", str(port)]), default_port=8360)
|
|
7
|
+
args = parser.parse_args(argv); return args.fn(args)
|
|
8
|
+
|
|
9
|
+
Each command sets `fn` on its parser; the handler returns the exit code."""
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import importlib
|
|
13
|
+
import sys
|
|
14
|
+
from collections.abc import Callable, Iterable
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from strata_python.settings import Settings
|
|
18
|
+
|
|
19
|
+
Sub = Any # argparse's subparsers object is a private generic type; only add_parser is used
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def add_doctor(sub: Sub, name: str, version: str, imports: Iterable[str]) -> None:
|
|
23
|
+
"""`doctor`: print the app and Python versions and whether each module in `imports` can be imported (exit 1 if any cannot)."""
|
|
24
|
+
mods = tuple(imports)
|
|
25
|
+
|
|
26
|
+
def doctor(_args: argparse.Namespace) -> int:
|
|
27
|
+
ok = True
|
|
28
|
+
print(f"{name} {version}, python {sys.version.split()[0]}")
|
|
29
|
+
for mod in mods:
|
|
30
|
+
try:
|
|
31
|
+
m = importlib.import_module(mod)
|
|
32
|
+
print(f" ok {mod} {getattr(m, '__version__', '')}".rstrip())
|
|
33
|
+
except ImportError:
|
|
34
|
+
ok = False
|
|
35
|
+
print(f" MISSING {mod}: uv sync")
|
|
36
|
+
return 0 if ok else 1
|
|
37
|
+
|
|
38
|
+
sub.add_parser("doctor", help="check the environment").set_defaults(fn=doctor)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def add_set(sub: Sub, settings: Settings) -> None:
|
|
42
|
+
"""`set KEY [VALUE]`: show a setting, change it, or reset it with the value `default`. A bad key or value exits with the message."""
|
|
43
|
+
|
|
44
|
+
def cmd_set(args: argparse.Namespace) -> int:
|
|
45
|
+
if args.key not in settings.keys:
|
|
46
|
+
sys.exit(f"unknown setting {args.key!r} (known: {', '.join(settings.keys)})")
|
|
47
|
+
if args.value is not None:
|
|
48
|
+
try:
|
|
49
|
+
settings.save({args.key: None if args.value == "default" else args.value})
|
|
50
|
+
except ValueError as e:
|
|
51
|
+
sys.exit(str(e))
|
|
52
|
+
print(f"{args.key} = {settings.get(args.key)}")
|
|
53
|
+
return 0
|
|
54
|
+
|
|
55
|
+
p = sub.add_parser("set", help=f'show or change a setting ({", ".join(settings.keys)}); value "default" resets it')
|
|
56
|
+
p.add_argument("key")
|
|
57
|
+
p.add_argument("value", nargs="?")
|
|
58
|
+
p.set_defaults(fn=cmd_set)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def add_serve(sub: Sub, run: Callable[[str, int], None], *, default_port: int) -> None:
|
|
62
|
+
"""`serve [--host] [--port]`: call `run(host, port)`."""
|
|
63
|
+
|
|
64
|
+
def cmd_serve(args: argparse.Namespace) -> int:
|
|
65
|
+
run(args.host, args.port)
|
|
66
|
+
return 0
|
|
67
|
+
|
|
68
|
+
p = sub.add_parser("serve", help="start the web server")
|
|
69
|
+
p.add_argument("--host", default="127.0.0.1")
|
|
70
|
+
p.add_argument("--port", type=int, default=default_port)
|
|
71
|
+
p.set_defaults(fn=cmd_serve)
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""A real HTTP server on 127.0.0.1 for tests of code that makes outbound requests. The code under test sends actual requests over a real socket (urllib, httpx, requests: whatever it uses), so URL building, headers, encodings and timeouts are all exercised; only the far end is scripted.
|
|
2
|
+
|
|
3
|
+
def test_fetch(http_server):
|
|
4
|
+
http_server.route("GET", "/items/1", {"id": 1}) # JSON body, 200
|
|
5
|
+
http_server.route("GET", "/slow", status=503, body="busy") # a failing reply
|
|
6
|
+
assert fetch(http_server.url + "/items/1") == {"id": 1}
|
|
7
|
+
assert http_server.requests[0].headers["accept"] == "application/json"
|
|
8
|
+
|
|
9
|
+
Every request is recorded in `.requests` (method, path, query, headers, body); a request no route answers gets a 404 and fails the test at teardown, so a forgotten route is never silent. Use it through the `http_server` fixture the strata_python pytest plugin provides."""
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import threading
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
15
|
+
from typing import Any
|
|
16
|
+
from urllib.parse import parse_qs, urlsplit
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class Recorded:
|
|
21
|
+
method: str
|
|
22
|
+
path: str
|
|
23
|
+
query: dict[str, list[str]]
|
|
24
|
+
headers: dict[str, str]
|
|
25
|
+
body: bytes
|
|
26
|
+
|
|
27
|
+
def json(self):
|
|
28
|
+
return json.loads(self.body)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class Route:
|
|
33
|
+
status: int
|
|
34
|
+
body: bytes
|
|
35
|
+
headers: dict[str, str]
|
|
36
|
+
once: bool
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class ScriptedServer:
|
|
41
|
+
httpd: ThreadingHTTPServer
|
|
42
|
+
routes: dict[tuple[str, str], list[Route]] = field(default_factory=lambda: {})
|
|
43
|
+
requests: list[Recorded] = field(default_factory=lambda: [])
|
|
44
|
+
unexpected: list[Recorded] = field(default_factory=lambda: [])
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def url(self) -> str:
|
|
48
|
+
return f"http://127.0.0.1:{self.httpd.server_address[1]}"
|
|
49
|
+
|
|
50
|
+
def route(
|
|
51
|
+
self,
|
|
52
|
+
method: str,
|
|
53
|
+
path: str,
|
|
54
|
+
body: object = b"",
|
|
55
|
+
*,
|
|
56
|
+
status: int = 200,
|
|
57
|
+
headers: dict[str, str] | None = None,
|
|
58
|
+
once: bool = False,
|
|
59
|
+
):
|
|
60
|
+
"""Answer `method path` (query ignored) with `body` (bytes, str, or anything JSON-serialisable). A route answers every matching request; with `once=True` it answers one and is then used up, so several `once` routes for the same request script a sequence (503, then 200)."""
|
|
61
|
+
if isinstance(body, bytes):
|
|
62
|
+
raw, ctype = body, "application/octet-stream"
|
|
63
|
+
elif isinstance(body, str):
|
|
64
|
+
raw, ctype = body.encode(), "text/plain; charset=utf-8"
|
|
65
|
+
else:
|
|
66
|
+
raw, ctype = json.dumps(body).encode(), "application/json"
|
|
67
|
+
self.routes.setdefault((method.upper(), path), []).append(
|
|
68
|
+
Route(status, raw, {"Content-Type": ctype, **(headers or {})}, once)
|
|
69
|
+
)
|
|
70
|
+
return self
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def make_handler(state: "ScriptedServer"):
|
|
74
|
+
class Handler(BaseHTTPRequestHandler):
|
|
75
|
+
def _serve(self):
|
|
76
|
+
parts = urlsplit(self.path)
|
|
77
|
+
length = int(self.headers.get("Content-Length") or 0)
|
|
78
|
+
rec = Recorded(
|
|
79
|
+
self.command,
|
|
80
|
+
parts.path,
|
|
81
|
+
parse_qs(parts.query),
|
|
82
|
+
{k.lower(): v for k, v in self.headers.items()},
|
|
83
|
+
self.rfile.read(length) if length else b"",
|
|
84
|
+
)
|
|
85
|
+
state.requests.append(rec)
|
|
86
|
+
queue = state.routes.get((self.command, parts.path))
|
|
87
|
+
if not queue:
|
|
88
|
+
state.unexpected.append(rec)
|
|
89
|
+
self.send_response(404)
|
|
90
|
+
self.send_header("Content-Length", "0")
|
|
91
|
+
self.end_headers()
|
|
92
|
+
return
|
|
93
|
+
route = queue.pop(0) if queue[0].once else queue[0]
|
|
94
|
+
self.send_response(route.status)
|
|
95
|
+
for k, v in route.headers.items():
|
|
96
|
+
self.send_header(k, v)
|
|
97
|
+
self.send_header("Content-Length", str(len(route.body)))
|
|
98
|
+
self.end_headers()
|
|
99
|
+
self.wfile.write(route.body)
|
|
100
|
+
|
|
101
|
+
do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = do_HEAD = _serve
|
|
102
|
+
|
|
103
|
+
def log_message(self, format: str, *args: Any) -> None:
|
|
104
|
+
pass
|
|
105
|
+
|
|
106
|
+
return Handler
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def start() -> ScriptedServer:
|
|
110
|
+
httpd = ThreadingHTTPServer(("127.0.0.1", 0), BaseHTTPRequestHandler)
|
|
111
|
+
state = ScriptedServer(httpd)
|
|
112
|
+
httpd.RequestHandlerClass = make_handler(state)
|
|
113
|
+
threading.Thread(target=httpd.serve_forever, daemon=True).start()
|
|
114
|
+
return state
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def stop(state: ScriptedServer) -> None:
|
|
118
|
+
state.httpd.shutdown()
|
|
119
|
+
state.httpd.server_close()
|
strata_python/live.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Run a FastAPI app on a real loopback port, so a test makes actual HTTP requests (urllib, httpx) against the real stack instead of a TestClient."""
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import threading
|
|
5
|
+
import time
|
|
6
|
+
from collections.abc import Generator
|
|
7
|
+
|
|
8
|
+
import uvicorn
|
|
9
|
+
from fastapi import FastAPI
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@contextlib.contextmanager
|
|
13
|
+
def live_server(app: FastAPI, *, timeout: float = 10.0) -> Generator[str]:
|
|
14
|
+
"""Yield the base URL (`http://127.0.0.1:<port>`) of `app` served by uvicorn on a free port; the server stops when the block ends."""
|
|
15
|
+
server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=0, log_level="warning"))
|
|
16
|
+
thread = threading.Thread(target=server.run, daemon=True)
|
|
17
|
+
thread.start()
|
|
18
|
+
deadline = time.monotonic() + timeout
|
|
19
|
+
while not server.started:
|
|
20
|
+
if not thread.is_alive() or time.monotonic() > deadline:
|
|
21
|
+
server.should_exit = True # do not leave a half-started server running
|
|
22
|
+
thread.join(10)
|
|
23
|
+
raise RuntimeError("the server did not start")
|
|
24
|
+
time.sleep(0.01)
|
|
25
|
+
port = server.servers[0].sockets[0].getsockname()[1]
|
|
26
|
+
try:
|
|
27
|
+
yield f"http://127.0.0.1:{port}"
|
|
28
|
+
finally:
|
|
29
|
+
server.should_exit = True
|
|
30
|
+
thread.join(timeout)
|
strata_python/oslib.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# pyright: basic, reportAttributeAccessIssue=false, reportUnknownMemberType=false, reportUnknownVariableType=false, reportUnknownArgumentType=false, reportDeprecated=false
|
|
2
|
+
# (relaxed for this file only: the Windows branches use msvcrt and ctypes.windll, which the Linux type stubs lack. Every other file is strict.)
|
|
3
|
+
"""OS differences in one place: file locks, process liveness and termination, priority, and how to start the CLI again.
|
|
4
|
+
|
|
5
|
+
POSIX (macOS, Linux) uses fcntl, os.kill and os.nice; Windows uses msvcrt, the Win32 API through ctypes and taskkill. Other modules should call these
|
|
6
|
+
instead of importing fcntl or calling os.kill(pid, 0) (on Windows that would terminate the process)."""
|
|
7
|
+
|
|
8
|
+
import contextlib
|
|
9
|
+
import os
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
import time
|
|
13
|
+
from collections.abc import Generator
|
|
14
|
+
from typing import IO, Any, cast
|
|
15
|
+
|
|
16
|
+
WIN = sys.platform == "win32"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@contextlib.contextmanager
|
|
20
|
+
def file_lock(f: IO[Any]) -> Generator[None]:
|
|
21
|
+
"""Exclusive lock on an open file, held for the duration of the block (other processes block until it is released)."""
|
|
22
|
+
if WIN:
|
|
23
|
+
import msvcrt
|
|
24
|
+
|
|
25
|
+
f.seek(0)
|
|
26
|
+
while True:
|
|
27
|
+
try:
|
|
28
|
+
msvcrt.locking(f.fileno(), msvcrt.LK_NBLCK, 1)
|
|
29
|
+
break
|
|
30
|
+
except OSError:
|
|
31
|
+
time.sleep(0.02)
|
|
32
|
+
try:
|
|
33
|
+
yield
|
|
34
|
+
finally:
|
|
35
|
+
f.seek(0)
|
|
36
|
+
with contextlib.suppress(OSError):
|
|
37
|
+
msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, 1)
|
|
38
|
+
else:
|
|
39
|
+
import fcntl
|
|
40
|
+
|
|
41
|
+
fcntl.flock(f, fcntl.LOCK_EX)
|
|
42
|
+
try:
|
|
43
|
+
yield
|
|
44
|
+
finally:
|
|
45
|
+
fcntl.flock(f, fcntl.LOCK_UN)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def pid_alive(pid: object) -> bool:
|
|
49
|
+
"""Is that process still running?"""
|
|
50
|
+
try:
|
|
51
|
+
pid = int(cast("Any", pid))
|
|
52
|
+
except (TypeError, ValueError):
|
|
53
|
+
return False
|
|
54
|
+
if pid <= 0:
|
|
55
|
+
return False
|
|
56
|
+
if WIN:
|
|
57
|
+
import ctypes
|
|
58
|
+
|
|
59
|
+
k = ctypes.windll.kernel32
|
|
60
|
+
h = k.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
|
|
61
|
+
if not h:
|
|
62
|
+
return False
|
|
63
|
+
try:
|
|
64
|
+
code = ctypes.c_ulong()
|
|
65
|
+
ok = k.GetExitCodeProcess(h, ctypes.byref(code))
|
|
66
|
+
return bool(ok) and code.value == 259 # STILL_ACTIVE
|
|
67
|
+
finally:
|
|
68
|
+
k.CloseHandle(h)
|
|
69
|
+
try:
|
|
70
|
+
os.kill(pid, 0)
|
|
71
|
+
return True
|
|
72
|
+
except ProcessLookupError:
|
|
73
|
+
return False
|
|
74
|
+
except PermissionError:
|
|
75
|
+
return True
|
|
76
|
+
except OSError:
|
|
77
|
+
return False
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def kill_tree(pid: int | str, sig: int = 15) -> None:
|
|
81
|
+
"""Terminate a worker and every process it started; errors are ignored."""
|
|
82
|
+
if WIN:
|
|
83
|
+
with contextlib.suppress(OSError):
|
|
84
|
+
subprocess.run(["taskkill", "/T", "/F", "/PID", str(int(pid))], capture_output=True) # noqa: S603, S607 (fixed command, pid is an int)
|
|
85
|
+
return
|
|
86
|
+
try:
|
|
87
|
+
kids = subprocess.run(["pgrep", "-P", str(pid)], stdout=subprocess.PIPE, text=True).stdout.split() # noqa: S603, S607 (fixed command, pid is an int)
|
|
88
|
+
except OSError:
|
|
89
|
+
kids = []
|
|
90
|
+
for k in kids:
|
|
91
|
+
kill_tree(int(k), sig)
|
|
92
|
+
with contextlib.suppress(OSError):
|
|
93
|
+
os.kill(int(pid), sig)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def lower_priority(nice: int = 19) -> None:
|
|
97
|
+
"""Run this process at lower CPU priority (nice value on POSIX, below-normal/idle class on Windows). Children inherit it."""
|
|
98
|
+
if WIN:
|
|
99
|
+
import ctypes
|
|
100
|
+
|
|
101
|
+
with contextlib.suppress(Exception):
|
|
102
|
+
ctypes.windll.kernel32.SetPriorityClass(
|
|
103
|
+
ctypes.windll.kernel32.GetCurrentProcess(), 0x40 if nice >= 15 else 0x4000
|
|
104
|
+
) # IDLE / BELOW_NORMAL
|
|
105
|
+
return
|
|
106
|
+
with contextlib.suppress(OSError, AttributeError):
|
|
107
|
+
os.nice(nice)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def venv_python(venv: str) -> str:
|
|
111
|
+
"""The interpreter of a virtual environment: bin/python on POSIX, Scripts\\python.exe on Windows."""
|
|
112
|
+
return os.path.join(venv, "Scripts", "python.exe") if WIN else os.path.join(venv, "bin", "python")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def cli_command(module: str) -> list[str]:
|
|
116
|
+
"""Command prefix that runs `module` (`python -m <module>`) with the interpreter running this process: works on POSIX and Windows, with or without a venv, and does not touch the environment."""
|
|
117
|
+
return [sys.executable, "-m", module]
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""`strata-public-check`: refuse to publish personal or machine-specific details.
|
|
2
|
+
|
|
3
|
+
The strata repos are public and their packages go to PyPI, where an upload can be yanked but never removed, so the
|
|
4
|
+
release workflow scans the built sdist and wheel (and CI scans the tree) before anything leaves. The built-in patterns
|
|
5
|
+
catch what is personal in any repo: email addresses, private IPv4 addresses and home-folder paths. Names that are
|
|
6
|
+
personal to one owner (a person, a host name, a port map) cannot be listed here without publishing them, so they come
|
|
7
|
+
from the `STRATA_PUBLIC_DENY` environment variable (one case-insensitive regex per line), which CI fills from a secret.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import io
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import sys
|
|
17
|
+
import tarfile
|
|
18
|
+
import zipfile
|
|
19
|
+
from collections.abc import Iterable, Iterator
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
DENY_ENV = "STRATA_PUBLIC_DENY"
|
|
24
|
+
|
|
25
|
+
# Placeholders the docs use on purpose (AGENTS.md: examples use /home/ada/..., myapp).
|
|
26
|
+
PLACEHOLDER_USERS = {"ada", "user", "me", "you", "name", "myapp", "runner"}
|
|
27
|
+
|
|
28
|
+
BUILT_IN: dict[str, re.Pattern[str]] = {
|
|
29
|
+
# Only the two automated addresses git trailers use are allowed: GitHub's per-user noreply domain and Claude's
|
|
30
|
+
# co-author address. A whole domain is never exempt (review finding: a personal address there would pass).
|
|
31
|
+
"email address": re.compile(
|
|
32
|
+
r"\b(?!noreply@anthropic\.com\b)[A-Za-z0-9._%+-]+@(?!users\.noreply\.github\.com\b)[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b"
|
|
33
|
+
),
|
|
34
|
+
"private IPv4 address": re.compile(r"\b(?:10|192\.168|172\.(?:1[6-9]|2\d|3[01]))(?:\.\d{1,3}){2,3}\b"),
|
|
35
|
+
"home folder path": re.compile(r"(?:/home/|/Users/|[A-Za-z]:\\+Users\\+)(?P<user>[A-Za-z0-9._-]+)"),
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
# Text files only: a binary (an image, a compiled extension) is skipped rather than decoded into noise.
|
|
39
|
+
TEXT_SUFFIXES = {".py", ".pyi", ".md", ".txt", ".toml", ".cfg", ".ini", ".json", ".yml", ".yaml", ".typed", ".sh", ""}
|
|
40
|
+
SKIP_PARTS = {
|
|
41
|
+
"__pycache__",
|
|
42
|
+
"node_modules",
|
|
43
|
+
"dist",
|
|
44
|
+
"build",
|
|
45
|
+
} # and hidden folders (.git, .venv, caches), but not .github
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class Finding:
|
|
50
|
+
where: str # path (inside the archive, when scanning one)
|
|
51
|
+
line: int
|
|
52
|
+
kind: str
|
|
53
|
+
text: str
|
|
54
|
+
|
|
55
|
+
def __str__(self) -> str:
|
|
56
|
+
return f"{self.where}:{self.line}: {self.kind}: {self.text}"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def deny_patterns(env: str | None = None) -> list[re.Pattern[str]]:
|
|
60
|
+
"""The owner's own patterns from `STRATA_PUBLIC_DENY`, one regex per line; blank lines are ignored."""
|
|
61
|
+
raw = os.environ.get(DENY_ENV, "") if env is None else env
|
|
62
|
+
return [re.compile(line.strip(), re.IGNORECASE) for line in raw.splitlines() if line.strip()]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def scan_text(where: str, text: str, extra: Iterable[re.Pattern[str]] = ()) -> Iterator[Finding]:
|
|
66
|
+
extra = list(extra)
|
|
67
|
+
for number, line in enumerate(text.splitlines(), 1):
|
|
68
|
+
for kind, pattern in BUILT_IN.items():
|
|
69
|
+
for match in pattern.finditer(line):
|
|
70
|
+
if kind == "home folder path" and match.group("user").lower() in PLACEHOLDER_USERS:
|
|
71
|
+
continue
|
|
72
|
+
yield Finding(where, number, kind, match.group(0))
|
|
73
|
+
for pattern in extra:
|
|
74
|
+
# The match itself is not printed: the log of a public repo's CI is public too.
|
|
75
|
+
if pattern.search(line):
|
|
76
|
+
yield Finding(where, number, f"matches {DENY_ENV} pattern", "(hidden)")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _is_text(name: str) -> bool:
|
|
80
|
+
path = Path(name)
|
|
81
|
+
hidden = any(part.startswith(".") and part != ".github" for part in path.parts[:-1])
|
|
82
|
+
return path.suffix in TEXT_SUFFIXES and not hidden and not (set(path.parts) & SKIP_PARTS)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _members(path: Path) -> Iterator[tuple[str, bytes]]:
|
|
86
|
+
if path.is_dir():
|
|
87
|
+
for file in sorted(path.rglob("*")):
|
|
88
|
+
relative = file.relative_to(path).as_posix()
|
|
89
|
+
if file.is_file() and _is_text(relative):
|
|
90
|
+
yield relative, file.read_bytes()
|
|
91
|
+
elif path.name.endswith((".tar.gz", ".tgz")):
|
|
92
|
+
with tarfile.open(path) as archive:
|
|
93
|
+
for member in archive.getmembers():
|
|
94
|
+
handle = archive.extractfile(member) if member.isfile() and _is_text(member.name) else None
|
|
95
|
+
if handle is not None:
|
|
96
|
+
yield f"{path.name}/{member.name}", handle.read()
|
|
97
|
+
elif path.suffix in {".whl", ".zip"}:
|
|
98
|
+
with zipfile.ZipFile(path) as archive:
|
|
99
|
+
for name in archive.namelist():
|
|
100
|
+
if not name.endswith("/") and _is_text(name):
|
|
101
|
+
yield f"{path.name}/{name}", archive.read(name)
|
|
102
|
+
else:
|
|
103
|
+
yield path.as_posix(), path.read_bytes()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def scan(paths: Iterable[Path], extra: Iterable[re.Pattern[str]] = ()) -> list[Finding]:
|
|
107
|
+
"""Every finding in the given folders, files, sdists (.tar.gz) and wheels (.whl)."""
|
|
108
|
+
extra = list(extra)
|
|
109
|
+
findings: list[Finding] = []
|
|
110
|
+
for path in paths:
|
|
111
|
+
for where, data in _members(path):
|
|
112
|
+
text = io.TextIOWrapper(io.BytesIO(data), encoding="utf-8", errors="replace").read()
|
|
113
|
+
findings.extend(scan_text(where, text, extra))
|
|
114
|
+
return findings
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def main(argv: list[str] | None = None) -> int:
|
|
118
|
+
parser = argparse.ArgumentParser(
|
|
119
|
+
prog="strata-public-check", description="Refuse to publish personal or machine-specific details."
|
|
120
|
+
)
|
|
121
|
+
parser.add_argument("paths", nargs="*", type=Path, default=[Path()], help="folders, files, sdists or wheels")
|
|
122
|
+
args = parser.parse_args(argv)
|
|
123
|
+
findings = scan(args.paths, deny_patterns())
|
|
124
|
+
for finding in findings:
|
|
125
|
+
print(finding, file=sys.stderr)
|
|
126
|
+
if findings:
|
|
127
|
+
print(f"{len(findings)} personal or machine-specific detail(s); see AGENTS.md (rule 4)", file=sys.stderr)
|
|
128
|
+
return 1
|
|
129
|
+
return 0
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
if __name__ == "__main__":
|
|
133
|
+
raise SystemExit(main())
|
strata_python/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""The pytest plugin (loaded automatically once strata-python is installed): hermetic tests and the real-over-mock fixtures.
|
|
2
|
+
|
|
3
|
+
Configure it in the app's `[tool.pytest.ini_options]`:
|
|
4
|
+
|
|
5
|
+
strata_env_prefix = "MYAPP" # MYAPP_HOME and MYAPP_DATA are pointed into a tmp dir for every test
|
|
6
|
+
strata_tuning_vars = ["MYAPP_GREETING"] # removed from the environment for every test
|
|
7
|
+
|
|
8
|
+
Without `strata_env_prefix` the plugin changes nothing but the no-network guard and the fixtures, so it is safe to have installed.
|
|
9
|
+
|
|
10
|
+
isolated_env (autouse) HOME/USERPROFILE and the app's home and data variables point into a tmp dir (outside the test's own tmp_path), so nothing reads or writes the
|
|
11
|
+
developer's real settings or data; override variables are removed. Returns that dir.
|
|
12
|
+
no_network (autouse) an outbound connection fails the test at once; loopback and unix sockets are fine.
|
|
13
|
+
http_server a real scripted HTTP server on loopback (strata_python.http_server); fails the test at teardown if a request reached no route.
|
|
14
|
+
live_app `with live_app(app) as base_url:` runs a FastAPI app on a real loopback port (strata_python.live)."""
|
|
15
|
+
|
|
16
|
+
import contextlib
|
|
17
|
+
import socket
|
|
18
|
+
from collections.abc import Callable, Iterator
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any, cast
|
|
21
|
+
|
|
22
|
+
import pytest
|
|
23
|
+
from fastapi import FastAPI
|
|
24
|
+
|
|
25
|
+
from strata_python import http_server as hs
|
|
26
|
+
from strata_python.live import live_server
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def pytest_addoption(parser: pytest.Parser) -> None:
|
|
30
|
+
parser.addini(
|
|
31
|
+
"strata_env_prefix", "environment prefix of the app under test (APP -> APP_HOME, APP_DATA)", default=""
|
|
32
|
+
)
|
|
33
|
+
parser.addini("strata_tuning_vars", "environment variables removed for every test", type="args", default=[])
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@pytest.fixture(autouse=True)
|
|
37
|
+
def isolated_env(
|
|
38
|
+
request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch
|
|
39
|
+
) -> Path:
|
|
40
|
+
base = tmp_path_factory.mktemp("env")
|
|
41
|
+
monkeypatch.setenv("HOME", str(base / "home"))
|
|
42
|
+
monkeypatch.setenv("USERPROFILE", str(base / "home"))
|
|
43
|
+
prefix = str(request.config.getini("strata_env_prefix"))
|
|
44
|
+
if prefix:
|
|
45
|
+
monkeypatch.setenv(f"{prefix}_HOME", str(base / "app-home"))
|
|
46
|
+
monkeypatch.setenv(f"{prefix}_DATA", str(base / "data"))
|
|
47
|
+
for k in request.config.getini("strata_tuning_vars"):
|
|
48
|
+
monkeypatch.delenv(k, raising=False)
|
|
49
|
+
return base
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _host(address: object) -> object:
|
|
53
|
+
"""The host of an inet address tuple, None for anything else (a unix socket path)."""
|
|
54
|
+
return cast("tuple[object, ...]", address)[0] if isinstance(address, tuple) else None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@pytest.fixture(autouse=True)
|
|
58
|
+
def no_network(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
59
|
+
real = socket.socket.connect
|
|
60
|
+
|
|
61
|
+
def guarded(self: socket.socket, address: Any, *a: Any, **kw: Any) -> Any:
|
|
62
|
+
if self.family in (socket.AF_INET, socket.AF_INET6) and _host(address) not in ("127.0.0.1", "::1", "localhost"):
|
|
63
|
+
raise AssertionError(f"tests must not use the network (tried {address!r})")
|
|
64
|
+
return real(self, address, *a, **kw)
|
|
65
|
+
|
|
66
|
+
monkeypatch.setattr(socket.socket, "connect", guarded)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@pytest.fixture
|
|
70
|
+
def http_server() -> Iterator[hs.ScriptedServer]:
|
|
71
|
+
state = hs.start()
|
|
72
|
+
yield state
|
|
73
|
+
hs.stop(state)
|
|
74
|
+
if state.unexpected: # not an assert: python -O would strip it
|
|
75
|
+
pytest.fail(f"requests no route answered: {[(r.method, r.path) for r in state.unexpected]}", pytrace=False)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@pytest.fixture
|
|
79
|
+
def live_app() -> Callable[[FastAPI], contextlib.AbstractContextManager[str]]:
|
|
80
|
+
return live_server
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""User settings for an app: one JSON file, `~/.<app>/settings.json`, with environment overrides.
|
|
2
|
+
|
|
3
|
+
An app declares its settings once (`Setting`: key, default, optional normaliser) and gets the file handling, the override order and the validation:
|
|
4
|
+
|
|
5
|
+
SETTINGS = Settings("myapp", [Setting("data_dir", default=lambda: "/srv/data", normalise=absolute_path),
|
|
6
|
+
Setting("greeting", default="Hello", normalise=non_empty)])
|
|
7
|
+
SETTINGS.get("greeting") # MYAPP_GREETING, else the file, else the default
|
|
8
|
+
SETTINGS.save({"greeting": "Hi"}) # validated, written atomically; None resets to the default
|
|
9
|
+
|
|
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
|
|
11
|
+
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."""
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import tempfile
|
|
17
|
+
import threading
|
|
18
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from typing import Any, cast
|
|
21
|
+
|
|
22
|
+
from strata_python.oslib import file_lock
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def non_empty(value: str) -> str:
|
|
26
|
+
"""Normaliser: trim, and refuse a blank value."""
|
|
27
|
+
v = value.strip()
|
|
28
|
+
if not v:
|
|
29
|
+
raise ValueError("must not be blank")
|
|
30
|
+
return v
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def absolute_path(value: str) -> str:
|
|
34
|
+
"""Normaliser: `~` expanded, and the path must then be absolute (a relative one would mean a different folder for every working directory)."""
|
|
35
|
+
p = os.path.expanduser(value.strip())
|
|
36
|
+
if not os.path.isabs(p):
|
|
37
|
+
raise ValueError("must be an absolute path")
|
|
38
|
+
return os.path.abspath(p)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _identity(value: str) -> str:
|
|
42
|
+
return value
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class Setting:
|
|
47
|
+
key: str
|
|
48
|
+
default: str | Callable[[], str]
|
|
49
|
+
normalise: Callable[[str], str] = _identity
|
|
50
|
+
env: str | None = None # environment variable; default `<APP>_<KEY>`
|
|
51
|
+
|
|
52
|
+
def default_value(self) -> str:
|
|
53
|
+
d = self.default
|
|
54
|
+
return d if isinstance(d, str) else d()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class Settings:
|
|
58
|
+
def __init__(self, app: str, settings: Sequence[Setting], *, prefix: str | None = None) -> None:
|
|
59
|
+
"""`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."""
|
|
61
|
+
self.app = app
|
|
62
|
+
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
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def keys(self) -> tuple[str, ...]:
|
|
68
|
+
return tuple(self._by_key)
|
|
69
|
+
|
|
70
|
+
def home(self) -> str:
|
|
71
|
+
"""The folder that holds the settings file (`<APP>_HOME`, else `~/.<app>`)."""
|
|
72
|
+
return os.environ.get(f"{self.prefix}_HOME") or os.path.join(os.path.expanduser("~"), f".{self.app}")
|
|
73
|
+
|
|
74
|
+
def path(self) -> str:
|
|
75
|
+
return os.path.join(self.home(), "settings.json")
|
|
76
|
+
|
|
77
|
+
def env_name(self, key: str) -> str:
|
|
78
|
+
return self._by_key[key].env or f"{self.prefix}_{key.upper()}"
|
|
79
|
+
|
|
80
|
+
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 {}
|
|
88
|
+
|
|
89
|
+
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."""
|
|
92
|
+
for k in changes:
|
|
93
|
+
if k not in self._by_key:
|
|
94
|
+
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
|
|
113
|
+
|
|
114
|
+
def get(self, key: str) -> str:
|
|
115
|
+
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):
|
|
118
|
+
if raw is not None: # "" is a value; the normaliser decides whether it is acceptable
|
|
119
|
+
try:
|
|
120
|
+
return s.normalise(raw)
|
|
121
|
+
except ValueError:
|
|
122
|
+
continue
|
|
123
|
+
return s.normalise(s.default_value())
|
|
124
|
+
|
|
125
|
+
def all(self) -> dict[str, str]:
|
|
126
|
+
return {k: self.get(k) for k in self._by_key}
|
|
127
|
+
|
|
128
|
+
def folder(self, key: str) -> str:
|
|
129
|
+
"""The setting `key` as a folder that exists (created when asked for)."""
|
|
130
|
+
p = self.get(key)
|
|
131
|
+
os.makedirs(p, exist_ok=True)
|
|
132
|
+
return p
|
strata_python/web.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""The web side every app shares: health and settings routes, the built web app (or a stand-in page), and the uvicorn runner.
|
|
2
|
+
|
|
3
|
+
app = base_app("myapp", __version__, SETTINGS) # /api/health, GET/PUT /api/settings
|
|
4
|
+
... app routes under /api ...
|
|
5
|
+
add_web(app, STATIC, LANDING) # last: assets + the page at every other path
|
|
6
|
+
|
|
7
|
+
Reverse proxies: the server only sees the path under its own root, never the proxy's prefix, but the depth of that path says how many `../` lead back to the root, so each page
|
|
8
|
+
gets a relative `<base href>` (`with_base`) and one build works at the server's root and behind a proxy at /<prefix>/. The web app reads its base from `document.baseURI`, and its
|
|
9
|
+
assets are relative (Vite `base: './'`)."""
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import os
|
|
13
|
+
from collections.abc import Sequence
|
|
14
|
+
|
|
15
|
+
import uvicorn
|
|
16
|
+
from fastapi import FastAPI, HTTPException
|
|
17
|
+
from fastapi.responses import FileResponse, HTMLResponse
|
|
18
|
+
from fastapi.staticfiles import StaticFiles
|
|
19
|
+
|
|
20
|
+
from strata_python.settings import Settings
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def with_base(html: str, path: str) -> str:
|
|
24
|
+
"""Insert `<base href>` pointing back at the server root for a page served at `path` (no leading slash)."""
|
|
25
|
+
tag = f'<base href="{"../" * path.count("/") or "./"}">'
|
|
26
|
+
return html.replace("<head>", "<head>" + tag, 1) if "<head>" in html else tag + html
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def static_file(static: str, path: str) -> str | None:
|
|
30
|
+
"""The file directly inside `static` that `path` names, or None. Only a plain file name is served: a path with either separator, a drive or `..` could reach outside
|
|
31
|
+
the folder (on Windows `..\\app.py` has no `/`, and `os.path.join` drops the root for `C:\\...`), so the resolved file must also sit directly in `static`."""
|
|
32
|
+
if not path or "/" in path or "\\" in path or ":" in path or path in (".", ".."):
|
|
33
|
+
return None
|
|
34
|
+
root = os.path.realpath(static)
|
|
35
|
+
full = os.path.realpath(os.path.join(root, path))
|
|
36
|
+
return full if os.path.dirname(full) == root and os.path.isfile(full) else None
|
|
37
|
+
|
|
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)."""
|
|
41
|
+
app = FastAPI(
|
|
42
|
+
title=title,
|
|
43
|
+
docs_url="/api/docs" if docs else None,
|
|
44
|
+
openapi_url="/api/openapi.json" if docs else None,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
@app.get("/api/health")
|
|
48
|
+
def get_health() -> dict[str, object]: # pyright: ignore[reportUnusedFunction]
|
|
49
|
+
return {"ok": True, "version": version}
|
|
50
|
+
|
|
51
|
+
if settings is not None:
|
|
52
|
+
|
|
53
|
+
@app.get("/api/settings")
|
|
54
|
+
def get_settings() -> dict[str, str]: # pyright: ignore[reportUnusedFunction]
|
|
55
|
+
return settings.all()
|
|
56
|
+
|
|
57
|
+
@app.put("/api/settings")
|
|
58
|
+
def put_settings(changes: dict[str, str | None]) -> dict[str, str]: # pyright: ignore[reportUnusedFunction]
|
|
59
|
+
try:
|
|
60
|
+
settings.save(changes)
|
|
61
|
+
except (KeyError, ValueError) as e:
|
|
62
|
+
raise HTTPException(400, str(e.args[0]) if isinstance(e, KeyError) else str(e)) from e
|
|
63
|
+
return settings.all()
|
|
64
|
+
|
|
65
|
+
return app
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def add_web(app: FastAPI, static: str, landing: str | None = None) -> None:
|
|
69
|
+
"""Serve the built web app: `static/assets` at /assets, files directly in `static` (favicon and the like) at their name, and `static/index.html` (else the plain `landing` page)
|
|
70
|
+
at every other path outside /api, so a reload or a shared link opens that screen (the app routes in the browser). Call it after the app's own routes: the catch-all is registered here."""
|
|
71
|
+
if os.path.isdir(os.path.join(static, "assets")):
|
|
72
|
+
app.mount("/assets", StaticFiles(directory=os.path.join(static, "assets")), name="assets")
|
|
73
|
+
|
|
74
|
+
@app.get("/{path:path}", response_class=HTMLResponse, response_model=None, include_in_schema=False)
|
|
75
|
+
def page(path: str) -> HTMLResponse | FileResponse: # pyright: ignore[reportUnusedFunction]
|
|
76
|
+
if path.startswith("api/"):
|
|
77
|
+
raise HTTPException(404, "no such endpoint")
|
|
78
|
+
top = static_file(static, path)
|
|
79
|
+
if top:
|
|
80
|
+
return FileResponse(top)
|
|
81
|
+
built = os.path.join(static, "index.html")
|
|
82
|
+
source = built if os.path.exists(built) else landing
|
|
83
|
+
if source is None:
|
|
84
|
+
raise HTTPException(404, "the web app has not been built")
|
|
85
|
+
with open(source, encoding="utf8") as f:
|
|
86
|
+
return HTMLResponse(with_base(f.read(), path))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def serve(app: FastAPI, argv: Sequence[str] | None = None, *, default_port: int = 8000, banner: str = "") -> None:
|
|
90
|
+
"""Run `app` with uvicorn: `--host` (default 127.0.0.1) and `--port`. The banner (what the app wants shown, such as its data folder) is printed before the URL."""
|
|
91
|
+
a = argparse.ArgumentParser()
|
|
92
|
+
a.add_argument("--host", default="127.0.0.1")
|
|
93
|
+
a.add_argument("--port", type=int, default=default_port)
|
|
94
|
+
ns = a.parse_args(argv)
|
|
95
|
+
print(
|
|
96
|
+
f"{banner}\nhttp://{ns.host}:{ns.port}/" if banner else f"http://{ns.host}:{ns.port}/", flush=True
|
|
97
|
+
) # flushed: a service logs to a pipe
|
|
98
|
+
uvicorn.run(app, host=ns.host, port=ns.port, log_level="warning")
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: strata-python
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Common code for Python web server apps: OS helpers, settings, FastAPI serving, CLI commands, test fixtures and the strata-check gate
|
|
5
|
+
Project-URL: Homepage, https://github.com/jburnhams/strata-python
|
|
6
|
+
Project-URL: Source, https://github.com/jburnhams/strata-python
|
|
7
|
+
Project-URL: Changelog, https://github.com/jburnhams/strata-python/blob/main/CHANGELOG.md
|
|
8
|
+
Author: jburnhams
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: cli,fastapi,pytest,settings
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Framework :: FastAPI
|
|
14
|
+
Classifier: Framework :: Pytest
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Requires-Dist: fastapi>=0.115
|
|
23
|
+
Requires-Dist: pydantic>=2.9
|
|
24
|
+
Requires-Dist: pytest>=8
|
|
25
|
+
Requires-Dist: tzdata; sys_platform == 'win32'
|
|
26
|
+
Requires-Dist: uvicorn>=0.32
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# strata-python
|
|
30
|
+
|
|
31
|
+
Common code for the strata Python web server apps (FastAPI + CLI), the Python counterpart of [strata-react](https://github.com/jburnhams/strata-react). Every app made from [python-app-template](https://github.com/jburnhams/python-app-template) used to carry its own drifting copy of these modules; they live here once. It is opinionated and built for those apps rather than as a general-purpose library, but it is public, MIT-licensed and on PyPI.
|
|
32
|
+
|
|
33
|
+
| Module | What it gives an app |
|
|
34
|
+
|---|---|
|
|
35
|
+
| `strata_python.oslib` | Cross-platform file locks, process liveness (`pid_alive`), `kill_tree`, `lower_priority`, `venv_python`, `cli_command(module)` |
|
|
36
|
+
| `strata_python.settings` | `Settings` / `Setting`: one JSON file in `~/.<app>` with `<APP>_*` environment overrides, validation (`absolute_path`, `non_empty`), atomic saves |
|
|
37
|
+
| `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` |
|
|
38
|
+
| `strata_python.cli` | `add_doctor`, `add_set`, `add_serve` for the app's argparse subcommands |
|
|
39
|
+
| `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
|
|
40
|
+
| pytest plugin | Loaded automatically: hermetic home and data folders, a no-network guard, `http_server` and `live_app` fixtures |
|
|
41
|
+
| `strata-check` | The one gate: lockfile, ruff, `ruff format`, pyright strict, ty, unit tests with coverage |
|
|
42
|
+
| `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 |
|
|
43
|
+
|
|
44
|
+
## Use it in an app
|
|
45
|
+
|
|
46
|
+
```toml
|
|
47
|
+
# pyproject.toml
|
|
48
|
+
[project]
|
|
49
|
+
dependencies = ["strata-python>=0.2,<0.3"] # from PyPI; while 0.x a minor release may break, so cap below the next one
|
|
50
|
+
|
|
51
|
+
[tool.pytest.ini_options]
|
|
52
|
+
strata_env_prefix = "MYAPP" # MYAPP_HOME and MYAPP_DATA point into a tmp dir for every test
|
|
53
|
+
strata_tuning_vars = ["MYAPP_GREETING"] # removed from the environment for every test
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from strata_python import cli, web
|
|
58
|
+
from strata_python.settings import Setting, Settings, absolute_path, non_empty
|
|
59
|
+
|
|
60
|
+
SETTINGS = Settings(
|
|
61
|
+
"myapp",
|
|
62
|
+
[
|
|
63
|
+
Setting("data_dir", default=lambda: "/srv/myapp", normalise=absolute_path),
|
|
64
|
+
Setting("greeting", default="Hello", normalise=non_empty),
|
|
65
|
+
],
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def create_app():
|
|
70
|
+
app = web.base_app("myapp", __version__, SETTINGS) # /api/health, GET/PUT /api/settings
|
|
71
|
+
# ... the app's own /api routes ...
|
|
72
|
+
web.add_web(app, STATIC_DIR, LANDING_HTML) # last: it registers the catch-all page route
|
|
73
|
+
return app
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
To try an unreleased commit, add `[tool.uv.sources] strata-python = { git = "https://github.com/jburnhams/strata-python", rev = "<sha>" }` for the moment and remove it once the release is out.
|
|
77
|
+
|
|
78
|
+
`scripts/check` in the app is `exec uv run --locked strata-check "$@"`; git hooks and CI call it. Optional `[tool.strata-check]` in `pyproject.toml` sets `paths` (default `src`, `tests`, `scripts`) and `tests` (default `tests/unit`).
|
|
79
|
+
|
|
80
|
+
## Develop
|
|
81
|
+
|
|
82
|
+
`uv sync`, then `scripts/check` (add `--fast` to skip the tests, `--fix` for safe ruff fixes). Integration tests (`uv run pytest tests/integration`) run the gate on a tiny project and `serve` in a separate process. Read [AGENTS.md](AGENTS.md) before changing anything; every change gets a [CHANGELOG.md](CHANGELOG.md) entry. Merging to main releases: `release.yml` bumps the version through its own PR, tags it and creates the GitHub release, and `pypi-publish.yml` uploads it to PyPI.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
strata_python/__init__.py,sha256=VYE4MXdwr1SPPaMtxZKfICzRFHl_q9Ktb0-GMgx1d5M,1207
|
|
2
|
+
strata_python/check.py,sha256=lFjXuPjVIWn6dBu2yMKIW-76RloUREijuMHCRsBW4Z8,2932
|
|
3
|
+
strata_python/cli.py,sha256=Vdqq2S2BJpGR3zjyRxqSZX9k65ecWL2SV5Zb7aVqUMY,2856
|
|
4
|
+
strata_python/http_server.py,sha256=64uYWy4zFxughOgtvkssGXMJDZ7jhRj1bxUIfnzte8w,4475
|
|
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
|
|
8
|
+
strata_python/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
strata_python/pytest_plugin.py,sha256=JbXnerUDy95nSJit6bHPXKjj0GUVh1Zp66TKZPSg5Qc,3574
|
|
10
|
+
strata_python/settings.py,sha256=DzzZr-h39lLTXhi078Ed3dl2BPjteTTChvKN-33kEdI,5888
|
|
11
|
+
strata_python/web.py,sha256=mhqW0-w0bbYG8O8dBQbKsU8unzKdvmhbsPayTdz4zYQ,5204
|
|
12
|
+
strata_python-0.2.0.dist-info/METADATA,sha256=G_x_KtYpJIUOHVbfW-A12CWen5EfilCevKeqTy1W8YY,4797
|
|
13
|
+
strata_python-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
14
|
+
strata_python-0.2.0.dist-info/entry_points.txt,sha256=LL3ID4wRlAUxHpRnCkjgFzoxmNu_uwzjqg1QA247tnA,168
|
|
15
|
+
strata_python-0.2.0.dist-info/licenses/LICENSE,sha256=9yVMCPoK7unONyTAiDYjMTt3MZPGJ639nWOwxyNsZGg,1066
|
|
16
|
+
strata_python-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 jburnhams
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|