"""Validated, briefly cached JSON representations for hot read endpoints. The semantic topology is read by the UI after every event burst and by integrations such as ITWorx Forge on a fixed poll. Its content changes far less often than it is read: in production only ``generated_at`` differed between polls. Two mechanisms make an unchanged read nearly free: * A strong ``ETag`` computed over the content *excluding* ``generated_at``. A client that sends ``If-None-Match`` gets ``304 Not Modified`` with no body. Because the tag is derived from the content itself it is always correct, including after writes that publish no event. * A short-lived computation cache. It is reused only while no event has been published since it was built, no evidence freshness boundary (fresh→stale→expired) has been crossed, and it is younger than ``max_age_seconds``. The age cap bounds staleness for the few write paths that publish no event (for example discovery relation evidence). """ from __future__ import annotations import hashlib import time from collections.abc import Callable from dataclasses import dataclass from datetime import datetime, timedelta from threading import Lock from pydantic import BaseModel from .models import HealthEvidence GENERATED_AT_HEADER = "X-ServiceMap-Generated-At" @dataclass(frozen=True) class CachedRepresentation: body: bytes etag: str generated_at: str def representation(model: BaseModel, *, timestamp_field: str = "generated_at") -> CachedRepresentation: """Serialize once and tag the content independent of its timestamp.""" content = model.model_dump_json(exclude={timestamp_field}) stamp = model.model_dump_json(include={timestamp_field}) # Splice ``{"generated_at": ...}`` in front of the remaining fields: one # serialization for the body, the hash covers everything but the stamp. body = stamp if content == "{}" else f"{stamp[:-1]},{content[1:]}" digest = hashlib.sha256(content.encode()).hexdigest()[:32] generated_at = str(getattr(model, timestamp_field).isoformat()) return CachedRepresentation(body=body.encode(), etag=f'"{digest}"', generated_at=generated_at) def etag_matches(if_none_match: str | None, etag: str) -> bool: if not if_none_match: return False for candidate in if_none_match.split(","): value = candidate.strip() if value == "*" or value.removeprefix("W/") == etag: return True return False def next_freshness_boundary(evidence: list[HealthEvidence], now: datetime) -> datetime | None: """Earliest future instant at which any claim changes freshness.""" boundary: datetime | None = None for item in evidence: ttl = max(item.valid_until - item.observed_at, timedelta(seconds=1)) for instant in (item.valid_until, item.valid_until + ttl): if instant > now and (boundary is None or instant < boundary): boundary = instant return boundary @dataclass class _Entry: value: CachedRepresentation revision: int expires_at: float class RepresentationCache: """Thread-safe cache keyed by request variant and event revision.""" def __init__( self, *, max_age_seconds: float = 10.0, clock: Callable[[], float] = time.monotonic, ) -> None: self.max_age_seconds = max_age_seconds self._clock = clock self._entries: dict[object, _Entry] = {} self._lock = Lock() def get(self, key: object, revision: int) -> CachedRepresentation | None: with self._lock: entry = self._entries.get(key) if entry is None: return None if entry.revision != revision or self._clock() >= entry.expires_at: del self._entries[key] return None return entry.value def put( self, key: object, revision: int, value: CachedRepresentation, *, valid_for_seconds: float | None = None, ) -> None: ttl = self.max_age_seconds if valid_for_seconds is None else min(self.max_age_seconds, valid_for_seconds) if ttl <= 0: return with self._lock: self._entries[key] = _Entry(value=value, revision=revision, expires_at=self._clock() + ttl) def clear(self) -> None: with self._lock: self._entries.clear()