Files
second-screen/poller.py
T
2026-10-22 13:18:00 +02:00

83 lines
2.5 KiB
Python

"""Background fetcher: keeps the last good value so a slow or failing source never blocks drawing."""
import logging
import threading
import time
from typing import Callable, Generic, TypeVar
log = logging.getLogger(__name__)
T = TypeVar("T")
MAX_RETRY_S = 60.0
class Poller(Generic[T]):
def __init__(self, fetch: Callable[[], T], interval: float,
clock: Callable[[], float] = time.monotonic) -> None:
self._fetch = fetch
self._interval = interval
self._clock = clock
self._lock = threading.Lock()
self._value: T | None = None
self._version = 0
self._failures = 0
self._updated_at: float | None = None
self._stop = threading.Event()
self._thread: threading.Thread | None = None
@property
def value(self) -> T | None:
with self._lock:
return self._value
@property
def version(self) -> int:
with self._lock:
return self._version
@property
def failures(self) -> int:
with self._lock:
return self._failures
def age(self) -> float | None:
"""Seconds since the last successful fetch, None if there has been none."""
with self._lock:
return None if self._updated_at is None else self._clock() - self._updated_at
def poll_once(self) -> bool:
"""Run the fetch now; never raises. Returns whether it succeeded."""
try:
value = self._fetch()
except Exception as exc:
with self._lock:
self._failures += 1
first_in_streak = self._failures == 1
if first_in_streak:
log.warning("fetch failed: %s", exc)
return False
with self._lock:
recovered = self._failures > 0
self._value = value
self._version += 1
self._failures = 0
self._updated_at = self._clock()
if recovered:
log.info("fetch recovered")
return True
def start(self) -> None:
if self._thread is not None:
return
self._thread = threading.Thread(target=self._loop, name="poller", daemon=True)
self._thread.start()
def stop(self) -> None:
self._stop.set()
if self._thread is not None:
self._thread.join(timeout=1)
def _loop(self) -> None:
while not self._stop.is_set():
ok = self.poll_once()
self._stop.wait(self._interval if ok else min(self._interval, MAX_RETRY_S))