Реализация ЛР 3 на оценку 3: HAProxy, 2 реплики API, идемпотентность, evidence

This commit is contained in:
2026-11-10 01:26:52 +03:00
parent 0ab3a341aa
commit de55dd1d8a
29 changed files with 2032 additions and 0 deletions
+82
View File
@@ -0,0 +1,82 @@
import asyncio
import json
import logging
import time
import uuid
from datetime import datetime
from typing import Optional
import redis.asyncio as redis
from redis.exceptions import RedisError
from . import config
from .common import iso
logger = logging.getLogger("messenger")
_FAILURES = (RedisError, OSError, asyncio.TimeoutError)
_RETRY_AFTER = 5.0 # после сбоя 5 секунд не обращаемся к кэшу, чтобы не ждать таймаут на каждом запросе
def _key(digest: bytes) -> str:
return "sess:" + digest.hex()
class SessionCache:
"""Кэш проверенных сессий. Любой сбой = промах: ответ берётся из PostgreSQL."""
def __init__(self, url: str):
self._client = (
redis.Redis.from_url(
url, decode_responses=True,
socket_timeout=config.CACHE_TIMEOUT, socket_connect_timeout=config.CACHE_TIMEOUT,
) if url else None
)
self._down_until = 0.0
def _usable(self) -> bool:
return self._client is not None and time.monotonic() >= self._down_until
def _mark_down(self, exc: Exception) -> None:
self._down_until = time.monotonic() + _RETRY_AFTER
logger.warning("Cache unavailable, bypassing: %s", type(exc).__name__)
async def get(self, digest: bytes) -> Optional[dict]:
if not self._usable():
return None
try:
raw = await self._client.get(_key(digest))
except _FAILURES as exc:
self._mark_down(exc)
return None
if raw is None:
return None
try:
d = json.loads(raw)
return {"id": uuid.UUID(d["id"]), "username": d["username"],
"display_name": d["display_name"], "created_at": datetime.fromisoformat(d["created_at"])}
except (ValueError, KeyError):
return None
async def put(self, digest: bytes, user: dict, remaining_seconds: int) -> None:
ttl = min(remaining_seconds, config.CACHE_TTL_SECONDS) # кэш никогда не живёт дольше сессии
if ttl < 1 or not self._usable():
return
value = json.dumps({"id": str(user["id"]), "username": user["username"],
"display_name": user["display_name"], "created_at": iso(user["created_at"])})
try:
await self._client.set(_key(digest), value, ex=ttl)
except _FAILURES as exc:
self._mark_down(exc)
async def delete(self, digest: bytes) -> None:
if not self._usable():
return
try:
await self._client.delete(_key(digest))
except _FAILURES as exc:
self._mark_down(exc)
async def close(self) -> None:
if self._client is not None:
await self._client.aclose()