123 lines
4.9 KiB
Python
123 lines
4.9 KiB
Python
"""Stale-while-revalidate for what the host asks plugins on every page load
|
||
(composer shortcuts and modes, ``plugins/shortcuts.py`` / ``waiting.py``).
|
||
|
||
Each of those is a handler subprocess (0.3–2 s on a busy hub). A fresh entry
|
||
is served as is; an entry past ``ttl`` but within ``max_stale`` is served at
|
||
once while one background thread runs the plugin again; only a missing (or
|
||
too old) entry makes the caller wait — and concurrent callers of that key
|
||
wait for one run, not one each.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import concurrent.futures
|
||
import logging
|
||
import threading
|
||
import time
|
||
from collections.abc import Callable
|
||
from typing import Any
|
||
|
||
log = logging.getLogger(__name__)
|
||
|
||
|
||
class SWRCache:
|
||
def __init__(self, ttl: float, max_stale: float, name: str = "swr"):
|
||
self.ttl = ttl
|
||
self.max_stale = max_stale
|
||
self.name = name
|
||
self._lock = threading.Lock()
|
||
self._data: dict[str, tuple[float, Any]] = {}
|
||
# key → Event set when its run ends (a cold miss or a refresh)
|
||
self._running: dict[str, threading.Event] = {}
|
||
|
||
def get(self, key: str, compute: Callable[[], Any]) -> Any:
|
||
now = time.monotonic()
|
||
with self._lock:
|
||
hit = self._data.get(key)
|
||
age = None if hit is None else now - hit[0]
|
||
if hit is not None and age is not None and age < self.ttl:
|
||
return hit[1]
|
||
running = self._running.get(key)
|
||
if hit is not None and age is not None and age < self.max_stale:
|
||
if running is None:
|
||
self._running[key] = threading.Event()
|
||
threading.Thread(target=self._refresh, args=(key, compute),
|
||
name=f"{self.name}-refresh", daemon=True).start()
|
||
return hit[1]
|
||
if running is None:
|
||
self._running[key] = ev = threading.Event()
|
||
leader = True
|
||
else:
|
||
ev, leader = running, False
|
||
if not leader:
|
||
ev.wait(timeout=60)
|
||
with self._lock:
|
||
hit = self._data.get(key)
|
||
if hit is not None:
|
||
return hit[1]
|
||
return compute()
|
||
return self._run(key, compute, ev)
|
||
|
||
def is_warm(self, key: str) -> bool:
|
||
"""True when ``key`` holds an entry inside ``max_stale`` so :meth:`get`
|
||
returns immediately without running ``compute``."""
|
||
now = time.monotonic()
|
||
with self._lock:
|
||
hit = self._data.get(key)
|
||
return hit is not None and (now - hit[0]) < self.max_stale
|
||
|
||
def get_many(self, items: list[tuple[str, Callable[[], Any]]]) -> list[Any]:
|
||
"""Resolve ``[(key, compute), ...]`` in order, running >1 cold miss
|
||
concurrently via a bounded thread pool."""
|
||
if not items:
|
||
return []
|
||
results: list[Any] = [None] * len(items)
|
||
misses: list[tuple[int, str, Callable[[], Any]]] = []
|
||
for i, (key, compute) in enumerate(items):
|
||
if self.is_warm(key):
|
||
results[i] = self.get(key, compute)
|
||
else:
|
||
misses.append((i, key, compute))
|
||
if len(misses) == 1:
|
||
i, key, compute = misses[0]
|
||
results[i] = self.get(key, compute)
|
||
elif len(misses) > 1:
|
||
with concurrent.futures.ThreadPoolExecutor(max_workers=min(len(misses), 6)) as pool:
|
||
for i, val in pool.map(lambda m: (m[0], self.get(m[1], m[2])), misses):
|
||
results[i] = val
|
||
return results
|
||
|
||
def _refresh(self, key: str, compute: Callable[[], Any]) -> None:
|
||
with self._lock:
|
||
ev = self._running.get(key) or threading.Event()
|
||
try:
|
||
self._run(key, compute, ev)
|
||
except Exception as e: # noqa: BLE001 — the stale value stays served
|
||
log.warning("%s refresh of %s failed: %s", self.name, key, e)
|
||
|
||
def _run(self, key: str, compute: Callable[[], Any], ev: threading.Event) -> Any:
|
||
try:
|
||
value = compute()
|
||
with self._lock:
|
||
# A drop() while this ran wins: its key is gone from _running.
|
||
if self._running.get(key) is ev:
|
||
self._data[key] = (time.monotonic(), value)
|
||
return value
|
||
finally:
|
||
with self._lock:
|
||
if self._running.get(key) is ev:
|
||
self._running.pop(key, None)
|
||
ev.set()
|
||
|
||
def drop(self, match: Callable[[str], bool] | None = None) -> None:
|
||
"""Forget every entry (or those whose key ``match``es) — a plugin
|
||
changed; a run in flight for one of them is not stored."""
|
||
with self._lock:
|
||
for k in [k for k in self._data if match is None or match(k)]:
|
||
self._data.pop(k, None)
|
||
for k in [k for k in self._running if match is None or match(k)]:
|
||
self._running.pop(k, None)
|
||
|
||
def clear(self) -> None:
|
||
self.drop(None)
|