strata-python 0.2.2__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/client.py +184 -0
- strata_python/clients/models.py +5 -2
- strata_python/contracts.py +149 -0
- strata_python/oslib.py +131 -2
- strata_python/pytest_plugin.py +10 -0
- strata_python/settings.py +13 -0
- 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 +159 -6
- {strata_python-0.2.2.dist-info → strata_python-0.2.3.dist-info}/METADATA +47 -9
- {strata_python-0.2.2.dist-info → strata_python-0.2.3.dist-info}/RECORD +22 -12
- {strata_python-0.2.2.dist-info → strata_python-0.2.3.dist-info}/WHEEL +0 -0
- {strata_python-0.2.2.dist-info → strata_python-0.2.3.dist-info}/entry_points.txt +0 -0
- {strata_python-0.2.2.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/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
|
strata_python/clients/models.py
CHANGED
|
@@ -38,14 +38,17 @@ from collections.abc import Generator, Mapping, Sequence
|
|
|
38
38
|
from dataclasses import dataclass, field
|
|
39
39
|
from typing import Any, Literal, cast
|
|
40
40
|
|
|
41
|
+
from strata_python import client
|
|
42
|
+
|
|
41
43
|
Json = dict[str, Any]
|
|
42
44
|
Priority = Literal["high", "normal", "low"]
|
|
43
45
|
POLL_S = 30 # one long-poll request waits this long at most
|
|
44
46
|
DEFAULT_URL = "http://127.0.0.1:8366"
|
|
45
47
|
|
|
46
48
|
|
|
47
|
-
class Unavailable(
|
|
48
|
-
"""The service is not running (or not reachable).
|
|
49
|
+
class Unavailable(client.Unavailable):
|
|
50
|
+
"""The service is not running (or not reachable). A `strata_python.client.Unavailable`, so an app's
|
|
51
|
+
`web.add_error_handlers` answers it as 503 like any other service outage."""
|
|
49
52
|
|
|
50
53
|
|
|
51
54
|
class JobFailed(RuntimeError):
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""The data shapes the strata apps share across their HTTP APIs, written once as pydantic models.
|
|
2
|
+
|
|
3
|
+
Every app's server returned these as plain dicts and every web app retyped them by hand (`web/src/api.ts`), with the
|
|
4
|
+
field names drifting (a job's `state` or `status`, progress text as `current`, `text` or `stage`). Declared as a route's
|
|
5
|
+
`response_model`, a shape is checked on the way out and lands in `/api/openapi.json`, so a web app's TypeScript can be
|
|
6
|
+
generated from it instead of copied.
|
|
7
|
+
|
|
8
|
+
Health GET /api/health: ok, version, commit, plus the app's own fields (web.base_app)
|
|
9
|
+
SystemInfo GET /api/system: version, commit, Python, platform, folders with their disks, services it calls (web.add_system)
|
|
10
|
+
ErrorBody every error response: detail, and a payload when the error carries one (web.add_error_handlers)
|
|
11
|
+
Task a job or task row: id, kind, state, times, error, result, progress (tasks.Queue answers these)
|
|
12
|
+
Progress how far a task has got: done of total, a line of text, the stage (tasks.ProgressReporter writes these)
|
|
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
|
+
FileRef a file by content and place: sha256, size, mtime, root, rel (the path under that root)
|
|
15
|
+
Judgment one pairwise choice by a person or a model: a, b, the winner (a, b or tie), who, when, undone when
|
|
16
|
+
|
|
17
|
+
Times are timezone-aware datetimes, sent as ISO 8601 with their offset: the apps had both ISO text and float epochs,
|
|
18
|
+
and only one of those reads correctly in a browser. Use `utc(epoch)` to turn a stored float into one."""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import datetime
|
|
23
|
+
from typing import Any, Generic, Literal, TypeVar
|
|
24
|
+
|
|
25
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def utc(epoch: float | None) -> datetime.datetime | None:
|
|
29
|
+
"""A float epoch (`time.time()`) as an aware UTC datetime; None stays None."""
|
|
30
|
+
return None if epoch is None else datetime.datetime.fromtimestamp(epoch, datetime.UTC)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Health(BaseModel):
|
|
34
|
+
"""What `GET /api/health` answers. Extra fields are the app's own (strata-models adds `gpu`)."""
|
|
35
|
+
|
|
36
|
+
model_config = ConfigDict(extra="allow")
|
|
37
|
+
ok: bool
|
|
38
|
+
version: str
|
|
39
|
+
commit: str | None = None # the source commit the server runs, so a probe can tell a stale deploy
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Folder(BaseModel):
|
|
43
|
+
"""A folder the app uses, and the disk it is on (None when the folder does not exist yet)."""
|
|
44
|
+
|
|
45
|
+
name: str
|
|
46
|
+
path: str
|
|
47
|
+
exists: bool
|
|
48
|
+
free_bytes: int | None = None
|
|
49
|
+
total_bytes: int | None = None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class ServiceStatus(BaseModel):
|
|
53
|
+
"""Another strata service this app calls, as its health endpoint answered just now."""
|
|
54
|
+
|
|
55
|
+
name: str
|
|
56
|
+
url: str
|
|
57
|
+
ok: bool
|
|
58
|
+
version: str | None = None
|
|
59
|
+
detail: str | None = None # why it is not ok: not reachable, or what it answered
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class SystemInfo(BaseModel):
|
|
63
|
+
"""What `GET /api/system` answers: what is running, where its data is, and whether its services answer."""
|
|
64
|
+
|
|
65
|
+
model_config = ConfigDict(extra="allow")
|
|
66
|
+
version: str
|
|
67
|
+
commit: str | None = None
|
|
68
|
+
python: str
|
|
69
|
+
platform: str
|
|
70
|
+
started_at: datetime.datetime
|
|
71
|
+
folders: list[Folder] = Field(default_factory=lambda: [])
|
|
72
|
+
services: list[ServiceStatus] = Field(default_factory=lambda: [])
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class ErrorBody(BaseModel):
|
|
76
|
+
"""The body of every error the app answers. `detail` is what FastAPI already uses, so clients that read it keep
|
|
77
|
+
working; `payload` carries what the error wants the client to have (the job row of a refused job)."""
|
|
78
|
+
|
|
79
|
+
detail: str
|
|
80
|
+
payload: Any = None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
TaskState = Literal["queued", "running", "done", "failed", "cancelled"]
|
|
84
|
+
FINISHED: frozenset[str] = frozenset({"done", "failed", "cancelled"})
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class Progress(BaseModel):
|
|
88
|
+
"""How far a task has got. `total` None means not known yet; `text` is the line a person reads ("Page 3 of 40")."""
|
|
89
|
+
|
|
90
|
+
done: float = 0
|
|
91
|
+
total: float | None = None
|
|
92
|
+
text: str = ""
|
|
93
|
+
stage: str | None = None
|
|
94
|
+
at: datetime.datetime | None = None
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def fraction(self) -> float | None:
|
|
98
|
+
return None if not self.total else min(max(self.done / self.total, 0.0), 1.0)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class Task(BaseModel):
|
|
102
|
+
"""A job or task row as an API answers it."""
|
|
103
|
+
|
|
104
|
+
id: int | str
|
|
105
|
+
kind: str
|
|
106
|
+
state: TaskState
|
|
107
|
+
created_at: datetime.datetime
|
|
108
|
+
started_at: datetime.datetime | None = None
|
|
109
|
+
finished_at: datetime.datetime | None = None
|
|
110
|
+
error: str | None = None
|
|
111
|
+
result: Any = None
|
|
112
|
+
progress: Progress | None = None
|
|
113
|
+
attempts: int = 0
|
|
114
|
+
domain: str | None = None # what the task is about in the app's terms (a book id, a folder)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
T = TypeVar("T")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class Page(BaseModel, Generic[T]): # Generic, not `Page[T]`: Python 3.11 is supported
|
|
121
|
+
"""One page of a list. `next` is an opaque cursor (pass it back as `after`), None on the last page; a cursor, not an
|
|
122
|
+
offset, so rows added while a person pages through do not repeat or vanish."""
|
|
123
|
+
|
|
124
|
+
items: list[T]
|
|
125
|
+
next: str | None = None
|
|
126
|
+
total: int | None = None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class FileRef(BaseModel):
|
|
130
|
+
"""A file by content and place. `sha256` is lower-case hex (the apps had hex and raw bytes); `rel` is the path under
|
|
131
|
+
`root` with `/` separators, so the same file found from two machines or two apps joins on (sha256) or (root, rel)."""
|
|
132
|
+
|
|
133
|
+
sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
|
|
134
|
+
size: int = Field(ge=0)
|
|
135
|
+
mtime: float
|
|
136
|
+
root: str
|
|
137
|
+
rel: str
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class Judgment(BaseModel):
|
|
141
|
+
"""One pairwise choice: `a` and `b` are the two things compared, `winner` names a side (or a tie), `rater` who chose
|
|
142
|
+
(a person's name in the app, or a model's). Undoing keeps the row and sets `undone_at`, so a ranking can be rebuilt."""
|
|
143
|
+
|
|
144
|
+
a: str
|
|
145
|
+
b: str
|
|
146
|
+
winner: Literal["a", "b", "tie"]
|
|
147
|
+
rater: str
|
|
148
|
+
at: datetime.datetime
|
|
149
|
+
undone_at: datetime.datetime | None = None
|
strata_python/oslib.py
CHANGED
|
@@ -9,9 +9,10 @@ import contextlib
|
|
|
9
9
|
import os
|
|
10
10
|
import subprocess
|
|
11
11
|
import sys
|
|
12
|
+
import threading
|
|
12
13
|
import time
|
|
13
|
-
from collections.abc import Generator
|
|
14
|
-
from typing import IO, Any, cast
|
|
14
|
+
from collections.abc import Generator, Mapping
|
|
15
|
+
from typing import IO, Any, Literal, cast, overload
|
|
15
16
|
|
|
16
17
|
WIN = sys.platform == "win32"
|
|
17
18
|
|
|
@@ -154,3 +155,131 @@ def venv_python(venv: str) -> str:
|
|
|
154
155
|
def cli_command(module: str) -> list[str]:
|
|
155
156
|
"""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."""
|
|
156
157
|
return [sys.executable, "-m", module]
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def detached_kwargs() -> dict[str, Any]:
|
|
161
|
+
"""`subprocess.Popen` keyword arguments that start a process outside this one's session (POSIX) or console and
|
|
162
|
+
process group (Windows), so it keeps running when the server that started it restarts, and a Ctrl+C or a stopped
|
|
163
|
+
service unit aimed at the server does not reach it. `kill_tree` still stops it and its children."""
|
|
164
|
+
if WIN:
|
|
165
|
+
return {"creationflags": 0x00000200 | 0x00000008} # CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS
|
|
166
|
+
return {"start_new_session": True}
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def load_average() -> tuple[float, float, float] | None:
|
|
170
|
+
"""The 1, 5 and 15 minute load averages, or None where the OS has none (Windows)."""
|
|
171
|
+
try:
|
|
172
|
+
return os.getloadavg()
|
|
173
|
+
except (AttributeError, OSError):
|
|
174
|
+
return None
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
# --- supervised children: listory's per-job process groups -----------------------------------------------------------
|
|
178
|
+
|
|
179
|
+
SUPERVISED_ENV = "STRATA_SUPERVISED"
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
@overload
|
|
183
|
+
def start_supervised(
|
|
184
|
+
cmd: list[str], *, env: Mapping[str, str] | None = None, cwd: str | None = None, text: Literal[False] = False
|
|
185
|
+
) -> subprocess.Popen[bytes]: ...
|
|
186
|
+
@overload
|
|
187
|
+
def start_supervised(
|
|
188
|
+
cmd: list[str], *, env: Mapping[str, str] | None = None, cwd: str | None = None, text: Literal[True]
|
|
189
|
+
) -> subprocess.Popen[str]: ...
|
|
190
|
+
def start_supervised(
|
|
191
|
+
cmd: list[str], *, env: Mapping[str, str] | None = None, cwd: str | None = None, text: bool = False
|
|
192
|
+
) -> subprocess.Popen[Any]:
|
|
193
|
+
"""Start `cmd` in its own process group, with a lifeline on its stdin, so that `kill_group` stops it and every
|
|
194
|
+
tool it started, and so that it stops itself when this process dies, however it dies (`watch_supervisor`, called
|
|
195
|
+
in the child, sees the pipe close). `text=True` also pipes its stdout, as text, for a child that answers on it
|
|
196
|
+
(`tasks.child`); otherwise its output goes where this process's goes."""
|
|
197
|
+
return subprocess.Popen( # noqa: S603 - the app's own command
|
|
198
|
+
cmd,
|
|
199
|
+
stdin=subprocess.PIPE,
|
|
200
|
+
stdout=subprocess.PIPE if text else None,
|
|
201
|
+
text=text,
|
|
202
|
+
encoding="utf8" if text else None,
|
|
203
|
+
env={**(env or os.environ), SUPERVISED_ENV: "1"},
|
|
204
|
+
cwd=cwd,
|
|
205
|
+
start_new_session=not WIN,
|
|
206
|
+
creationflags=0x00000200 if WIN else 0, # CREATE_NEW_PROCESS_GROUP
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def stdout_to_stderr() -> int:
|
|
211
|
+
"""Point this process's stdout at its stderr, for it and every process it starts, and return a new fd on the old
|
|
212
|
+
stdout (for a child that answers its parent there). On Windows the Win32 standard handle is moved too: moving
|
|
213
|
+
fd 1 alone leaves the handle a started tool inherits on the old pipe."""
|
|
214
|
+
sys.stdout.flush()
|
|
215
|
+
saved = os.dup(1)
|
|
216
|
+
os.dup2(2, 1)
|
|
217
|
+
if WIN:
|
|
218
|
+
import ctypes
|
|
219
|
+
import msvcrt
|
|
220
|
+
|
|
221
|
+
ctypes.windll.kernel32.SetStdHandle(-11, msvcrt.get_osfhandle(2)) # STD_OUTPUT_HANDLE
|
|
222
|
+
return saved
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def stdin_from_devnull() -> int:
|
|
226
|
+
"""Give this process (and every process it starts) an empty stdin, and return a new fd on the old one, for a
|
|
227
|
+
child that reads its parent's commands there. On Windows this is what keeps a tool from hanging: a thread blocked
|
|
228
|
+
reading a synchronous pipe holds that pipe, and a tool that inherits it as stdin blocks starting up."""
|
|
229
|
+
saved = os.dup(0)
|
|
230
|
+
null = os.open(os.devnull, os.O_RDONLY)
|
|
231
|
+
os.dup2(null, 0)
|
|
232
|
+
os.close(null)
|
|
233
|
+
if WIN:
|
|
234
|
+
import ctypes
|
|
235
|
+
import msvcrt
|
|
236
|
+
|
|
237
|
+
ctypes.windll.kernel32.SetStdHandle(-10, msvcrt.get_osfhandle(0)) # STD_INPUT_HANDLE
|
|
238
|
+
sys.stdin = open(0, closefd=False) # noqa: SIM115 - fd 0 for the life of the process
|
|
239
|
+
return saved
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def watch_supervisor() -> bool:
|
|
243
|
+
"""In a child that `start_supervised` started: end this process group when the parent's end of the lifeline
|
|
244
|
+
closes (the parent exited, crashed or was killed), so no tool is left running for a server that is gone. True
|
|
245
|
+
when it is watching; False when this process was not started that way."""
|
|
246
|
+
if os.environ.pop(SUPERVISED_ENV, None) != "1": # popped: this process's own children are not supervised by it
|
|
247
|
+
return False
|
|
248
|
+
|
|
249
|
+
def watch() -> None:
|
|
250
|
+
try:
|
|
251
|
+
while os.read(0, 1): # the parent never writes: this returns b"" (EOF) when its end closes
|
|
252
|
+
pass
|
|
253
|
+
finally:
|
|
254
|
+
terminate_own_group()
|
|
255
|
+
|
|
256
|
+
threading.Thread(target=watch, name="strata-supervisor-watch", daemon=True).start()
|
|
257
|
+
return True
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def terminate_own_group() -> None:
|
|
261
|
+
"""Kill this process and everything in its group (or, on Windows, its process tree), at once."""
|
|
262
|
+
if WIN:
|
|
263
|
+
kill_tree(os.getpid())
|
|
264
|
+
elif os.getpgrp() == os.getpid(): # only a group this process leads, never the server's own session
|
|
265
|
+
import signal
|
|
266
|
+
|
|
267
|
+
with contextlib.suppress(OSError):
|
|
268
|
+
os.killpg(os.getpid(), signal.SIGKILL)
|
|
269
|
+
os._exit(1)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def kill_group(proc: subprocess.Popen[Any], timeout: float = 5.0) -> None:
|
|
273
|
+
"""Stop a `start_supervised` child and every process in its group now, and reap it."""
|
|
274
|
+
if WIN:
|
|
275
|
+
kill_tree(proc.pid)
|
|
276
|
+
else:
|
|
277
|
+
import signal
|
|
278
|
+
|
|
279
|
+
with contextlib.suppress(OSError):
|
|
280
|
+
os.killpg(proc.pid, signal.SIGKILL)
|
|
281
|
+
with contextlib.suppress(subprocess.TimeoutExpired):
|
|
282
|
+
proc.wait(timeout)
|
|
283
|
+
if proc.stdin is not None:
|
|
284
|
+
with contextlib.suppress(OSError):
|
|
285
|
+
proc.stdin.close()
|
strata_python/pytest_plugin.py
CHANGED
|
@@ -18,6 +18,8 @@ Without `strata_env_prefix` the plugin changes nothing but the no-network guard
|
|
|
18
18
|
fake_popen `subprocess.Popen` starts nothing; `.instances` lists what was asked (`.cmd`, `.kw`), fresh for each test.
|
|
19
19
|
fake_run `subprocess.run` / `check_output`: `.returns["ffprobe"] = b"..."` for output, `.code = 1` to fail, `.calls`.
|
|
20
20
|
no_sleep `time.sleep` returns at once; `.delays` records the waits.
|
|
21
|
+
fake_models a stand-in strata-models on a real loopback port, with STRATA_MODELS_URL pointing at it: the app's own
|
|
22
|
+
`strata_python.clients.models` calls run unchanged. `.results`, `.fail(...)`, `.busy`, `.down`, `.jobs`.
|
|
21
23
|
The fakes are a last resort for a true external edge (strata_python.testing says when); prefer `http_server` and real programs."""
|
|
22
24
|
|
|
23
25
|
import contextlib
|
|
@@ -147,3 +149,11 @@ def no_sleep(monkeypatch: pytest.MonkeyPatch) -> testing.Sleeper:
|
|
|
147
149
|
sleeper = testing.Sleeper()
|
|
148
150
|
monkeypatch.setattr(time, "sleep", sleeper)
|
|
149
151
|
return sleeper
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@pytest.fixture
|
|
155
|
+
def fake_models(monkeypatch: pytest.MonkeyPatch) -> Iterator[testing.FakeModels]:
|
|
156
|
+
fake = testing.FakeModels()
|
|
157
|
+
with live_server(fake.app) as base:
|
|
158
|
+
monkeypatch.setenv("STRATA_MODELS_URL", base)
|
|
159
|
+
yield fake
|
strata_python/settings.py
CHANGED
|
@@ -326,6 +326,19 @@ class Settings:
|
|
|
326
326
|
def all(self) -> dict[str, Value]:
|
|
327
327
|
return {k: self.value(k) for k in self._by_key}
|
|
328
328
|
|
|
329
|
+
def model(self) -> type[Any]:
|
|
330
|
+
"""The settings as a pydantic model: a field per setting (`str`, or `list[str]` for a `ListSetting`), named
|
|
331
|
+
`<App>Settings`. `web.base_app` declares it as the settings routes' response, so `/api/openapi.json` describes
|
|
332
|
+
each setting and a web app's types can be generated from it. Built on each call; pydantic is imported here, so
|
|
333
|
+
a CLI that only reads settings does not load it."""
|
|
334
|
+
from pydantic import create_model
|
|
335
|
+
|
|
336
|
+
fields: dict[str, Any] = {
|
|
337
|
+
k: (list[str] if isinstance(s, ListSetting) else str, ...) for k, s in self._by_key.items()
|
|
338
|
+
}
|
|
339
|
+
name = "".join(p.capitalize() for p in re.split(r"[^0-9A-Za-z]+", self.app) if p) + "Settings"
|
|
340
|
+
return create_model(name, **fields)
|
|
341
|
+
|
|
329
342
|
def folder(self, key: str) -> str:
|
|
330
343
|
"""The setting `key` as a folder that exists (created when asked for)."""
|
|
331
344
|
p = self.get(key)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Running work outside a request: the small pieces every app wrote for itself, then (with the db extra) a durable
|
|
2
|
+
queue built on them.
|
|
3
|
+
|
|
4
|
+
retry next_state, backoff_s, RetryLater, PROGRAMMING_ERRORS: when a failure runs again
|
|
5
|
+
progress report_progress anywhere inside a task; ProgressReporter writes it at most once a second
|
|
6
|
+
flight SingleFlight: one in-process run per key, Conflict on a second start (409), a cooperative stop
|
|
7
|
+
status StatusFile and Detached: a process that outlives the server, with its state in an atomic JSON file
|
|
8
|
+
ticker Ticker: a function every N seconds on a daemon thread, surviving its own errors
|
|
9
|
+
queue Queue and Worker (needs strata-python[db]): durable jobs in the app's database; import it directly
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from strata_python.contracts import Progress
|
|
13
|
+
from strata_python.tasks.flight import Conflict, Flight, SingleFlight
|
|
14
|
+
from strata_python.tasks.progress import ProgressReporter, report_progress, reporting
|
|
15
|
+
from strata_python.tasks.retry import PROGRAMMING_ERRORS, Decision, RetryLater, backoff_s, describe, next_state
|
|
16
|
+
from strata_python.tasks.status import Detached, StatusFile, write_json_atomic
|
|
17
|
+
from strata_python.tasks.ticker import Ticker
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"PROGRAMMING_ERRORS",
|
|
21
|
+
"Conflict",
|
|
22
|
+
"Decision",
|
|
23
|
+
"Detached",
|
|
24
|
+
"Flight",
|
|
25
|
+
"Progress",
|
|
26
|
+
"ProgressReporter",
|
|
27
|
+
"RetryLater",
|
|
28
|
+
"SingleFlight",
|
|
29
|
+
"StatusFile",
|
|
30
|
+
"Ticker",
|
|
31
|
+
"backoff_s",
|
|
32
|
+
"describe",
|
|
33
|
+
"next_state",
|
|
34
|
+
"report_progress",
|
|
35
|
+
"reporting",
|
|
36
|
+
"write_json_atomic",
|
|
37
|
+
]
|