Files
mtusi2026lab5/src/app/storage/sessions.py
T

143 lines
4.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Хранилище сессий. Redis (основной режим, lab2 level 4) или PostgreSQL (fallback).
Ключевое: при недоступности Redis поднимаем RuntimeError("redis_unavailable"),
чтобы main.py отдал 503 unavailable, а не 500 internal_error.
"""
import json
import os
import secrets
from datetime import datetime, timedelta, timezone
from typing import Optional
from uuid import UUID
from ..models.schemas import User
from . import db as _db
try:
import redis as _redis
except ImportError: # pragma: no cover
_redis = None
_SESSION_PREFIX = "sess:"
def now_utc() -> datetime:
return datetime.now(timezone.utc)
def _store() -> str:
return os.environ.get("SESSION_STORE", "redis").strip().lower()
def _redis_client():
"""Возвращает подключённый клиент Redis или поднимает RuntimeError.
RuntimeError("redis_unavailable: ...") ловит main.runtime_error_handler → 503.
"""
if _redis is None:
raise RuntimeError("redis_unavailable: redis library is not installed")
url = os.environ.get("REDIS_URL", "redis://redis:6379/0")
try:
client = _redis.from_url(
url,
decode_responses=True,
socket_timeout=2.0,
socket_connect_timeout=2.0,
)
client.ping()
return client
except _redis.RedisError as exc:
raise RuntimeError("redis_unavailable: %s" % type(exc).__name__) from exc
def _user_key(user_id: UUID) -> str:
return str(user_id)
def create_session(user_id: UUID, ttl_seconds: int) -> tuple[str, datetime]:
token = secrets.token_urlsafe(32)
expires_at = now_utc() + timedelta(seconds=ttl_seconds)
if _store() == "redis":
r = _redis_client()
payload = json.dumps({"user_id": _user_key(user_id), "expires_at": expires_at.isoformat()})
try:
# SETEX: TTL — сама суть Redis-сессий
r.setex(_SESSION_PREFIX + token, ttl_seconds, payload)
except _redis.RedisError as exc:
raise RuntimeError("redis_unavailable: %s" % type(exc).__name__) from exc
else:
with _db.connection() as conn:
with conn.cursor() as cur:
cur.execute(
"INSERT INTO sessions (token, user_id, expires_at) VALUES (%s, %s, %s)",
(token, user_id, expires_at),
)
conn.commit()
return token, expires_at
def get_session_user(token: str) -> Optional[User]:
if _store() == "redis":
r = _redis_client()
try:
raw = r.get(_SESSION_PREFIX + token)
except _redis.RedisError as exc:
raise RuntimeError("redis_unavailable: %s" % type(exc).__name__) from exc
if raw is None:
return None
try:
data = json.loads(raw)
user_id = UUID(data["user_id"])
expires_at = datetime.fromisoformat(data["expires_at"])
except Exception:
return None
if expires_at <= now_utc():
try:
r.delete(_SESSION_PREFIX + token)
except _redis.RedisError:
pass
return None
return _load_user(user_id)
# postgres fallback
with _db.connection() as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at"
" FROM sessions s JOIN users u ON u.id = s.user_id"
" WHERE s.token = %s",
(token,),
)
row = cur.fetchone()
if row is None:
return None
if row[4] <= now_utc():
cur.execute("DELETE FROM sessions WHERE token = %s", (token,))
conn.commit()
return None
return User(id=row[0], username=row[1], display_name=row[2], created_at=row[3])
def revoke_session(token: str) -> None:
if _store() == "redis":
r = _redis_client()
try:
r.delete(_SESSION_PREFIX + token)
except _redis.RedisError as exc:
raise RuntimeError("redis_unavailable: %s" % type(exc).__name__) from exc
return
with _db.connection() as conn:
with conn.cursor() as cur:
cur.execute("DELETE FROM sessions WHERE token = %s", (token,))
conn.commit()
def _load_user(user_id: UUID) -> Optional[User]:
with _db.connection() as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
(user_id,),
)
row = cur.fetchone()
return User(id=row[0], username=row[1], display_name=row[2], created_at=row[3]) if row else None