strata-python 0.2.4__tar.gz → 0.2.5__tar.gz

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.
Files changed (82) hide show
  1. {strata_python-0.2.4 → strata_python-0.2.5}/CHANGELOG.md +14 -0
  2. {strata_python-0.2.4 → strata_python-0.2.5}/PKG-INFO +58 -14
  3. {strata_python-0.2.4 → strata_python-0.2.5}/README.md +55 -13
  4. {strata_python-0.2.4 → strata_python-0.2.5}/pyproject.toml +6 -2
  5. strata_python-0.2.5/src/strata_python/files.py +247 -0
  6. strata_python-0.2.5/src/strata_python/http.py +326 -0
  7. strata_python-0.2.5/src/strata_python/images.py +107 -0
  8. strata_python-0.2.5/src/strata_python/media.py +323 -0
  9. strata_python-0.2.5/src/strata_python/stats.py +196 -0
  10. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/tasks/__init__.py +2 -1
  11. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/tasks/status.py +1 -16
  12. strata_python-0.2.5/tests/unit/test_files.py +259 -0
  13. strata_python-0.2.5/tests/unit/test_http.py +333 -0
  14. strata_python-0.2.5/tests/unit/test_images.py +132 -0
  15. strata_python-0.2.5/tests/unit/test_media.py +165 -0
  16. strata_python-0.2.5/tests/unit/test_stats.py +116 -0
  17. {strata_python-0.2.4 → strata_python-0.2.5}/.gitignore +0 -0
  18. {strata_python-0.2.4 → strata_python-0.2.5}/LICENSE +0 -0
  19. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/__init__.py +0 -0
  20. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/check.py +0 -0
  21. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/cli.py +0 -0
  22. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/client.py +0 -0
  23. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/clients/__init__.py +0 -0
  24. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/clients/models.py +0 -0
  25. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/contracts.py +0 -0
  26. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/db/__init__.py +0 -0
  27. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/db/__main__.py +0 -0
  28. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/db/_alembic/env.py +0 -0
  29. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/db/_alembic/script.py.mako +0 -0
  30. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/db/cli.py +0 -0
  31. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/db/config.py +0 -0
  32. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/db/engine.py +0 -0
  33. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/db/guard.py +0 -0
  34. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/db/migrations.py +0 -0
  35. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/db/models.py +0 -0
  36. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/db/project.py +0 -0
  37. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/db/pytest_plugin.py +0 -0
  38. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/db/scratch.py +0 -0
  39. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/db/settings.py +0 -0
  40. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/db/testing.py +0 -0
  41. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/db/testserver.py +0 -0
  42. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/http_server.py +0 -0
  43. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/live.py +0 -0
  44. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/oslib.py +0 -0
  45. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/pages/__init__.py +0 -0
  46. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/pages/model.py +0 -0
  47. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/pages/render.py +0 -0
  48. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/public_check.py +0 -0
  49. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/py.typed +0 -0
  50. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/pytest_plugin.py +0 -0
  51. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/settings.py +0 -0
  52. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/tasks/child.py +0 -0
  53. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/tasks/flight.py +0 -0
  54. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/tasks/progress.py +0 -0
  55. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/tasks/queue.py +0 -0
  56. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/tasks/retry.py +0 -0
  57. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/tasks/ticker.py +0 -0
  58. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/testing.py +0 -0
  59. {strata_python-0.2.4 → strata_python-0.2.5}/src/strata_python/web.py +0 -0
  60. {strata_python-0.2.4 → strata_python-0.2.5}/tests/conftest.py +0 -0
  61. {strata_python-0.2.4 → strata_python-0.2.5}/tests/integration/test_db_cli.py +0 -0
  62. {strata_python-0.2.4 → strata_python-0.2.5}/tests/integration/test_serve.py +0 -0
  63. {strata_python-0.2.4 → strata_python-0.2.5}/tests/integration/test_strata_check.py +0 -0
  64. {strata_python-0.2.4 → strata_python-0.2.5}/tests/unit/job_handlers.py +0 -0
  65. {strata_python-0.2.4 → strata_python-0.2.5}/tests/unit/test_check.py +0 -0
  66. {strata_python-0.2.4 → strata_python-0.2.5}/tests/unit/test_cli.py +0 -0
  67. {strata_python-0.2.4 → strata_python-0.2.5}/tests/unit/test_client.py +0 -0
  68. {strata_python-0.2.4 → strata_python-0.2.5}/tests/unit/test_clients_models.py +0 -0
  69. {strata_python-0.2.4 → strata_python-0.2.5}/tests/unit/test_contracts.py +0 -0
  70. {strata_python-0.2.4 → strata_python-0.2.5}/tests/unit/test_db.py +0 -0
  71. {strata_python-0.2.4 → strata_python-0.2.5}/tests/unit/test_http_server.py +0 -0
  72. {strata_python-0.2.4 → strata_python-0.2.5}/tests/unit/test_live.py +0 -0
  73. {strata_python-0.2.4 → strata_python-0.2.5}/tests/unit/test_oslib.py +0 -0
  74. {strata_python-0.2.4 → strata_python-0.2.5}/tests/unit/test_package.py +0 -0
  75. {strata_python-0.2.4 → strata_python-0.2.5}/tests/unit/test_pages.py +0 -0
  76. {strata_python-0.2.4 → strata_python-0.2.5}/tests/unit/test_plugin.py +0 -0
  77. {strata_python-0.2.4 → strata_python-0.2.5}/tests/unit/test_public_check.py +0 -0
  78. {strata_python-0.2.4 → strata_python-0.2.5}/tests/unit/test_queue.py +0 -0
  79. {strata_python-0.2.4 → strata_python-0.2.5}/tests/unit/test_settings.py +0 -0
  80. {strata_python-0.2.4 → strata_python-0.2.5}/tests/unit/test_tasks.py +0 -0
  81. {strata_python-0.2.4 → strata_python-0.2.5}/tests/unit/test_testing.py +0 -0
  82. {strata_python-0.2.4 → strata_python-0.2.5}/tests/unit/test_web.py +0 -0
