forked from mtusi2026/mtusi2026lab5
Переиспользован стек lab4 (LB/2 реплики/Postgres/SeaweedFS). upload теперь 202 queued; отдельный worker-процесс генерирует thumbnail/crop/optimized. Transactional outbox закрывает разрыв COMMIT/publish; durable retry (job_retry_schedule) переживает падение worker во время backoff; lease recovery через XAUTOCLAIM; DLQ-реестр (job_failures) с явным operator replay (scripts/replay_failed.py). make test/test-persistence/test-failover/ validate зелёные; в процессе экспериментов найдены и исправлены два реальных бага (неполный try/except вокруг S3-записи вариантов, ошибка типов asyncpg в построении interval) — см. REPORT.md и evidence/. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
55 lines
1.5 KiB
Python
55 lines
1.5 KiB
Python
"""Opaque Bearer sessions backed by Redis/Valkey, TTL-bound, AOF-persistent."""
|
|
import json
|
|
import os
|
|
import secrets
|
|
import uuid
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
import redis.asyncio as redis
|
|
|
|
_client: redis.Redis | None = None
|
|
TTL_SECONDS = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
|
|
|
|
|
def init(url: str) -> None:
|
|
global _client
|
|
_client = redis.from_url(url, decode_responses=True, socket_timeout=3, socket_connect_timeout=3)
|
|
|
|
|
|
async def close() -> None:
|
|
if _client is not None:
|
|
await _client.close()
|
|
|
|
|
|
def client() -> redis.Redis:
|
|
if _client is None:
|
|
raise RuntimeError("session store is not initialized")
|
|
return _client
|
|
|
|
|
|
async def ping() -> bool:
|
|
try:
|
|
return bool(await client().ping())
|
|
except Exception: # noqa: BLE001 - readiness probe
|
|
return False
|
|
|
|
|
|
async def create(user_id: uuid.UUID) -> tuple[str, datetime]:
|
|
token = secrets.token_urlsafe(32) # 256 bits of entropy, opaque and non-guessable
|
|
expires_at = datetime.now(timezone.utc) + timedelta(seconds=TTL_SECONDS)
|
|
payload = json.dumps({"user_id": str(user_id), "expires_at": expires_at.isoformat()})
|
|
await client().set(f"session:{token}", payload, ex=TTL_SECONDS)
|
|
return token, expires_at
|
|
|
|
|
|
async def resolve(token: str) -> uuid.UUID | None:
|
|
raw = await client().get(f"session:{token}")
|
|
if raw is None:
|
|
return None
|
|
data = json.loads(raw)
|
|
return uuid.UUID(data["user_id"])
|
|
|
|
|
|
async def revoke(token: str) -> None:
|
|
await client().delete(f"session:{token}")
|