Перенесла весь код из лаб. р. 2
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
import base64
|
||||
import binascii
|
||||
import os
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
||||
|
||||
from ..models.schemas import Session
|
||||
from ..storage.postgres import storage
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
|
||||
|
||||
basic_scheme = HTTPBasic(auto_error=False)
|
||||
|
||||
DEFAULT_TTL_SECONDS = 3600
|
||||
|
||||
|
||||
def _ttl_seconds() -> int:
|
||||
try:
|
||||
return int(os.environ.get("SESSION_TTL_SECONDS", DEFAULT_TTL_SECONDS))
|
||||
except ValueError:
|
||||
return DEFAULT_TTL_SECONDS
|
||||
|
||||
|
||||
def _parse_basic(credentials: HTTPBasicCredentials | None) -> tuple[str, str] | None:
|
||||
"""HTTPBasic уже разобрал заголовок; сюда попадают username/password.
|
||||
|
||||
Дополнительно валидируем кодировку: username — ASCII, пароль — UTF-8.
|
||||
"""
|
||||
if credentials is None:
|
||||
return None
|
||||
username = credentials.username
|
||||
password = credentials.password
|
||||
if not username or not password:
|
||||
return None
|
||||
try:
|
||||
username.encode("ascii")
|
||||
except UnicodeEncodeError:
|
||||
return None
|
||||
return username, password
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/sessions",
|
||||
summary="Вход: Basic username:password; выдаёт сессию",
|
||||
response_model=Session,
|
||||
status_code=201,
|
||||
)
|
||||
def create_session(
|
||||
credentials: HTTPBasicCredentials | None = Depends(basic_scheme),
|
||||
) -> Session:
|
||||
parsed = _parse_basic(credentials)
|
||||
if parsed is None:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
username, password = parsed
|
||||
user = storage.verify_credentials(username, password)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
token, expires_at = storage.create_session(user.id, _ttl_seconds())
|
||||
return Session(token=token, token_type="Bearer", expires_at=expires_at, user=user)
|
||||
|
||||
|
||||
@router.delete(
|
||||
path="/sessions/current",
|
||||
summary="Отозвать текущую сессию",
|
||||
status_code=204,
|
||||
)
|
||||
def revoke_session(request: Request) -> None:
|
||||
auth = request.headers.get("Authorization", "")
|
||||
if not auth.lower().startswith("bearer "):
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
token = auth[7:].strip()
|
||||
if not token or storage.get_session_user(token) is None:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
storage.revoke_session(token)
|
||||
return None
|
||||
@@ -0,0 +1,83 @@
|
||||
import base64
|
||||
import json
|
||||
from uuid import UUID
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from ..models.schemas import Chat, ChatPage, CreateChat, User
|
||||
from ..storage.postgres import storage
|
||||
from .security import current_user
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["chats"])
|
||||
|
||||
|
||||
def _encode_cursor(user_id: UUID, chat: Chat) -> str:
|
||||
"""Простой курсор: user_id + id + created_at, base64."""
|
||||
data = {"user_id": str(user_id), "id": str(chat.id), "created_at": chat.created_at.isoformat()}
|
||||
return base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
|
||||
|
||||
|
||||
def _decode_cursor(user_id: UUID, cursor: str) -> tuple:
|
||||
try:
|
||||
data = json.loads(base64.urlsafe_b64decode(cursor.encode()).decode())
|
||||
if data.get("user_id") != str(user_id):
|
||||
raise ValueError("cursor_user_mismatch")
|
||||
return UUID(data["id"]), data["created_at"]
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
|
||||
@router.post(
|
||||
path="",
|
||||
summary="Создать чат",
|
||||
response_model=Chat,
|
||||
status_code=201,
|
||||
)
|
||||
def create_chat(
|
||||
payload: CreateChat,
|
||||
user: User = Depends(current_user),
|
||||
) -> Chat:
|
||||
"""Вызывающий должен входить в member_ids"""
|
||||
user_id = user.id
|
||||
if user_id not in payload.member_ids:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
if len(set(payload.member_ids)) != len(payload.member_ids):
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
try:
|
||||
return storage.create_chat(payload.title, list(payload.member_ids))
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
|
||||
@router.get(
|
||||
path="",
|
||||
summary="Получить список чатов текущего пользователя",
|
||||
response_model=ChatPage,
|
||||
)
|
||||
def list_chats(
|
||||
user: User = Depends(current_user),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
cursor: str | None = None,
|
||||
) -> ChatPage:
|
||||
user_id = user.id
|
||||
chats = storage.list_chats_for_user(user_id)
|
||||
if cursor:
|
||||
cid, ccreated = _decode_cursor(user_id, cursor)
|
||||
chats = [c for c in chats if (c.created_at.isoformat(), str(c.id)) > (ccreated, str(cid))]
|
||||
page = chats[:limit]
|
||||
next_cursor = _encode_cursor(user_id, page[-1]) if len(chats) > limit else None
|
||||
return ChatPage(items=page, next_cursor=next_cursor)
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/{chat_id}",
|
||||
summary="Получить доступный чат по идентификатору",
|
||||
response_model=Chat,
|
||||
)
|
||||
def get_chat(
|
||||
chat_id: UUID,
|
||||
user: User = Depends(current_user),
|
||||
) -> Chat:
|
||||
chat = storage.get_chat(chat_id)
|
||||
if chat is None or user.id not in chat.member_ids:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
return chat
|
||||
@@ -0,0 +1,38 @@
|
||||
from fastapi import APIRouter
|
||||
from ..models.schemas import Health
|
||||
from ..storage import db as _db
|
||||
from ..storage.sessions import _redis_client, _store
|
||||
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/health/live",
|
||||
summary="Проверка жизнеспособности процесса",
|
||||
response_model=Health,
|
||||
)
|
||||
def liveness() -> Health:
|
||||
"""Процесс жив"""
|
||||
return Health(status="ok")
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/health/ready",
|
||||
summary="Проверка готовности принимать трафик",
|
||||
response_model=Health,
|
||||
)
|
||||
def readiness() -> Health:
|
||||
"""200, если PostgreSQL и (в режиме redis) Redis доступны.
|
||||
|
||||
При недоступности зависимости исключение вылетает наверх, и main.py
|
||||
конвертирует его в 503 с телом Error из contracts/openapi.json.
|
||||
"""
|
||||
with _db.connection() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT 1")
|
||||
cur.fetchone()
|
||||
if _store() == "redis":
|
||||
# _redis_client() сам поднимает RuntimeError("redis_unavailable")
|
||||
# при ошибке; main.runtime_error_handler → 503 Error.
|
||||
_redis_client().ping()
|
||||
return Health(status="ok")
|
||||
@@ -0,0 +1,72 @@
|
||||
import base64
|
||||
import json
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from ..models.schemas import CreateMessage, Message, MessagePage, User
|
||||
from ..storage.postgres import storage
|
||||
from .security import current_user
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["messages"])
|
||||
|
||||
|
||||
def _require_member(chat_id: UUID, user_id: UUID):
|
||||
chat = storage.get_chat(chat_id)
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
return chat
|
||||
|
||||
|
||||
def _encode_cursor(chat_id: UUID, message: Message) -> str:
|
||||
data = {"chat_id": str(chat_id), "id": str(message.id), "created_at": message.created_at.isoformat()}
|
||||
return base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
|
||||
|
||||
|
||||
def _decode_cursor(chat_id: UUID, cursor: str) -> tuple:
|
||||
try:
|
||||
data = json.loads(base64.urlsafe_b64decode(cursor.encode()).decode())
|
||||
if data.get("chat_id") != str(chat_id):
|
||||
raise ValueError("cursor_chat_mismatch")
|
||||
return datetime.fromisoformat(data["created_at"]), UUID(data["id"])
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/{chat_id}/messages",
|
||||
summary="Отправить сообщение в чат",
|
||||
response_model=Message,
|
||||
status_code=201,
|
||||
)
|
||||
def create_message(
|
||||
chat_id: UUID,
|
||||
payload: CreateMessage,
|
||||
user: User = Depends(current_user),
|
||||
) -> Message:
|
||||
_require_member(chat_id, user.id)
|
||||
if not payload.text.strip():
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
return storage.add_message(chat_id, user.id, payload.text)
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/{chat_id}/messages",
|
||||
summary="Получить историю сообщений чата",
|
||||
response_model=MessagePage,
|
||||
)
|
||||
def list_messages(
|
||||
chat_id: UUID,
|
||||
user: User = Depends(current_user),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
cursor: str | None = None,
|
||||
) -> MessagePage:
|
||||
"""Keyset-пагинация в SQL: (created_at, id) по возрастанию, без полного scan истории."""
|
||||
_require_member(chat_id, user.id)
|
||||
after = _decode_cursor(chat_id, cursor) if cursor else None
|
||||
# Берём limit+1, чтобы понять, есть ли следующая страница
|
||||
rows = storage.list_messages_page(chat_id, limit + 1, after=after)
|
||||
has_more = len(rows) > limit
|
||||
items = rows[:limit]
|
||||
next_cursor = _encode_cursor(chat_id, items[-1]) if has_more and items else None
|
||||
return MessagePage(items=items, next_cursor=next_cursor)
|
||||
@@ -0,0 +1,24 @@
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import HTTPException, Security
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
|
||||
from ..models.schemas import User
|
||||
from ..storage.postgres import storage
|
||||
|
||||
bearer_scheme = HTTPBearer(auto_error=False, scheme_name="bearerAuth")
|
||||
|
||||
|
||||
def current_user(
|
||||
credentials: HTTPAuthorizationCredentials | None = Security(bearer_scheme),
|
||||
) -> User:
|
||||
"""Достаёт Bearer-токен и возвращает владельца сессии.
|
||||
|
||||
Basic на бизнес-endpoint не принимается, X-User-Id игнорируется.
|
||||
"""
|
||||
if credentials is None or credentials.scheme.lower() != "bearer":
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
user = storage.get_session_user(credentials.credentials)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
return user
|
||||
@@ -0,0 +1,30 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from ..models.schemas import CreateUser, User
|
||||
from ..storage.postgres import storage
|
||||
from .security import current_user
|
||||
|
||||
router = APIRouter(prefix="/api/v1", tags=["users"])
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/users",
|
||||
summary="Создать пользователя",
|
||||
response_model=User,
|
||||
status_code=201,
|
||||
)
|
||||
def register_user(payload: CreateUser) -> User:
|
||||
"""Публичная регистрация."""
|
||||
try:
|
||||
return storage.create_user(payload.username, payload.display_name, payload.password)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=409, detail="conflict")
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/users/me",
|
||||
summary="Получить текущего пользователя",
|
||||
response_model=User,
|
||||
)
|
||||
def current_user_me(user: User = Depends(current_user)) -> User:
|
||||
"""Текущий пользователь по Bearer-сессии."""
|
||||
return user
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.openapi.utils import get_openapi
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
import psycopg
|
||||
import uvicorn
|
||||
from .api import auth, chats, health, messages, users
|
||||
from .storage.db import init_schema, init_pool, close_pool
|
||||
|
||||
|
||||
# --- Логирование: структурированный stdout, без содержимого сообщений ---
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
stream=sys.stdout,
|
||||
)
|
||||
logger = logging.getLogger("app")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
init_pool() # пул соединений PostgreSQL с таймаутами (уровень 4)
|
||||
init_schema() # создать таблицы в БД если их ещё нет
|
||||
logger.info(
|
||||
"event=startup app_env=%s session_store=%s",
|
||||
os.environ.get("APP_ENV", "lab"),
|
||||
os.environ.get("SESSION_STORE", "postgres"),
|
||||
)
|
||||
yield
|
||||
close_pool()
|
||||
logger.info("event=shutdown_complete")
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUCI Messenger — lab2",
|
||||
version="1.2.0",
|
||||
lifespan=lifespan,
|
||||
swagger_ui_parameters={"persistAuthorization": True},
|
||||
)
|
||||
|
||||
|
||||
def custom_openapi():
|
||||
if app.openapi_schema:
|
||||
return app.openapi_schema
|
||||
schema = get_openapi(title=app.title, version=app.version, routes=app.routes)
|
||||
app.openapi_schema = schema
|
||||
return schema
|
||||
|
||||
|
||||
app.openapi = custom_openapi
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def observability_middleware(request: Request, call_next):
|
||||
"""X-Request-Id во всех ответах + структурный лог без тела сообщений."""
|
||||
request_id = request.headers.get("X-Request-Id") or uuid.uuid4().hex
|
||||
request.state.request_id = request_id
|
||||
started = time.monotonic()
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
duration_ms = round((time.monotonic() - started) * 1000, 2)
|
||||
# Логируем только метаданные: метод, путь без query, статус, длительность, request_id
|
||||
path = request.url.path
|
||||
logger.info(
|
||||
"event=http method=%s path=%s status=%s duration_ms=%s request_id=%s",
|
||||
request.method,
|
||||
path,
|
||||
response.status_code,
|
||||
duration_ms,
|
||||
request_id,
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
# Словарь HTTP-кодов → кодов ошибок из контракта
|
||||
_ERROR_CODES = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
404: "not_found",
|
||||
409: "conflict",
|
||||
413: "payload_too_large",
|
||||
415: "unsupported_media_type",
|
||||
429: "rate_limited",
|
||||
503: "unavailable",
|
||||
500: "internal_error",
|
||||
}
|
||||
|
||||
|
||||
def _unauthorized_challenge(path: str) -> str:
|
||||
"""Basic — только для POST /api/v1/auth/sessions; остальное — Bearer."""
|
||||
if path == "/api/v1/auth/sessions":
|
||||
return 'Basic realm="messenger", charset="UTF-8"'
|
||||
return 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
def _error_response(
|
||||
status_code: int, message: str, request_id: str, path: str = ""
|
||||
) -> JSONResponse:
|
||||
code = _ERROR_CODES.get(status_code, "internal_error")
|
||||
headers = {}
|
||||
if status_code == 401:
|
||||
headers["WWW-Authenticate"] = _unauthorized_challenge(path)
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content={"error": {"code": code, "message": message, "request_id": request_id}},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
message = exc.detail if isinstance(exc.detail, str) else "Ошибка"
|
||||
return _error_response(exc.status_code, message, request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
return _error_response(400, "Неверный запрос", request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(psycopg.OperationalError)
|
||||
async def db_unavailable_handler(request: Request, exc: psycopg.OperationalError):
|
||||
"""PostgreSQL недоступен → 503 unavailable, без внутренних деталей."""
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
logger.error(
|
||||
"event=db_unavailable type=%s request_id=%s",
|
||||
type(exc).__name__,
|
||||
request_id,
|
||||
)
|
||||
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(RuntimeError)
|
||||
async def runtime_error_handler(request: Request, exc: RuntimeError):
|
||||
"""Redis недоступен или конфигурация битая.
|
||||
|
||||
sessions.py поднимает RuntimeError("redis_unavailable") при ошибке Redis.
|
||||
Отдаём 503, чтобы смоук/resilience видели корректный unavailable,
|
||||
а не внутреннюю 500.
|
||||
"""
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
text = str(exc)
|
||||
if "redis_unavailable" in text:
|
||||
logger.error("event=redis_unavailable request_id=%s", request_id)
|
||||
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
|
||||
logger.error(
|
||||
"event=runtime_error type=%s request_id=%s",
|
||||
type(exc).__name__,
|
||||
request_id,
|
||||
)
|
||||
return _error_response(500, "Внутренняя ошибка", request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_exception_handler(request: Request, exc: Exception):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
# Внутренние детали не раскрываем; пишем в лог без секретов
|
||||
logger.error("event=unhandled_exception type=%s request_id=%s", type(exc).__name__, request_id)
|
||||
return _error_response(500, "Внутренняя ошибка", request_id, request.url.path)
|
||||
|
||||
|
||||
app.include_router(health.router)
|
||||
app.include_router(auth.router)
|
||||
app.include_router(users.router)
|
||||
app.include_router(chats.router)
|
||||
app.include_router(messages.router)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
config = uvicorn.Config(
|
||||
"app.main:app",
|
||||
host="0.0.0.0",
|
||||
port=8080,
|
||||
log_level="info",
|
||||
)
|
||||
server = uvicorn.Server(config)
|
||||
|
||||
def _handle_sigterm(signum, frame):
|
||||
"""SIGTERM: логируем и инициируем graceful shutdown uvicorn.
|
||||
|
||||
server.should_exit=True заставляет uvicorn закрыть слушающий сокет
|
||||
(healthcheck перестаёт отвечать) и корректно завершить процесс.
|
||||
"""
|
||||
logger.info("event=sigterm_received signal=%s", signum)
|
||||
server.should_exit = True
|
||||
|
||||
signal.signal(signal.SIGTERM, _handle_sigterm)
|
||||
server.run()
|
||||
@@ -0,0 +1,107 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Optional
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_serializer
|
||||
|
||||
|
||||
def _to_z(dt: datetime) -> str:
|
||||
"""RFC 3339 UTC с Z, как требует contracts/README.md."""
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
dt = dt.astimezone(timezone.utc)
|
||||
return dt.isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
class Health(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
status: str
|
||||
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
username: str = Field(pattern=r"^[a-z0-9_]{3,32}$")
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: datetime
|
||||
|
||||
@field_serializer("created_at")
|
||||
def _ser_created_at(self, dt: datetime) -> str:
|
||||
return _to_z(dt)
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: List[UUID] = Field(min_length=1, max_length=100)
|
||||
|
||||
|
||||
class Chat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: UUID
|
||||
title: str
|
||||
member_ids: List[UUID]
|
||||
created_at: datetime
|
||||
|
||||
@field_serializer("created_at")
|
||||
def _ser_created_at(self, dt: datetime) -> str:
|
||||
return _to_z(dt)
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
text: str = Field(min_length=1, max_length=4000)
|
||||
|
||||
|
||||
class Message(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
sender_id: UUID
|
||||
text: str
|
||||
created_at: datetime
|
||||
|
||||
@field_serializer("created_at")
|
||||
def _ser_created_at(self, dt: datetime) -> str:
|
||||
return _to_z(dt)
|
||||
|
||||
|
||||
class ChatPage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
items: List[Chat]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
class MessagePage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
items: List[Message]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
class Session(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
token: str
|
||||
token_type: str = "Bearer"
|
||||
expires_at: datetime
|
||||
user: User
|
||||
|
||||
@field_serializer("expires_at")
|
||||
def _ser_expires_at(self, dt: datetime) -> str:
|
||||
return _to_z(dt)
|
||||
|
||||
|
||||
class ErrorBody(BaseModel):
|
||||
code: str
|
||||
message: str
|
||||
request_id: str
|
||||
|
||||
|
||||
class ErrorResponse(BaseModel):
|
||||
error: ErrorBody
|
||||
@@ -0,0 +1,97 @@
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
from typing import Iterator
|
||||
|
||||
import psycopg
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
|
||||
_pool: ConnectionPool | None = None
|
||||
|
||||
|
||||
def _dsn() -> str:
|
||||
dsn = os.environ.get("DATABASE_URL")
|
||||
if not dsn:
|
||||
raise RuntimeError("DATABASE_URL is not set")
|
||||
return dsn
|
||||
|
||||
|
||||
def init_pool() -> None:
|
||||
"""Ограниченный пул соединений с таймаутами. Вызывается один раз на старте."""
|
||||
global _pool
|
||||
if _pool is not None:
|
||||
return
|
||||
_pool = ConnectionPool(
|
||||
conninfo=_dsn(),
|
||||
min_size=2,
|
||||
max_size=10,
|
||||
timeout=5.0,
|
||||
max_idle=300.0,
|
||||
kwargs={"options": "-c statement_timeout=5000"},
|
||||
open=True,
|
||||
)
|
||||
|
||||
|
||||
def close_pool() -> None:
|
||||
global _pool
|
||||
if _pool is not None:
|
||||
_pool.close()
|
||||
_pool = None
|
||||
|
||||
|
||||
@contextmanager
|
||||
def connection() -> Iterator[psycopg.Connection]:
|
||||
"""Соединение из пула; autocommit=False для явных транзакций."""
|
||||
if _pool is None:
|
||||
init_pool()
|
||||
assert _pool is not None
|
||||
with _pool.connection() as conn:
|
||||
yield conn
|
||||
|
||||
|
||||
SCHEMA_SQL = """
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id UUID PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
display_name TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS chats (
|
||||
id UUID PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS chat_members (
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
text TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_chat_created
|
||||
ON messages (chat_id, created_at, id);
|
||||
|
||||
-- sessions остаются как fallback, если SESSION_STORE=postgres.
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token TEXT PRIMARY KEY,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expires_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
def init_schema() -> None:
|
||||
"""Идемпотентная миграция: запускается на старте приложения."""
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(SCHEMA_SQL)
|
||||
conn.commit()
|
||||
@@ -0,0 +1,177 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
import threading
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Dict, List, Optional
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from ..models.schemas import Chat, Message, User
|
||||
|
||||
|
||||
def now_utc() -> datetime:
|
||||
"""Время сервера в UTC с суффиксом Z на выходе."""
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
# --- Password KDF (stdlib scrypt) ---
|
||||
_SCRYPT_N = 2 ** 14
|
||||
_SCRYPT_R = 8
|
||||
_SCRYPT_P = 1
|
||||
_SCRYPT_DKLEN = 32
|
||||
|
||||
|
||||
def _hash_password(password: str) -> str:
|
||||
salt = secrets.token_bytes(16)
|
||||
dk = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=salt,
|
||||
n=_SCRYPT_N,
|
||||
r=_SCRYPT_R,
|
||||
p=_SCRYPT_P,
|
||||
dklen=_SCRYPT_DKLEN,
|
||||
)
|
||||
return "scrypt$%d$%d$%d$%s$%s" % (
|
||||
_SCRYPT_N, _SCRYPT_R, _SCRYPT_P,
|
||||
salt.hex(), dk.hex(),
|
||||
)
|
||||
|
||||
|
||||
def _verify_password(password: str, stored: str) -> bool:
|
||||
try:
|
||||
scheme, n, r, p, salt_hex, dk_hex = stored.split("$")
|
||||
if scheme != "scrypt":
|
||||
return False
|
||||
dk = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=bytes.fromhex(salt_hex),
|
||||
n=int(n), r=int(r), p=int(p),
|
||||
dklen=len(bytes.fromhex(dk_hex)),
|
||||
)
|
||||
return hmac.compare_digest(dk.hex(), dk_hex)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
class MemoryStorage:
|
||||
"""Потокобезопасное In-memory хранилище пользователей, чатов, сообщений и сессий. Все данные исчезают при перезапуске процесса"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.RLock()
|
||||
self._users: Dict[UUID, User] = {}
|
||||
self._usernames: Dict[str, UUID] = {}
|
||||
self._passwords: Dict[UUID, str] = {}
|
||||
self._chats: Dict[UUID, Chat] = {}
|
||||
self._messages: Dict[UUID, List[Message]] = {}
|
||||
# token -> (user_id, expires_at)
|
||||
self._sessions: Dict[str, tuple] = {}
|
||||
|
||||
# ---------- Пользователи ----------
|
||||
def create_user(self, username: str, display_name: str, password: str) -> User:
|
||||
with self._lock:
|
||||
if username in self._usernames:
|
||||
raise ValueError("username_taken")
|
||||
user = User(
|
||||
id=uuid4(),
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
created_at=now_utc(),
|
||||
)
|
||||
self._users[user.id] = user
|
||||
self._usernames[username] = user.id
|
||||
self._passwords[user.id] = _hash_password(password)
|
||||
return user
|
||||
|
||||
def get_user(self, user_id: UUID) -> Optional[User]:
|
||||
with self._lock:
|
||||
return self._users.get(user_id)
|
||||
|
||||
def get_user_by_username(self, username: str) -> Optional[User]:
|
||||
with self._lock:
|
||||
uid = self._usernames.get(username)
|
||||
return self._users.get(uid) if uid else None
|
||||
|
||||
def verify_credentials(self, username: str, password: str) -> Optional[User]:
|
||||
with self._lock:
|
||||
uid = self._usernames.get(username)
|
||||
if uid is None:
|
||||
return None
|
||||
stored = self._passwords.get(uid)
|
||||
if not stored or not _verify_password(password, stored):
|
||||
return None
|
||||
return self._users.get(uid)
|
||||
|
||||
# ---------- Сессии ----------
|
||||
def create_session(self, user_id: UUID, ttl_seconds: int) -> tuple:
|
||||
with self._lock:
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_at = now_utc() + timedelta(seconds=ttl_seconds)
|
||||
self._sessions[token] = (user_id, expires_at)
|
||||
return token, expires_at
|
||||
|
||||
def get_session_user(self, token: str) -> Optional[User]:
|
||||
with self._lock:
|
||||
entry = self._sessions.get(token)
|
||||
if entry is None:
|
||||
return None
|
||||
user_id, expires_at = entry
|
||||
if expires_at <= now_utc():
|
||||
self._sessions.pop(token, None)
|
||||
return None
|
||||
return self._users.get(user_id)
|
||||
|
||||
def revoke_session(self, token: str) -> None:
|
||||
with self._lock:
|
||||
self._sessions.pop(token, None)
|
||||
|
||||
# ---------- Чаты ----------
|
||||
def create_chat(self, title: str, member_ids: List[UUID]) -> Chat:
|
||||
with self._lock:
|
||||
for uid in member_ids:
|
||||
if uid not in self._users:
|
||||
raise ValueError("unknown_member")
|
||||
chat = Chat(
|
||||
id=uuid4(),
|
||||
title=title,
|
||||
member_ids=list(member_ids),
|
||||
created_at=now_utc(),
|
||||
)
|
||||
self._chats[chat.id] = chat
|
||||
self._messages[chat.id] = []
|
||||
return chat
|
||||
|
||||
def get_chat(self, chat_id: UUID) -> Optional[Chat]:
|
||||
with self._lock:
|
||||
return self._chats.get(chat_id)
|
||||
|
||||
def list_chats_for_user(self, user_id: UUID) -> List[Chat]:
|
||||
with self._lock:
|
||||
chats = [c for c in self._chats.values() if user_id in c.member_ids]
|
||||
chats.sort(key=lambda c: (c.created_at, str(c.id)))
|
||||
return chats
|
||||
|
||||
# ---------- Сообщения ----------
|
||||
def add_message(self, chat_id: UUID, sender_id: UUID, text: str) -> Message:
|
||||
"""Улучшение Трека 1: список сообщений хранится уже отсортированным.
|
||||
created_at монотонен в пределах одного процесса, поэтому append
|
||||
сохраняет порядок (created_at, id) по возрастанию — сортировка на
|
||||
чтении не нужна. При конкурентных вставках под RLock порядок
|
||||
сохраняется, но монотонность часов не гарантируется контрактом."""
|
||||
with self._lock:
|
||||
message = Message(
|
||||
id=uuid4(),
|
||||
chat_id=chat_id,
|
||||
sender_id=sender_id,
|
||||
text=text,
|
||||
created_at=now_utc(),
|
||||
)
|
||||
self._messages.setdefault(chat_id, []).append(message)
|
||||
return message
|
||||
|
||||
def list_messages(self, chat_id: UUID) -> List[Message]:
|
||||
with self._lock:
|
||||
# Без пересортировки: список уже в порядке (created_at, id).
|
||||
return list(self._messages.get(chat_id, []))
|
||||
|
||||
|
||||
storage = MemoryStorage() # единственный экземпляр хранилища на процесс
|
||||
@@ -0,0 +1,267 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Optional
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from ..models.schemas import Chat, Message, User
|
||||
from .db import connection
|
||||
from .sessions import (
|
||||
create_session as _sess_create,
|
||||
get_session_user as _sess_get,
|
||||
revoke_session as _sess_revoke,
|
||||
)
|
||||
|
||||
|
||||
def now_utc() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
# --- Password KDF (stdlib scrypt) ---
|
||||
_SCRYPT_N = 2 ** 14
|
||||
_SCRYPT_R = 8
|
||||
_SCRYPT_P = 1
|
||||
_SCRYPT_DKLEN = 32
|
||||
|
||||
|
||||
def _hash_password(password: str) -> str:
|
||||
salt = secrets.token_bytes(16)
|
||||
dk = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=salt,
|
||||
n=_SCRYPT_N, r=_SCRYPT_R, p=_SCRYPT_P, dklen=_SCRYPT_DKLEN,
|
||||
)
|
||||
return "scrypt$%d$%d$%d$%s$%s" % (
|
||||
_SCRYPT_N, _SCRYPT_R, _SCRYPT_P, salt.hex(), dk.hex(),
|
||||
)
|
||||
|
||||
|
||||
def _verify_password(password: str, stored: str) -> bool:
|
||||
try:
|
||||
scheme, n, r, p, salt_hex, dk_hex = stored.split("$")
|
||||
if scheme != "scrypt":
|
||||
return False
|
||||
dk = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=bytes.fromhex(salt_hex),
|
||||
n=int(n), r=int(r), p=int(p),
|
||||
dklen=len(bytes.fromhex(dk_hex)),
|
||||
)
|
||||
return hmac.compare_digest(dk.hex(), dk_hex)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _row_to_user(row) -> User:
|
||||
return User(id=row[0], username=row[1], display_name=row[2], created_at=row[3])
|
||||
|
||||
|
||||
def _row_to_chat(row, member_ids: List[UUID]) -> Chat:
|
||||
return Chat(id=row[0], title=row[1], member_ids=member_ids, created_at=row[2])
|
||||
|
||||
|
||||
def _row_to_message(row) -> Message:
|
||||
return Message(
|
||||
id=row[0], chat_id=row[1], sender_id=row[2],
|
||||
text=row[3], created_at=row[4],
|
||||
)
|
||||
|
||||
|
||||
class PostgresStorage:
|
||||
"""Потокобезопасная обёртка; параллелизм обеспечивает PostgreSQL."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.RLock()
|
||||
|
||||
# ---------- Пользователи ----------
|
||||
def create_user(self, username: str, display_name: str, password: str) -> User:
|
||||
with self._lock, connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
# SELECT-проверка + INSERT в одной транзакции; уникальный индекс
|
||||
# users.username отсекает гонку на уровне БД (UniqueViolation).
|
||||
cur.execute("SELECT 1 FROM users WHERE username = %s", (username,))
|
||||
if cur.fetchone() is not None:
|
||||
raise ValueError("username_taken")
|
||||
user = User(
|
||||
id=uuid4(), username=username,
|
||||
display_name=display_name, created_at=now_utc(),
|
||||
)
|
||||
try:
|
||||
cur.execute(
|
||||
"INSERT INTO users (id, username, display_name, password_hash, created_at)"
|
||||
" VALUES (%s, %s, %s, %s, %s)",
|
||||
(user.id, user.username, user.display_name,
|
||||
_hash_password(password), user.created_at),
|
||||
)
|
||||
except Exception as exc:
|
||||
# Параллельная регистрация того же username: уникальный индекс
|
||||
# выбросил UniqueViolation — превращаем в доменную ошибку.
|
||||
if exc.__class__.__name__ == "UniqueViolation":
|
||||
raise ValueError("username_taken")
|
||||
raise
|
||||
conn.commit()
|
||||
return user
|
||||
|
||||
def get_user(self, user_id: UUID) -> Optional[User]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
|
||||
(user_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _row_to_user(row) if row else None
|
||||
|
||||
def get_user_by_username(self, username: str) -> Optional[User]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE username = %s",
|
||||
(username,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _row_to_user(row) if row else None
|
||||
|
||||
def verify_credentials(self, username: str, password: str) -> Optional[User]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, created_at, password_hash"
|
||||
" FROM users WHERE username = %s",
|
||||
(username,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
if not _verify_password(password, row[4]):
|
||||
return None
|
||||
return _row_to_user(row[:4])
|
||||
|
||||
# ---------- Сессии (Redis или PostgreSQL — см. storage/sessions.py) ----------
|
||||
# Тонкие делегаты: роутеры продолжают вызывать storage.create_session(...),
|
||||
# storage.get_session_user(...), storage.revoke_session(...) без изменений.
|
||||
def create_session(self, user_id: UUID, ttl_seconds: int) -> tuple:
|
||||
return _sess_create(user_id, ttl_seconds)
|
||||
|
||||
def get_session_user(self, token: str) -> Optional[User]:
|
||||
return _sess_get(token)
|
||||
|
||||
def revoke_session(self, token: str) -> None:
|
||||
_sess_revoke(token)
|
||||
|
||||
# ---------- Чаты ----------
|
||||
def create_chat(self, title: str, member_ids: List[UUID]) -> Chat:
|
||||
with self._lock, connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
# проверяем всех участников
|
||||
cur.execute(
|
||||
"SELECT id FROM users WHERE id = ANY(%s)",
|
||||
(list(member_ids),),
|
||||
)
|
||||
found = {r[0] for r in cur.fetchall()}
|
||||
if len(found) != len(set(member_ids)):
|
||||
raise ValueError("unknown_member")
|
||||
chat = Chat(
|
||||
id=uuid4(), title=title,
|
||||
member_ids=list(member_ids), created_at=now_utc(),
|
||||
)
|
||||
cur.execute(
|
||||
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
|
||||
(chat.id, chat.title, chat.created_at),
|
||||
)
|
||||
cur.executemany(
|
||||
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
|
||||
[(chat.id, uid) for uid in member_ids],
|
||||
)
|
||||
conn.commit()
|
||||
return chat
|
||||
|
||||
def get_chat(self, chat_id: UUID) -> Optional[Chat]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, title, created_at FROM chats WHERE id = %s",
|
||||
(chat_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
cur.execute(
|
||||
"SELECT user_id FROM chat_members WHERE chat_id = %s", (chat_id,),
|
||||
)
|
||||
members = [r[0] for r in cur.fetchall()]
|
||||
return _row_to_chat(row, members)
|
||||
|
||||
def list_chats_for_user(self, user_id: UUID) -> List[Chat]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT c.id, c.title, c.created_at FROM chats c"
|
||||
" JOIN chat_members m ON m.chat_id = c.id"
|
||||
" WHERE m.user_id = %s ORDER BY c.created_at, c.id",
|
||||
(user_id,),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
chats = []
|
||||
for row in rows:
|
||||
cur.execute(
|
||||
"SELECT user_id FROM chat_members WHERE chat_id = %s", (row[0],),
|
||||
)
|
||||
members = [r[0] for r in cur.fetchall()]
|
||||
chats.append(_row_to_chat(row, members))
|
||||
return chats
|
||||
|
||||
# ---------- Сообщения ----------
|
||||
def add_message(self, chat_id: UUID, sender_id: UUID, text: str) -> Message:
|
||||
with self._lock, connection() as conn:
|
||||
message = Message(
|
||||
id=uuid4(), chat_id=chat_id, sender_id=sender_id,
|
||||
text=text, created_at=now_utc(),
|
||||
)
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at)"
|
||||
" VALUES (%s, %s, %s, %s, %s)",
|
||||
(message.id, message.chat_id, message.sender_id,
|
||||
message.text, message.created_at),
|
||||
)
|
||||
conn.commit()
|
||||
return message
|
||||
|
||||
def list_messages(self, chat_id: UUID) -> List[Message]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, sender_id, text, created_at FROM messages"
|
||||
" WHERE chat_id = %s ORDER BY created_at, id",
|
||||
(chat_id,),
|
||||
)
|
||||
return [_row_to_message(r) for r in cur.fetchall()]
|
||||
|
||||
def list_messages_page(
|
||||
self,
|
||||
chat_id: UUID,
|
||||
limit: int,
|
||||
after: Optional[tuple] = None,
|
||||
) -> List[Message]:
|
||||
"""Keyset-пагинация в SQL
|
||||
|
||||
after = (created_at, id) последней записи предыдущей страницы или None.
|
||||
Запрос использует индекс idx_messages_chat_created (chat_id, created_at, id)
|
||||
и не делает полный scan всей истории на каждую страницу.
|
||||
"""
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
if after is None:
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, sender_id, text, created_at FROM messages"
|
||||
" WHERE chat_id = %s ORDER BY created_at, id LIMIT %s",
|
||||
(chat_id, limit),
|
||||
)
|
||||
else:
|
||||
after_ts, after_id = after
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, sender_id, text, created_at FROM messages"
|
||||
" WHERE chat_id = %s AND (created_at, id) > (%s, %s)"
|
||||
" ORDER BY created_at, id LIMIT %s",
|
||||
(chat_id, after_ts, after_id, limit),
|
||||
)
|
||||
return [_row_to_message(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
storage = PostgresStorage() # единственный экземпляр на процесс
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Хранилище сессий. 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
|
||||
Reference in New Issue
Block a user