lab2: fix cache revocation, DB timeouts, add failure tests
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-10-03 12:12:45 +03:00
parent c69143c215
commit ead398e9ba
12 changed files with 477 additions and 77 deletions
+74 -6
View File
@@ -2,7 +2,8 @@ from __future__ import annotations
import logging
import os
from typing import Optional
import time
from typing import Optional, Set
import redis
@@ -11,6 +12,9 @@ log = logging.getLogger("messenger.cache")
_client: Optional[redis.Redis] = None
_failures: int = 0
_MAX_FAILURES_BEFORE_DISABLE: int = 3
_REVOKED_TTL_SECONDS: int = int(os.environ.get("REVOKED_TTL_SECONDS", "86400"))
_pending_revocations: Set[str] = set()
_pending_sessions: dict[str, tuple[str, int]] = {}
def _cache_url() -> Optional[str]:
@@ -34,12 +38,47 @@ def init_cache() -> None:
client.ping()
_client = client
_failures = 0
log.info("cache connected")
_replay_pending_revocations(client)
log.info("cache connected (session prefix flushed, %d pending revocations replayed)",
len(_pending_revocations))
except Exception as exc:
log.warning("cache unavailable at startup: %s; running in degraded mode", exc)
_client = None
def _flush_session_prefix(client: redis.Redis) -> None:
"""Удаляет все ключи session:*. Кэш — не источник истины, это безопасно."""
try:
cursor = 0
deleted = 0
while True:
cursor, keys = client.scan(cursor=cursor, match="session:*", count=500)
if keys:
client.delete(*keys)
deleted += len(keys)
if cursor == 0:
break
if deleted:
log.info("flushed %d stale session keys after cache (re)connect", deleted)
except Exception as exc:
log.warning("failed to flush session prefix: %s", exc)
def _replay_pending_revocations(client: redis.Redis) -> None:
"""Пробует записать в Valkey отзывы, накопленные пока он был недоступен."""
global _pending_revocations
if not _pending_revocations:
return
still_pending: Set[str] = set()
for token_hash in _pending_revocations:
try:
client.setex(f"revoked:{token_hash}", _REVOKED_TTL_SECONDS, "1")
except Exception:
still_pending.add(token_hash)
_pending_revocations = still_pending
def close_cache() -> None:
global _client
if _client is not None:
@@ -74,6 +113,38 @@ def is_available() -> bool:
return _client is not None
# ---------- tombstone (revoked) ----------
def mark_revoked(token_hash: str) -> None:
if _client is None:
_pending_revocations.add(token_hash)
log.warning("cache unavailable; revocation queued locally (%d pending)",
len(_pending_revocations))
return
try:
_client.setex(f"revoked:{token_hash}", _REVOKED_TTL_SECONDS, "1")
_note_success()
except Exception as exc:
log.warning("mark_revoked failed: %s", exc)
_pending_revocations.add(token_hash)
_note_failure()
def is_revoked(token_hash: str) -> bool:
if _client is None:
return False
try:
exists = _client.exists(f"revoked:{token_hash}")
_note_success()
return exists == 1
except Exception as exc:
log.warning("is_revoked failed: %s", exc)
_note_failure()
return False
# ---------- session cache ----------
def get_user_id(token_hash: str) -> Optional[str]:
if _client is None:
return None
@@ -97,10 +168,7 @@ def set_user_id(token_hash: str, user_id: str, ttl_seconds: int) -> None:
_note_success()
except Exception as exc:
log.warning("cache set failed: %s", exc)
try:
_note_failure()
except Exception as inner:
log.warning("cache failure handler crashed: %s", inner)
_note_failure()
def invalidate(token_hash: str) -> None:
+18 -1
View File
@@ -19,17 +19,34 @@ def _database_url() -> str:
return url
from psycopg_pool import ConnectionPool
def init_pool(min_size: int = 1, max_size: int = 10) -> None:
global _pool
if _pool is not None:
return
dsn = _database_url()
sep = "&" if "?" in dsn else "?"
dsn_with_opts = (
dsn
+ sep
+ "options="
+ "-c%20statement_timeout%3D5000"
+ "%20-c%20lock_timeout%3D3000"
+ "%20-c%20idle_in_transaction_session_timeout%3D10000"
)
_pool = ConnectionPool(
conninfo=_database_url(),
conninfo=dsn_with_opts,
min_size=min_size,
max_size=max_size,
kwargs={"row_factory": dict_row},
open=True,
timeout=5.0,
check=ConnectionPool.check_connection,
max_lifetime=120,
max_idle=60,
)