77 lines
2.5 KiB
Python
77 lines
2.5 KiB
Python
"""Durable cache-invalidation drainer (lab3).
|
|
|
|
Logout writes a pending invalidation to PostgreSQL in the same transaction as
|
|
the authoritative session delete. This tiny background thread (one per API
|
|
replica, not an external broker) removes the corresponding Valkey key and then
|
|
the queue row. Multiple replicas may process the same row; cache deletes are
|
|
idempotent, so this is safe and needs no distributed lock.
|
|
|
|
The worker is deliberately not on the request path: it only runs when a cache
|
|
is configured, and it retries forever while Valkey is unreachable. That is what
|
|
lets a logout survive a Valkey outage: the session is already gone from
|
|
PostgreSQL, and the stale cache entry is evicted as soon as the cache returns.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import threading
|
|
from typing import Optional
|
|
|
|
from . import repositories as repo
|
|
from . import sessions
|
|
from .config import settings
|
|
from .db import pool
|
|
|
|
logger = logging.getLogger("messenger.invalidation")
|
|
|
|
_BATCH = 200
|
|
_stop = threading.Event()
|
|
_thread: Optional[threading.Thread] = None
|
|
|
|
|
|
def _drain_once() -> None:
|
|
with pool().connection() as conn:
|
|
pending = repo.list_pending_invalidations(conn, _BATCH)
|
|
if not pending:
|
|
return
|
|
|
|
invalidated = [token_hash for token_hash in pending if sessions.invalidate_session_key(token_hash)]
|
|
if not invalidated:
|
|
# Cache still unreachable; keep the rows for the next attempt.
|
|
return
|
|
with pool().connection() as conn:
|
|
repo.delete_cache_invalidations(conn, invalidated)
|
|
logger.debug("drained %d cache invalidations", len(invalidated))
|
|
|
|
|
|
def _loop() -> None:
|
|
while not _stop.is_set():
|
|
try:
|
|
_drain_once()
|
|
except Exception as exc: # noqa: BLE001 - never kill the drainer
|
|
logger.warning("cache invalidation drain failed: %s", type(exc).__name__)
|
|
_stop.wait(settings.cache_invalidation_interval_seconds)
|
|
|
|
|
|
def start_worker() -> None:
|
|
global _thread
|
|
if not settings.cache_enabled:
|
|
return
|
|
if _thread is not None and _thread.is_alive():
|
|
return
|
|
_stop.clear()
|
|
_thread = threading.Thread(target=_loop, name="cache-invalidation", daemon=True)
|
|
_thread.start()
|
|
logger.info(
|
|
"cache invalidation drainer started (interval=%.2fs)",
|
|
settings.cache_invalidation_interval_seconds,
|
|
)
|
|
|
|
|
|
def stop_worker() -> None:
|
|
global _thread
|
|
_stop.set()
|
|
if _thread is not None:
|
|
_thread.join(timeout=2)
|
|
_thread = None
|