@@ -4,6 +4,20 @@ What each release adds or changes for an app that depends on strata-python, newe
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## 0.2.5 (2026-11-23)
8
+
9
+ ### Added
10
+
11
+ - `strata_python.files`: `atomic_path(path)` (a temp path beside the file, keeping its extension so ffmpeg can write to it, replaced on success and removed on error), `atomic_open`, `write_text_atomic`, `write_bytes_atomic`, `write_json_atomic(path, data, indent=1)`, `read_json(path, default)` (missing or broken file: the default), `sha256`/`sha256_hex`, `quick_fingerprint` (size and both ends of a big file), `stat_key(path, *extra)`, `inside(root, path)` (a path from a request, refused with `ValueError` if it leaves the root) and `DiskCache` (bytes or `json(key, fetch, max_age_s)` on disk with an age). Replace the app's `tmp` + `os.replace` writes, its sha256 helpers and its response caches.
12
+ - `strata_python.http.Http(user_agent, ...)`: the polite client for public web APIs. A gap per host across threads (`min_interval`) and processes (`throttle_file`), 429 and 503 waiting for Retry-After (seconds or a date, capped at `max_wait`), a `cool_down` for a host still saying 429, retries of 5xx and network errors only for idempotent requests (`idempotent=True` for a read sent as POST), `max_bytes`, `https_only`, an optional `DiskCache` (`cache_s=`; 200 and 404 kept), and `observe(reply, attempt)`. Errors come back as a `Reply` (`ok`, `status` 0 when unreachable, `error`, `limited`, `cached`, `json()`, `text()`); `raise_for_status()` and `get_json()` raise `HttpError`. Replace the app's own throttle, Retry-After and cache code.
13
+ - `strata_python.media`: `probe(path)` returns a `Probe` (duration, format, size, bit rate, tags, `streams` as `Stream`, `chapters`, `video`/`audio`, ffprobe's `warnings`, `raw`); `duration(path)`; `ffmpeg(args, input=, timeout=, progress=)` with `-nostdin -hide_banner -v error -y`, raising `MediaError` with the tail of ffmpeg's stderr; `tool(name)` honours `STRATA_FFMPEG` and `STRATA_FFPROBE`; `available()`. Replace the app's ffprobe and ffmpeg wrappers.
14
+ - `strata_python.images` and the `[images]` extra (Pillow): `thumbnail(src, px, cache_dir=, quality=, version=, make=)` returns the path of a cached upright JPEG (keyed on the file, the size, the quality and `version`; never enlarged; one maker per file at a time and `slots` at once); `open_upright`, `flatten`, `jpeg_bytes`. Replace the app's thumbnail cache.
15
+ - `strata_python.stats`: `bradley_terry(votes, side=)` (a `Fit` with `strengths`, the side advantage, `ratings()` on the Elo scale and `p_beats`), `intervals` (bootstrap over votes), `head_to_head`, `votes_from(judgments)`, `wilson`, `mcnemar`, `holm`. Pure Python. Replace the arena's and the evals' copies.
16
+
17
+ ### Changed
18
+
19
+ - `tasks.write_json_atomic` is now `files.write_json_atomic` (the same import still works). It also fsyncs before the replace, writes non-ASCII characters as they are instead of `\u` escapes, and takes `indent=`.
20
+
7
21
  ## 0.2.4 (2026-11-23)
8
22
 
9
23
  ### Fixed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: strata-python
3
- Version: 0.2.4
3
+ Version: 0.2.5
4
4
  Summary: Common code for Python web server apps: OS helpers, settings, FastAPI serving, CLI commands, test fixtures and the strata-check gate
5
5
  Project-URL: Homepage, https://github.com/jburnhams/strata-python
6
6
  Project-URL: Source, https://github.com/jburnhams/strata-python
@@ -37,6 +37,8 @@ Requires-Dist: pytest-timeout<3,>=2; extra == 'dev'
37
37
  Requires-Dist: pytest-xdist<4,>=3; extra == 'dev'
38
38
  Requires-Dist: ruff<0.18,>=0.17; extra == 'dev'
39
39
  Requires-Dist: ty<0.1,>=0.0.99; extra == 'dev'
40
+ Provides-Extra: images
41
+ Requires-Dist: pillow<14,>=13; extra == 'images'
40
42
  Provides-Extra: pdf
41
43
  Requires-Dist: pillow<14,>=13; extra == 'pdf'
42
44
  Requires-Dist: pypdfium2<6,>=4.30; extra == 'pdf'
@@ -56,6 +58,11 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
56
58
  | `strata_python.contracts` | The shapes the apps' APIs share, as pydantic models for `response_model`: `Health`, `SystemInfo`, `ErrorBody`, `Task` (with `TaskState`), `Progress`, `Page[T]`, `FileRef`, `Judgment` |
57
59
  | `strata_python.client` | `ServiceClient`, the standard-library base for calling a strata service: JSON calls, `Rejected` (4xx, with the reason and payload) and `Unavailable` (down or 5xx), retried reads, a long-poll `wait`, `available()`, and `env_url` |
58
60
  | `strata_python.tasks` | Work outside a request: `next_state`/`backoff_s`/`RetryLater` (when to retry), `report_progress` and `ProgressReporter` (throttled), `SingleFlight` (one run per key, `Conflict` on a second), `StatusFile` and `Detached` (a process that outlives the server), `Ticker` (a loop that survives its errors), and with the `[db]` extra `tasks.queue` (`Queue`, `Worker`, `jobs_table`: durable jobs with retry, dedupe, resources, cancel and crash recovery) |
61
+ | `strata_python.files` | Atomic writes (`atomic_path` keeps the extension for ffmpeg, `atomic_open`, `write_json_atomic`, `write_text_atomic`, `write_bytes_atomic`), `read_json(path, default)`, `sha256`/`sha256_hex`, `quick_fingerprint` (size and both ends), `stat_key` (a cache key that follows the file), `inside(root, path)` (refuses `..` and links out), and `DiskCache` (values on disk with an age; `json(key, fetch, max_age_s)`) |
62
+ | `strata_python.http` | `Http(user_agent, min_interval=...)`, the polite client for other people's APIs: a gap per host across threads (and processes with `throttle_file`), Retry-After as seconds or a date, a cool-down for a host that keeps saying 429, retries that never replay a write, a size cap, an optional `DiskCache`, and errors returned as a `Reply` (`raise_for_status()`, `get_json()` for code that wants exceptions) |
63
+ | `strata_python.media` | `probe(path)` (a typed `Probe`: duration, format, tags, streams, chapters, ffprobe's warnings), `duration`, `ffmpeg(args, progress=...)` raising `MediaError` with ffmpeg's own reason, `available()` |
64
+ | `strata_python.images` (extra `[images]`) | `thumbnail(src, px, cache_dir=...)` (an upright JPEG, made once, keyed on the file, never enlarged, the app's own reader through `make=`), `open_upright`, `flatten` (alpha and 16-bit greys to 8-bit RGB), `jpeg_bytes` |
65
+ | `strata_python.stats` | Pairwise rankings and eval statistics in pure Python: `bradley_terry` (ties, an optional side advantage, Elo-scale `ratings()`), `intervals` (bootstrap), `head_to_head`, `votes_from(judgments)`, `wilson`, `mcnemar`, `holm` |
59
66
  | `strata_python.clients.models` | The strata-models client, standard library only: `run`, `submit`, `wait`, `role_model`, `gpu_lease`, a shortcut for every role the service runs (`faces`, `face_kind`, `transcribe`, `ocr`, `speak`, `denoise_audio`, `audio_quality`, `generate_image`, `embed`, `enhance_video`, and `ask` for the language models) and a typed result for each |
60
67
  | `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
61
68
  | pytest plugin | Loaded automatically: hermetic home and data folders (`strata_env` adds the app's own variables), a no-network guard, `http_server` and `live_app`, the `fake_urlopen`, `fake_popen`, `fake_run` and `no_sleep` fixtures, `fake_models` (a stand-in strata-models), and the `integration` marker on everything under `tests/integration` |
@@ -145,8 +152,8 @@ To keep the values in the app's database instead of the file, add the table to t
145
152
  ```python
146
153
  from strata_python.db.settings import TableStore, settings_table
147
154
 
148
- SETTINGS_TABLE = settings_table(Base.metadata) # in models.py, so the migrations create it
149
- SETTINGS.bind(TableStore(engine, SETTINGS_TABLE)) # any object with load() and update(changes) is a store
155
+ SETTINGS_TABLE = settings_table(Base.metadata) # in models.py, so the migrations create it
156
+ SETTINGS.bind(TableStore(engine, SETTINGS_TABLE)) # any object with load() and update(changes) is a store
150
157
  ```
151
158
 
152
159
  ### 4. The server
@@ -165,11 +172,15 @@ def create_app():
165
172
  Two more that replace code most servers carry:
166
173
 
167
174
  ```python
168
- web.add_error_handlers(app) # ValueError 400, PermissionError 403, KeyError and FileNotFoundError 404,
169
- # tasks.Conflict 409, client.Rejected 502, client.Unavailable 503: {detail, payload}
170
- web.add_system(app, __version__, commit=web.source_commit(__file__),
171
- folders={"data": lambda: SETTINGS.get("data_dir")},
172
- services={"strata-models": "http://127.0.0.1:8366"}) # GET /api/system, a SystemInfo
175
+ web.add_error_handlers(app) # ValueError 400, PermissionError 403, KeyError and FileNotFoundError 404,
176
+ # tasks.Conflict 409, client.Rejected 502, client.Unavailable 503: {detail, payload}
177
+ web.add_system(
178
+ app,
179
+ __version__,
180
+ commit=web.source_commit(__file__),
181
+ folders={"data": lambda: SETTINGS.get("data_dir")},
182
+ services={"strata-models": "http://127.0.0.1:8366"},
183
+ ) # GET /api/system, a SystemInfo
173
184
  ```
174
185
 
175
186
  Delete the app's `guard()` (or each route's `try/except` raising `HTTPException`), passing its own exceptions as `add_error_handlers(app, {BookLocked: 423})`, and its `/api/system` route. Give `base_app` the same `commit=` so `/api/health` says which source the server runs. Declare a route's answer with a shape from `strata_python.contracts` (`response_model=Page[Task]`) where the app already returns that shape, so the web app's types can come from `/api/openapi.json`.
@@ -219,9 +230,9 @@ A check returns `(status, text)` with status `ok`, `missing`, `slow` (works, but
219
230
  Drop the `strata-models-client` path or git dependency and change the import. The functions, their arguments and the exceptions are the same:
220
231
 
221
232
  ```python
222
- from strata_python.clients import models as sm # was: import strata_models_client as sm
233
+ from strata_python.clients import models as sm # was: import strata_models_client as sm
223
234
 
224
- page = sm.OcrPage.from_json(sm.ocr("/path/page.png", app="strata-scan")) # typed: page.lines[0].words[0].box
235
+ page = sm.OcrPage.from_json(sm.ocr("/path/page.png", app="strata-scan")) # typed: page.lines[0].words[0].box
225
236
  talk = sm.Transcript.from_json(sm.transcribe("/path/talk.wav", app="strata-360"))
226
237
  with sm.gpu_lease("strata-stills", vram_gb=4):
227
238
  run_my_own_cuda_code()
@@ -246,15 +257,48 @@ Replace the app's job dicts and loops with `strata_python.tasks`:
246
257
  ```python
247
258
  from strata_python.tasks.queue import Job, Queue, Worker
248
259
 
249
- QUEUE = Queue(engine, JOBS, on_fail=cascade) # on_fail(conn, job, error), in the failing transaction
260
+ QUEUE = Queue(engine, JOBS, on_fail=cascade) # on_fail(conn, job, error), in the failing transaction
250
261
  QUEUE.enqueue("ocr", {"page": 3}, domain="book:12", dedupe=True, resources=["gpu"], timeout_s=600)
251
- WORKER = Worker(QUEUE, {"ocr": ocr_page}, concurrency=2).start() # a job process per thread, reused; recovers dead workers' jobs
252
- QUEUE.page(state="running", after=cursor) # Page[Task] for GET /api/jobs
253
- QUEUE.cancel(job_id); QUEUE.retry(job_id); QUEUE.prune(older_than_s=30 * 86400)
262
+ WORKER = Worker(
263
+ QUEUE, {"ocr": ocr_page}, concurrency=2
264
+ ).start() # a job process per thread, reused; recovers dead workers' jobs
265
+ QUEUE.page(state="running", after=cursor) # Page[Task] for GET /api/jobs
266
+ QUEUE.cancel(job_id)
267
+ QUEUE.retry(job_id)
268
+ QUEUE.prune(older_than_s=30 * 86400)
254
269
  ```
255
270
 
256
271
  A handler is a module-level `fn(job) -> result` that reads `job.options` and reports progress. By default jobs run in job processes (`python -m strata_python.tasks.child`, one per worker thread, kept between jobs and importing the handlers by name), so a cancel, a timeout or `WORKER.stop()` kills the job and every tool it started, and jobs die with the server; a quick job costs about half a millisecond more than on a thread (3.5 ms against 2.9 ms a job on SQLite), since only a kill starts a new process. `max_jobs=N` replaces a process after N jobs, for code that leaks. The worker checks at start-up that every handler can be imported. `Worker(lower_priority=True)` runs the jobs at idle CPU and disk priority. `Worker(isolate=False)` runs handlers on the server's threads instead, where they return early when `job.stopping`. In tests, `QUEUE.step(handlers)` claims and runs one job in the test's own thread.
257
272
 
273
+ ### 6c. Files, web APIs, media, pictures and rankings
274
+
275
+ Each of these replaces code that two to six apps wrote for themselves; move to it when you next touch that code.
276
+
277
+ - **Writes.** Every `tmp = path + ".tmp"; ...; os.replace(tmp, path)` becomes `write_json_atomic(path, data)` (or `write_text_atomic`, `write_bytes_atomic`, `with atomic_open(path, "wb") as f:`). A tool that writes the file itself writes to `with atomic_path(out) as tmp:`; the temp name keeps the extension, so `ffmpeg ... tmp` still picks the format. Reads that tolerate a missing or broken file are `read_json(path, default)`. Delete the app's `_save`, `write_status` and `.part` helpers.
278
+ - **Hashes and keys.** `sha256(path)` (bytes, for a `LargeBinary` column) and `sha256_hex(path)` replace listory's two copies, filecat's and stills' scripts'. `quick_fingerprint(path)` is 360's `clips.fingerprint` idea on SHA-256 (an app that stored the old 12-character SHA-1 keeps its own until it re-keys). A cache that must follow a file's changes keys on `stat_key(path, px, version)`.
279
+ - **Paths from a request.** `files.inside(root, name)` before opening a file a request names; it raises `ValueError` (400 with `add_error_handlers`) for `..`, an absolute path elsewhere, or a link out of the root.
280
+ - **Other people's APIs.** One `Http` per service, at module level so its gap is shared:
281
+
282
+ ```python
283
+ from strata_python.files import DiskCache
284
+ from strata_python.http import Http
285
+
286
+ NOMINATIM = Http(
287
+ "myapp/1.0 (reverse geocoding of my own tracks)",
288
+ min_interval=1.1,
289
+ throttle_file=cache_dir / ".nominatim",
290
+ cache=DiskCache(cache_dir),
291
+ )
292
+ reply = NOMINATIM.get(URL, params={"lat": lat, "lon": lon, "format": "json"}, cache_s=30 * 86400)
293
+ if reply.ok:
294
+ place = reply.json() # reply.status == 0 when unreachable; reply.limited when rate limited
295
+ ```
296
+
297
+ The User-Agent names the app and what it is for, never a person. Delete the app's `_throttle`, `_retry_after`, `_cool_until`, `_open`/`_get` wrappers and its response cache; listory's `providers.base.Http` keeps its own `emit` through `observe=`. A provider result worth keeping (not an HTTP body) is `DiskCache(...).json(key, fetch, max_age_s)`.
298
+ - **ffprobe and ffmpeg.** `media.probe(path)` replaces every hand-written `ffprobe -show_entries` call; read `info.duration`, `info.audio.sample_rate`, `info.video.fps`, `info.chapters`, `info.tags`, and `info.raw` for anything else. `media.ffmpeg(args)` adds `-nostdin -hide_banner -v error -y` and raises `MediaError` with ffmpeg's last lines; `progress=` reports seconds written. Map `MediaError` in `add_error_handlers` if the app answers it over HTTP. A doctor row is `cli.program("ffmpeg")`.
299
+ - **Thumbnails** (`strata-python[images]`): `images.thumbnail(src, px, cache_dir=settings.thumbs_dir())` returns the cached JPEG's path for a `FileResponse`. An app with its own reader (stills' raw previews, 360's video frames) passes `make=lambda path, px: ...` returning a Pillow image. Bump `version=` when the way a thumbnail is made changes.
300
+ - **Rankings and evals.** `stats.bradley_terry(votes, side=True)` with votes as `(a, b, "a" | "b" | "tie")` (or `stats.votes_from(judgments)`), `.ratings()` for the Elo scale, `stats.intervals(votes)` for how far to trust a gap; `wilson`, `mcnemar` and `holm` for eval write-ups. The numpy bootstraps over items in strata-models' evals stay there until a second app needs them.
301
+
258
302
  ### 7. Tests
259
303
 
260
304
  The pytest plugin loads itself once strata-python is installed. Configure it in `pyproject.toml`:
@@ -11,6 +11,11 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
11
11
  | `strata_python.contracts` | The shapes the apps' APIs share, as pydantic models for `response_model`: `Health`, `SystemInfo`, `ErrorBody`, `Task` (with `TaskState`), `Progress`, `Page[T]`, `FileRef`, `Judgment` |
12
12
  | `strata_python.client` | `ServiceClient`, the standard-library base for calling a strata service: JSON calls, `Rejected` (4xx, with the reason and payload) and `Unavailable` (down or 5xx), retried reads, a long-poll `wait`, `available()`, and `env_url` |
13
13
  | `strata_python.tasks` | Work outside a request: `next_state`/`backoff_s`/`RetryLater` (when to retry), `report_progress` and `ProgressReporter` (throttled), `SingleFlight` (one run per key, `Conflict` on a second), `StatusFile` and `Detached` (a process that outlives the server), `Ticker` (a loop that survives its errors), and with the `[db]` extra `tasks.queue` (`Queue`, `Worker`, `jobs_table`: durable jobs with retry, dedupe, resources, cancel and crash recovery) |
14
+ | `strata_python.files` | Atomic writes (`atomic_path` keeps the extension for ffmpeg, `atomic_open`, `write_json_atomic`, `write_text_atomic`, `write_bytes_atomic`), `read_json(path, default)`, `sha256`/`sha256_hex`, `quick_fingerprint` (size and both ends), `stat_key` (a cache key that follows the file), `inside(root, path)` (refuses `..` and links out), and `DiskCache` (values on disk with an age; `json(key, fetch, max_age_s)`) |
15
+ | `strata_python.http` | `Http(user_agent, min_interval=...)`, the polite client for other people's APIs: a gap per host across threads (and processes with `throttle_file`), Retry-After as seconds or a date, a cool-down for a host that keeps saying 429, retries that never replay a write, a size cap, an optional `DiskCache`, and errors returned as a `Reply` (`raise_for_status()`, `get_json()` for code that wants exceptions) |
16
+ | `strata_python.media` | `probe(path)` (a typed `Probe`: duration, format, tags, streams, chapters, ffprobe's warnings), `duration`, `ffmpeg(args, progress=...)` raising `MediaError` with ffmpeg's own reason, `available()` |
17
+ | `strata_python.images` (extra `[images]`) | `thumbnail(src, px, cache_dir=...)` (an upright JPEG, made once, keyed on the file, never enlarged, the app's own reader through `make=`), `open_upright`, `flatten` (alpha and 16-bit greys to 8-bit RGB), `jpeg_bytes` |
18
+ | `strata_python.stats` | Pairwise rankings and eval statistics in pure Python: `bradley_terry` (ties, an optional side advantage, Elo-scale `ratings()`), `intervals` (bootstrap), `head_to_head`, `votes_from(judgments)`, `wilson`, `mcnemar`, `holm` |
14
19
  | `strata_python.clients.models` | The strata-models client, standard library only: `run`, `submit`, `wait`, `role_model`, `gpu_lease`, a shortcut for every role the service runs (`faces`, `face_kind`, `transcribe`, `ocr`, `speak`, `denoise_audio`, `audio_quality`, `generate_image`, `embed`, `enhance_video`, and `ask` for the language models) and a typed result for each |
15
20
  | `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
16
21
  | pytest plugin | Loaded automatically: hermetic home and data folders (`strata_env` adds the app's own variables), a no-network guard, `http_server` and `live_app`, the `fake_urlopen`, `fake_popen`, `fake_run` and `no_sleep` fixtures, `fake_models` (a stand-in strata-models), and the `integration` marker on everything under `tests/integration` |
@@ -100,8 +105,8 @@ To keep the values in the app's database instead of the file, add the table to t
100
105
  ```python
101
106
  from strata_python.db.settings import TableStore, settings_table
102
107
 
103
- SETTINGS_TABLE = settings_table(Base.metadata) # in models.py, so the migrations create it
104
- SETTINGS.bind(TableStore(engine, SETTINGS_TABLE)) # any object with load() and update(changes) is a store
108
+ SETTINGS_TABLE = settings_table(Base.metadata) # in models.py, so the migrations create it
109
+ SETTINGS.bind(TableStore(engine, SETTINGS_TABLE)) # any object with load() and update(changes) is a store
105
110
  ```
106
111
 
107
112
  ### 4. The server
@@ -120,11 +125,15 @@ def create_app():
120
125
  Two more that replace code most servers carry:
121
126
 
122
127
  ```python
123
- web.add_error_handlers(app) # ValueError 400, PermissionError 403, KeyError and FileNotFoundError 404,
124
- # tasks.Conflict 409, client.Rejected 502, client.Unavailable 503: {detail, payload}
125
- web.add_system(app, __version__, commit=web.source_commit(__file__),
126
- folders={"data": lambda: SETTINGS.get("data_dir")},
127
- services={"strata-models": "http://127.0.0.1:8366"}) # GET /api/system, a SystemInfo
128
+ web.add_error_handlers(app) # ValueError 400, PermissionError 403, KeyError and FileNotFoundError 404,
129
+ # tasks.Conflict 409, client.Rejected 502, client.Unavailable 503: {detail, payload}
130
+ web.add_system(
131
+ app,
132
+ __version__,
133
+ commit=web.source_commit(__file__),
134
+ folders={"data": lambda: SETTINGS.get("data_dir")},
135
+ services={"strata-models": "http://127.0.0.1:8366"},
136
+ ) # GET /api/system, a SystemInfo
128
137
  ```
129
138
 
130
139
  Delete the app's `guard()` (or each route's `try/except` raising `HTTPException`), passing its own exceptions as `add_error_handlers(app, {BookLocked: 423})`, and its `/api/system` route. Give `base_app` the same `commit=` so `/api/health` says which source the server runs. Declare a route's answer with a shape from `strata_python.contracts` (`response_model=Page[Task]`) where the app already returns that shape, so the web app's types can come from `/api/openapi.json`.
@@ -174,9 +183,9 @@ A check returns `(status, text)` with status `ok`, `missing`, `slow` (works, but
174
183
  Drop the `strata-models-client` path or git dependency and change the import. The functions, their arguments and the exceptions are the same:
175
184
 
176
185
  ```python
177
- from strata_python.clients import models as sm # was: import strata_models_client as sm
186
+ from strata_python.clients import models as sm # was: import strata_models_client as sm
178
187
 
179
- page = sm.OcrPage.from_json(sm.ocr("/path/page.png", app="strata-scan")) # typed: page.lines[0].words[0].box
188
+ page = sm.OcrPage.from_json(sm.ocr("/path/page.png", app="strata-scan")) # typed: page.lines[0].words[0].box
180
189
  talk = sm.Transcript.from_json(sm.transcribe("/path/talk.wav", app="strata-360"))
181
190
  with sm.gpu_lease("strata-stills", vram_gb=4):
182
191
  run_my_own_cuda_code()
@@ -201,15 +210,48 @@ Replace the app's job dicts and loops with `strata_python.tasks`:
201
210
  ```python
202
211
  from strata_python.tasks.queue import Job, Queue, Worker
203
212
 
204
- QUEUE = Queue(engine, JOBS, on_fail=cascade) # on_fail(conn, job, error), in the failing transaction
213
+ QUEUE = Queue(engine, JOBS, on_fail=cascade) # on_fail(conn, job, error), in the failing transaction
205
214
  QUEUE.enqueue("ocr", {"page": 3}, domain="book:12", dedupe=True, resources=["gpu"], timeout_s=600)
206
- WORKER = Worker(QUEUE, {"ocr": ocr_page}, concurrency=2).start() # a job process per thread, reused; recovers dead workers' jobs
207
- QUEUE.page(state="running", after=cursor) # Page[Task] for GET /api/jobs
208
- QUEUE.cancel(job_id); QUEUE.retry(job_id); QUEUE.prune(older_than_s=30 * 86400)
215
+ WORKER = Worker(
216
+ QUEUE, {"ocr": ocr_page}, concurrency=2
217
+ ).start() # a job process per thread, reused; recovers dead workers' jobs
218
+ QUEUE.page(state="running", after=cursor) # Page[Task] for GET /api/jobs
219
+ QUEUE.cancel(job_id)
220
+ QUEUE.retry(job_id)
221
+ QUEUE.prune(older_than_s=30 * 86400)
209
222
  ```
210
223
 
211
224
  A handler is a module-level `fn(job) -> result` that reads `job.options` and reports progress. By default jobs run in job processes (`python -m strata_python.tasks.child`, one per worker thread, kept between jobs and importing the handlers by name), so a cancel, a timeout or `WORKER.stop()` kills the job and every tool it started, and jobs die with the server; a quick job costs about half a millisecond more than on a thread (3.5 ms against 2.9 ms a job on SQLite), since only a kill starts a new process. `max_jobs=N` replaces a process after N jobs, for code that leaks. The worker checks at start-up that every handler can be imported. `Worker(lower_priority=True)` runs the jobs at idle CPU and disk priority. `Worker(isolate=False)` runs handlers on the server's threads instead, where they return early when `job.stopping`. In tests, `QUEUE.step(handlers)` claims and runs one job in the test's own thread.
212
225
 
226
+ ### 6c. Files, web APIs, media, pictures and rankings
227
+
228
+ Each of these replaces code that two to six apps wrote for themselves; move to it when you next touch that code.
229
+
230
+ - **Writes.** Every `tmp = path + ".tmp"; ...; os.replace(tmp, path)` becomes `write_json_atomic(path, data)` (or `write_text_atomic`, `write_bytes_atomic`, `with atomic_open(path, "wb") as f:`). A tool that writes the file itself writes to `with atomic_path(out) as tmp:`; the temp name keeps the extension, so `ffmpeg ... tmp` still picks the format. Reads that tolerate a missing or broken file are `read_json(path, default)`. Delete the app's `_save`, `write_status` and `.part` helpers.
231
+ - **Hashes and keys.** `sha256(path)` (bytes, for a `LargeBinary` column) and `sha256_hex(path)` replace listory's two copies, filecat's and stills' scripts'. `quick_fingerprint(path)` is 360's `clips.fingerprint` idea on SHA-256 (an app that stored the old 12-character SHA-1 keeps its own until it re-keys). A cache that must follow a file's changes keys on `stat_key(path, px, version)`.
232
+ - **Paths from a request.** `files.inside(root, name)` before opening a file a request names; it raises `ValueError` (400 with `add_error_handlers`) for `..`, an absolute path elsewhere, or a link out of the root.
233
+ - **Other people's APIs.** One `Http` per service, at module level so its gap is shared:
234
+
235
+ ```python
236
+ from strata_python.files import DiskCache
237
+ from strata_python.http import Http
238
+
239
+ NOMINATIM = Http(
240
+ "myapp/1.0 (reverse geocoding of my own tracks)",
241
+ min_interval=1.1,
242
+ throttle_file=cache_dir / ".nominatim",
243
+ cache=DiskCache(cache_dir),
244
+ )
245
+ reply = NOMINATIM.get(URL, params={"lat": lat, "lon": lon, "format": "json"}, cache_s=30 * 86400)
246
+ if reply.ok:
247
+ place = reply.json() # reply.status == 0 when unreachable; reply.limited when rate limited
248
+ ```
249
+
250
+ The User-Agent names the app and what it is for, never a person. Delete the app's `_throttle`, `_retry_after`, `_cool_until`, `_open`/`_get` wrappers and its response cache; listory's `providers.base.Http` keeps its own `emit` through `observe=`. A provider result worth keeping (not an HTTP body) is `DiskCache(...).json(key, fetch, max_age_s)`.
251
+ - **ffprobe and ffmpeg.** `media.probe(path)` replaces every hand-written `ffprobe -show_entries` call; read `info.duration`, `info.audio.sample_rate`, `info.video.fps`, `info.chapters`, `info.tags`, and `info.raw` for anything else. `media.ffmpeg(args)` adds `-nostdin -hide_banner -v error -y` and raises `MediaError` with ffmpeg's last lines; `progress=` reports seconds written. Map `MediaError` in `add_error_handlers` if the app answers it over HTTP. A doctor row is `cli.program("ffmpeg")`.
252
+ - **Thumbnails** (`strata-python[images]`): `images.thumbnail(src, px, cache_dir=settings.thumbs_dir())` returns the cached JPEG's path for a `FileResponse`. An app with its own reader (stills' raw previews, 360's video frames) passes `make=lambda path, px: ...` returning a Pillow image. Bump `version=` when the way a thumbnail is made changes.
253
+ - **Rankings and evals.** `stats.bradley_terry(votes, side=True)` with votes as `(a, b, "a" | "b" | "tie")` (or `stats.votes_from(judgments)`), `.ratings()` for the Elo scale, `stats.intervals(votes)` for how far to trust a gap; `wilson`, `mcnemar` and `holm` for eval write-ups. The numpy bootstraps over items in strata-models' evals stay there until a second app needs them.
254
+
213
255
  ### 7. Tests
214
256
 
215
257
  The pytest plugin loads itself once strata-python is installed. Configure it in `pyproject.toml`:
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "strata-python"
7
- version = "0.2.4" # the single source of truth: `strata_python.__version__` reads it back with importlib.metadata
7
+ version = "0.2.5" # the single source of truth: `strata_python.__version__` reads it back with importlib.metadata
8
8
  description = "Common code for Python web server apps: OS helpers, settings, FastAPI serving, CLI commands, test fixtures and the strata-check gate"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -62,6 +62,10 @@ pdf = [
62
62
  "pypdfium2>=4.30,<6",
63
63
  "pillow>=13,<14", # 13.0.0 fixes eight advisories, most in PDF parsing, which this extra exists for
64
64
  ]
65
+ # strata_python.images: pictures turned by their EXIF orientation and cached JPEG thumbnails of them.
66
+ images = [
67
+ "pillow>=13,<14",
68
+ ]
65
69
 
66
70
  [project.urls]
67
71
  Homepage = "https://github.com/jburnhams/strata-python"
@@ -78,7 +82,7 @@ strata_python = "strata_python.pytest_plugin"
78
82
  strata_python_db = "strata_python.db.pytest_plugin" # inert unless the db extra is installed and the project has [tool.strata-db]
79
83
 
80
84
  [dependency-groups]
81
- dev = ["strata-python[dev,db,pdf]"] # the same tools the apps get, and the db and pdf extras so their tests run
85
+ dev = ["strata-python[dev,db,pdf,images]"] # the same tools the apps get, and the extras so their tests run
82
86
 
83
87
  [tool.hatch.build.targets.wheel]
84
88
  packages = ["src/strata_python"]
@@ -0,0 +1,247 @@
1
+ """Files the apps write, hash and cache: atomic writes, content hashes, safe paths under a root and a disk cache.
2
+
3
+ The survey found about 120 hand-written `tmp` + `os.replace` sites across strata-360, listory, stills, takeout, tubes
4
+ and models, four copies of a chunked sha256 (listory twice, filecat, stills' scripts) and two disk caches (360's places
5
+ lookups, listory's provider responses). The copies differ in the details that matter: whether the temp file is in the
6
+ same folder (`os.replace` across file systems is not atomic), whether a failed write leaves the temp file behind,
7
+ whether two threads writing the same file share a temp name, and whether a tool such as ffmpeg can still tell the
8
+ format from the temp name's extension. Here each is decided once:
9
+
10
+ with atomic_path("out/voice.wav") as tmp: # "out/.voice.<random>.part.wav": same folder, same extension
11
+ ffmpeg(["-i", src, tmp]) # replaced on success, removed on any error
12
+ with atomic_open("notes.json", "w") as f: ... # the same for a file you write yourself
13
+ write_json_atomic(path, data); write_text_atomic(path, text); write_bytes_atomic(path, raw)
14
+ read_json(path, default={}) # missing or half-written by an old copy: the default
15
+
16
+ sha256(path) -> bytes; sha256_hex(path) -> str # 1 MiB reads, never the whole file in memory
17
+ quick_fingerprint(path) # size + first and last MiB: tells files apart in milliseconds
18
+ stat_key(path, *extra) # path, size and mtime (+ what you pass): a cache key that changes with the file
19
+
20
+ inside(root, user_path) # the resolved path, or ValueError (FastAPI answers 400) if it leaves root
21
+ DiskCache(folder).json(key, fetch, max_age_s) # fetch() once per max_age_s, its JSON kept on disk
22
+
23
+ Nothing here imports beyond the standard library."""
24
+
25
+ from __future__ import annotations
26
+
27
+ import contextlib
28
+ import hashlib
29
+ import json
30
+ import os
31
+ import secrets
32
+ import sys
33
+ import time
34
+ from collections.abc import Callable, Generator
35
+ from typing import IO, Any, Protocol, TypeVar
36
+
37
+ T = TypeVar("T")
38
+
39
+ WIN = sys.platform == "win32"
40
+ CHUNK = 1 << 20 # 1 MiB: big enough that the hash, not the syscalls, is the cost; small enough to stay out of memory
41
+
42
+
43
+ def _windows_patient(fn: Callable[[], T], wait_s: float = 2.0) -> T:
44
+ """`fn()`, retried for up to `wait_s` on Windows while it raises PermissionError. Windows refuses to replace a file
45
+ another process (or thread) has open, and refuses to open one while it is being replaced, so a writer and a
46
+ reader that would never see each other on POSIX collide there for a few milliseconds. Elsewhere it runs once."""
47
+ if WIN:
48
+ end = time.monotonic() + wait_s
49
+ while True:
50
+ try:
51
+ return fn()
52
+ except PermissionError:
53
+ if time.monotonic() >= end:
54
+ raise
55
+ time.sleep(0.01)
56
+ return fn()
57
+
58
+
59
+ # ---- atomic writes ---------------------------------------------------------------------------------------------------
60
+
61
+
62
+ def _temp_name(path: str) -> str:
63
+ """A temp file beside `path`, hidden, unique per call, keeping the extension so tools infer the format from it."""
64
+ folder, name = os.path.split(os.path.abspath(path))
65
+ stem, ext = os.path.splitext(name)
66
+ return os.path.join(folder, f".{stem}.{secrets.token_hex(4)}.part{ext}")
67
+
68
+
69
+ @contextlib.contextmanager
70
+ def atomic_path(path: str | os.PathLike[str]) -> Generator[str]:
71
+ """A temp path to write `path` through: on a clean exit it replaces `path` in one step, on an error it is removed.
72
+ A reader sees the old file or the new one, never half of either. The folder is created."""
73
+ target = os.fspath(path)
74
+ os.makedirs(os.path.dirname(os.path.abspath(target)), exist_ok=True)
75
+ tmp = _temp_name(target)
76
+ try:
77
+ yield tmp
78
+ _windows_patient(lambda: os.replace(tmp, target))
79
+ except BaseException:
80
+ with contextlib.suppress(OSError):
81
+ os.unlink(tmp)
82
+ raise
83
+
84
+
85
+ @contextlib.contextmanager
86
+ def atomic_open(path: str | os.PathLike[str], mode: str = "w", encoding: str | None = "utf8") -> Generator[IO[Any]]:
87
+ """`open(path, mode)` through `atomic_path`: write or text mode only (`w`, `wb`, `x` is not atomic and refused).
88
+ The data is flushed and fsynced before the replace, so a crash right after cannot leave an empty file."""
89
+ if "w" not in mode or "+" in mode:
90
+ raise ValueError(f"atomic_open writes a new file: mode {mode!r} is not 'w' or 'wb'")
91
+ with atomic_path(path) as tmp, open(tmp, mode, encoding=None if "b" in mode else encoding) as f:
92
+ yield f
93
+ f.flush()
94
+ os.fsync(f.fileno())
95
+
96
+
97
+ def write_bytes_atomic(path: str | os.PathLike[str], data: bytes) -> None:
98
+ with atomic_open(path, "wb") as f:
99
+ f.write(data)
100
+
101
+
102
+ def write_text_atomic(path: str | os.PathLike[str], text: str) -> None:
103
+ with atomic_open(path, "w") as f:
104
+ f.write(text)
105
+
106
+
107
+ def write_json_atomic(path: str | os.PathLike[str], data: object, *, indent: int | None = 1) -> None:
108
+ """JSON written atomically; values JSON cannot encode (a datetime, a Path) are written as their `str`."""
109
+ with atomic_open(path, "w") as f:
110
+ json.dump(data, f, indent=indent, default=str, ensure_ascii=False)
111
+
112
+
113
+ def read_json(path: str | os.PathLike[str], default: Any = None) -> Any:
114
+ """The parsed file, or `default` when it is missing or not JSON (half-written by code that did not write it
115
+ atomically, or a file the app never made). A permission error still raises: that is not "no file"."""
116
+
117
+ def load() -> Any:
118
+ with open(path, encoding="utf8") as f:
119
+ return json.load(f)
120
+
121
+ try:
122
+ return _windows_patient(load)
123
+ except (FileNotFoundError, NotADirectoryError, ValueError):
124
+ return default
125
+
126
+
127
+ # ---- identity ----------------------------------------------------------------------------------------------------------
128
+
129
+
130
+ class _Hasher(Protocol):
131
+ def update(self, data: bytes, /) -> None: ...
132
+ def digest(self) -> bytes: ...
133
+ def hexdigest(self) -> str: ...
134
+
135
+
136
+ def _hash_file(path: str | os.PathLike[str]) -> _Hasher:
137
+ h = hashlib.sha256()
138
+ with open(path, "rb", buffering=0) as f:
139
+ while block := f.read(CHUNK):
140
+ h.update(block)
141
+ return h
142
+
143
+
144
+ def sha256(path: str | os.PathLike[str]) -> bytes:
145
+ """The file's SHA-256 as 32 bytes (what a `LargeBinary` column stores; filecat and listory's store use this)."""
146
+ return _hash_file(path).digest()
147
+
148
+
149
+ def sha256_hex(path: str | os.PathLike[str]) -> str:
150
+ """The file's SHA-256 as 64 hex characters (what a JSON row or a file name uses)."""
151
+ return _hash_file(path).hexdigest()
152
+
153
+
154
+ def quick_fingerprint(path: str | os.PathLike[str], block: int = CHUNK) -> str:
155
+ """A cheap identity: SHA-256 of the size and the first and last `block` bytes, as hex. Two different videos of the
156
+ same size almost never share both ends, and a re-encoded or truncated file changes, so it tells a folder of large
157
+ clips apart in milliseconds. Not a content hash: an edit in the middle of a big file is not seen."""
158
+ size = os.path.getsize(path)
159
+ h = hashlib.sha256(str(size).encode())
160
+ with open(path, "rb") as f:
161
+ h.update(f.read(block))
162
+ if size > block:
163
+ f.seek(max(size - block, block))
164
+ h.update(f.read(block))
165
+ return h.hexdigest()
166
+
167
+
168
+ def stat_key(path: str | os.PathLike[str], *extra: object) -> str:
169
+ """A cache key that changes whenever the file does (its absolute path, size and modification time to the
170
+ nanosecond) and with whatever else the cached thing depends on (`extra`: a size, a version). Hex SHA-256."""
171
+ p = os.path.normcase(os.path.abspath(path))
172
+ st = os.stat(p)
173
+ return hashlib.sha256(json.dumps([p, st.st_size, st.st_mtime_ns, *extra], default=str).encode()).hexdigest()
174
+
175
+
176
+ # ---- paths -------------------------------------------------------------------------------------------------------------
177
+
178
+
179
+ def inside(root: str | os.PathLike[str], path: str | os.PathLike[str]) -> str:
180
+ """`path` (absolute, or relative to `root`) resolved, links followed, and checked to be `root` or under it.
181
+ ValueError otherwise, which `web.add_error_handlers` answers as 400: a route that takes a file name from the
182
+ request passes it through this before opening anything, so `../../etc/passwd` and a link out are refused."""
183
+ base = os.path.realpath(root)
184
+ full = os.path.realpath(os.path.join(base, path))
185
+ if os.path.normcase(full) != os.path.normcase(base) and not os.path.normcase(full).startswith(
186
+ os.path.normcase(os.path.join(base, ""))
187
+ ):
188
+ raise ValueError(f"{os.fspath(path)!r} is outside {os.fspath(root)!r}")
189
+ return full
190
+
191
+
192
+ # ---- a disk cache ------------------------------------------------------------------------------------------------------
193
+
194
+
195
+ class DiskCache:
196
+ """Values kept on disk under a key, each in its own file named by the key's hash, with the time it was stored.
197
+
198
+ COVERS = DiskCache(settings.cache_dir() + "/covers")
199
+ COVERS.json(f"openlibrary:{isbn}", lambda: fetch(isbn), max_age_s=7 * 86400) # None is cached too
200
+ COVERS.get(key, max_age_s) / COVERS.put(key, raw) / COVERS.forget(key) # bytes
201
+
202
+ A cached `None` means "asked, nothing there" and is kept like any value, so a lookup that found nothing is not
203
+ repeated until it is old. Writes are atomic, so several processes can share the folder; the last write wins.
204
+ The clock is injectable for tests."""
205
+
206
+ def __init__(self, folder: str | os.PathLike[str], *, clock: Callable[[], float] = time.time) -> None:
207
+ self.folder = os.fspath(folder)
208
+ self._clock = clock
209
+
210
+ def path(self, key: str) -> str:
211
+ h = hashlib.sha256(key.encode()).hexdigest()
212
+ return os.path.join(self.folder, h[:2], h + ".cache")
213
+
214
+ def get(self, key: str, max_age_s: float | None = None) -> bytes | None:
215
+ """The stored bytes, or None when there are none or they are older than `max_age_s`."""
216
+
217
+ def load() -> tuple[bytes, bytes]:
218
+ with open(self.path(key), "rb") as f:
219
+ return f.readline(), f.read()
220
+
221
+ try:
222
+ head, body = _windows_patient(load)
223
+ stored = float(json.loads(head)["at"])
224
+ except (OSError, ValueError, KeyError, TypeError):
225
+ return None
226
+ if max_age_s is not None and self._clock() - stored > max_age_s:
227
+ return None
228
+ return body
229
+
230
+ def put(self, key: str, value: bytes) -> None:
231
+ head = json.dumps({"at": self._clock(), "key": key[:200]}).encode() + b"\n"
232
+ write_bytes_atomic(self.path(key), head + value)
233
+
234
+ def forget(self, key: str) -> None:
235
+ with contextlib.suppress(FileNotFoundError):
236
+ os.unlink(self.path(key))
237
+
238
+ def json(self, key: str, fetch: Callable[[], Any], max_age_s: float | None = None) -> Any:
239
+ """`fetch()`'s result, from the cache when it is there and young enough, else fetched and stored. An exception
240
+ from `fetch` is not cached (a failure is not an answer)."""
241
+ raw = self.get(key, max_age_s)
242
+ if raw is not None:
243
+ with contextlib.suppress(ValueError):
244
+ return json.loads(raw)
245
+ value = fetch()
246
+ self.put(key, json.dumps(value, default=str).encode())
247
+ return value