forked from mtusi2026/mtusi2026lab3
Реализовать lab3 на оценку 4: HAProxy, реплики API и общая идемпотентность.
This commit is contained in:
@@ -0,0 +1,136 @@
|
||||
"""Opaque Bearer sessions in Redis with TTL (durable via Redis AOF)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
|
||||
import redis
|
||||
|
||||
from messenger import config
|
||||
|
||||
log = logging.getLogger("messenger.sessions")
|
||||
|
||||
_client: Optional[redis.Redis] = None
|
||||
|
||||
TOKEN_BYTES = 32 # 256-bit entropy
|
||||
KEY_PREFIX = "sess:"
|
||||
|
||||
|
||||
def utc_now() -> datetime:
|
||||
return datetime.now(timezone.utc).replace(microsecond=0)
|
||||
|
||||
|
||||
def format_ts(value: datetime) -> str:
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def parse_ts(value: str) -> datetime:
|
||||
return datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def init_client() -> redis.Redis:
|
||||
global _client
|
||||
if _client is not None:
|
||||
return _client
|
||||
url = config.cache_url()
|
||||
_client = redis.Redis.from_url(
|
||||
url,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=3,
|
||||
socket_timeout=3,
|
||||
health_check_interval=30,
|
||||
)
|
||||
return _client
|
||||
|
||||
|
||||
def close_client() -> None:
|
||||
global _client
|
||||
if _client is not None:
|
||||
try:
|
||||
_client.close()
|
||||
except Exception:
|
||||
pass
|
||||
_client = None
|
||||
|
||||
|
||||
def get_client() -> redis.Redis:
|
||||
if _client is None:
|
||||
raise RuntimeError("Redis client is not initialized")
|
||||
return _client
|
||||
|
||||
|
||||
def ping() -> bool:
|
||||
try:
|
||||
return bool(get_client().ping())
|
||||
except Exception as exc:
|
||||
log.warning("redis ping failed: %s", type(exc).__name__)
|
||||
return False
|
||||
|
||||
|
||||
class SessionStoreError(Exception):
|
||||
"""Raised when Redis is unavailable for session operations."""
|
||||
|
||||
|
||||
def create_session(user_id: str) -> dict:
|
||||
ttl = config.session_ttl_seconds()
|
||||
token = secrets.token_urlsafe(TOKEN_BYTES)
|
||||
now = utc_now()
|
||||
expires_at = now + timedelta(seconds=ttl)
|
||||
payload = {
|
||||
"user_id": user_id,
|
||||
"expires_at": format_ts(expires_at),
|
||||
"created_at": format_ts(now),
|
||||
}
|
||||
key = KEY_PREFIX + token
|
||||
try:
|
||||
client = get_client()
|
||||
# SET with EX: Redis is sole session store; AOF keeps it across restart.
|
||||
client.set(key, json.dumps(payload), ex=ttl)
|
||||
except redis.RedisError as exc:
|
||||
raise SessionStoreError("session store unavailable") from exc
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": payload["expires_at"],
|
||||
"user_id": user_id,
|
||||
}
|
||||
|
||||
|
||||
def get_session(token: str) -> Optional[dict]:
|
||||
if not token:
|
||||
return None
|
||||
key = KEY_PREFIX + token
|
||||
try:
|
||||
raw = get_client().get(key)
|
||||
except redis.RedisError as exc:
|
||||
raise SessionStoreError("session store unavailable") from exc
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
expires_at = parse_ts(data["expires_at"])
|
||||
except (ValueError, KeyError, TypeError, json.JSONDecodeError):
|
||||
return None
|
||||
if expires_at <= utc_now():
|
||||
try:
|
||||
get_client().delete(key)
|
||||
except redis.RedisError:
|
||||
pass
|
||||
return None
|
||||
return data
|
||||
|
||||
|
||||
def revoke_session(token: str) -> bool:
|
||||
if not token:
|
||||
return False
|
||||
key = KEY_PREFIX + token
|
||||
try:
|
||||
return bool(get_client().delete(key))
|
||||
except redis.RedisError as exc:
|
||||
raise SessionStoreError("session store unavailable") from exc
|
||||
Reference in New Issue
Block a user