strata-python 0.2.1__py3-none-any.whl → 0.2.3__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 +5 -1
- strata_python/cli.py +99 -20
- strata_python/client.py +184 -0
- strata_python/clients/__init__.py +2 -0
- strata_python/clients/models.py +783 -0
- strata_python/contracts.py +149 -0
- strata_python/db/__init__.py +6 -3
- strata_python/db/models.py +15 -3
- strata_python/db/project.py +29 -16
- strata_python/db/pytest_plugin.py +63 -9
- strata_python/db/settings.py +63 -0
- strata_python/oslib.py +175 -7
- strata_python/pages/__init__.py +21 -0
- strata_python/pages/model.py +241 -0
- strata_python/pages/render.py +273 -0
- strata_python/public_check.py +54 -8
- strata_python/pytest_plugin.py +10 -0
- strata_python/settings.py +256 -42
- strata_python/tasks/__init__.py +37 -0
- strata_python/tasks/child.py +236 -0
- strata_python/tasks/flight.py +146 -0
- strata_python/tasks/progress.py +92 -0
- strata_python/tasks/queue.py +716 -0
- strata_python/tasks/retry.py +101 -0
- strata_python/tasks/status.py +188 -0
- strata_python/tasks/ticker.py +85 -0
- strata_python/testing.py +164 -0
- strata_python/web.py +172 -10
- strata_python-0.2.3.dist-info/METADATA +372 -0
- strata_python-0.2.3.dist-info/RECORD +48 -0
- strata_python-0.2.1.dist-info/METADATA +0 -274
- strata_python-0.2.1.dist-info/RECORD +0 -32
- {strata_python-0.2.1.dist-info → strata_python-0.2.3.dist-info}/WHEEL +0 -0
- {strata_python-0.2.1.dist-info → strata_python-0.2.3.dist-info}/entry_points.txt +0 -0
- {strata_python-0.2.1.dist-info → strata_python-0.2.3.dist-info}/licenses/LICENSE +0 -0
strata_python/__init__.py
CHANGED
|
@@ -2,8 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
oslib file locks, process liveness and termination, priority, how to start a CLI (POSIX and Windows)
|
|
4
4
|
settings one JSON settings file per app with environment overrides and validation
|
|
5
|
-
web reverse-proxy-safe page serving, health and
|
|
5
|
+
web reverse-proxy-safe page serving, health, settings and system routes, error handlers, static files, the uvicorn runner
|
|
6
6
|
cli argparse commands every app has: doctor, set, serve
|
|
7
|
+
contracts the shapes the apps' APIs share (Health, SystemInfo, ErrorBody, Task, Progress, Page, FileRef, Judgment)
|
|
8
|
+
client ServiceClient: the standard-library base for calling a strata service
|
|
9
|
+
clients one typed client per strata service (models)
|
|
10
|
+
tasks retry rules, progress reporting, SingleFlight, StatusFile and Detached, Ticker; a durable queue with [db]
|
|
7
11
|
http_server a real scripted HTTP server on loopback for tests of outbound requests
|
|
8
12
|
live run a FastAPI app on a real loopback port for tests
|
|
9
13
|
testing the fakes for HTTP, subprocesses and sleep, and CLI runners, shared by every app's tests
|
strata_python/cli.py
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
"""The CLI commands every app has, added to the app's own argparse subparsers.
|
|
2
2
|
|
|
3
3
|
sub = parser.add_subparsers(dest="cmd", required=True)
|
|
4
|
-
add_doctor(sub, "myapp", __version__, ("fastapi", "
|
|
4
|
+
add_doctor(sub, "myapp", __version__, ("fastapi", ("opencv", "cv2"), Module("ultralytics", optional=True)),
|
|
5
|
+
checks=[Check("ffmpeg", program("ffmpeg"))])
|
|
5
6
|
add_set(sub, SETTINGS)
|
|
6
7
|
add_serve(sub, lambda host, port: web.serve(create_app(), ["--host", host, "--port", str(port)]), default_port=8360)
|
|
7
8
|
args = parser.parse_args(argv); return args.fn(args)
|
|
@@ -10,32 +11,110 @@ Each command sets `fn` on its parser; the handler returns the exit code."""
|
|
|
10
11
|
|
|
11
12
|
import argparse
|
|
12
13
|
import importlib
|
|
14
|
+
import shutil
|
|
13
15
|
import sys
|
|
14
16
|
from collections.abc import Callable, Iterable
|
|
15
|
-
from
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from typing import Any, Literal
|
|
16
19
|
|
|
17
20
|
from strata_python.settings import Settings
|
|
18
21
|
|
|
19
22
|
Sub = Any # argparse's subparsers object is a private generic type; only add_parser is used
|
|
20
23
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
24
|
+
Status = Literal["ok", "missing", "slow", "broken"]
|
|
25
|
+
"""A doctor row: `ok`; `missing` (not installed or not found); `slow` (works, but not as it should: a CPU fallback,
|
|
26
|
+
cuDNN off), which never fails the run; `broken` (there, but does not work)."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class Module:
|
|
31
|
+
"""A module `doctor` imports: `label` is what a person recognises ("rawpy (DNG decoding)"), `module` the import
|
|
32
|
+
name (default: the label). An `optional` one that is missing is shown with the hint but does not fail the run."""
|
|
33
|
+
|
|
34
|
+
label: str
|
|
35
|
+
module: str = ""
|
|
36
|
+
optional: bool = False
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def name(self) -> str:
|
|
40
|
+
return self.module or self.label
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class Check:
|
|
45
|
+
"""What an import cannot tell (a program on the PATH, whether the GPU runs a kernel): `fn` returns a status and a
|
|
46
|
+
line of text. `missing` or `broken` fails the run unless the check is `optional`; an exception counts as
|
|
47
|
+
`broken`, with the exception as its text."""
|
|
48
|
+
|
|
49
|
+
label: str
|
|
50
|
+
fn: Callable[[], tuple[Status, str]]
|
|
51
|
+
optional: bool = False
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def program(name: str, hint: str = "") -> Callable[[], tuple[Status, str]]:
|
|
55
|
+
"""A check function for a program on the PATH (`ffmpeg`, `exiftool`): `ok` with its path, else `missing`."""
|
|
56
|
+
|
|
57
|
+
def check() -> tuple[Status, str]:
|
|
58
|
+
found = shutil.which(name)
|
|
59
|
+
return ("ok", found) if found else ("missing", hint or "not on the PATH")
|
|
60
|
+
|
|
61
|
+
return check
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _row(status: Status, label: str, text: str, fails: bool) -> str:
|
|
65
|
+
word = status.upper() if fails else status # failing rows shout, so they are found in a long list
|
|
66
|
+
return f" {word:<9}{label}{': ' if text and status != 'ok' else ' '}{text}".rstrip()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def doctor(
|
|
70
|
+
name: str,
|
|
71
|
+
version: str,
|
|
72
|
+
imports: Iterable[str | tuple[str, str] | Module],
|
|
73
|
+
*,
|
|
74
|
+
checks: Iterable[Check] = (),
|
|
75
|
+
hint: str = "uv sync",
|
|
76
|
+
) -> int:
|
|
77
|
+
"""Print the app and Python versions, then one row per module and per check, in the same columns for every app.
|
|
78
|
+
Returns 1 when a required module is missing or a required check is missing or broken, else 0."""
|
|
79
|
+
ok = True
|
|
80
|
+
print(f"{name} {version}, python {sys.version.split()[0]}")
|
|
81
|
+
for item in imports:
|
|
82
|
+
mod = Module(item) if isinstance(item, str) else Module(*item) if isinstance(item, tuple) else item
|
|
83
|
+
try:
|
|
84
|
+
m = importlib.import_module(mod.name)
|
|
85
|
+
print(_row("ok", mod.label, str(getattr(m, "__version__", "")), False))
|
|
86
|
+
except ImportError:
|
|
87
|
+
ok = ok and mod.optional
|
|
88
|
+
print(_row("missing", mod.label, hint, not mod.optional))
|
|
89
|
+
for check in checks:
|
|
90
|
+
try:
|
|
91
|
+
status, text = check.fn()
|
|
92
|
+
except Exception as e: # a check that crashes is a broken row, not a crashed doctor
|
|
93
|
+
status, text = "broken", f"{type(e).__name__}: {e}"
|
|
94
|
+
fails = status in ("missing", "broken") and not check.optional
|
|
95
|
+
ok = ok and not fails
|
|
96
|
+
print(_row(status, check.label, text, fails))
|
|
97
|
+
return 0 if ok else 1
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def add_doctor(
|
|
101
|
+
sub: Sub,
|
|
102
|
+
name: str,
|
|
103
|
+
version: str,
|
|
104
|
+
imports: Iterable[str | tuple[str, str] | Module],
|
|
105
|
+
*,
|
|
106
|
+
checks: Iterable[Check] = (),
|
|
107
|
+
hint: str = "uv sync",
|
|
108
|
+
) -> None:
|
|
109
|
+
"""`doctor`: the app and Python versions, whether each module in `imports` can be imported (a name, a
|
|
110
|
+
`(label, module)` pair or a `Module`), then each of the app's `checks`; `hint` is what a missing module says to
|
|
111
|
+
run. Exit 1 if a required module or check fails (see `doctor`)."""
|
|
112
|
+
mods, chks = tuple(imports), tuple(checks)
|
|
113
|
+
|
|
114
|
+
def cmd_doctor(_args: argparse.Namespace) -> int:
|
|
115
|
+
return doctor(name, version, mods, checks=chks, hint=hint)
|
|
116
|
+
|
|
117
|
+
sub.add_parser("doctor", help="check the environment").set_defaults(fn=cmd_doctor)
|
|
39
118
|
|
|
40
119
|
|
|
41
120
|
def add_set(sub: Sub, settings: Settings) -> None:
|
strata_python/client.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""A typed base for calling another strata service's HTTP API: standard library only, so it runs in any venv.
|
|
2
|
+
|
|
3
|
+
The models client, the 360 and models self-CLIs and the homepage probes each wrote the same urllib wrapper: build a
|
|
4
|
+
JSON request, map a refusal to one error and an outage to another, poll until a row finishes. This is that once.
|
|
5
|
+
|
|
6
|
+
MODELS = ServiceClient(env_url("STRATA_MODELS_URL", "http://127.0.0.1:8366"), app="strata-scan")
|
|
7
|
+
MODELS.get("/api/registry") # parsed JSON
|
|
8
|
+
MODELS.post("/api/jobs", {"role": "ocr", ...})
|
|
9
|
+
MODELS.wait(f"/api/jobs/{jid}", lambda row: row["status"] in FINISHED, timeout=600) # long-polls with ?wait=
|
|
10
|
+
MODELS.available() # GET /api/health answered ok
|
|
11
|
+
|
|
12
|
+
Errors: `Rejected` when the service answered 4xx (it understood and said no: `.status`, `.detail`, `.payload`, the
|
|
13
|
+
`ErrorBody` shape), `Unavailable` when it could not be asked or answered 5xx. Reads (GET, PUT, DELETE, HEAD: the
|
|
14
|
+
idempotent methods) are retried `retries` times on `Unavailable`, with a doubling pause; a POST is not, since a
|
|
15
|
+
retried POST can do the work twice.
|
|
16
|
+
|
|
17
|
+
The URL is read on every call, so `env_url` picks up a changed environment variable (a test's stand-in service) and
|
|
18
|
+
no URL is fixed at import. `app` is sent as `X-Strata-App` and in the User-Agent, so the service can say who asked."""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import time
|
|
25
|
+
import urllib.error
|
|
26
|
+
import urllib.parse
|
|
27
|
+
import urllib.request
|
|
28
|
+
from collections.abc import Callable, Mapping
|
|
29
|
+
from typing import Any, cast
|
|
30
|
+
|
|
31
|
+
Json = dict[str, Any]
|
|
32
|
+
IDEMPOTENT = frozenset({"GET", "HEAD", "PUT", "DELETE"})
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Unavailable(RuntimeError):
|
|
36
|
+
"""The service could not be asked (not running, not reachable) or failed while answering (5xx)."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Rejected(RuntimeError):
|
|
40
|
+
"""The service answered 4xx: the request was understood and refused. `.detail` is its reason, `.payload` what it
|
|
41
|
+
sent with it (an `ErrorBody` payload, or the whole body when it was not one)."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, status: int, detail: str, payload: Any = None) -> None:
|
|
44
|
+
super().__init__(detail)
|
|
45
|
+
self.status = status
|
|
46
|
+
self.detail = detail
|
|
47
|
+
self.payload = payload
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def env_url(var: str, default: str) -> Callable[[], str]:
|
|
51
|
+
"""The service URL from environment variable `var`, read on each call, else `default`."""
|
|
52
|
+
return lambda: os.environ.get(var) or default
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ServiceClient:
|
|
56
|
+
def __init__(
|
|
57
|
+
self,
|
|
58
|
+
base_url: str | Callable[[], str],
|
|
59
|
+
*,
|
|
60
|
+
app: str | None = None,
|
|
61
|
+
timeout: float = 30,
|
|
62
|
+
retries: int = 2,
|
|
63
|
+
backoff_s: float = 0.5,
|
|
64
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
65
|
+
) -> None:
|
|
66
|
+
self._base = base_url
|
|
67
|
+
self.app = app
|
|
68
|
+
self.timeout = timeout
|
|
69
|
+
self.retries = retries
|
|
70
|
+
self.backoff_s = backoff_s
|
|
71
|
+
self._sleep = sleep
|
|
72
|
+
|
|
73
|
+
def url(self) -> str:
|
|
74
|
+
b = self._base
|
|
75
|
+
return (b if isinstance(b, str) else b()).rstrip("/")
|
|
76
|
+
|
|
77
|
+
def call(
|
|
78
|
+
self,
|
|
79
|
+
method: str,
|
|
80
|
+
path: str,
|
|
81
|
+
body: object = None,
|
|
82
|
+
*,
|
|
83
|
+
params: Mapping[str, object] | None = None,
|
|
84
|
+
timeout: float | None = None,
|
|
85
|
+
) -> Any:
|
|
86
|
+
"""Send one request and return the parsed JSON answer (None for an empty body)."""
|
|
87
|
+
method = method.upper()
|
|
88
|
+
attempts = 1 + (self.retries if method in IDEMPOTENT else 0)
|
|
89
|
+
for attempt in range(attempts):
|
|
90
|
+
try:
|
|
91
|
+
return self._once(method, path, body, params, self.timeout if timeout is None else timeout)
|
|
92
|
+
except Unavailable:
|
|
93
|
+
if attempt == attempts - 1:
|
|
94
|
+
raise
|
|
95
|
+
self._sleep(self.backoff_s * 2**attempt)
|
|
96
|
+
raise AssertionError("unreachable") # pragma: no cover - the loop returns or raises
|
|
97
|
+
|
|
98
|
+
def _once(self, method: str, path: str, body: object, params: Mapping[str, object] | None, timeout: float) -> Any:
|
|
99
|
+
url = self.url() + path
|
|
100
|
+
if params:
|
|
101
|
+
url += ("&" if "?" in url else "?") + urllib.parse.urlencode({k: str(v) for k, v in params.items()})
|
|
102
|
+
data = None if body is None else json.dumps(body).encode()
|
|
103
|
+
headers = {"Accept": "application/json"}
|
|
104
|
+
if data is not None:
|
|
105
|
+
headers["Content-Type"] = "application/json"
|
|
106
|
+
if self.app:
|
|
107
|
+
headers["X-Strata-App"] = self.app
|
|
108
|
+
headers["User-Agent"] = f"{self.app} (strata-python)"
|
|
109
|
+
req = urllib.request.Request(url, data=data, method=method, headers=headers) # noqa: S310 - the service's own URL
|
|
110
|
+
try:
|
|
111
|
+
with urllib.request.urlopen(req, timeout=timeout) as r: # noqa: S310
|
|
112
|
+
raw = r.read()
|
|
113
|
+
except urllib.error.HTTPError as e:
|
|
114
|
+
answer = _parse(e.read())
|
|
115
|
+
detail, payload = _reason(answer, e)
|
|
116
|
+
if 400 <= e.code < 500:
|
|
117
|
+
raise Rejected(e.code, detail, payload) from None
|
|
118
|
+
raise Unavailable(f"{self.url()} answered {e.code}: {detail}") from None
|
|
119
|
+
except (urllib.error.URLError, OSError) as e:
|
|
120
|
+
raise Unavailable(f"{self.url()} is not reachable: {getattr(e, 'reason', e)}") from None
|
|
121
|
+
return _parse(raw) if raw else None
|
|
122
|
+
|
|
123
|
+
def get(self, path: str, **kw: Any) -> Any:
|
|
124
|
+
return self.call("GET", path, **kw)
|
|
125
|
+
|
|
126
|
+
def post(self, path: str, body: object = None, **kw: Any) -> Any:
|
|
127
|
+
return self.call("POST", path, body, **kw)
|
|
128
|
+
|
|
129
|
+
def put(self, path: str, body: object = None, **kw: Any) -> Any:
|
|
130
|
+
return self.call("PUT", path, body, **kw)
|
|
131
|
+
|
|
132
|
+
def delete(self, path: str, **kw: Any) -> Any:
|
|
133
|
+
return self.call("DELETE", path, **kw)
|
|
134
|
+
|
|
135
|
+
def health(self, timeout: float = 2.0) -> Json:
|
|
136
|
+
"""`GET /api/health`, once (no retries: a probe wants the answer now)."""
|
|
137
|
+
return cast("Json", self._once("GET", "/api/health", None, None, timeout) or {})
|
|
138
|
+
|
|
139
|
+
def available(self, timeout: float = 2.0) -> bool:
|
|
140
|
+
"""Is the service up and saying it is ok?"""
|
|
141
|
+
try:
|
|
142
|
+
return bool(self.health(timeout).get("ok"))
|
|
143
|
+
except (Unavailable, Rejected):
|
|
144
|
+
return False
|
|
145
|
+
|
|
146
|
+
def wait(
|
|
147
|
+
self,
|
|
148
|
+
path: str,
|
|
149
|
+
done: Callable[[Json], bool],
|
|
150
|
+
*,
|
|
151
|
+
timeout: float | None = None,
|
|
152
|
+
poll_s: float = 30,
|
|
153
|
+
clock: Callable[[], float] = time.monotonic,
|
|
154
|
+
) -> Json:
|
|
155
|
+
"""Long-poll `path?wait=<s>` until `done(row)`; TimeoutError (with the last row's state) after `timeout`.
|
|
156
|
+
The service holds each request up to `wait` seconds and answers early when the row changes, so this costs one
|
|
157
|
+
request per change, not one per second."""
|
|
158
|
+
end = None if timeout is None else clock() + timeout
|
|
159
|
+
while True:
|
|
160
|
+
step = poll_s if end is None else max(min(poll_s, end - clock()), 0)
|
|
161
|
+
row = cast("Json", self.get(path, params={"wait": f"{step:.1f}"}, timeout=step + 15))
|
|
162
|
+
if done(row):
|
|
163
|
+
return row
|
|
164
|
+
if end is not None and clock() >= end:
|
|
165
|
+
raise TimeoutError(
|
|
166
|
+
f"{path} did not finish in {timeout} s (last: {row.get('status') or row.get('state')})"
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _parse(raw: bytes) -> Any:
|
|
171
|
+
try:
|
|
172
|
+
return json.loads(raw)
|
|
173
|
+
except ValueError:
|
|
174
|
+
return raw.decode(errors="replace").strip() or None
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _reason(answer: Any, e: urllib.error.HTTPError) -> tuple[str, Any]:
|
|
178
|
+
"""The reason and payload in an error answer: `ErrorBody` ({detail, payload}), FastAPI's {detail}, or plain text."""
|
|
179
|
+
if isinstance(answer, dict):
|
|
180
|
+
d = cast("Json", answer)
|
|
181
|
+
detail = d.get("detail")
|
|
182
|
+
text = detail if isinstance(detail, str) else json.dumps(detail) if detail is not None else str(e.reason)
|
|
183
|
+
return text, d.get("payload", d if set(d) - {"detail"} else None)
|
|
184
|
+
return (answer if isinstance(answer, str) and answer else str(e.reason)), None
|