Download backend/reader/document/domain/range_cache.py from VoiceOfML/Search: direct link, hf CLI and curl.
- Browser
- Download file 8.18 kB
-
https://huggingface.co/spaces/VoiceOfML/Search/resolve/main/backend/reader/document/domain/range_cache.py
- Command line
-
hf download hf://spaces/VoiceOfML/Search/backend/reader/document/domain/range_cache.py
-
curl -L -o range_cache.py https://huggingface.co/spaces/VoiceOfML/Search/resolve/main/backend/reader/document/domain/range_cache.py
8.18 kB
| """Safe exact-byte subrange reuse for the Reader proxy's bounded cache.""" | |
| from __future__ import annotations | |
| from collections import OrderedDict | |
| from collections.abc import Callable, Mapping | |
| from typing import Protocol | |
| from weakref import WeakValueDictionary | |
| import re | |
| RangeKey = tuple[str, str, int | None, str | None] | |
| RangeCacheEntry = tuple[float, bytes, dict[str, str]] | |
| RangeCacheScope = tuple[str, int | None, str | None] | |
| class RangeCacheState(Protocol): | |
| reader_range_cache: OrderedDict[RangeKey, RangeCacheEntry] | |
| reader_range_cache_bytes: int | |
| class RangeObservationState(RangeCacheState, Protocol): | |
| reader_range_observations: WeakValueDictionary[RangeCacheScope, RangeObservation] | |
| def strong_etag(value: str) -> str | None: | |
| etag = value.strip(" \t") | |
| return etag if re.fullmatch(r'"[!\x23-\x7e\x80-\xff]*"', etag) else None | |
| def range_representation_matches(previous: str, etag: str | None, *, fresh: bool) -> bool: | |
| # Ordinary opaque misses retain the existing TTL policy when neither | |
| # response provides evidence of a change. An explicit refresh needs proof. | |
| return strong_etag(previous) == etag and (etag is not None or not fresh) | |
| class RangeObservation: | |
| """Order successful observations by upstream start, not by header/body completion.""" | |
| def __init__(self, scope: RangeCacheScope) -> None: | |
| self.scope = scope | |
| self.started = 0 | |
| self.latest = 0 | |
| self.etag: str | None = None | |
| def observe(self, state: RangeCacheState, ticket: int, etag: str | None, *, fresh: bool, moved: bool) -> bool: | |
| if ticket < self.latest: | |
| return False | |
| reconcile = moved or self.latest == 0 or self.etag != etag or (etag is None and fresh) | |
| self.latest = ticket | |
| self.etag = etag | |
| if not reconcile: | |
| return False | |
| cache = state.reader_range_cache | |
| for key in list(cache): | |
| if (key[0], key[2], key[3]) != self.scope: | |
| continue | |
| # Strong validators only identify bytes within the same resource. | |
| if moved or not range_representation_matches(cache[key][2].get("ETag", ""), etag, fresh=fresh): | |
| _, payload, _ = cache.pop(key) | |
| state.reader_range_cache_bytes -= len(payload) | |
| return True | |
| def can_store(self, ticket: int, etag: str | None) -> bool: | |
| return ticket == self.latest or (etag is not None and etag == self.etag) | |
| def begin_range_observation(state: RangeObservationState, scope: RangeCacheScope) -> tuple[RangeObservation, int]: | |
| # Active transports hold the strong references; never retain a per-URL | |
| # tombstone after all overlapping operations have gone away. | |
| if not hasattr(state, "reader_range_observations"): | |
| state.reader_range_observations = WeakValueDictionary() | |
| active = state.reader_range_observations | |
| observation = active.get(scope) | |
| if observation is None: | |
| observation = active[scope] = RangeObservation(scope) | |
| observation.started += 1 | |
| return observation, observation.started | |
| def requested_range_bounds(header: str | None, total: int) -> tuple[int, int] | None: | |
| """Resolve an ordinary single byte range; unknown/unsatisfiable forms return None.""" | |
| if header is None or total <= 0: | |
| return None | |
| match = re.fullmatch(r"bytes=([0-9]{0,20})-([0-9]{0,20})", header) | |
| if match is None: | |
| return None | |
| first, last = match.groups() | |
| if not first: | |
| if not last or int(last) == 0: | |
| return None | |
| return max(0, total - int(last)), total - 1 | |
| start = int(first) | |
| end = min(int(last), total - 1) if last else total - 1 | |
| if start > end: | |
| return None | |
| return start, end | |
| def requires_fresh_range(headers: Mapping[str, str]) -> bool: | |
| """Requests asking for fresh bytes must not join a cached range or flight.""" | |
| return (any(name in ("no-cache", "no-store") or (name == "max-age" and value.isdigit() and not value.strip("0")) | |
| for name, value in _cache_directives(headers.get("Cache-Control", ""))) | |
| or "no-cache" in {value.strip().lower() for value in headers.get("Pragma", "").split(",")}) | |
| def _cache_directives(raw: str) -> list[tuple[str, str]]: | |
| return [(name.strip().lower(), value.strip().strip('"')) | |
| for name, _, value in (part.partition("=") for part in raw.split(","))] | |
| def _cache_seconds(raw: str) -> int: | |
| # Bound the conversion as well as the cache lifetime. Extremely large | |
| # delta-seconds exceed our configured TTL in any case. | |
| if not raw.isascii() or not raw.isdecimal(): | |
| return 0 | |
| significant = raw.lstrip("0") | |
| return min(2147483647, int(significant[:10] or "0")) | |
| def _cache_control_lifetime(raw: str) -> int | None: | |
| # -1 is an explicit prohibition, distinct from max-age=0 or no directive. | |
| ages: dict[str, int] = {} | |
| for name, value in _cache_directives(raw): | |
| if name in ("no-store", "no-cache", "private"): | |
| return -1 | |
| if name in ("s-maxage", "max-age"): | |
| lifetime = _cache_seconds(value) | |
| ages[name] = min(ages.get(name, lifetime), lifetime) | |
| return ages.get("s-maxage", ages.get("max-age")) | |
| def range_cache_seconds(headers: Mapping[str, str], ttl: int) -> int: | |
| """Freshness at insertion, before browser-only PDF cache overrides.""" | |
| return _range_cache_seconds_for_lifetime(headers, ttl, _cache_control_lifetime(headers.get("Cache-Control", ""))) | |
| def _range_cache_seconds_for_lifetime(headers: Mapping[str, str], ttl: int, lifetime: int | None) -> int: | |
| if lifetime == -1: | |
| return 0 | |
| if lifetime is None: | |
| return ttl | |
| return min(ttl, max(0, lifetime - _cache_seconds(headers.get("Age", "").strip()))) | |
| def resident_age_headers(headers: Mapping[str, str], cached_at: float, current_time: float) -> dict[str, str]: | |
| """Return response headers with origin age and nonnegative resident seconds.""" | |
| age = _cache_seconds(headers.get("Age", "").strip()) | |
| return {**headers, "Age": str(age + int(max(0, current_time - cached_at)))} | |
| def cached_subrange(range_key: RangeKey, get_state: Callable[[], RangeCacheState], | |
| get_limit: Callable[[], int], get_ttl: Callable[[], int], | |
| now: Callable[[], float]) -> tuple[bytes, dict[str, str]] | None: | |
| """Serve a verified contained range, evicting stale entries in LRU order.""" | |
| requested = re.fullmatch(r"bytes=([0-9]{1,20})-([0-9]{1,20})", range_key[1]) | |
| if requested is None: | |
| return None | |
| start, end = (int(value) for value in requested.groups()) | |
| if start > end or end - start + 1 > get_limit(): | |
| return None | |
| cache = get_state().reader_range_cache | |
| current_time = now() | |
| scan_lifetimes: dict[str, int | None] = {} | |
| for key in reversed(list(cache)): | |
| cached_at, payload, headers = cache[key] | |
| elapsed = current_time - cached_at | |
| ttl = get_ttl() | |
| raw = headers.get("Cache-Control", "") | |
| lifetime = scan_lifetimes.get(raw, -2) # -2 is a memo miss; not a parsed value. | |
| if lifetime == -2: | |
| lifetime = scan_lifetimes[raw] = _cache_control_lifetime(raw) | |
| if elapsed >= _range_cache_seconds_for_lifetime(headers, ttl, lifetime): | |
| cache.pop(key) | |
| get_state().reader_range_cache_bytes -= len(payload) | |
| continue | |
| if key[0] != range_key[0] or key[2:] != range_key[2:]: | |
| continue | |
| match = re.fullmatch(r"bytes ([0-9]+)-([0-9]+)/([0-9]+)", headers.get("Content-Range", "")) | |
| if match is None: | |
| continue | |
| cached_start, cached_end, total = (int(value) for value in match.groups()) | |
| final_end = min(end, total - 1) | |
| if cached_start <= start <= final_end <= cached_end and len(payload) == cached_end - cached_start + 1: | |
| cache.move_to_end(key) | |
| body = payload[start - cached_start:final_end - cached_start + 1] | |
| return body, {**resident_age_headers(headers, cached_at, current_time), "Content-Range": f"bytes {start}-{final_end}/{total}", | |
| "Content-Length": str(len(body))} | |
| return None | |