File size: 8,181 Bytes
eeb144a
 
 
 
63e3e38
eeb144a
8c62083
eeb144a
 
 
 
8c62083
eeb144a
 
 
 
 
 
 
8c62083
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeb144a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63e3e38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28e5090
 
63e3e38
28e5090
63e3e38
28e5090
63e3e38
 
 
28e5090
 
 
 
 
 
 
 
 
 
 
63e3e38
 
 
 
 
9bec131
 
 
 
 
 
eeb144a
 
 
 
 
 
 
 
 
 
 
 
28e5090
eeb144a
 
28e5090
 
 
 
 
 
 
eeb144a
 
 
 
 
 
 
 
 
 
 
 
 
9bec131
eeb144a
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
"""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