Перенёс основу приложения из лабораторной 1
This commit is contained in:
+135
@@ -0,0 +1,135 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import ValidationError as PydanticValidationError
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from src.models import ErrorResponse
|
||||
from src.routes import chats, health, messages, users
|
||||
from src.storage import storage
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
"""Создать и настроить приложение FastAPI."""
|
||||
app = FastAPI(title="MTUSI Messenger Lab1", version="1.1.0")
|
||||
|
||||
@app.middleware("http")
|
||||
async def add_request_id(request: Request, call_next):
|
||||
"""Middleware: добавляет X-Request-Id и реализует ограничение очереди запросов (трек 2)."""
|
||||
request_id = request.headers.get("X-Request-Id", "") or str(uuid.uuid4())
|
||||
request.state.request_id = request_id
|
||||
|
||||
# Трек 2: ограничение очереди запросов — возвращаем 503 при переполнении
|
||||
if not storage.acquire_request_slot():
|
||||
return JSONResponse(
|
||||
status_code=503,
|
||||
content=ErrorResponse(
|
||||
error={
|
||||
"code": "unavailable",
|
||||
"message": "сервер перегружен, попробуйте позже",
|
||||
"request_id": request_id,
|
||||
}
|
||||
).model_dump(),
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
try:
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
return response
|
||||
finally:
|
||||
storage.release_request_slot()
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
||||
"""Обработчик HTTPException: возвращает ошибку в формате контракта {"error": ...}."""
|
||||
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
||||
if isinstance(exc.detail, dict) and "error" in exc.detail:
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content=exc.detail,
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content=ErrorResponse(
|
||||
error={
|
||||
"code": "internal_error",
|
||||
"message": str(exc.detail),
|
||||
"request_id": request_id,
|
||||
}
|
||||
).model_dump(),
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def request_validation_handler(request: Request, exc: RequestValidationError):
|
||||
"""Перехватываем ошибки валидации запроса (422 -> 400 по контракту)."""
|
||||
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
||||
errors = exc.errors()
|
||||
messages = []
|
||||
for err in errors:
|
||||
loc = ".".join(str(x) for x in err.get("loc", []))
|
||||
messages.append(f"{loc}: {err.get('msg', 'invalid')}")
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content=ErrorResponse(
|
||||
error={
|
||||
"code": "invalid_request",
|
||||
"message": "; ".join(messages),
|
||||
"request_id": request_id,
|
||||
}
|
||||
).model_dump(),
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
@app.exception_handler(PydanticValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: PydanticValidationError):
|
||||
"""Перехватываем ошибки Pydantic (422 -> 400 по контракту)."""
|
||||
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
||||
errors = exc.errors()
|
||||
messages = []
|
||||
for err in errors:
|
||||
loc = ".".join(str(x) for x in err.get("loc", []))
|
||||
messages.append(f"{loc}: {err.get('msg', 'invalid')}")
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content=ErrorResponse(
|
||||
error={
|
||||
"code": "invalid_request",
|
||||
"message": "; ".join(messages),
|
||||
"request_id": request_id,
|
||||
}
|
||||
).model_dump(),
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def generic_exception_handler(request: Request, exc: Exception):
|
||||
"""Обработчик непредвиденных исключений: скрываем детали, возвращаем 500."""
|
||||
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content=ErrorResponse(
|
||||
error={
|
||||
"code": "internal_error",
|
||||
"message": "внутренняя ошибка сервера",
|
||||
"request_id": request_id,
|
||||
}
|
||||
).model_dump(),
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
# Подключаем роуты
|
||||
app.include_router(health.router)
|
||||
app.include_router(users.router)
|
||||
app.include_router(chats.router)
|
||||
app.include_router(messages.router)
|
||||
|
||||
return app
|
||||
|
||||
|
||||
# Экземпляр приложения для uvicorn
|
||||
app = create_app()
|
||||
@@ -0,0 +1,9 @@
|
||||
import os
|
||||
|
||||
import uvicorn
|
||||
|
||||
if __name__ == "__main__":
|
||||
"""Точка входа: запуск Uvicorn с параметрами из переменных окружения."""
|
||||
host = os.getenv("APP_HOST", "0.0.0.0")
|
||||
port = int(os.getenv("APP_PORT", "8080"))
|
||||
uvicorn.run("src.app:app", host=host, port=port, log_level="info")
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
|
||||
def utc_now() -> str:
|
||||
"""Возвращает текущее время в формате RFC 3339 UTC с суффиксом Z."""
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
class ErrorDetail(BaseModel):
|
||||
"""Детали ошибки API."""
|
||||
code: str
|
||||
message: str
|
||||
request_id: str
|
||||
|
||||
|
||||
class ErrorResponse(BaseModel):
|
||||
"""Стандартный ответ об ошибке."""
|
||||
error: ErrorDetail
|
||||
|
||||
|
||||
class Health(BaseModel):
|
||||
"""Ответ проверки работоспособности."""
|
||||
status: str = "ok"
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
"""Модель пользователя."""
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: 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)
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def display_name_not_whitespace_only(cls, v: str) -> str:
|
||||
"""Запрещаем display_name, состоящий только из пробельных символов."""
|
||||
if v.strip() == "":
|
||||
raise ValueError("display_name не может состоять только из пробелов")
|
||||
return v
|
||||
|
||||
|
||||
class Chat(BaseModel):
|
||||
"""Модель чата."""
|
||||
id: str
|
||||
title: str
|
||||
member_ids: list[str]
|
||||
created_at: str
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
"""Данные для создания чата."""
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
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 title_not_whitespace_only(cls, v: str) -> str:
|
||||
"""Запрещаем title, состоящий только из пробельных символов."""
|
||||
if v.strip() == "":
|
||||
raise ValueError("title не может состоять только из пробелов")
|
||||
return v
|
||||
|
||||
|
||||
class Message(BaseModel):
|
||||
"""Модель сообщения."""
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
text: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
"""Данные для отправки сообщения."""
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
text: str = Field(..., min_length=1, max_length=4000)
|
||||
|
||||
@field_validator("text")
|
||||
@classmethod
|
||||
def text_not_whitespace_only(cls, v: str) -> str:
|
||||
"""Запрещаем текст, состоящий только из пробельных символов."""
|
||||
if v.strip() == "":
|
||||
raise ValueError("текст не может состоять только из пробелов")
|
||||
return v
|
||||
|
||||
|
||||
class ChatPage(BaseModel):
|
||||
"""Страница списка чатов с курсорной пагинацией."""
|
||||
items: list[Chat]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
class MessagePage(BaseModel):
|
||||
"""Страница истории сообщений с курсорной пагинацией."""
|
||||
items: list[Message]
|
||||
next_cursor: Optional[str] = None
|
||||
@@ -0,0 +1,82 @@
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, Request
|
||||
|
||||
from src.models import Chat, ChatPage, CreateChat
|
||||
from src.routes.common import get_request_id, make_error, require_user
|
||||
from src.storage import LimitExceeded, ValidationError, storage
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/v1/chats", response_model=Chat, status_code=201)
|
||||
async def create_chat(
|
||||
request: Request,
|
||||
body: CreateChat,
|
||||
x_user_id: str | None = Header(None, alias="X-User-Id"),
|
||||
):
|
||||
"""Создать чат. Создатель обязательно должен входить в member_ids."""
|
||||
request_id = get_request_id(request)
|
||||
require_user(request, x_user_id)
|
||||
|
||||
try:
|
||||
chat = storage.create_chat(body.title, body.member_ids, x_user_id)
|
||||
return chat
|
||||
except ValidationError as e:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=make_error("invalid_request", str(e), request_id).model_dump(),
|
||||
)
|
||||
except LimitExceeded as e:
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail=make_error("rate_limited", str(e), request_id).model_dump(),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats", response_model=ChatPage)
|
||||
async def list_chats(
|
||||
request: Request,
|
||||
x_user_id: str | None = Header(None, alias="X-User-Id"),
|
||||
limit: int = 50,
|
||||
cursor: str | None = None,
|
||||
):
|
||||
"""Список чатов текущего пользователя с курсорной пагинацией."""
|
||||
request_id = get_request_id(request)
|
||||
require_user(request, x_user_id)
|
||||
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=make_error("invalid_request", "limit должен быть от 1 до 100", request_id).model_dump(),
|
||||
)
|
||||
|
||||
try:
|
||||
items, next_cursor = storage.list_chats_for_user(x_user_id, cursor, limit)
|
||||
return ChatPage(items=items, next_cursor=next_cursor)
|
||||
except ValidationError as e:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=make_error("invalid_request", str(e), request_id).model_dump(),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}", response_model=Chat)
|
||||
async def get_chat(
|
||||
request: Request,
|
||||
chat_id: UUID,
|
||||
x_user_id: str | None = Header(None, alias="X-User-Id"),
|
||||
):
|
||||
"""Получить чат по id. Доступен только участникам чата (чужой — 404)."""
|
||||
request_id = get_request_id(request)
|
||||
require_user(request, x_user_id)
|
||||
|
||||
chat_id_str = str(chat_id)
|
||||
chat = storage.get_chat(chat_id_str)
|
||||
if not chat or x_user_id not in chat.member_ids:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=make_error("not_found", "чат не найден", request_id).model_dump(),
|
||||
)
|
||||
|
||||
return chat
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Общие утилиты для всех роутов API.
|
||||
|
||||
Вынесено сюда, чтобы не повторять в каждом файле роутов (DRY).
|
||||
"""
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
from src.models import ErrorResponse
|
||||
from src.storage import storage
|
||||
|
||||
|
||||
def make_error(code: str, message: str, request_id: str) -> ErrorResponse:
|
||||
"""Собрать стандартный ответ об ошибке по контракту API."""
|
||||
return ErrorResponse(error={"code": code, "message": message, "request_id": request_id})
|
||||
|
||||
|
||||
def get_request_id(request: Request) -> str:
|
||||
"""Достать X-Request-Id из middleware. Если нет — сгенерировать новый."""
|
||||
return getattr(request.state, "request_id", "") or str(id(request))
|
||||
|
||||
|
||||
def require_user(request: Request, x_user_id: str | None) -> str:
|
||||
"""Проверить, что пользователь передал валидный X-User-Id.
|
||||
Возвращает user_id или выбрасывает HTTPException(401).
|
||||
"""
|
||||
request_id = get_request_id(request)
|
||||
if not x_user_id:
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail=make_error("unauthorized", "отсутствует идентификатор пользователя", request_id).model_dump(),
|
||||
)
|
||||
user = storage.get_user(x_user_id)
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail=make_error("unauthorized", "недействительный идентификатор пользователя", request_id).model_dump(),
|
||||
)
|
||||
return x_user_id
|
||||
@@ -0,0 +1,30 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from src.models import Health
|
||||
from src.storage import storage
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/health/live")
|
||||
async def liveness() -> Health:
|
||||
"""Проверка жизни процесса. Всегда возвращает 200, если процесс работает."""
|
||||
return Health(status="ok")
|
||||
|
||||
|
||||
@router.get("/health/ready")
|
||||
async def readiness() -> Health:
|
||||
"""Проверка готовности принимать трафик.
|
||||
|
||||
Для lab1 возвращает 200, так как нет внешних зависимостей.
|
||||
В следующих лабах здесь будет проверка БД и других сервисов.
|
||||
"""
|
||||
return Health(status="ok")
|
||||
|
||||
|
||||
@router.get("/stats")
|
||||
async def stats():
|
||||
"""Текущая статистика сервера: количество пользователей, чатов, сообщений,
|
||||
а также метрики rate limiting'а для наблюдения за деградацией.
|
||||
"""
|
||||
return storage.get_stats()
|
||||
@@ -0,0 +1,74 @@
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, Request
|
||||
|
||||
from src.models import CreateMessage, Message, MessagePage
|
||||
from src.routes.common import get_request_id, make_error, require_user
|
||||
from src.storage import LimitExceeded, ValidationError, storage
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201)
|
||||
async def create_message(
|
||||
request: Request,
|
||||
chat_id: UUID,
|
||||
body: CreateMessage,
|
||||
x_user_id: str | None = Header(None, alias="X-User-Id"),
|
||||
):
|
||||
"""Отправить сообщение в чат. Отправитель определяется по X-User-Id."""
|
||||
request_id = get_request_id(request)
|
||||
require_user(request, x_user_id)
|
||||
|
||||
chat_id_str = str(chat_id)
|
||||
chat = storage.get_chat(chat_id_str)
|
||||
if not chat or x_user_id not in chat.member_ids:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=make_error("not_found", "чат не найден", request_id).model_dump(),
|
||||
)
|
||||
|
||||
try:
|
||||
msg = storage.create_message(chat_id_str, x_user_id, body.text)
|
||||
return msg
|
||||
except LimitExceeded as e:
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail=make_error("rate_limited", str(e), request_id).model_dump(),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
async def list_messages(
|
||||
request: Request,
|
||||
chat_id: UUID,
|
||||
x_user_id: str | None = Header(None, alias="X-User-Id"),
|
||||
limit: int = 50,
|
||||
cursor: str | None = None,
|
||||
):
|
||||
"""История сообщений чата с курсорной пагинацией. Доступно только участникам."""
|
||||
request_id = get_request_id(request)
|
||||
require_user(request, x_user_id)
|
||||
|
||||
chat_id_str = str(chat_id)
|
||||
chat = storage.get_chat(chat_id_str)
|
||||
if not chat or x_user_id not in chat.member_ids:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=make_error("not_found", "чат не найден", request_id).model_dump(),
|
||||
)
|
||||
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=make_error("invalid_request", "limit должен быть от 1 до 100", request_id).model_dump(),
|
||||
)
|
||||
|
||||
try:
|
||||
items, next_cursor = storage.list_messages(chat_id_str, cursor, limit)
|
||||
return MessagePage(items=items, next_cursor=next_cursor)
|
||||
except ValidationError as e:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=make_error("invalid_request", str(e), request_id).model_dump(),
|
||||
)
|
||||
@@ -0,0 +1,51 @@
|
||||
from fastapi import APIRouter, Header, HTTPException, Request
|
||||
|
||||
from src.models import CreateUser, User
|
||||
from src.routes.common import get_request_id, make_error
|
||||
from src.storage import ConflictError, LimitExceeded, storage
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/v1/users", response_model=User, status_code=201)
|
||||
async def register_user(request: Request, body: CreateUser):
|
||||
"""Создать нового пользователя. Публичный endpoint, не требует авторизации."""
|
||||
request_id = get_request_id(request)
|
||||
try:
|
||||
user = storage.create_user(body.username, body.display_name)
|
||||
return user
|
||||
except ConflictError as e:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail=make_error("conflict", str(e), request_id).model_dump(),
|
||||
)
|
||||
except LimitExceeded as e:
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail=make_error("rate_limited", str(e), request_id).model_dump(),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/users/me", response_model=User)
|
||||
async def current_user(
|
||||
request: Request,
|
||||
x_user_id: str | None = Header(None, alias="X-User-Id"),
|
||||
):
|
||||
"""Получить текущего пользователя по заголовку X-User-Id.
|
||||
|
||||
Это учебный механизм: любой клиент может выдать себя за другого,
|
||||
зная UUID пользователя. Настоящая аутентификация появится позже.
|
||||
"""
|
||||
request_id = get_request_id(request)
|
||||
if not x_user_id:
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail=make_error("unauthorized", "отсутствует идентификатор пользователя", request_id).model_dump(),
|
||||
)
|
||||
user = storage.get_user(x_user_id)
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail=make_error("unauthorized", "недействительный идентификатор пользователя", request_id).model_dump(),
|
||||
)
|
||||
return user
|
||||
+339
@@ -0,0 +1,339 @@
|
||||
import base64
|
||||
import binascii
|
||||
from datetime import datetime
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from src.models import Chat, Message, User, utc_now
|
||||
|
||||
|
||||
_CURSOR_FIELDS = {"scope", "resource_id", "created_at", "id"}
|
||||
|
||||
|
||||
class StorageLimits:
|
||||
"""Лимиты хранилища для защиты от перегрузки (трек 2)."""
|
||||
def __init__(self):
|
||||
self.max_users = int(os.getenv("MAX_USERS", "1000"))
|
||||
self.max_chats = int(os.getenv("MAX_CHATS", "1000"))
|
||||
self.max_messages_total = int(os.getenv("MAX_MESSAGES", "10000"))
|
||||
self.max_messages_per_chat = int(os.getenv("MAX_MESSAGES_PER_CHAT", "1000"))
|
||||
self.max_request_queue = int(os.getenv("MAX_REQUEST_QUEUE", "100"))
|
||||
self.max_messages_per_second = float(os.getenv("MAX_MESSAGES_PER_SECOND", "10.0"))
|
||||
|
||||
|
||||
class InMemoryStorage:
|
||||
"""Хранилище данных в оперативной памяти.
|
||||
|
||||
Все данные живут внутри одного процесса и исчезают при перезапуске.
|
||||
Это требование текущей лабораторной — научиться работать с контейнерами
|
||||
без внешних баз данных.
|
||||
|
||||
Для защиты от гонок используется threading.RLock.
|
||||
"""
|
||||
def __init__(self):
|
||||
self._users: dict[str, User] = {}
|
||||
self._users_by_username: dict[str, str] = {}
|
||||
self._chats: dict[str, Chat] = {}
|
||||
self._messages: dict[str, Message] = {}
|
||||
self._chat_messages: dict[str, list[str]] = {}
|
||||
self._lock = threading.RLock()
|
||||
self._limits = StorageLimits()
|
||||
self._request_count = 0
|
||||
|
||||
# Token bucket для ограничения сообщений в секунду (трек 2)
|
||||
self._message_tokens = self._limits.max_messages_per_second
|
||||
self._last_token_update = time.monotonic()
|
||||
|
||||
# Метрики для наблюдения за деградацией
|
||||
self._rate_limited_count = 0
|
||||
self._total_message_attempts = 0
|
||||
|
||||
@staticmethod
|
||||
def _encode_cursor(scope: str, resource_id: str, created_at: str, item_id: str) -> str:
|
||||
"""Собрать непрозрачный курсор, привязанный к конкретному ресурсу."""
|
||||
payload = {
|
||||
"scope": scope,
|
||||
"resource_id": resource_id,
|
||||
"created_at": created_at,
|
||||
"id": item_id,
|
||||
}
|
||||
raw = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii")
|
||||
|
||||
@staticmethod
|
||||
def _decode_cursor(cursor: str, expected_scope: str, expected_resource_id: str) -> tuple[str, str]:
|
||||
"""Разобрать и проверить курсор.
|
||||
|
||||
Клиент видит курсор как непрозрачную строку, поэтому любые пустые,
|
||||
повреждённые или относящиеся к другому ресурсу значения отклоняем.
|
||||
"""
|
||||
if cursor == "":
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
allowed_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_="
|
||||
if any(char not in allowed_chars for char in cursor) or "=" in cursor.rstrip("="):
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
try:
|
||||
raw = base64.b64decode(cursor.encode("ascii"), altchars=b"-_", validate=True)
|
||||
payload = json.loads(raw.decode("utf-8"))
|
||||
except (UnicodeEncodeError, UnicodeDecodeError, binascii.Error, json.JSONDecodeError):
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
if not isinstance(payload, dict) or set(payload) != _CURSOR_FIELDS:
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
if not all(isinstance(payload[field], str) for field in _CURSOR_FIELDS):
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
if payload["scope"] != expected_scope or payload["resource_id"] != expected_resource_id:
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
try:
|
||||
uuid.UUID(payload["resource_id"])
|
||||
uuid.UUID(payload["id"])
|
||||
datetime.strptime(payload["created_at"], "%Y-%m-%dT%H:%M:%SZ")
|
||||
except ValueError:
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
return payload["created_at"], payload["id"]
|
||||
|
||||
# --- Пользователи ---
|
||||
|
||||
def create_user(self, username: str, display_name: str) -> User:
|
||||
"""Создать пользователя. Проверяет лимит и уникальность username."""
|
||||
with self._lock:
|
||||
if len(self._users) >= self._limits.max_users:
|
||||
raise LimitExceeded("превышен лимит пользователей")
|
||||
if username in self._users_by_username:
|
||||
raise ConflictError(f"username '{username}' уже занят")
|
||||
|
||||
user = User(
|
||||
id=str(uuid.uuid4()),
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
created_at=utc_now(),
|
||||
)
|
||||
self._users[user.id] = user
|
||||
self._users_by_username[user.username] = user.id
|
||||
return user
|
||||
|
||||
def get_user(self, user_id: str) -> User | None:
|
||||
"""Найти пользователя по UUID."""
|
||||
with self._lock:
|
||||
return self._users.get(user_id)
|
||||
|
||||
# --- Чаты ---
|
||||
|
||||
def create_chat(self, title: str, member_ids: list[str], creator_id: str) -> Chat:
|
||||
"""Создать чат. Проверяет существование участников и лимиты."""
|
||||
with self._lock:
|
||||
if len(self._chats) >= self._limits.max_chats:
|
||||
raise LimitExceeded("превышен лимит чатов")
|
||||
|
||||
seen = set()
|
||||
for mid in member_ids:
|
||||
if mid not in self._users:
|
||||
raise ValidationError(f"пользователь {mid} не существует")
|
||||
if mid in seen:
|
||||
raise ValidationError("дублирующиеся member_ids")
|
||||
seen.add(mid)
|
||||
|
||||
if creator_id not in seen:
|
||||
raise ValidationError("создатель должен входить в member_ids")
|
||||
|
||||
chat = Chat(
|
||||
id=str(uuid.uuid4()),
|
||||
title=title,
|
||||
member_ids=member_ids,
|
||||
created_at=utc_now(),
|
||||
)
|
||||
self._chats[chat.id] = chat
|
||||
self._chat_messages[chat.id] = []
|
||||
return chat
|
||||
|
||||
def get_chat(self, chat_id: str) -> Chat | None:
|
||||
"""Найти чат по UUID."""
|
||||
with self._lock:
|
||||
return self._chats.get(chat_id)
|
||||
|
||||
def list_chats_for_user(self, user_id: str, cursor: str | None, limit: int) -> tuple[list[Chat], str | None]:
|
||||
"""Список чатов пользователя с курсорной пагинацией."""
|
||||
with self._lock:
|
||||
chats = [
|
||||
chat for chat in self._chats.values()
|
||||
if user_id in chat.member_ids
|
||||
]
|
||||
chats.sort(key=lambda c: (c.created_at, c.id))
|
||||
|
||||
if cursor is not None:
|
||||
cursor_time, cursor_id = self._decode_cursor(cursor, "chats", user_id)
|
||||
cursor_chat = self._chats.get(cursor_id)
|
||||
if (
|
||||
cursor_chat is None
|
||||
or user_id not in cursor_chat.member_ids
|
||||
or cursor_chat.created_at != cursor_time
|
||||
):
|
||||
raise ValidationError("некорректный cursor")
|
||||
chats = [
|
||||
c for c in chats
|
||||
if (c.created_at, c.id) > (cursor_time, cursor_id)
|
||||
]
|
||||
|
||||
page = chats[:limit]
|
||||
next_cursor = None
|
||||
if len(page) == limit and len(chats) > limit:
|
||||
last = page[-1]
|
||||
next_cursor = self._encode_cursor("chats", user_id, last.created_at, last.id)
|
||||
|
||||
return page, next_cursor
|
||||
|
||||
# --- Сообщения ---
|
||||
|
||||
def _refill_message_tokens(self):
|
||||
"""Пополнить токены bucket'а пропорционально прошедшему времени."""
|
||||
now = time.monotonic()
|
||||
elapsed = now - self._last_token_update
|
||||
if elapsed > 0:
|
||||
self._message_tokens = min(
|
||||
self._limits.max_messages_per_second,
|
||||
self._message_tokens + elapsed * self._limits.max_messages_per_second,
|
||||
)
|
||||
self._last_token_update = now
|
||||
|
||||
def acquire_message_token(self) -> bool:
|
||||
"""Попытаться взять токен из bucket'а для отправки сообщения.
|
||||
|
||||
Возвращает True, если токен есть и сообщение можно отправить.
|
||||
False означает превышение rate limit → 429.
|
||||
"""
|
||||
with self._lock:
|
||||
self._total_message_attempts += 1
|
||||
self._refill_message_tokens()
|
||||
if self._message_tokens >= 1.0:
|
||||
self._message_tokens -= 1.0
|
||||
return True
|
||||
self._rate_limited_count += 1
|
||||
return False
|
||||
|
||||
def create_message(self, chat_id: str, sender_id: str, text: str) -> Message:
|
||||
"""Отправить сообщение. Проверяет лимиты и права доступа."""
|
||||
with self._lock:
|
||||
chat = self._chats.get(chat_id)
|
||||
if not chat:
|
||||
raise NotFoundError("чат не найден")
|
||||
if sender_id not in chat.member_ids:
|
||||
raise NotFoundError("чат не найден")
|
||||
|
||||
chat_msg_ids = self._chat_messages.get(chat_id, [])
|
||||
if len(chat_msg_ids) >= self._limits.max_messages_per_chat:
|
||||
raise LimitExceeded("превышен лимит сообщений в чате")
|
||||
if len(self._messages) >= self._limits.max_messages_total:
|
||||
raise LimitExceeded("превышен общий лимит сообщений")
|
||||
|
||||
# Проверяем rate limit (сообщений в секунду)
|
||||
if not self.acquire_message_token():
|
||||
raise LimitExceeded("превышен лимит сообщений в секунду")
|
||||
|
||||
msg = Message(
|
||||
id=str(uuid.uuid4()),
|
||||
chat_id=chat_id,
|
||||
sender_id=sender_id,
|
||||
text=text,
|
||||
created_at=utc_now(),
|
||||
)
|
||||
self._messages[msg.id] = msg
|
||||
chat_msg_ids.append(msg.id)
|
||||
return msg
|
||||
|
||||
def list_messages(self, chat_id: str, cursor: str | None, limit: int) -> tuple[list[Message], str | None]:
|
||||
"""История сообщений чата с курсорной пагинацией."""
|
||||
with self._lock:
|
||||
chat_msg_ids = self._chat_messages.get(chat_id, [])
|
||||
messages = [self._messages[mid] for mid in chat_msg_ids]
|
||||
messages.sort(key=lambda m: (m.created_at, m.id))
|
||||
|
||||
if cursor is not None:
|
||||
cursor_time, cursor_id = self._decode_cursor(cursor, "messages", chat_id)
|
||||
cursor_message = self._messages.get(cursor_id)
|
||||
if (
|
||||
cursor_message is None
|
||||
or cursor_message.chat_id != chat_id
|
||||
or cursor_message.created_at != cursor_time
|
||||
):
|
||||
raise ValidationError("некорректный cursor")
|
||||
messages = [
|
||||
m for m in messages
|
||||
if (m.created_at, m.id) > (cursor_time, cursor_id)
|
||||
]
|
||||
|
||||
page = messages[:limit]
|
||||
next_cursor = None
|
||||
if len(page) == limit and len(messages) > limit:
|
||||
last = page[-1]
|
||||
next_cursor = self._encode_cursor("messages", chat_id, last.created_at, last.id)
|
||||
|
||||
return page, next_cursor
|
||||
|
||||
# --- Очередь запросов (трек 2: управляемая деградация) ---
|
||||
|
||||
def acquire_request_slot(self) -> bool:
|
||||
"""Занять слот в очереди запросов. False = переполнение → 503."""
|
||||
with self._lock:
|
||||
if self._request_count >= self._limits.max_request_queue:
|
||||
return False
|
||||
self._request_count += 1
|
||||
return True
|
||||
|
||||
def release_request_slot(self):
|
||||
"""Освободить слот в очереди запросов."""
|
||||
with self._lock:
|
||||
self._request_count = max(0, self._request_count - 1)
|
||||
|
||||
# --- Статистика ---
|
||||
|
||||
def get_stats(self) -> dict:
|
||||
"""Текущая статистика хранилища и метрики деградации."""
|
||||
with self._lock:
|
||||
self._refill_message_tokens()
|
||||
return {
|
||||
"users": len(self._users),
|
||||
"chats": len(self._chats),
|
||||
"messages": len(self._messages),
|
||||
"requests_in_flight": self._request_count,
|
||||
"rate_limit": {
|
||||
"max_messages_per_second": self._limits.max_messages_per_second,
|
||||
"available_tokens": round(self._message_tokens, 2),
|
||||
},
|
||||
"metrics": {
|
||||
"total_message_attempts": self._total_message_attempts,
|
||||
"rate_limited_count": self._rate_limited_count,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class ValidationError(Exception):
|
||||
"""Неверные входные данные — HTTP 400."""
|
||||
pass
|
||||
|
||||
|
||||
class NotFoundError(Exception):
|
||||
"""Ресурс не найден или недоступен — HTTP 404."""
|
||||
pass
|
||||
|
||||
|
||||
class ConflictError(Exception):
|
||||
"""Конфликт, например дублирующийся username — HTTP 409."""
|
||||
pass
|
||||
|
||||
|
||||
class LimitExceeded(Exception):
|
||||
"""Превышен лимит ресурсов — HTTP 429 или 503."""
|
||||
pass
|
||||
|
||||
|
||||
# Единственное хранилище на весь процесс
|
||||
storage = InMemoryStorage()
|
||||
Reference in New Issue
Block a user