Files
mtusi2026lab2/app/sessions.py
T
Artu-RitoandClaude Sonnet 5 d12159a8cc Лаба 2: PostgreSQL-хранилище и Redis-сессии (оценка 4)
FastAPI + asyncpg + Redis/argon2id. Пользователи/чаты/участники/сообщения
в Postgres с версионируемой миграцией и keyset-пагинацией. Basic-вход,
Bearer-сессии в Redis с TTL и AOF-персистентностью. make check/test/
test-persistence/validate зелёные; evidence по EXPLAIN ANALYZE, короткому
TTL и падению Redis приложены в REPORT.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-30 00:23:26 +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}")