strata-python 0.2.3__py3-none-any.whl → 0.2.5__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/files.py ADDED
@@ -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
strata_python/http.py ADDED
@@ -0,0 +1,326 @@
1
+ """A polite client for other people's web APIs: a gap between requests to each host, Retry-After honoured, a host that
2
+ keeps saying 429 left alone for a while, retries that never replay a write, and an optional disk cache.
3
+
4
+ Six apps call public services (Open Library, Audible, Overpass, Nominatim, Mapillary, tile servers, YouTube, Plex,
5
+ planning portals) and about ten copies of this loop grew there: listory's `covers/net.py` (the most complete: per-host
6
+ throttle, Retry-After as seconds or a date, a cool-down), its providers' `Http` (404 as None, resets retried for reads
7
+ only), strata-360's `places._get` (a throttle shared across processes through a lock file, a disk cache) and
8
+ `streetview._open` (errors returned, not raised), and smaller ones in takeout, tubes and planning. This is that loop
9
+ once, with each copy's best rule:
10
+
11
+ OL = Http("strata-listory/0.3 (audiobook catalogue)", min_interval=0.4, cache=DiskCache(cache_dir))
12
+ reply = OL.get("https://openlibrary.org/search.json", params={"q": title}, cache_s=7 * 86400)
13
+ if reply.ok: data = reply.json()
14
+ elif reply.limited: ... # still rate limited after the retries, or cooling down
15
+ OL.get(url).raise_for_status().json() # or raise HttpError(status, url, detail)
16
+
17
+ Rules:
18
+ - `user_agent` is required: public services ask to be told who is calling, and an app name says it without naming a
19
+ person. Never put a person's name, address or e-mail in it here; the app passes its own.
20
+ - Requests to one host are spaced `min_interval` apart, across threads (each takes the next free slot, so ten threads
21
+ do not all fire after one gap). `throttle_file=` spaces them across processes as well (several workers, a CLI beside
22
+ the server), through a lock file.
23
+ - 429 (any request) and 503 (an idempotent one) wait for the server's Retry-After (seconds or an HTTP date), capped at `max_wait`, else 1, 2, 4... s. A host
24
+ still saying 429 after `attempts` is left alone for `cool_down` seconds: calls return a `limited` reply at once instead
25
+ of making every lookup wait out the limit again.
26
+ - 500, 502, 504 and network errors (refused, reset, timed out) are retried only for an idempotent request (GET, HEAD,
27
+ PUT, DELETE, OPTIONS, or `idempotent=True` for a POST that only reads, such as an Overpass query). A 429 is retried
28
+ for any method: the server said it did nothing.
29
+ - Errors come back as a `Reply` (status 0 when the server could not be reached, `.error` saying why), not exceptions,
30
+ so a caller can record why a source found nothing. `raise_for_status()` turns one into `HttpError` for code that
31
+ wants an exception. Only `https://` and `http://` URLs are fetched; `https_only=True` refuses plain http.
32
+ - Bodies over `max_bytes` are cut and the reply carries `error="body larger than ..."`, so one huge answer cannot fill
33
+ memory.
34
+ - With `cache=DiskCache(...)`, a request with `cache_s=` is answered from disk while its copy is younger than that.
35
+ The key is the method, URL, body and the headers sent (so different credentials never share an answer), or `cache_key=`.
36
+ Statuses in `cache_status` (200 and 404 by default: "not there" is an answer worth keeping) are stored.
37
+ - `observe(reply, attempt)` sees every attempt (listory's provider log, a test's record).
38
+
39
+ Standard library only. The clock, sleep and opener are arguments, but tests should prefer the `http_server` fixture,
40
+ which answers real requests on loopback."""
41
+
42
+ from __future__ import annotations
43
+
44
+ import contextlib
45
+ import json
46
+ import os
47
+ import threading
48
+ import time
49
+ import urllib.error
50
+ import urllib.parse
51
+ import urllib.request
52
+ from collections.abc import Callable, Mapping
53
+ from dataclasses import dataclass, field
54
+ from email.utils import parsedate_to_datetime
55
+ from http.client import HTTPException
56
+ from typing import Any
57
+
58
+ from strata_python import oslib
59
+ from strata_python.files import DiskCache
60
+
61
+ IDEMPOTENT = frozenset({"GET", "HEAD", "PUT", "DELETE", "OPTIONS"})
62
+ RETRY_STATUS = frozenset({500, 502, 503, 504})
63
+ WAIT_STATUS = frozenset({429, 503}) # statuses whose Retry-After is honoured
64
+
65
+
66
+ @dataclass
67
+ class Reply:
68
+ """What the server said. `status` is 0 when it could not be reached; `error` says why anything went wrong."""
69
+
70
+ url: str
71
+ status: int
72
+ body: bytes = b""
73
+ headers: dict[str, str] = field(default_factory=lambda: {}) # names lower-cased
74
+ error: str = ""
75
+ limited: bool = False # still rate limited after the retries, or the host is cooling down
76
+ cached: bool = False # answered from the disk cache
77
+
78
+ @property
79
+ def ok(self) -> bool:
80
+ return 200 <= self.status < 300 and not self.error
81
+
82
+ def json(self) -> Any:
83
+ return json.loads(self.body)
84
+
85
+ def text(self) -> str:
86
+ ctype = self.headers.get("content-type", "")
87
+ charset = ctype.split("charset=")[-1].split(";")[0].strip() if "charset=" in ctype else "utf-8"
88
+ return self.body.decode(charset or "utf-8", errors="replace")
89
+
90
+ def raise_for_status(self) -> Reply:
91
+ """This reply, or `HttpError` when it is not `ok`."""
92
+ if not self.ok:
93
+ raise HttpError(self)
94
+ return self
95
+
96
+
97
+ class HttpError(RuntimeError):
98
+ """A reply that was not ok, for code that wants an exception: `.status`, `.url`, `.reply`, `.limited`."""
99
+
100
+ def __init__(self, reply: Reply) -> None:
101
+ host = urllib.parse.urlsplit(reply.url).netloc
102
+ what = reply.error or reply.body[:200].decode(errors="replace").strip()
103
+ said = f"answered {reply.status}" if reply.status else "could not be reached"
104
+ super().__init__(f"{host} {said}" + (f": {what}" if what else ""))
105
+ self.reply, self.status, self.url, self.limited = reply, reply.status, reply.url, reply.limited
106
+
107
+
108
+ def retry_after(headers: Mapping[str, str], attempt: int, *, max_wait: float, now: float | None = None) -> float:
109
+ """Seconds to wait before attempt `attempt + 1`: the server's Retry-After (seconds or an HTTP date) when it sent
110
+ one, else 1, 2, 4... s; at least 0.5 s and at most `max_wait`."""
111
+ value = {k.lower(): v for k, v in headers.items()}.get("retry-after", "").strip()
112
+ try:
113
+ wait = float(value)
114
+ except ValueError:
115
+ try:
116
+ when = parsedate_to_datetime(value)
117
+ wait = when.timestamp() - (time.time() if now is None else now)
118
+ except (TypeError, ValueError, IndexError):
119
+ wait = 2.0 ** (attempt - 1)
120
+ return max(0.5, min(wait, max_wait))
121
+
122
+
123
+ Opener = Callable[[urllib.request.Request, float], Any]
124
+
125
+
126
+ def _urlopen(req: urllib.request.Request, timeout: float) -> Any:
127
+ return urllib.request.urlopen(req, timeout=timeout) # noqa: S310 - the scheme is checked before this is called
128
+
129
+
130
+ def _time_sleep(seconds: float) -> None:
131
+ time.sleep(seconds) # looked up per call, so a test's patched time.sleep applies
132
+
133
+
134
+ class Http:
135
+ def __init__(
136
+ self,
137
+ user_agent: str,
138
+ *,
139
+ min_interval: float = 1.0,
140
+ attempts: int = 4,
141
+ max_wait: float = 60.0,
142
+ cool_down: float = 600.0,
143
+ timeout: float = 30.0,
144
+ max_bytes: int = 50_000_000,
145
+ headers: Mapping[str, str] | None = None,
146
+ https_only: bool = False,
147
+ throttle_file: str | os.PathLike[str] | None = None,
148
+ cache: DiskCache | None = None,
149
+ cache_status: frozenset[int] = frozenset({200, 404}),
150
+ observe: Callable[[Reply, int], None] | None = None,
151
+ opener: Opener = _urlopen,
152
+ clock: Callable[[], float] = time.monotonic,
153
+ sleep: Callable[[float], None] | None = None,
154
+ ) -> None:
155
+ if not user_agent.strip():
156
+ raise ValueError("user_agent is required: name the app (and its purpose) so the service knows who asks")
157
+ self.user_agent = user_agent
158
+ self.min_interval, self.attempts, self.max_wait, self.cool_down = (
159
+ min_interval,
160
+ max(1, attempts),
161
+ max_wait,
162
+ cool_down,
163
+ )
164
+ self.timeout, self.max_bytes, self.https_only = timeout, max_bytes, https_only
165
+ self.headers = dict(headers or {})
166
+ self.throttle_file = None if throttle_file is None else os.fspath(throttle_file)
167
+ self.cache, self.cache_status, self.observe = cache, cache_status, observe
168
+ self._open, self._clock = opener, clock
169
+ self._sleep = sleep or _time_sleep
170
+ self._lock = threading.Lock()
171
+ self._next: dict[str, float] = {} # host -> the earliest time the next request may start
172
+ self._cool_until: dict[str, float] = {}
173
+
174
+ # ---- pacing ----------------------------------------------------------------------------------------------------
175
+
176
+ def _wait_turn(self, host: str) -> None:
177
+ """Take the next free slot for `host` and sleep until it. Slots are handed out under a lock, so concurrent
178
+ threads queue up `min_interval` apart instead of all firing after one gap."""
179
+ with self._lock:
180
+ now = self._clock()
181
+ start = max(now, self._next.get(host, now))
182
+ self._next[host] = start + self.min_interval
183
+ if start > now:
184
+ self._sleep(start - now)
185
+ if self.throttle_file:
186
+ self._wait_file(self.throttle_file)
187
+
188
+ def _wait_file(self, path: str) -> None:
189
+ """The same gap across processes: the lock file holds the wall-clock time the last request started."""
190
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
191
+ with open(path, "a+", encoding="utf8") as f, oslib.file_lock(f):
192
+ f.seek(0)
193
+ try:
194
+ last = float(f.read().strip() or 0)
195
+ except ValueError:
196
+ last = 0.0
197
+ wait = last + self.min_interval - time.time()
198
+ if wait > 0:
199
+ self._sleep(min(wait, self.min_interval))
200
+ f.seek(0)
201
+ f.truncate()
202
+ f.write(repr(time.time()))
203
+ f.flush()
204
+
205
+ def cooling(self, url_or_host: str) -> bool:
206
+ """Is this host being left alone after a rate limit?"""
207
+ host = urllib.parse.urlsplit(url_or_host).netloc or url_or_host
208
+ return self._cool_until.get(host, 0.0) > self._clock()
209
+
210
+ # ---- requests --------------------------------------------------------------------------------------------------
211
+
212
+ def request(
213
+ self,
214
+ method: str,
215
+ url: str,
216
+ *,
217
+ params: Mapping[str, object] | None = None,
218
+ json_body: object = None,
219
+ data: bytes | None = None,
220
+ headers: Mapping[str, str] | None = None,
221
+ timeout: float | None = None,
222
+ idempotent: bool | None = None,
223
+ cache_s: float | None = None,
224
+ cache_key: str | None = None,
225
+ ) -> Reply:
226
+ """Send one request with the rules above and return what came back (never raises for an HTTP or network
227
+ failure). `json_body` is sent as JSON; `data` as it is. `cache_s` reads and fills the cache."""
228
+ method = method.upper()
229
+ if params:
230
+ url += ("&" if "?" in url else "?") + urllib.parse.urlencode({k: str(v) for k, v in params.items()})
231
+ scheme, host = urllib.parse.urlsplit(url)[:2]
232
+ if scheme != "https" and (self.https_only or scheme != "http"):
233
+ return Reply(url, 0, error=f"only {'https' if self.https_only else 'http(s)'} addresses are fetched")
234
+ body = json.dumps(json_body).encode() if json_body is not None else data
235
+ hdrs = {"User-Agent": self.user_agent, **self.headers, **(headers or {})}
236
+ if json_body is not None:
237
+ hdrs.setdefault("Content-Type", "application/json")
238
+ key = None
239
+ if cache_s is not None and self.cache is not None:
240
+ # The headers are part of the key, so two callers with different credentials never share an answer.
241
+ sent = sorted((k.lower(), v) for k, v in hdrs.items() if k.lower() != "user-agent")
242
+ key = cache_key or json.dumps([method, url, body.decode(errors="replace") if body else None, sent])
243
+ hit = self._from_cache(self.cache, url, key, cache_s)
244
+ if hit is not None:
245
+ return hit
246
+ if self.cooling(host):
247
+ return Reply(url, 429, error="rate limited a moment ago; not asking again yet", limited=True)
248
+ safe = method in IDEMPOTENT if idempotent is None else idempotent
249
+ reply = Reply(url, 0, error="not attempted")
250
+ for attempt in range(1, self.attempts + 1):
251
+ self._wait_turn(host)
252
+ reply = self._once(method, url, body, hdrs, self.timeout if timeout is None else timeout)
253
+ if self.observe:
254
+ self.observe(reply, attempt)
255
+ if reply.status == 429 or (safe and reply.status == 503 and "retry-after" in reply.headers):
256
+ reply.limited = reply.status == 429
257
+ wait = retry_after(reply.headers, attempt, max_wait=self.max_wait)
258
+ elif safe and (reply.status in RETRY_STATUS or reply.status == 0):
259
+ wait = 2.0 ** (attempt - 1)
260
+ else:
261
+ break
262
+ if attempt < self.attempts:
263
+ self._sleep(wait)
264
+ if reply.limited:
265
+ with self._lock:
266
+ self._cool_until[host] = self._clock() + self.cool_down
267
+ if key is not None and self.cache is not None and reply.status in self.cache_status and not reply.error:
268
+ self._to_cache(self.cache, key, reply)
269
+ return reply
270
+
271
+ def _once(self, method: str, url: str, body: bytes | None, headers: dict[str, str], timeout: float) -> Reply:
272
+ req = urllib.request.Request(url, data=body, headers=headers, method=method) # noqa: S310 - scheme checked
273
+ try:
274
+ with self._open(req, timeout) as r:
275
+ raw = r.read(self.max_bytes + 1)
276
+ status = int(getattr(r, "status", None) or r.getcode())
277
+ hdrs = {k.lower(): v for k, v in dict(r.headers).items()}
278
+ except urllib.error.HTTPError as e:
279
+ with contextlib.suppress(OSError, HTTPException):
280
+ raw = e.read(self.max_bytes + 1)
281
+ return Reply(
282
+ url, e.code, raw[: self.max_bytes], {k.lower(): v for k, v in dict(e.headers or {}).items()}
283
+ )
284
+ return Reply(url, e.code, error=str(e))
285
+ except (urllib.error.URLError, OSError, ValueError, HTTPException) as e:
286
+ return Reply(url, 0, error=str(getattr(e, "reason", None) or e))
287
+ if len(raw) > self.max_bytes:
288
+ return Reply(url, status, raw[: self.max_bytes], hdrs, error=f"body larger than {self.max_bytes} bytes")
289
+ return Reply(url, status, raw, hdrs)
290
+
291
+ @staticmethod
292
+ def _from_cache(cache: DiskCache, url: str, key: str, max_age_s: float) -> Reply | None:
293
+ raw = cache.get(key, max_age_s)
294
+ if raw is None:
295
+ return None
296
+ head, _, body = raw.partition(b"\n")
297
+ try:
298
+ meta = json.loads(head)
299
+ return Reply(url, int(meta["status"]), body, dict(meta.get("headers") or {}), cached=True)
300
+ except (ValueError, KeyError, TypeError):
301
+ return None
302
+
303
+ @staticmethod
304
+ def _to_cache(cache: DiskCache, key: str, reply: Reply) -> None:
305
+ keep = {k: v for k, v in reply.headers.items() if k in ("content-type", "etag", "last-modified")}
306
+ cache.put(key, json.dumps({"status": reply.status, "headers": keep}).encode() + b"\n" + reply.body)
307
+
308
+ def get(self, url: str, **kw: Any) -> Reply:
309
+ return self.request("GET", url, **kw)
310
+
311
+ def post(self, url: str, **kw: Any) -> Reply:
312
+ return self.request("POST", url, **kw)
313
+
314
+ def get_json(self, url: str, *, missing: Any = None, **kw: Any) -> Any:
315
+ """The parsed JSON of a GET; `missing` for a 404; `HttpError` for anything else that is not ok, or a body
316
+ that is not JSON."""
317
+ reply = self.get(url, **kw)
318
+ if reply.status == 404:
319
+ return missing
320
+ reply.raise_for_status()
321
+ try:
322
+ return reply.json()
323
+ except ValueError:
324
+ raise HttpError(
325
+ Reply(reply.url, reply.status, reply.body, reply.headers, error="the body is not JSON")
326
+ ) from None
@@ -0,0 +1,107 @@
1
+ """Pictures the right way up, and cached JPEG thumbnails of them (needs `strata-python[images]`, which is Pillow).
2
+
3
+ strata-360 (`photos.thumb`, a thumb route per kind), strata-stills (`browser.cached`), bright-horizons and strata-scan
4
+ each make a small JPEG of a picture on first request and keep it. Each copy turns it by its EXIF orientation, flattens
5
+ transparency and 16-bit greys, keys the cache on the file and the size, and writes through a temp file; each copy does
6
+ a different subset of that. Here:
7
+
8
+ path = thumbnail(src, 320, cache_dir=settings.thumbs_dir()) # the cached JPEG's path, made if missing
9
+ path = thumbnail(raw, 320, cache_dir=d, make=develop_preview) # the app's own reader for what Pillow cannot open
10
+ im = open_upright(src, draft=(640, 640)) # EXIF-turned, decoded at a reduced size when it can
11
+ rgb = flatten(im) # alpha on white, 16-bit and float scaled to 8-bit
12
+ jpeg_bytes(im, quality=85)
13
+
14
+ The cache key is `files.stat_key(src, px, quality, version)`: a changed file, size, quality or the app's `version`
15
+ (bump it when the way a thumbnail is made changes) is a new file, so there is never a stale one to clear. The long side
16
+ is `px` (clamped to 16..4096) and a picture is never enlarged. `slots` limits how many are made at once, since a page of
17
+ 200 thumbnails would otherwise decode 200 large pictures together; a second request for one being made waits for it
18
+ rather than making it again."""
19
+
20
+ from __future__ import annotations
21
+
22
+ import io
23
+ import os
24
+ import threading
25
+ from collections.abc import Callable
26
+
27
+ from PIL import Image, ImageOps
28
+
29
+ from strata_python.files import stat_key, write_bytes_atomic
30
+
31
+ MIN_PX, MAX_PX = 16, 4096
32
+ _LIMITS: dict[int, threading.BoundedSemaphore] = {}
33
+ _LIMITS_LOCK = threading.Lock()
34
+ _MAKING: dict[str, threading.Lock] = {}
35
+
36
+
37
+ def open_upright(path: str | os.PathLike[str], *, draft: tuple[int, int] | None = None) -> Image.Image:
38
+ """The picture turned by its EXIF orientation. `draft` lets a JPEG decode at a reduced scale (at least that big),
39
+ which is far faster for a thumbnail of a 24-megapixel photo."""
40
+ im = Image.open(path)
41
+ if draft:
42
+ im.draft("RGB", draft)
43
+ return ImageOps.exif_transpose(im)
44
+
45
+
46
+ def flatten(im: Image.Image, background: tuple[int, int, int] = (255, 255, 255)) -> Image.Image:
47
+ """An 8-bit RGB copy: transparency laid on `background`, 16-bit and float greys scaled to 0..255 (Pillow's plain
48
+ `convert("RGB")` clips a 16-bit grey to white)."""
49
+ if im.mode in ("I;16", "I;16B", "I;16L", "I"):
50
+ im = im.point(lambda v: v / 256).convert("L") # pyright: ignore[reportUnknownMemberType]
51
+ elif im.mode == "F":
52
+ im = im.point(lambda v: v * 255).convert("L") # pyright: ignore[reportUnknownMemberType]
53
+ if im.mode in ("RGBA", "LA", "PA") or (im.mode == "P" and "transparency" in im.info):
54
+ rgba = im.convert("RGBA")
55
+ bg = Image.new("RGB", rgba.size, background)
56
+ bg.paste(rgba, mask=rgba.getchannel("A"))
57
+ return bg
58
+ return im.convert("RGB")
59
+
60
+
61
+ def jpeg_bytes(im: Image.Image, quality: int = 85) -> bytes:
62
+ buf = io.BytesIO()
63
+ flatten(im).save(buf, "JPEG", quality=quality, optimize=True)
64
+ return buf.getvalue()
65
+
66
+
67
+ def clamp_px(px: int) -> int:
68
+ return max(MIN_PX, min(int(px), MAX_PX))
69
+
70
+
71
+ def _slots(n: int) -> threading.BoundedSemaphore:
72
+ with _LIMITS_LOCK:
73
+ return _LIMITS.setdefault(n, threading.BoundedSemaphore(n))
74
+
75
+
76
+ def thumbnail(
77
+ src: str | os.PathLike[str],
78
+ px: int,
79
+ *,
80
+ cache_dir: str | os.PathLike[str],
81
+ quality: int = 85,
82
+ version: object = 1,
83
+ make: Callable[[str, int], Image.Image] | None = None,
84
+ slots: int = 4,
85
+ ) -> str:
86
+ """The path of a JPEG of `src` whose long side is at most `px`, made on first request and kept in `cache_dir`.
87
+ `make(src, px)` returns the picture for files Pillow cannot read (a camera raw's embedded preview, a video frame);
88
+ it should return one at least `px` on its long side, and it is still turned, shrunk and flattened here."""
89
+ px = clamp_px(px)
90
+ path = os.fspath(src)
91
+ key = stat_key(path, px, quality, version)
92
+ out = os.path.join(os.fspath(cache_dir), key[:2], key + ".jpg")
93
+ if os.path.exists(out):
94
+ return out
95
+ with _LIMITS_LOCK:
96
+ making = _MAKING.setdefault(out, threading.Lock())
97
+ with making:
98
+ if os.path.exists(out): # made by another thread while this one waited
99
+ return out
100
+ with _slots(slots):
101
+ im = make(path, px) if make else open_upright(path, draft=(px, px))
102
+ im = ImageOps.exif_transpose(im) if make else im
103
+ im.thumbnail((px, px), Image.Resampling.LANCZOS) # never enlarges
104
+ write_bytes_atomic(out, jpeg_bytes(im, quality))
105
+ with _LIMITS_LOCK:
106
+ _MAKING.pop(out, None)
107
+ return out