Files
mtusi2026lab3/app/sessions.py
T
Artu-RitoandClaude Sonnet 5 2f1cf3afac Лаба 3: Nginx LB, 2 реплики API и общая идемпотентность (оценка 4)
Переиспользован стек lab2 (Postgres/Redis/Argon2id). Добавлены: Nginx
балансировщик перед api1/api2, общая идемпотентность POST-сообщений
(idempotency_keys + advisory-lock сериализация в Postgres), explicit
stop-one/restart hooks. make test/test-persistence/test-failover/validate
зелёные для обеих реплик; найдены и исправлены гонка миграций и гонка
рестарта Nginx/DNS — см. REPORT.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-30 00:35:53 +03:00

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}")