| 1 | """Run-scoped memo for source fetches. |
| 2 | |
| 3 | Subquery streams for TikTok, Instagram, YouTube, and X all search the raw |
| 4 | topic, and the thin-source retry repeats that search (and, for Polymarket and |
| 5 | Digg, a planner subquery that equals the retry's core subject), so one run can |
| 6 | issue the same request several times. :func:`fetch_once` runs a fetch at most once per |
| 7 | key: the first caller fetches, concurrent callers wait for it (bounded by |
| 8 | their own timeout), and later callers get a copy of the cached result. |
| 9 | |
| 10 | Only clean results are cached. A failure (a raised exception, a result the |
| 11 | caller's ``cacheable`` predicate rejects, or HTTP failures an adapter |
| 12 | swallowed into the failure sink) reaches only the callers already waiting on |
| 13 | that fetch; the next call fetches again, so the thin-source retry still makes |
| 14 | a real second attempt after a transient failure. |
| 15 | |
| 16 | Reset once per command (``last30days.py``) and between tests (``conftest``). |
| 17 | """ |
| 18 | |
| 19 | from __future__ import annotations |
| 20 | |
| 21 | from collections import OrderedDict |
| 22 | import contextlib |
| 23 | import contextvars |
| 24 | import copy |
| 25 | import threading |
| 26 | import time |
| 27 | from typing import Any, Callable, Hashable, Iterator, TypeVar |
| 28 | |
| 29 | from . import health, http |
| 30 | |
| 31 | T = TypeVar("T") |
| 32 | |
| 33 | MAX_ENTRIES = 512 |
| 34 | |
| 35 | |
| 36 | class MemoWaitTimeout(TimeoutError): |
| 37 | """A waiter's budget expired before the in-flight fetch it shares finished.""" |
| 38 | |
| 39 | outcome_state = health.TIMEOUT |
| 40 | |
| 41 | |
| 42 | class _Slot: |
| 43 | __slots__ = ("event", "outcome") |
| 44 | |
| 45 | def __init__(self) -> None: |
| 46 | self.event = threading.Event() |
| 47 | # (ok, value_or_exception, recorded_failures) once the owner finishes. |
| 48 | self.outcome: tuple[bool, Any, list] | None = None |
| 49 | |
| 50 | |
| 51 | class _MemoStore: |
| 52 | __slots__ = ("cache", "inflight", "lock") |
| 53 | |
| 54 | def __init__(self) -> None: |
| 55 | self.cache: OrderedDict[Hashable, Any] = OrderedDict() |
| 56 | self.inflight: dict[Hashable, _Slot] = {} |
| 57 | self.lock = threading.Lock() |
| 58 | |
| 59 | |
| 60 | _DEFAULT_STORE = _MemoStore() |
| 61 | _CACHE: OrderedDict[Hashable, Any] = _DEFAULT_STORE.cache |
| 62 | _INFLIGHT: dict[Hashable, _Slot] = _DEFAULT_STORE.inflight |
| 63 | _LOCK = _DEFAULT_STORE.lock |
| 64 | |
| 65 | _CURRENT_STORE: contextvars.ContextVar[_MemoStore | None] = contextvars.ContextVar( |
| 66 | "fetch_memo_store", default=None, |
| 67 | ) |
| 68 | |
| 69 | |
| 70 | def _active_store() -> _MemoStore: |
| 71 | store = _CURRENT_STORE.get() |
| 72 | return store if store is not None else _DEFAULT_STORE |
| 73 | |
| 74 | |
| 75 | @contextlib.contextmanager |
| 76 | def run_scope() -> Iterator[_MemoStore]: |
| 77 | """Scope fetch memo state to a single top-level run without touching concurrent runs.""" |
| 78 | store = _MemoStore() |
| 79 | token = _CURRENT_STORE.set(store) |
| 80 | try: |
| 81 | yield store |
| 82 | finally: |
| 83 | _CURRENT_STORE.reset(token) |
| 84 | |
| 85 | |
| 86 | def reset() -> None: |
| 87 | """Forget cached and in-flight fetches in the active store.""" |
| 88 | store = _active_store() |
| 89 | with store.lock: |
| 90 | store.cache.clear() |
| 91 | store.inflight.clear() |
| 92 | |
| 93 | |
| 94 | def _always(_value: Any) -> bool: |
| 95 | return True |
| 96 | |
| 97 | |
| 98 | def _deliver_shared(outcome: tuple[bool, Any, list]) -> Any: |
| 99 | ok, value, failures = outcome |
| 100 | # The owner's swallowed HTTP failures reach this caller's sink too, or a |
| 101 | # shared empty result reads as a clean no-results. |
| 102 | for failure in failures: |
| 103 | http._record_failure(failure) |
| 104 | if not ok: |
| 105 | raise value |
| 106 | return copy.deepcopy(value) |
| 107 | |
| 108 | |
| 109 | def fetch_once( |
| 110 | key: Hashable, |
| 111 | fetch: Callable[[], T], |
| 112 | *, |
| 113 | timeout: float, |
| 114 | cacheable: Callable[[T], bool] = _always, |
| 115 | cancel: threading.Event | None = None, |
| 116 | ) -> T: |
| 117 | """Return ``fetch()``, running it at most once per ``key`` while it stays clean. |
| 118 | |
| 119 | ``key`` must include every input that changes the request. ``timeout`` |
| 120 | bounds how long a caller waits on another caller's in-flight fetch; past |
| 121 | it, :class:`MemoWaitTimeout` is raised. When ``cancel`` is set, waiting |
| 122 | callers unblock promptly with :class:`MemoWaitTimeout`. Every caller gets |
| 123 | its own copy. |
| 124 | """ |
| 125 | store = _active_store() |
| 126 | deadline = time.monotonic() + max(0.0, timeout) |
| 127 | while True: |
| 128 | if cancel is not None and cancel.is_set(): |
| 129 | raise MemoWaitTimeout("fetch cancelled") |
| 130 | with store.lock: |
| 131 | hit = key in store.cache |
| 132 | if hit: |
| 133 | store.cache.move_to_end(key) |
| 134 | cached = store.cache[key] |
| 135 | else: |
| 136 | slot = store.inflight.get(key) |
| 137 | owner = slot is None |
| 138 | if owner: |
| 139 | slot = _Slot() |
| 140 | store.inflight[key] = slot |
| 141 | if hit: |
| 142 | return copy.deepcopy(cached) |
| 143 | if owner: |
| 144 | break |
| 145 | while not slot.event.is_set(): |
| 146 | if cancel is not None and cancel.is_set(): |
| 147 | raise MemoWaitTimeout("fetch cancelled") |
| 148 | remaining = deadline - time.monotonic() |
| 149 | if remaining <= 0: |
| 150 | raise MemoWaitTimeout( |
| 151 | f"waited {timeout:g}s for an identical in-flight fetch" |
| 152 | ) |
| 153 | wait_step = min(0.1, remaining) if cancel is not None else remaining |
| 154 | if slot.event.wait(wait_step): |
| 155 | break |
| 156 | if slot.outcome is not None: |
| 157 | return _deliver_shared(slot.outcome) |
| 158 | # The owner was interrupted before publishing (e.g. KeyboardInterrupt): |
| 159 | # loop and elect a new owner. |
| 160 | |
| 161 | try: |
| 162 | with http.tee_failures() as recorded: |
| 163 | try: |
| 164 | value = fetch() |
| 165 | ok = True |
| 166 | except Exception as exc: |
| 167 | value = exc |
| 168 | ok = False |
| 169 | clean = ok and not recorded and cacheable(value) |
| 170 | # Waiters and the cache copy from this snapshot, never from the |
| 171 | # owner's own value, which the owner's caller may mutate. |
| 172 | shared = copy.deepcopy(value) if ok else value |
| 173 | slot.outcome = (ok, shared, list(recorded)) |
| 174 | with store.lock: |
| 175 | # Slot identity guards against a reset() during the fetch. |
| 176 | if clean and store.inflight.get(key) is slot: |
| 177 | if MAX_ENTRIES > 0: |
| 178 | store.cache[key] = shared |
| 179 | store.cache.move_to_end(key) |
| 180 | while len(store.cache) > MAX_ENTRIES: |
| 181 | store.cache.popitem(last=False) |
| 182 | finally: |
| 183 | with store.lock: |
| 184 | if store.inflight.get(key) is slot: |
| 185 | store.inflight.pop(key) |
| 186 | slot.event.set() |
| 187 | if not ok: |
| 188 | raise value |
| 189 | return value |
| 190 |