Files
mtusi2026lab3/src/sessions.py
T
2026-10-15 00:18:02 +03:00

87 lines
1.9 KiB
Python

import os
import secrets
from uuid import UUID
from redis.asyncio import Redis
from redis.exceptions import RedisError
from src.errors import APIError
CACHE_URL_FILE = "/run/secrets/cache_url"
DEFAULT_SESSION_TTL_SECONDS = 3600
def read_cache_url() -> str:
with open(CACHE_URL_FILE, encoding="utf-8") as file:
return file.read().strip()
def get_session_ttl_seconds() -> int:
return int(
os.getenv(
"SESSION_TTL_SECONDS",
str(DEFAULT_SESSION_TTL_SECONDS),
)
)
redis_client = Redis.from_url(
read_cache_url(),
decode_responses=True,
socket_connect_timeout=5,
socket_timeout=5,
)
def session_store_unavailable() -> APIError:
return APIError(
status_code=503,
code="service_unavailable",
message="Session store unavailable",
)
async def create_session(user_id: UUID) -> tuple[str, int]:
token = secrets.token_urlsafe(32)
ttl = get_session_ttl_seconds()
try:
await redis_client.set(
f"session:{token}",
str(user_id),
ex=ttl,
)
except RedisError as exc:
raise session_store_unavailable() from exc
return token, ttl
async def get_session_user_id(token: str) -> UUID | None:
try:
value = await redis_client.get(f"session:{token}")
except RedisError as exc:
raise session_store_unavailable() from exc
if value is None:
return None
try:
return UUID(value)
except ValueError:
return None
async def delete_session(token: str) -> None:
try:
await redis_client.delete(f"session:{token}")
except RedisError as exc:
raise session_store_unavailable() from exc
async def ping_session_store() -> bool:
try:
return bool(await redis_client.ping())
except RedisError:
return False