forked from mtusi2026/mtusi2026lab4
feat: перенос структуры приложения из третьей лабы
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Messenger application package."""
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError
|
||||
|
||||
_hasher = PasswordHasher()
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""Хэширует пароль с использованием Argon2id."""
|
||||
return _hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(hash_str: str, password: str) -> bool:
|
||||
"""Проверяет пароль на соответствие хэшу Argon2id."""
|
||||
try:
|
||||
return _hasher.verify(hash_str, password)
|
||||
except VerifyMismatchError:
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def generate_session_token() -> str:
|
||||
"""Генерирует криптографически стойкий непрозрачный токен сессии (256 бит энтропии)."""
|
||||
return secrets.token_urlsafe(32)
|
||||
@@ -0,0 +1,36 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import socket
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _get_val(env_name: str, file_env_name: str | None = None, default: str = "") -> str:
|
||||
if file_env_name and file_env_name in os.environ:
|
||||
file_path = Path(os.environ[file_env_name])
|
||||
if file_path.is_file():
|
||||
return file_path.read_text(encoding="utf-8").strip()
|
||||
return os.getenv(env_name, default)
|
||||
|
||||
|
||||
APP_HOST: str = os.getenv("APP_HOST", "0.0.0.0")
|
||||
APP_PORT: int = int(os.getenv("APP_PORT", "8080"))
|
||||
APP_ENV: str = os.getenv("APP_ENV", "lab")
|
||||
LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO")
|
||||
|
||||
SESSION_TTL_SECONDS: int = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
SESSION_STORE: str = os.getenv("SESSION_STORE", "redis").lower()
|
||||
INSTANCE_ID: str = os.getenv("INSTANCE_ID") or socket.gethostname() or "api-1"
|
||||
IDEMPOTENCY_TTL_SECONDS: int = int(os.getenv("IDEMPOTENCY_TTL_SECONDS", "86400"))
|
||||
|
||||
DATABASE_URL: str = _get_val(
|
||||
"DATABASE_URL",
|
||||
"DATABASE_URL_FILE",
|
||||
"postgresql://postgres:postgres@postgres:5432/messenger",
|
||||
)
|
||||
|
||||
CACHE_URL: str = _get_val(
|
||||
"CACHE_URL",
|
||||
"CACHE_URL_FILE",
|
||||
"redis://redis:6379/0",
|
||||
)
|
||||
@@ -0,0 +1,30 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import Depends, Header, Request
|
||||
|
||||
from app.errors import UnauthorizedError
|
||||
from app.schemas import UserResponse
|
||||
from app.storage import storage
|
||||
|
||||
|
||||
async def get_current_token(
|
||||
authorization: str | None = Header(default=None, alias="Authorization"),
|
||||
) -> str:
|
||||
if not authorization or not authorization.strip():
|
||||
raise UnauthorizedError("Отсутствует заголовок Authorization")
|
||||
|
||||
parts = authorization.strip().split(maxsplit=1)
|
||||
if len(parts) != 2 or parts[0].lower() != "bearer":
|
||||
raise UnauthorizedError("Неверная схема авторизации (ожидается Bearer)")
|
||||
|
||||
token = parts[1].strip()
|
||||
if not token:
|
||||
raise UnauthorizedError("Пустой Bearer токен")
|
||||
return token
|
||||
|
||||
|
||||
async def get_current_user(token: str = Depends(get_current_token)) -> UserResponse:
|
||||
user = await storage.get_session_user(token)
|
||||
if not user:
|
||||
raise UnauthorizedError("Недействительная или истекшая сессия")
|
||||
return user
|
||||
+223
@@ -0,0 +1,223 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
import asyncpg
|
||||
from fastapi import FastAPI, Request, status
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
import redis.exceptions
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from app.config import INSTANCE_ID
|
||||
from app.schemas import ErrorCode, ErrorDetail, ErrorResponse
|
||||
|
||||
|
||||
class StorageError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class UnavailableError(StorageError):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidRequestError(StorageError):
|
||||
pass
|
||||
|
||||
|
||||
class NotFoundError(StorageError):
|
||||
pass
|
||||
|
||||
|
||||
class ConflictError(StorageError):
|
||||
pass
|
||||
|
||||
|
||||
class UnauthorizedError(StorageError):
|
||||
pass
|
||||
|
||||
|
||||
logger = logging.getLogger("app.errors")
|
||||
|
||||
|
||||
def get_request_id(request: Request) -> str:
|
||||
req_id = getattr(request.state, "request_id", None)
|
||||
if not req_id:
|
||||
req_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
|
||||
return req_id
|
||||
|
||||
|
||||
def make_error_response(
|
||||
status_code: int,
|
||||
code: ErrorCode,
|
||||
message: str,
|
||||
request_id: str,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> JSONResponse:
|
||||
payload = ErrorResponse(
|
||||
error=ErrorDetail(code=code, message=message, request_id=request_id)
|
||||
).model_dump()
|
||||
resp_headers = {
|
||||
"X-Request-Id": request_id,
|
||||
"X-Instance-Id": INSTANCE_ID,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
if headers:
|
||||
resp_headers.update(headers)
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content=payload,
|
||||
headers=resp_headers,
|
||||
)
|
||||
|
||||
|
||||
def register_error_handlers(app: FastAPI) -> None:
|
||||
@app.exception_handler(InvalidRequestError)
|
||||
async def invalid_request_handler(
|
||||
request: Request, exc: InvalidRequestError
|
||||
) -> JSONResponse:
|
||||
req_id = get_request_id(request)
|
||||
return make_error_response(
|
||||
status.HTTP_400_BAD_REQUEST, ErrorCode.INVALID_REQUEST, str(exc), req_id
|
||||
)
|
||||
|
||||
@app.exception_handler(UnauthorizedError)
|
||||
async def unauthorized_handler(
|
||||
request: Request, exc: UnauthorizedError
|
||||
) -> JSONResponse:
|
||||
req_id = get_request_id(request)
|
||||
scheme = (
|
||||
'Basic realm="messenger", charset="UTF-8"'
|
||||
if request.url.path == "/api/v1/auth/sessions"
|
||||
else 'Bearer realm="messenger"'
|
||||
)
|
||||
return make_error_response(
|
||||
status.HTTP_401_UNAUTHORIZED,
|
||||
ErrorCode.UNAUTHORIZED,
|
||||
str(exc),
|
||||
req_id,
|
||||
headers={"WWW-Authenticate": scheme},
|
||||
)
|
||||
|
||||
@app.exception_handler(NotFoundError)
|
||||
async def not_found_handler(request: Request, exc: NotFoundError) -> JSONResponse:
|
||||
req_id = get_request_id(request)
|
||||
return make_error_response(
|
||||
status.HTTP_404_NOT_FOUND, ErrorCode.NOT_FOUND, str(exc), req_id
|
||||
)
|
||||
|
||||
@app.exception_handler(ConflictError)
|
||||
async def conflict_handler(request: Request, exc: ConflictError) -> JSONResponse:
|
||||
req_id = get_request_id(request)
|
||||
return make_error_response(
|
||||
status.HTTP_409_CONFLICT, ErrorCode.CONFLICT, str(exc), req_id
|
||||
)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error_handler(
|
||||
request: Request, exc: RequestValidationError
|
||||
) -> JSONResponse:
|
||||
req_id = get_request_id(request)
|
||||
errors = exc.errors()
|
||||
messages = []
|
||||
for err in errors:
|
||||
loc = ".".join(str(x) for x in err.get("loc", []) if x != "body")
|
||||
msg = err.get("msg", "invalid")
|
||||
messages.append(f"{loc}: {msg}" if loc else msg)
|
||||
detail_msg = "; ".join(messages) or "Некорректное тело запроса или параметры"
|
||||
return make_error_response(
|
||||
status.HTTP_400_BAD_REQUEST, ErrorCode.INVALID_REQUEST, detail_msg, req_id
|
||||
)
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(
|
||||
request: Request, exc: StarletteHTTPException
|
||||
) -> JSONResponse:
|
||||
req_id = get_request_id(request)
|
||||
code = ErrorCode.INTERNAL_ERROR
|
||||
extra_headers: dict[str, str] = {}
|
||||
if exc.status_code == 400:
|
||||
code = ErrorCode.INVALID_REQUEST
|
||||
elif exc.status_code == 401:
|
||||
code = ErrorCode.UNAUTHORIZED
|
||||
scheme = (
|
||||
'Basic realm="messenger", charset="UTF-8"'
|
||||
if request.url.path == "/api/v1/auth/sessions"
|
||||
else 'Bearer realm="messenger"'
|
||||
)
|
||||
extra_headers["WWW-Authenticate"] = scheme
|
||||
elif exc.status_code == 404:
|
||||
code = ErrorCode.NOT_FOUND
|
||||
elif exc.status_code == 409:
|
||||
code = ErrorCode.CONFLICT
|
||||
elif exc.status_code == 413:
|
||||
code = ErrorCode.PAYLOAD_TOO_LARGE
|
||||
elif exc.status_code == 415:
|
||||
code = ErrorCode.UNSUPPORTED_MEDIA_TYPE
|
||||
elif exc.status_code == 429:
|
||||
code = ErrorCode.RATE_LIMITED
|
||||
elif exc.status_code == 503:
|
||||
code = ErrorCode.UNAVAILABLE
|
||||
|
||||
msg = exc.detail if isinstance(exc.detail, str) else "HTTP ошибка"
|
||||
return make_error_response(
|
||||
exc.status_code, code, msg, req_id, headers=extra_headers
|
||||
)
|
||||
|
||||
async def dependency_unavailable_handler(
|
||||
request: Request, exc: Exception
|
||||
) -> JSONResponse:
|
||||
req_id = get_request_id(request)
|
||||
logger.warning(
|
||||
"Upstream storage dependency unavailable for request %s: %s",
|
||||
req_id,
|
||||
exc,
|
||||
)
|
||||
return make_error_response(
|
||||
status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
ErrorCode.UNAVAILABLE,
|
||||
"Зависимость недоступна",
|
||||
req_id,
|
||||
)
|
||||
|
||||
for exc_cls in (
|
||||
UnavailableError,
|
||||
asyncpg.PostgresError,
|
||||
asyncpg.InterfaceError,
|
||||
redis.exceptions.RedisError,
|
||||
TimeoutError,
|
||||
asyncio.TimeoutError,
|
||||
ConnectionError,
|
||||
OSError,
|
||||
):
|
||||
app.add_exception_handler(exc_cls, dependency_unavailable_handler)
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_exception_handler(
|
||||
request: Request, exc: Exception
|
||||
) -> JSONResponse:
|
||||
req_id = get_request_id(request)
|
||||
if isinstance(
|
||||
exc,
|
||||
(
|
||||
UnavailableError,
|
||||
asyncpg.PostgresError,
|
||||
asyncpg.InterfaceError,
|
||||
redis.exceptions.RedisError,
|
||||
TimeoutError,
|
||||
asyncio.TimeoutError,
|
||||
ConnectionError,
|
||||
OSError,
|
||||
),
|
||||
):
|
||||
return await dependency_unavailable_handler(request, exc)
|
||||
|
||||
logger.error(
|
||||
"Unhandled exception for request %s: %s", req_id, exc, exc_info=True
|
||||
)
|
||||
return make_error_response(
|
||||
status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
ErrorCode.INTERNAL_ERROR,
|
||||
"Внутренняя ошибка сервера",
|
||||
req_id,
|
||||
)
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
import uvicorn
|
||||
from fastapi import FastAPI
|
||||
|
||||
from app.config import APP_HOST, APP_PORT, LOG_LEVEL
|
||||
from app.errors import register_error_handlers
|
||||
from app.middleware import RequestIdAndLoggingMiddleware
|
||||
from app.routes.auth import router as auth_router
|
||||
from app.routes.chats import router as chats_router
|
||||
from app.routes.health import router as health_router
|
||||
from app.routes.messages import router as messages_router
|
||||
from app.routes.users import router as users_router
|
||||
from app.storage import storage
|
||||
|
||||
logger = logging.getLogger("app.lifecycle")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
logger.info(
|
||||
"Starting messenger server on %s:%d (env: %s)", APP_HOST, APP_PORT, LOG_LEVEL
|
||||
)
|
||||
await storage.connect()
|
||||
yield
|
||||
logger.info("Graceful shutdown: closing connections...")
|
||||
await storage.disconnect()
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="highload-messenger",
|
||||
version="1.3.0",
|
||||
docs_url="/docs",
|
||||
redoc_url=None,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
app.add_middleware(RequestIdAndLoggingMiddleware)
|
||||
|
||||
register_error_handlers(app)
|
||||
|
||||
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__":
|
||||
uvicorn.run(
|
||||
"app.main:app",
|
||||
host=APP_HOST,
|
||||
port=APP_PORT,
|
||||
log_level=LOG_LEVEL.lower(),
|
||||
timeout_graceful_shutdown=10,
|
||||
)
|
||||
@@ -0,0 +1,77 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import Response
|
||||
|
||||
from app.config import INSTANCE_ID
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||
stream=sys.stdout,
|
||||
)
|
||||
logger = logging.getLogger("app.access")
|
||||
|
||||
|
||||
class RequestIdAndLoggingMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(
|
||||
self, request: Request, call_next: RequestResponseEndpoint
|
||||
) -> Response:
|
||||
# Получаем X-Request-Id или генерируем новый
|
||||
request_id = request.headers.get("X-Request-Id")
|
||||
if not request_id or not request_id.strip():
|
||||
request_id = str(uuid.uuid4())
|
||||
|
||||
request.state.request_id = request_id
|
||||
start_time = time.monotonic()
|
||||
|
||||
if request.method in ("POST", "PUT", "PATCH") and request.url.path != "/api/v1/auth/sessions":
|
||||
ct = request.headers.get("content-type")
|
||||
if ct:
|
||||
ct_clean = ct.split(";")[0].strip().lower()
|
||||
if ct_clean != "application/json":
|
||||
from fastapi import status
|
||||
from app.errors import make_error_response
|
||||
from app.schemas import ErrorCode
|
||||
return make_error_response(
|
||||
status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
|
||||
ErrorCode.UNSUPPORTED_MEDIA_TYPE,
|
||||
f"Неподдерживаемый тип содержимого '{ct}'. Ожидается application/json",
|
||||
request_id,
|
||||
)
|
||||
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except Exception:
|
||||
# Исключение перехватится exception_handler
|
||||
duration_ms = (time.monotonic() - start_time) * 1000
|
||||
logger.error(
|
||||
"%s %s -> 500 error | duration=%.2fms | request_id=%s",
|
||||
request.method,
|
||||
request.url.path,
|
||||
duration_ms,
|
||||
request_id,
|
||||
)
|
||||
raise
|
||||
|
||||
duration_ms = (time.monotonic() - start_time) * 1000
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
|
||||
# лог без логирования тела запросов и текстов сообщений
|
||||
logger.info(
|
||||
"%s %s -> %d | duration=%.2fms | request_id=%s",
|
||||
request.method,
|
||||
request.url.path,
|
||||
response.status_code,
|
||||
duration_ms,
|
||||
request_id,
|
||||
)
|
||||
|
||||
return response
|
||||
@@ -0,0 +1,63 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from fastapi import APIRouter, Depends, Header, Request, Response, status
|
||||
|
||||
from app.dependencies import get_current_token
|
||||
from app.errors import InvalidRequestError, UnauthorizedError
|
||||
from app.schemas import SessionResponse
|
||||
from app.storage import storage
|
||||
|
||||
router = APIRouter(prefix="/api/v1/auth/sessions", tags=["auth"])
|
||||
|
||||
|
||||
@router.post("", response_model=SessionResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_session(
|
||||
request: Request,
|
||||
authorization: str | None = Header(default=None, alias="Authorization"),
|
||||
) -> SessionResponse:
|
||||
"""Аутентификация пользователя через Basic Auth и создание новой сессии."""
|
||||
body = await request.body()
|
||||
if body and body.strip():
|
||||
raise InvalidRequestError("Тело запроса для создания сессии должно быть пустым")
|
||||
|
||||
if not authorization or not authorization.strip():
|
||||
raise UnauthorizedError("Отсутствует заголовок Authorization")
|
||||
|
||||
parts = authorization.strip().split(maxsplit=1)
|
||||
if len(parts) != 2 or parts[0].lower() != "basic":
|
||||
raise UnauthorizedError("Неверная схема авторизации (ожидается Basic)")
|
||||
|
||||
try:
|
||||
raw_bytes = base64.b64decode(parts[1].strip())
|
||||
raw_str = raw_bytes.decode("utf-8")
|
||||
if ":" not in raw_str:
|
||||
raise UnauthorizedError("Некорректный формат Basic credentials")
|
||||
username, password = raw_str.split(":", 1)
|
||||
except Exception:
|
||||
raise UnauthorizedError("Некорректный заголовок Basic авторизации")
|
||||
|
||||
user = await storage.authenticate_user(username, password)
|
||||
if not user:
|
||||
raise UnauthorizedError("Неверное имя пользователя или пароль")
|
||||
|
||||
session = await storage.create_session(user)
|
||||
return session
|
||||
|
||||
|
||||
@router.delete("/current", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_current_session(
|
||||
request: Request,
|
||||
token: str = Depends(get_current_token),
|
||||
) -> Response:
|
||||
"""Отзыв текущей сессии."""
|
||||
body = await request.body()
|
||||
if body and body.strip():
|
||||
raise InvalidRequestError("Тело запроса для отзыва сессии должно быть пустым")
|
||||
|
||||
user = await storage.get_session_user(token)
|
||||
if not user:
|
||||
raise UnauthorizedError("Недействительная или уже отозванная сессия")
|
||||
|
||||
await storage.delete_session(token)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -0,0 +1,64 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, status
|
||||
|
||||
from app.dependencies import get_current_user
|
||||
from app.schemas import (
|
||||
ChatPageResponse,
|
||||
ChatResponse,
|
||||
CreateChatRequest,
|
||||
UserResponse,
|
||||
)
|
||||
from app.storage import InvalidRequestError, storage
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["chats"])
|
||||
|
||||
|
||||
def validate_uuid(value: str, field_name: str = "id") -> str:
|
||||
try:
|
||||
UUID(value)
|
||||
return value
|
||||
except ValueError as exc:
|
||||
raise InvalidRequestError(f"Поле '{field_name}' не является валидным UUID") from exc
|
||||
|
||||
|
||||
@router.post("", response_model=ChatResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_chat(
|
||||
body: CreateChatRequest,
|
||||
current_user: UserResponse = Depends(get_current_user),
|
||||
) -> ChatResponse:
|
||||
"""Создание нового чата."""
|
||||
chat = await storage.create_chat(
|
||||
caller_id=current_user.id,
|
||||
title=body.title,
|
||||
member_ids=body.member_ids,
|
||||
)
|
||||
return chat
|
||||
|
||||
|
||||
@router.get("", response_model=ChatPageResponse, status_code=status.HTTP_200_OK)
|
||||
async def list_chats(
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: str | None = Query(default=None),
|
||||
current_user: UserResponse = Depends(get_current_user),
|
||||
) -> ChatPageResponse:
|
||||
"""Список чатов, в которых состоит текущий пользователь."""
|
||||
items, next_cursor = await storage.list_chats(
|
||||
caller_id=current_user.id,
|
||||
limit=limit,
|
||||
cursor=cursor,
|
||||
)
|
||||
return ChatPageResponse(items=items, next_cursor=next_cursor)
|
||||
|
||||
|
||||
@router.get("/{chat_id}", response_model=ChatResponse, status_code=status.HTTP_200_OK)
|
||||
async def get_chat(
|
||||
chat_id: str,
|
||||
current_user: UserResponse = Depends(get_current_user),
|
||||
) -> ChatResponse:
|
||||
"""Получение информации о чате по ID."""
|
||||
valid_id = validate_uuid(chat_id, "chat_id")
|
||||
chat = await storage.get_chat(caller_id=current_user.id, chat_id=valid_id)
|
||||
return chat
|
||||
@@ -0,0 +1,31 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, status
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from app.schemas import HealthResponse
|
||||
from app.storage import storage
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/health/live", response_model=HealthResponse, status_code=status.HTTP_200_OK
|
||||
)
|
||||
async def health_live() -> HealthResponse:
|
||||
"""Проверка жизни процесса (Liveness)."""
|
||||
return HealthResponse(status="ok")
|
||||
|
||||
|
||||
@router.get(
|
||||
"/health/ready", response_model=HealthResponse, status_code=status.HTTP_200_OK
|
||||
)
|
||||
async def health_ready() -> HealthResponse:
|
||||
"""Проверка готовности сервиса и его зависимостей (Readiness)."""
|
||||
is_ready = await storage.check_health()
|
||||
if not is_ready:
|
||||
raise StarletteHTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Сервис или его хранилища недоступны",
|
||||
)
|
||||
return HealthResponse(status="ok")
|
||||
@@ -0,0 +1,73 @@
|
||||
import re
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, Query, status
|
||||
|
||||
from app.dependencies import get_current_user
|
||||
from app.schemas import (
|
||||
CreateMessageRequest,
|
||||
MessagePageResponse,
|
||||
MessageResponse,
|
||||
UserResponse,
|
||||
)
|
||||
from app.storage import InvalidRequestError, storage
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["messages"])
|
||||
|
||||
IDEMPOTENCY_KEY_REGEX = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
|
||||
|
||||
def validate_uuid(value: str, field_name: str = "id") -> str:
|
||||
try:
|
||||
UUID(value)
|
||||
return value
|
||||
except ValueError as exc:
|
||||
raise InvalidRequestError(f"Поле '{field_name}' не является валидным UUID") from exc
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{chat_id}/messages",
|
||||
response_model=MessageResponse,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
async def create_message(
|
||||
chat_id: str,
|
||||
body: CreateMessageRequest,
|
||||
idempotency_key: str | None = Header(default=None, alias="Idempotency-Key"),
|
||||
current_user: UserResponse = Depends(get_current_user),
|
||||
) -> MessageResponse:
|
||||
"""Отправка сообщения в чат."""
|
||||
if not idempotency_key or not IDEMPOTENCY_KEY_REGEX.match(idempotency_key):
|
||||
raise InvalidRequestError(
|
||||
"Заголовок 'Idempotency-Key' обязателен и должен соответствовать шаблону ^[A-Za-z0-9._:-]{1,128}$"
|
||||
)
|
||||
valid_id = validate_uuid(chat_id, "chat_id")
|
||||
msg = await storage.send_message(
|
||||
caller_id=current_user.id,
|
||||
chat_id=valid_id,
|
||||
text=body.text,
|
||||
idempotency_key=idempotency_key,
|
||||
)
|
||||
return msg
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{chat_id}/messages",
|
||||
response_model=MessagePageResponse,
|
||||
status_code=status.HTTP_200_OK,
|
||||
)
|
||||
async def list_messages(
|
||||
chat_id: str,
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: str | None = Query(default=None),
|
||||
current_user: UserResponse = Depends(get_current_user),
|
||||
) -> MessagePageResponse:
|
||||
"""Получение истории сообщений чата с keyset-пагинацией."""
|
||||
valid_id = validate_uuid(chat_id, "chat_id")
|
||||
items, next_cursor = await storage.list_messages(
|
||||
caller_id=current_user.id,
|
||||
chat_id=valid_id,
|
||||
limit=limit,
|
||||
cursor=cursor,
|
||||
)
|
||||
return MessagePageResponse(items=items, next_cursor=next_cursor)
|
||||
@@ -0,0 +1,28 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, status
|
||||
|
||||
from app.dependencies import get_current_user
|
||||
from app.schemas import CreateUserRequest, UserResponse
|
||||
from app.storage import storage
|
||||
|
||||
router = APIRouter(prefix="/api/v1/users", tags=["users"])
|
||||
|
||||
|
||||
@router.post("", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_user(body: CreateUserRequest) -> UserResponse:
|
||||
"""Регистрация нового пользователя."""
|
||||
user = await storage.create_user(
|
||||
username=body.username,
|
||||
display_name=body.display_name,
|
||||
password=body.password,
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
@router.get("/me", response_model=UserResponse, status_code=status.HTTP_200_OK)
|
||||
async def get_me(
|
||||
current_user: UserResponse = Depends(get_current_user),
|
||||
) -> UserResponse:
|
||||
"""Получение профиля текущего пользователя."""
|
||||
return current_user
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import re
|
||||
from enum import Enum
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
|
||||
def now_utc_iso() -> str:
|
||||
"""Возвращает текущее время в формате RFC 3339 UTC с суффиксом Z."""
|
||||
return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
|
||||
|
||||
class ErrorCode(str, Enum):
|
||||
INVALID_REQUEST = "invalid_request"
|
||||
UNAUTHORIZED = "unauthorized"
|
||||
NOT_FOUND = "not_found"
|
||||
CONFLICT = "conflict"
|
||||
PAYLOAD_TOO_LARGE = "payload_too_large"
|
||||
UNSUPPORTED_MEDIA_TYPE = "unsupported_media_type"
|
||||
RATE_LIMITED = "rate_limited"
|
||||
UNAVAILABLE = "unavailable"
|
||||
INTERNAL_ERROR = "internal_error"
|
||||
|
||||
|
||||
class ErrorDetail(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
code: ErrorCode
|
||||
message: str = Field(min_length=1)
|
||||
request_id: str = Field(min_length=1)
|
||||
|
||||
|
||||
class ErrorResponse(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
error: ErrorDetail
|
||||
|
||||
|
||||
class HealthResponse(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
status: str = Field(default="ok")
|
||||
|
||||
|
||||
class CreateUserRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
username: str = Field(min_length=3, max_length=32)
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def validate_username(cls, v: str) -> str:
|
||||
if not re.match(r"^[a-z0-9_]{3,32}\Z", v):
|
||||
raise ValueError("Имя пользователя должно соответствовать шаблону ^[a-z0-9_]{3,32}$")
|
||||
return v
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def validate_display_name(cls, v: str) -> str:
|
||||
if not v.strip():
|
||||
raise ValueError("Отображаемое имя не может состоять только из пробелов")
|
||||
return v
|
||||
|
||||
@field_validator("password")
|
||||
@classmethod
|
||||
def validate_password(cls, v: str) -> str:
|
||||
if not v.strip():
|
||||
raise ValueError("Пароль не может состоять только из пробелов")
|
||||
return v
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class SessionResponse(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
token: str = Field(min_length=32)
|
||||
token_type: str = Field(default="Bearer")
|
||||
expires_at: str
|
||||
user: UserResponse
|
||||
|
||||
|
||||
class CreateChatRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: list[str] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def validate_title(cls, v: str) -> str:
|
||||
if not v.strip():
|
||||
raise ValueError("Название не может состоять только из пробелов")
|
||||
return v
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def validate_member_ids(cls, v: list[str]) -> list[str]:
|
||||
if len(v) != len(set(v)):
|
||||
raise ValueError("Идентификаторы участников должны быть уникальными")
|
||||
for member_id in v:
|
||||
try:
|
||||
UUID(member_id)
|
||||
except ValueError:
|
||||
raise ValueError(f"Идентификатор участника '{member_id}' не является валидным UUID")
|
||||
return v
|
||||
|
||||
|
||||
class ChatResponse(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
id: str
|
||||
title: str
|
||||
member_ids: list[str]
|
||||
created_at: str
|
||||
|
||||
|
||||
class ChatPageResponse(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
items: list[ChatResponse]
|
||||
next_cursor: str | None = None
|
||||
|
||||
|
||||
class CreateMessageRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
text: str = Field(min_length=1, max_length=4000)
|
||||
|
||||
@field_validator("text")
|
||||
@classmethod
|
||||
def validate_text(cls, v: str) -> str:
|
||||
if not v.strip():
|
||||
raise ValueError("Текст сообщения не может состоять только из пробелов")
|
||||
return v
|
||||
|
||||
|
||||
class MessageResponse(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
text: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class MessagePageResponse(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
items: list[MessageResponse]
|
||||
next_cursor: str | None = None
|
||||
+623
@@ -0,0 +1,623 @@
|
||||
import asyncio
|
||||
import base64
|
||||
from contextlib import asynccontextmanager
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
import asyncpg
|
||||
import redis.asyncio as redis
|
||||
|
||||
from app.auth import generate_session_token, hash_password, verify_password
|
||||
from app.config import (
|
||||
CACHE_URL,
|
||||
DATABASE_URL,
|
||||
SESSION_TTL_SECONDS,
|
||||
)
|
||||
from app.errors import (
|
||||
ConflictError,
|
||||
InvalidRequestError,
|
||||
NotFoundError,
|
||||
UnauthorizedError,
|
||||
)
|
||||
from app.schemas import (
|
||||
ChatResponse,
|
||||
MessageResponse,
|
||||
SessionResponse,
|
||||
UserResponse,
|
||||
now_utc_iso,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("app.storage")
|
||||
|
||||
|
||||
def encode_cursor(data: dict) -> str:
|
||||
raw = json.dumps(data, separators=(",", ":")).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("utf-8").rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(cursor_str: str) -> dict:
|
||||
if not isinstance(cursor_str, str) or not cursor_str.strip():
|
||||
raise InvalidRequestError("Некорректный курсор")
|
||||
try:
|
||||
padded = cursor_str + "=" * (-len(cursor_str) % 4)
|
||||
raw = base64.urlsafe_b64decode(padded.encode("utf-8"))
|
||||
data = json.loads(raw.decode("utf-8"))
|
||||
if not isinstance(data, dict):
|
||||
raise InvalidRequestError("Некорректный курсор")
|
||||
return data
|
||||
except InvalidRequestError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise InvalidRequestError("Некорректный курсор") from exc
|
||||
|
||||
|
||||
def _format_dt(d: dt.datetime) -> str:
|
||||
if d.tzinfo is None:
|
||||
d = d.replace(tzinfo=dt.timezone.utc)
|
||||
return d.astimezone(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
|
||||
|
||||
def _to_text(val: Any) -> str:
|
||||
if isinstance(val, (bytes, bytearray, memoryview)):
|
||||
return bytes(val).decode("utf-8")
|
||||
return str(val)
|
||||
|
||||
|
||||
class PostgresStorage:
|
||||
def __init__(self) -> None:
|
||||
self.pg_pool: asyncpg.Pool | None = None
|
||||
self.redis_client: redis.Redis | None = None
|
||||
|
||||
@asynccontextmanager
|
||||
async def acquire_conn(self, timeout: float = 5.0):
|
||||
if self.pg_pool is None:
|
||||
raise asyncpg.InterfaceError("Пул подключений к PostgreSQL не инициализирован")
|
||||
async with asyncio.timeout(10.0):
|
||||
async with self.pg_pool.acquire(timeout=timeout) as conn:
|
||||
yield conn
|
||||
|
||||
async def connect(self) -> None:
|
||||
logger.info("Подключение к PostgreSQL: %s", DATABASE_URL.split("@")[-1])
|
||||
self.pg_pool = await asyncpg.create_pool(
|
||||
DATABASE_URL,
|
||||
min_size=2,
|
||||
max_size=20,
|
||||
command_timeout=5.0,
|
||||
timeout=5.0,
|
||||
)
|
||||
|
||||
logger.info("Подключение к Redis: %s", CACHE_URL.split("@")[-1])
|
||||
self.redis_client = redis.from_url(
|
||||
CACHE_URL,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=3.0,
|
||||
socket_timeout=3.0,
|
||||
)
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
if self.pg_pool:
|
||||
await self.pg_pool.close()
|
||||
self.pg_pool = None
|
||||
if self.redis_client:
|
||||
await self.redis_client.close()
|
||||
self.redis_client = None
|
||||
|
||||
async def check_health(self) -> bool:
|
||||
if not self.pg_pool or not self.redis_client:
|
||||
return False
|
||||
try:
|
||||
async with self.acquire_conn() as conn:
|
||||
await conn.fetchval("SELECT 1")
|
||||
await self.redis_client.ping()
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.warning("Ошибка проверки health: %s", exc)
|
||||
return False
|
||||
|
||||
# ------------------ Пользователи и аутентификация ------------------
|
||||
|
||||
async def create_user(
|
||||
self, username: str, display_name: str, password: str
|
||||
) -> UserResponse:
|
||||
user_id = uuid.uuid4()
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
pwd_hash = await asyncio.to_thread(hash_password, password)
|
||||
|
||||
try:
|
||||
async with self.acquire_conn() as conn:
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
""",
|
||||
user_id,
|
||||
username,
|
||||
display_name,
|
||||
pwd_hash,
|
||||
now,
|
||||
)
|
||||
except asyncpg.UniqueViolationError:
|
||||
raise ConflictError("Имя пользователя уже занято")
|
||||
|
||||
return UserResponse(
|
||||
id=str(user_id),
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
created_at=_format_dt(now),
|
||||
)
|
||||
|
||||
async def authenticate_user(
|
||||
self, username: str, password: str
|
||||
) -> UserResponse | None:
|
||||
async with self.acquire_conn() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
""",
|
||||
username,
|
||||
)
|
||||
|
||||
if not row:
|
||||
return None
|
||||
|
||||
is_valid = await asyncio.to_thread(verify_password, row["password_hash"], password)
|
||||
if not is_valid:
|
||||
return None
|
||||
|
||||
return UserResponse(
|
||||
id=str(row["id"]),
|
||||
username=row["username"],
|
||||
display_name=_to_text(row["display_name"]),
|
||||
created_at=_format_dt(row["created_at"]),
|
||||
)
|
||||
|
||||
async def get_user_by_id(self, user_id: str) -> UserResponse | None:
|
||||
try:
|
||||
uid = uuid.UUID(user_id)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
async with self.acquire_conn() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
SELECT id, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE id = $1
|
||||
""",
|
||||
uid,
|
||||
)
|
||||
|
||||
if not row:
|
||||
return None
|
||||
|
||||
return UserResponse(
|
||||
id=str(row["id"]),
|
||||
username=row["username"],
|
||||
display_name=_to_text(row["display_name"]),
|
||||
created_at=_format_dt(row["created_at"]),
|
||||
)
|
||||
|
||||
# ------------------ Сессии (Redis) ------------------
|
||||
|
||||
async def create_session(self, user: UserResponse) -> SessionResponse:
|
||||
assert self.redis_client is not None
|
||||
token = generate_session_token()
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
expires_at = now + dt.timedelta(seconds=SESSION_TTL_SECONDS)
|
||||
expires_at_str = _format_dt(expires_at)
|
||||
|
||||
session_data = json.dumps(
|
||||
{
|
||||
"user_id": user.id,
|
||||
"expires_at": expires_at_str,
|
||||
}
|
||||
)
|
||||
|
||||
key = f"session:{token}"
|
||||
await self.redis_client.set(key, session_data, ex=SESSION_TTL_SECONDS)
|
||||
|
||||
return SessionResponse(
|
||||
token=token,
|
||||
token_type="Bearer",
|
||||
expires_at=expires_at_str,
|
||||
user=user,
|
||||
)
|
||||
|
||||
async def get_session_user(self, token: str) -> UserResponse | None:
|
||||
if not token or not self.redis_client:
|
||||
return None
|
||||
|
||||
key = f"session:{token}"
|
||||
raw = await self.redis_client.get(key)
|
||||
if not raw:
|
||||
return None
|
||||
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
user_id = data.get("user_id")
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
if not user_id:
|
||||
return None
|
||||
|
||||
return await self.get_user_by_id(user_id)
|
||||
|
||||
async def delete_session(self, token: str) -> bool:
|
||||
if not token or not self.redis_client:
|
||||
return False
|
||||
key = f"session:{token}"
|
||||
res = await self.redis_client.delete(key)
|
||||
return res > 0
|
||||
|
||||
# ------------------ Чаты ------------------
|
||||
|
||||
async def create_chat(
|
||||
self, caller_id: str, title: str, member_ids: list[str]
|
||||
) -> ChatResponse:
|
||||
if caller_id not in member_ids:
|
||||
raise InvalidRequestError("Создатель чата должен быть в списке участников")
|
||||
|
||||
chat_id = uuid.uuid4()
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
|
||||
member_uuids = [uuid.UUID(m) for m in member_ids]
|
||||
|
||||
async with self.acquire_conn() as conn:
|
||||
# Проверяем существование всех участников
|
||||
found = await conn.fetch(
|
||||
"SELECT id FROM users WHERE id = ANY($1::uuid[])", member_uuids
|
||||
)
|
||||
if len(found) != len(member_uuids):
|
||||
raise InvalidRequestError(
|
||||
"Один или несколько участников чата не найдены"
|
||||
)
|
||||
|
||||
async with conn.transaction():
|
||||
await conn.execute(
|
||||
"INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)",
|
||||
chat_id,
|
||||
title,
|
||||
now,
|
||||
)
|
||||
member_records = [(chat_id, m) for m in member_uuids]
|
||||
await conn.executemany(
|
||||
"INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)",
|
||||
member_records,
|
||||
)
|
||||
|
||||
return ChatResponse(
|
||||
id=str(chat_id),
|
||||
title=title,
|
||||
member_ids=member_ids,
|
||||
created_at=_format_dt(now),
|
||||
)
|
||||
|
||||
async def get_chat(self, caller_id: str, chat_id: str) -> ChatResponse:
|
||||
try:
|
||||
cid = uuid.UUID(chat_id)
|
||||
c_caller = uuid.UUID(caller_id)
|
||||
except ValueError:
|
||||
raise NotFoundError("Чат не найден")
|
||||
|
||||
async with self.acquire_conn() as conn:
|
||||
# Проверяем членство вызывающего
|
||||
is_member = await conn.fetchval(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
|
||||
cid,
|
||||
c_caller,
|
||||
)
|
||||
if not is_member:
|
||||
raise NotFoundError("Чат не найден")
|
||||
|
||||
chat_row = await conn.fetchrow(
|
||||
"SELECT id, title, created_at FROM chats WHERE id = $1", cid
|
||||
)
|
||||
if not chat_row:
|
||||
raise NotFoundError("Чат не найден")
|
||||
|
||||
members_rows = await conn.fetch(
|
||||
"SELECT user_id FROM chat_members WHERE chat_id = $1", cid
|
||||
)
|
||||
member_ids = [str(r["user_id"]) for r in members_rows]
|
||||
|
||||
return ChatResponse(
|
||||
id=str(chat_row["id"]),
|
||||
title=_to_text(chat_row["title"]),
|
||||
member_ids=member_ids,
|
||||
created_at=_format_dt(chat_row["created_at"]),
|
||||
)
|
||||
|
||||
async def list_chats(
|
||||
self, caller_id: str, limit: int = 50, cursor: str | None = None
|
||||
) -> tuple[list[ChatResponse], str | None]:
|
||||
try:
|
||||
c_caller = uuid.UUID(caller_id)
|
||||
except ValueError:
|
||||
return [], None
|
||||
|
||||
c_created: dt.datetime | None = None
|
||||
c_id: uuid.UUID | None = None
|
||||
|
||||
if cursor is not None:
|
||||
c_data = decode_cursor(cursor)
|
||||
if c_data.get("type") != "chats":
|
||||
raise InvalidRequestError("Недействительный тип курсора")
|
||||
c_created_str = c_data.get("created_at")
|
||||
c_id_str = c_data.get("id")
|
||||
if (
|
||||
not isinstance(c_created_str, str)
|
||||
or not isinstance(c_id_str, str)
|
||||
or not c_created_str.strip()
|
||||
or not c_id_str.strip()
|
||||
):
|
||||
raise InvalidRequestError("Поврежденный курсор")
|
||||
try:
|
||||
c_created = dt.datetime.fromisoformat(
|
||||
c_created_str.replace("Z", "+00:00")
|
||||
)
|
||||
c_id = uuid.UUID(c_id_str)
|
||||
except Exception:
|
||||
raise InvalidRequestError("Некорректные параметры курсора")
|
||||
|
||||
async with self.acquire_conn() as conn:
|
||||
query = """
|
||||
SELECT c.id, c.title, c.created_at, array_agg(cm.user_id::text) as member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members my_m ON c.id = my_m.chat_id AND my_m.user_id = $1
|
||||
JOIN chat_members cm ON c.id = cm.chat_id
|
||||
WHERE ($2::timestamptz IS NULL OR (c.created_at, c.id) > ($2::timestamptz, $3::uuid))
|
||||
GROUP BY c.id, c.title, c.created_at
|
||||
ORDER BY c.created_at ASC, c.id ASC
|
||||
LIMIT $4
|
||||
"""
|
||||
rows = await conn.fetch(query, c_caller, c_created, c_id, limit + 1)
|
||||
|
||||
has_next = len(rows) > limit
|
||||
items_rows = rows[:limit]
|
||||
|
||||
items = [
|
||||
ChatResponse(
|
||||
id=str(r["id"]),
|
||||
title=_to_text(r["title"]),
|
||||
member_ids=list(r["member_ids"]),
|
||||
created_at=_format_dt(r["created_at"]),
|
||||
)
|
||||
for r in items_rows
|
||||
]
|
||||
|
||||
next_cursor = None
|
||||
if has_next and items:
|
||||
last = items[-1]
|
||||
next_cursor = encode_cursor(
|
||||
{
|
||||
"type": "chats",
|
||||
"created_at": last.created_at,
|
||||
"id": last.id,
|
||||
}
|
||||
)
|
||||
|
||||
return items, next_cursor
|
||||
|
||||
# ------------------ Сообщения ------------------
|
||||
|
||||
@staticmethod
|
||||
def compute_request_hash(text: str) -> str:
|
||||
canonical = json.dumps({"text": text}, sort_keys=True, ensure_ascii=False)
|
||||
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
|
||||
async def send_message(
|
||||
self, caller_id: str, chat_id: str, text: str, idempotency_key: str
|
||||
) -> MessageResponse:
|
||||
try:
|
||||
cid = uuid.UUID(chat_id)
|
||||
c_caller = uuid.UUID(caller_id)
|
||||
except ValueError:
|
||||
raise NotFoundError("Чат не найден")
|
||||
|
||||
req_hash = self.compute_request_hash(text)
|
||||
|
||||
async with self.acquire_conn() as conn:
|
||||
is_member = await conn.fetchval(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
|
||||
cid,
|
||||
c_caller,
|
||||
)
|
||||
if not is_member:
|
||||
raise NotFoundError("Чат не найден")
|
||||
|
||||
# 1. Проверяем, обрабатывался ли уже этот idempotency_key
|
||||
existing = await conn.fetchrow(
|
||||
"""
|
||||
SELECT ik.message_id, ik.request_hash, m.text, m.created_at AS msg_created_at
|
||||
FROM idempotency_keys ik
|
||||
JOIN messages m ON m.id = ik.message_id
|
||||
WHERE ik.user_id = $1 AND ik.chat_id = $2 AND ik.idempotency_key = $3
|
||||
""",
|
||||
c_caller,
|
||||
cid,
|
||||
idempotency_key,
|
||||
)
|
||||
if existing:
|
||||
if existing["request_hash"] == req_hash:
|
||||
raw_text = existing["text"]
|
||||
msg_text = (
|
||||
raw_text.decode("utf-8")
|
||||
if isinstance(raw_text, (bytes, bytearray))
|
||||
else str(raw_text)
|
||||
)
|
||||
return MessageResponse(
|
||||
id=str(existing["message_id"]),
|
||||
chat_id=chat_id,
|
||||
sender_id=caller_id,
|
||||
text=msg_text,
|
||||
created_at=_format_dt(existing["msg_created_at"]),
|
||||
)
|
||||
else:
|
||||
raise ConflictError("Ключ идемпотентности уже использован с другим телом запроса")
|
||||
|
||||
msg_id = uuid.uuid4()
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
text_bytes = text.encode("utf-8")
|
||||
|
||||
try:
|
||||
async with conn.transaction():
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
""",
|
||||
msg_id,
|
||||
cid,
|
||||
c_caller,
|
||||
text_bytes,
|
||||
now,
|
||||
)
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO idempotency_keys (user_id, chat_id, idempotency_key, message_id, request_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
""",
|
||||
c_caller,
|
||||
cid,
|
||||
idempotency_key,
|
||||
msg_id,
|
||||
req_hash,
|
||||
now,
|
||||
)
|
||||
except asyncpg.UniqueViolationError:
|
||||
# Конкурентная вставка из другой реплики выиграла гонку
|
||||
winner = await conn.fetchrow(
|
||||
"""
|
||||
SELECT ik.message_id, ik.request_hash, m.text, m.created_at AS msg_created_at
|
||||
FROM idempotency_keys ik
|
||||
JOIN messages m ON m.id = ik.message_id
|
||||
WHERE ik.user_id = $1 AND ik.chat_id = $2 AND ik.idempotency_key = $3
|
||||
""",
|
||||
c_caller,
|
||||
cid,
|
||||
idempotency_key,
|
||||
)
|
||||
if winner:
|
||||
if winner["request_hash"] == req_hash:
|
||||
raw_text = winner["text"]
|
||||
msg_text = (
|
||||
raw_text.decode("utf-8")
|
||||
if isinstance(raw_text, (bytes, bytearray))
|
||||
else str(raw_text)
|
||||
)
|
||||
return MessageResponse(
|
||||
id=str(winner["message_id"]),
|
||||
chat_id=chat_id,
|
||||
sender_id=caller_id,
|
||||
text=msg_text,
|
||||
created_at=_format_dt(winner["msg_created_at"]),
|
||||
)
|
||||
else:
|
||||
raise ConflictError("Ключ идемпотентности уже использован с другим телом запроса")
|
||||
raise
|
||||
|
||||
return MessageResponse(
|
||||
id=str(msg_id),
|
||||
chat_id=chat_id,
|
||||
sender_id=caller_id,
|
||||
text=text,
|
||||
created_at=_format_dt(now),
|
||||
)
|
||||
|
||||
async def list_messages(
|
||||
self, caller_id: str, chat_id: str, limit: int = 50, cursor: str | None = None
|
||||
) -> tuple[list[MessageResponse], str | None]:
|
||||
try:
|
||||
cid = uuid.UUID(chat_id)
|
||||
c_caller = uuid.UUID(caller_id)
|
||||
except ValueError:
|
||||
raise NotFoundError("Чат не найден")
|
||||
|
||||
async with self.acquire_conn() as conn:
|
||||
is_member = await conn.fetchval(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
|
||||
cid,
|
||||
c_caller,
|
||||
)
|
||||
if not is_member:
|
||||
raise NotFoundError("Чат не найден")
|
||||
|
||||
c_created: dt.datetime | None = None
|
||||
c_id: uuid.UUID | None = None
|
||||
|
||||
if cursor is not None:
|
||||
c_data = decode_cursor(cursor)
|
||||
if c_data.get("type") != "messages" or c_data.get("chat_id") != chat_id:
|
||||
raise InvalidRequestError(
|
||||
"Курсор принадлежит другому чату или недействителен"
|
||||
)
|
||||
c_created_str = c_data.get("created_at")
|
||||
c_id_str = c_data.get("id")
|
||||
if (
|
||||
not isinstance(c_created_str, str)
|
||||
or not isinstance(c_id_str, str)
|
||||
or not c_created_str.strip()
|
||||
or not c_id_str.strip()
|
||||
):
|
||||
raise InvalidRequestError("Поврежденный курсор")
|
||||
try:
|
||||
c_created = dt.datetime.fromisoformat(
|
||||
c_created_str.replace("Z", "+00:00")
|
||||
)
|
||||
c_id = uuid.UUID(c_id_str)
|
||||
except Exception:
|
||||
raise InvalidRequestError("Некорректные параметры курсора")
|
||||
|
||||
query = """
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND ($2::timestamptz IS NULL OR (created_at, id) > ($2::timestamptz, $3::uuid))
|
||||
ORDER BY created_at ASC, id ASC
|
||||
LIMIT $4
|
||||
"""
|
||||
rows = await conn.fetch(query, cid, c_created, c_id, limit + 1)
|
||||
|
||||
has_next = len(rows) > limit
|
||||
items_rows = rows[:limit]
|
||||
|
||||
def _to_text(val: Any) -> str:
|
||||
if isinstance(val, (bytes, bytearray, memoryview)):
|
||||
return bytes(val).decode("utf-8")
|
||||
return str(val)
|
||||
|
||||
items = [
|
||||
MessageResponse(
|
||||
id=str(r["id"]),
|
||||
chat_id=str(r["chat_id"]),
|
||||
sender_id=str(r["sender_id"]),
|
||||
text=_to_text(r["text"]),
|
||||
created_at=_format_dt(r["created_at"]),
|
||||
)
|
||||
for r in items_rows
|
||||
]
|
||||
|
||||
next_cursor = None
|
||||
if has_next and items:
|
||||
last = items[-1]
|
||||
next_cursor = encode_cursor(
|
||||
{
|
||||
"type": "messages",
|
||||
"chat_id": chat_id,
|
||||
"created_at": last.created_at,
|
||||
"id": last.id,
|
||||
}
|
||||
)
|
||||
|
||||
return items, next_cursor
|
||||
|
||||
|
||||
# Глобальный экземпляр хранилища
|
||||
storage = PostgresStorage()
|
||||
Reference in New Issue
Block a user