strata-python 0.2.2__py3-none-any.whl → 0.2.4__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 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 settings routes, static files, the uvicorn runner
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
@@ -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
@@ -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(RuntimeError):
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
 
@@ -100,8 +101,12 @@ MAC = sys.platform == "darwin"
100
101
 
101
102
 
102
103
  def lower_priority(nice: int = 19, io: bool = False) -> None:
103
- """Run this process at lower CPU priority (nice value on POSIX, below-normal/idle class on Windows). Children
104
- inherit it. Best effort: a refusal is skipped.
104
+ """Run this process at lower CPU priority (nice value `nice` on POSIX, below-normal/idle class on Windows).
105
+ Children inherit it. Best effort: a refusal is skipped.
106
+
107
+ `nice` is the value the process ends at, not an increment: it is set absolutely and never lowers the current
108
+ one, so `lower_priority(19)` gives 19 even from a process that starts below 0 (issue #28; `os.nice` adds, so a
109
+ CI runner at -10 ended at 9).
105
110
 
106
111
  `io=True` also lowers its disk priority, for batch jobs that read many large files (hashing an archive, exiftool
107
112
  over a folder) and should not slow interactive use of the same disk: the idle I/O class on Linux (children
@@ -117,7 +122,9 @@ def lower_priority(nice: int = 19, io: bool = False) -> None:
117
122
  k32.SetPriorityClass(k32.GetCurrentProcess(), 0x00100000) # PROCESS_MODE_BACKGROUND_BEGIN
118
123
  return
119
124
  with contextlib.suppress(OSError, AttributeError):
120
- os.nice(nice)
125
+ current = os.getpriority(os.PRIO_PROCESS, 0)
126
+ if nice > current:
127
+ os.setpriority(os.PRIO_PROCESS, 0, nice)
121
128
  if io:
122
129
  _lower_io_priority()
123
130
 
@@ -154,3 +161,131 @@ def venv_python(venv: str) -> str:
154
161
  def cli_command(module: str) -> list[str]:
155
162
  """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
163
  return [sys.executable, "-m", module]
164
+
165
+
166
+ def detached_kwargs() -> dict[str, Any]:
167
+ """`subprocess.Popen` keyword arguments that start a process outside this one's session (POSIX) or console and
168
+ process group (Windows), so it keeps running when the server that started it restarts, and a Ctrl+C or a stopped
169
+ service unit aimed at the server does not reach it. `kill_tree` still stops it and its children."""
170
+ if WIN:
171
+ return {"creationflags": 0x00000200 | 0x00000008} # CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS
172
+ return {"start_new_session": True}
173
+
174
+
175
+ def load_average() -> tuple[float, float, float] | None:
176
+ """The 1, 5 and 15 minute load averages, or None where the OS has none (Windows)."""
177
+ try:
178
+ return os.getloadavg()
179
+ except (AttributeError, OSError):
180
+ return None
181
+
182
+
183
+ # --- supervised children: listory's per-job process groups -----------------------------------------------------------
184
+
185
+ SUPERVISED_ENV = "STRATA_SUPERVISED"
186
+
187
+
188
+ @overload
189
+ def start_supervised(
190
+ cmd: list[str], *, env: Mapping[str, str] | None = None, cwd: str | None = None, text: Literal[False] = False
191
+ ) -> subprocess.Popen[bytes]: ...
192
+ @overload
193
+ def start_supervised(
194
+ cmd: list[str], *, env: Mapping[str, str] | None = None, cwd: str | None = None, text: Literal[True]
195
+ ) -> subprocess.Popen[str]: ...
196
+ def start_supervised(
197
+ cmd: list[str], *, env: Mapping[str, str] | None = None, cwd: str | None = None, text: bool = False
198
+ ) -> subprocess.Popen[Any]:
199
+ """Start `cmd` in its own process group, with a lifeline on its stdin, so that `kill_group` stops it and every
200
+ tool it started, and so that it stops itself when this process dies, however it dies (`watch_supervisor`, called
201
+ in the child, sees the pipe close). `text=True` also pipes its stdout, as text, for a child that answers on it
202
+ (`tasks.child`); otherwise its output goes where this process's goes."""
203
+ return subprocess.Popen( # noqa: S603 - the app's own command
204
+ cmd,
205
+ stdin=subprocess.PIPE,
206
+ stdout=subprocess.PIPE if text else None,
207
+ text=text,
208
+ encoding="utf8" if text else None,
209
+ env={**(env or os.environ), SUPERVISED_ENV: "1"},
210
+ cwd=cwd,
211
+ start_new_session=not WIN,
212
+ creationflags=0x00000200 if WIN else 0, # CREATE_NEW_PROCESS_GROUP
213
+ )
214
+
215
+
216
+ def stdout_to_stderr() -> int:
217
+ """Point this process's stdout at its stderr, for it and every process it starts, and return a new fd on the old
218
+ stdout (for a child that answers its parent there). On Windows the Win32 standard handle is moved too: moving
219
+ fd 1 alone leaves the handle a started tool inherits on the old pipe."""
220
+ sys.stdout.flush()
221
+ saved = os.dup(1)
222
+ os.dup2(2, 1)
223
+ if WIN:
224
+ import ctypes
225
+ import msvcrt
226
+
227
+ ctypes.windll.kernel32.SetStdHandle(-11, msvcrt.get_osfhandle(2)) # STD_OUTPUT_HANDLE
228
+ return saved
229
+
230
+
231
+ def stdin_from_devnull() -> int:
232
+ """Give this process (and every process it starts) an empty stdin, and return a new fd on the old one, for a
233
+ child that reads its parent's commands there. On Windows this is what keeps a tool from hanging: a thread blocked
234
+ reading a synchronous pipe holds that pipe, and a tool that inherits it as stdin blocks starting up."""
235
+ saved = os.dup(0)
236
+ null = os.open(os.devnull, os.O_RDONLY)
237
+ os.dup2(null, 0)
238
+ os.close(null)
239
+ if WIN:
240
+ import ctypes
241
+ import msvcrt
242
+
243
+ ctypes.windll.kernel32.SetStdHandle(-10, msvcrt.get_osfhandle(0)) # STD_INPUT_HANDLE
244
+ sys.stdin = open(0, closefd=False) # noqa: SIM115 - fd 0 for the life of the process
245
+ return saved
246
+
247
+
248
+ def watch_supervisor() -> bool:
249
+ """In a child that `start_supervised` started: end this process group when the parent's end of the lifeline
250
+ closes (the parent exited, crashed or was killed), so no tool is left running for a server that is gone. True
251
+ when it is watching; False when this process was not started that way."""
252
+ if os.environ.pop(SUPERVISED_ENV, None) != "1": # popped: this process's own children are not supervised by it
253
+ return False
254
+
255
+ def watch() -> None:
256
+ try:
257
+ while os.read(0, 1): # the parent never writes: this returns b"" (EOF) when its end closes
258
+ pass
259
+ finally:
260
+ terminate_own_group()
261
+
262
+ threading.Thread(target=watch, name="strata-supervisor-watch", daemon=True).start()
263
+ return True
264
+
265
+
266
+ def terminate_own_group() -> None:
267
+ """Kill this process and everything in its group (or, on Windows, its process tree), at once."""
268
+ if WIN:
269
+ kill_tree(os.getpid())
270
+ elif os.getpgrp() == os.getpid(): # only a group this process leads, never the server's own session
271
+ import signal
272
+
273
+ with contextlib.suppress(OSError):
274
+ os.killpg(os.getpid(), signal.SIGKILL)
275
+ os._exit(1)
276
+
277
+
278
+ def kill_group(proc: subprocess.Popen[Any], timeout: float = 5.0) -> None:
279
+ """Stop a `start_supervised` child and every process in its group now, and reap it."""
280
+ if WIN:
281
+ kill_tree(proc.pid)
282
+ else:
283
+ import signal
284
+
285
+ with contextlib.suppress(OSError):
286
+ os.killpg(proc.pid, signal.SIGKILL)
287
+ with contextlib.suppress(subprocess.TimeoutExpired):
288
+ proc.wait(timeout)
289
+ if proc.stdin is not None:
290
+ with contextlib.suppress(OSError):
291
+ proc.stdin.close()
@@ -244,14 +244,22 @@ def page_count(pdf: bytes) -> int:
244
244
 
245
245
 
246
246
  def rasterise(pdf: bytes, page: int = 0, dpi: float = 300.0) -> Image.Image:
247
- """One page of a PDF as a greyscale picture at `dpi` (the scan's dpi gives the scan's size in pixels), white paper."""
247
+ """One page of a PDF as a greyscale picture at `dpi` (the scan's dpi gives the scan's size in pixels), white paper.
248
+
249
+ The picture is the page's size in points times `dpi / 72`, rounded to whole pixels. pdfium rounds up, so a scan
250
+ page 2660 px wide at 500 dpi (383.04 pt, stored a hair over) came back 2661 px (issue #27) and an ink comparison
251
+ against the scan had to pad or crop; the sliver of a pixel past the rounded edge is cut off here instead."""
248
252
  doc = _document(pdf)
249
253
  try:
250
254
  if not 0 <= page < len(doc):
251
255
  raise PageError(f"no page {page} in a PDF of {len(doc)}")
252
256
  p = doc[page]
253
- img = p.render(scale=dpi / 72.0).to_pil().convert("L")
257
+ scale = dpi / 72.0
258
+ img = p.render(scale=scale).to_pil().convert("L")
259
+ w, h = round(p.get_width() * scale), round(p.get_height() * scale) # pdfium's sizes already follow /Rotate
254
260
  p.close()
261
+ if img.size != (w, h): # pdfium's ceil is at most one pixel over round, so this only ever trims
262
+ img = img.crop((0, 0, min(img.width, w), min(img.height, h)))
255
263
  return img
256
264
  finally:
257
265
  doc.close()
@@ -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
+ ]