Files
mtusi2026lab5/app/sessions.py
T

169 lines
7.2 KiB
Python

"""
Сессии: PostgreSQL — источник истины, Redis/Valkey — кэш поиска сессии.
Чтение (проверка Bearer):
1. Ищем в Redis ключ sess:<sha256(token)>. Нашли и не истёк → пользователь.
2. Нет в кэше / Redis недоступен → читаем sessions в PostgreSQL
(не отозвана и expires_at > now()) и кладём результат в кэш.
Политика expiry: срок жизни сессии задаёт PostgreSQL (expires_at).
TTL ключа в Redis = min(SESSION_CACHE_TTL_SECONDS, время до expires_at),
поэтому кэш никогда не продлевает сессию.
Инвалидация (logout) — атомарно для БД и кэша:
в одной транзакции UPDATE sessions SET revoked_at (строка блокируется),
затем DEL ключа в Redis. Если Redis не ответил — транзакция откатывается и
клиент получает 503: logout НЕ подтверждён, 204 отдаётся только когда
копии отозванной сессии в кэше гарантированно нет.
Гонка «чтение кладёт старую сессию в кэш после DEL» закрыта блокировкой:
чтение из БД идёт с FOR SHARE и кладёт в кэш, не отпуская строку, поэтому
logout ждёт окончания такого чтения и удаляет ключ уже после него.
Отказ Redis: кэш обходится, всё читается из PostgreSQL (медленнее, но верно).
Flush/рестарт Redis: кэш пустой → сессии восстанавливаются из PostgreSQL.
Отказ PostgreSQL: новые проверки идут в БД → 503, анонимный запрос не принимается.
"""
from __future__ import annotations
import json
import logging
from datetime import datetime, timedelta, timezone
import redis.asyncio as aioredis
from redis.exceptions import RedisError
from .config import settings
from .security import new_token, token_hash
log = logging.getLogger("messenger.sessions")
_redis: aioredis.Redis | None = None
def init_redis() -> None:
global _redis
if settings.redis_url:
_redis = aioredis.Redis.from_url(
settings.redis_url,
socket_timeout=settings.redis_timeout,
socket_connect_timeout=settings.redis_timeout,
decode_responses=True,
)
async def close_redis() -> None:
if _redis is not None:
await _redis.aclose()
def redis_enabled() -> bool:
return _redis is not None
async def redis_ping() -> bool:
if _redis is None:
return False
try:
return bool(await _redis.ping())
except (RedisError, OSError):
return False
def _key(th: bytes) -> str:
return "sess:" + th.hex()
async def _cache_get(th: bytes) -> dict | None:
if _redis is None:
return None
try:
raw = await _redis.get(_key(th))
except (RedisError, OSError) as exc:
log.warning("redis unavailable on read, bypassing cache: %s", type(exc).__name__)
return None
return json.loads(raw) if raw else None
async def _cache_put(th: bytes, user: dict, expires_at: datetime) -> None:
if _redis is None:
return
left = int((expires_at - datetime.now(timezone.utc)).total_seconds())
ttl = min(settings.session_cache_ttl_seconds, left)
if ttl <= 0:
return
try:
await _redis.set(_key(th), json.dumps({"user": user, "exp": expires_at.isoformat()}), ex=ttl)
except (RedisError, OSError) as exc:
log.warning("redis unavailable on write, skipping cache: %s", type(exc).__name__)
class CacheUnavailable(Exception):
"""Redis не подтвердил удаление ключа — отзыв сессии нельзя гарантировать."""
async def _cache_delete_strict(th: bytes) -> None:
"""Удалить копию сессии из кэша или поднять CacheUnavailable.
Молча проглатывать ошибку нельзя: если Redis «приостановлен», ключ
переживёт сбой и после восстановления отозванный токен снова примут."""
if _redis is None:
return
try:
await _redis.delete(_key(th))
except (RedisError, OSError) as exc:
log.warning("redis unavailable on invalidate: %s", type(exc).__name__)
raise CacheUnavailable() from exc
async def create_session(conn, user_id) -> tuple[str, datetime]:
token = new_token()
now = datetime.now(timezone.utc)
expires_at = now + timedelta(seconds=settings.session_ttl_seconds)
await conn.execute(
"INSERT INTO sessions (token_hash, user_id, created_at, expires_at) "
"VALUES (%s, %s, %s, %s)",
(token_hash(token), user_id, now, expires_at))
return token, expires_at
async def resolve(pool, token: str, load_user) -> dict | None:
"""Вернёт пользователя (dict) для действующего токена или None."""
th = token_hash(token)
cached = await _cache_get(th)
if cached is not None:
if datetime.fromisoformat(cached["exp"]) > datetime.now(timezone.utc):
return cached["user"]
return None
async with pool.connection() as conn:
# FOR SHARE: пока эта транзакция не закончилась (вместе с записью в кэш),
# logout не сможет отозвать строку — он дождётся и удалит ключ после нас.
cur = await conn.execute(
"SELECT user_id, expires_at FROM sessions "
"WHERE token_hash = %s AND revoked_at IS NULL AND expires_at > now() "
"FOR SHARE",
(th,))
row = await cur.fetchone()
if row is None:
return None
user = await load_user(conn, row[0])
if user is None:
return None
await _cache_put(th, user, row[1])
return user
async def revoke(pool, token: str) -> bool:
"""Отозвать сессию. True — была действующая и теперь отозвана (и в БД, и в кэше).
False — сессии нет/уже отозвана. CacheUnavailable — Redis не ответил:
транзакция откатана, сессия осталась действующей, logout не подтверждён."""
th = token_hash(token)
async with pool.connection() as conn:
async with conn.transaction():
cur = await conn.execute(
"UPDATE sessions SET revoked_at = now() "
"WHERE token_hash = %s AND revoked_at IS NULL AND expires_at > now() "
"RETURNING 1", (th,))
if await cur.fetchone() is None:
return False
# Внутри транзакции: ошибка Redis → исключение → ROLLBACK отзыва.
await _cache_delete_strict(th)
return True