forked from mtusi2026/mtusi2026lab2
feat: перенос структуры приложения из первой лабы
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Messenger application package."""
|
||||
@@ -0,0 +1,6 @@
|
||||
import os
|
||||
|
||||
APP_HOST = os.getenv("APP_HOST", "0.0.0.0")
|
||||
APP_PORT = int(os.getenv("APP_PORT", "8080"))
|
||||
APP_ENV = os.getenv("APP_ENV", "lab")
|
||||
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO")
|
||||
@@ -0,0 +1,26 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import Header, Request
|
||||
|
||||
from app.schemas import UserResponse
|
||||
from app.storage import UnauthorizedError, storage
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
request: Request,
|
||||
x_user_id: str | None = Header(default=None, alias="X-User-Id"),
|
||||
) -> UserResponse:
|
||||
if not x_user_id or not x_user_id.strip():
|
||||
raise UnauthorizedError("Отсутствует заголовок X-User-Id")
|
||||
|
||||
# валидация формата UUID
|
||||
try:
|
||||
UUID(x_user_id)
|
||||
except ValueError:
|
||||
raise UnauthorizedError("Неверный формат заголовка X-User-Id")
|
||||
|
||||
# проверка существования пользователя
|
||||
user = await storage.get_user_by_id(x_user_id)
|
||||
return user
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
from fastapi import FastAPI, Request, status
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from app.schemas import ErrorCode, ErrorDetail, ErrorResponse
|
||||
from app.storage import (
|
||||
ConflictError,
|
||||
InvalidRequestError,
|
||||
NotFoundError,
|
||||
UnauthorizedError,
|
||||
)
|
||||
|
||||
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
|
||||
) -> JSONResponse:
|
||||
payload = ErrorResponse(
|
||||
error=ErrorDetail(code=code, message=message, request_id=request_id)
|
||||
).model_dump()
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content=payload,
|
||||
headers={"X-Request-Id": request_id, "Content-Type": "application/json"},
|
||||
)
|
||||
|
||||
|
||||
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)
|
||||
return make_error_response(
|
||||
status.HTTP_401_UNAUTHORIZED, ErrorCode.UNAUTHORIZED, str(exc), req_id
|
||||
)
|
||||
|
||||
@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)
|
||||
# Ошибки валидации входного JSON маппятся на 400
|
||||
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
|
||||
if exc.status_code == 400:
|
||||
code = ErrorCode.INVALID_REQUEST
|
||||
elif exc.status_code == 401:
|
||||
code = ErrorCode.UNAUTHORIZED
|
||||
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)
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_exception_handler(
|
||||
request: Request, exc: Exception
|
||||
) -> JSONResponse:
|
||||
req_id = get_request_id(request)
|
||||
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,
|
||||
)
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
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.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
|
||||
|
||||
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
|
||||
)
|
||||
yield
|
||||
logger.info("Graceful shutdown: closing connections and cleaning up...")
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="highload-messenger",
|
||||
version="1.1.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(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,59 @@
|
||||
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
|
||||
|
||||
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()
|
||||
|
||||
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
|
||||
|
||||
# лог без логирования тела запросов и текстов сообщений
|
||||
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,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,21 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, status
|
||||
|
||||
from app.schemas import HealthResponse
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/health/live", response_model=HealthResponse, status_code=status.HTTP_200_OK
|
||||
)
|
||||
async def health_live() -> HealthResponse:
|
||||
return HealthResponse(status="ok")
|
||||
|
||||
|
||||
@router.get(
|
||||
"/health/ready", response_model=HealthResponse, status_code=status.HTTP_200_OK
|
||||
)
|
||||
async def health_ready() -> HealthResponse:
|
||||
return HealthResponse(status="ok")
|
||||
@@ -0,0 +1,66 @@
|
||||
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 (
|
||||
CreateMessageRequest,
|
||||
MessagePageResponse,
|
||||
MessageResponse,
|
||||
UserResponse,
|
||||
)
|
||||
from app.storage import InvalidRequestError, storage
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["messages"])
|
||||
|
||||
|
||||
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,
|
||||
current_user: UserResponse = Depends(get_current_user),
|
||||
) -> MessageResponse:
|
||||
"""Отправка сообщения в чат."""
|
||||
valid_id = validate_uuid(chat_id, "chat_id")
|
||||
msg = await storage.create_message(
|
||||
caller_id=current_user.id,
|
||||
chat_id=valid_id,
|
||||
text=body.text,
|
||||
)
|
||||
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,26 @@
|
||||
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
|
||||
)
|
||||
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
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
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")
|
||||
|
||||
username: str = Field(min_length=3, max_length=32)
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
|
||||
@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
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class CreateChatRequest(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 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("Идентификаторы участников должны быть уникальными")
|
||||
# Проверка формата каждого UUID
|
||||
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")
|
||||
|
||||
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
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from app.schemas import (
|
||||
ChatResponse,
|
||||
MessageResponse,
|
||||
UserResponse,
|
||||
now_utc_iso,
|
||||
)
|
||||
|
||||
|
||||
class StorageError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidRequestError(StorageError):
|
||||
pass
|
||||
|
||||
|
||||
class NotFoundError(StorageError):
|
||||
pass
|
||||
|
||||
|
||||
class ConflictError(StorageError):
|
||||
pass
|
||||
|
||||
|
||||
class UnauthorizedError(StorageError):
|
||||
pass
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
class InMemoryStorage:
|
||||
def __init__(self) -> None:
|
||||
self._lock = asyncio.Lock()
|
||||
self._users_by_id: dict[str, UserResponse] = {}
|
||||
self._users_by_username: dict[str, UserResponse] = {}
|
||||
self._chats_by_id: dict[str, ChatResponse] = {}
|
||||
self._messages_by_chat: dict[str, list[MessageResponse]] = {}
|
||||
|
||||
async def create_user(self, username: str, display_name: str) -> UserResponse:
|
||||
async with self._lock:
|
||||
if username in self._users_by_username:
|
||||
raise ConflictError("Имя пользователя уже занято")
|
||||
|
||||
user_id = str(uuid.uuid4())
|
||||
created_at = now_utc_iso()
|
||||
user = UserResponse(
|
||||
id=user_id,
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
created_at=created_at,
|
||||
)
|
||||
self._users_by_id[user_id] = user
|
||||
self._users_by_username[username] = user
|
||||
return user
|
||||
|
||||
async def get_user_by_id(self, user_id: str) -> UserResponse:
|
||||
async with self._lock:
|
||||
user = self._users_by_id.get(user_id)
|
||||
if not user:
|
||||
raise UnauthorizedError("Пользователь не найден или не авторизован")
|
||||
return user
|
||||
|
||||
async def create_chat(
|
||||
self, caller_id: str, title: str, member_ids: list[str]
|
||||
) -> ChatResponse:
|
||||
async with self._lock:
|
||||
# Вызывающий обязан быть в списке участников
|
||||
if caller_id not in member_ids:
|
||||
raise InvalidRequestError("Создатель чата должен быть в списке участников member_ids")
|
||||
|
||||
# Все участники обязаны существовать
|
||||
for mid in member_ids:
|
||||
if mid not in self._users_by_id:
|
||||
raise InvalidRequestError(f"Пользователь {mid} не существует")
|
||||
|
||||
chat_id = str(uuid.uuid4())
|
||||
created_at = now_utc_iso()
|
||||
chat = ChatResponse(
|
||||
id=chat_id,
|
||||
title=title,
|
||||
member_ids=list(member_ids),
|
||||
created_at=created_at,
|
||||
)
|
||||
self._chats_by_id[chat_id] = chat
|
||||
self._messages_by_chat[chat_id] = []
|
||||
return chat
|
||||
|
||||
async def get_chat(self, caller_id: str, chat_id: str) -> ChatResponse:
|
||||
async with self._lock:
|
||||
chat = self._chats_by_id.get(chat_id)
|
||||
# Если чата нет или вызывающий не участник — строго 404
|
||||
if not chat or caller_id not in chat.member_ids:
|
||||
raise NotFoundError("Чат не найден")
|
||||
return chat
|
||||
|
||||
async def list_chats(
|
||||
self, caller_id: str, limit: int = 50, cursor: str | None = None
|
||||
) -> tuple[list[ChatResponse], str | None]:
|
||||
async with self._lock:
|
||||
# Фильтруем только чаты, где пользователь — участник
|
||||
user_chats = [
|
||||
chat
|
||||
for chat in self._chats_by_id.values()
|
||||
if caller_id in chat.member_ids
|
||||
]
|
||||
# Сортировка по (created_at, id) по возрастанию
|
||||
user_chats.sort(key=lambda x: (x.created_at, x.id))
|
||||
|
||||
start_idx = 0
|
||||
if cursor is not None:
|
||||
c_data = decode_cursor(cursor)
|
||||
if c_data.get("type") != "chats":
|
||||
raise InvalidRequestError("Курсор недействителен для списка чатов")
|
||||
c_created = c_data.get("created_at")
|
||||
c_id = c_data.get("id")
|
||||
if (
|
||||
not isinstance(c_created, str)
|
||||
or not isinstance(c_id, str)
|
||||
or not c_created.strip()
|
||||
or not c_id.strip()
|
||||
):
|
||||
raise InvalidRequestError("Поврежденный курсор")
|
||||
|
||||
# Ищем первый элемент, строго больший курсора
|
||||
start_idx = len(user_chats)
|
||||
for idx, chat in enumerate(user_chats):
|
||||
if (chat.created_at, chat.id) > (c_created, c_id):
|
||||
start_idx = idx
|
||||
break
|
||||
|
||||
items = user_chats[start_idx : start_idx + limit]
|
||||
has_next = (start_idx + limit) < len(user_chats)
|
||||
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
|
||||
|
||||
async def create_message(
|
||||
self, caller_id: str, chat_id: str, text: str
|
||||
) -> MessageResponse:
|
||||
async with self._lock:
|
||||
chat = self._chats_by_id.get(chat_id)
|
||||
if not chat or caller_id not in chat.member_ids:
|
||||
raise NotFoundError("Чат не найден")
|
||||
|
||||
message_id = str(uuid.uuid4())
|
||||
created_at = now_utc_iso()
|
||||
msg = MessageResponse(
|
||||
id=message_id,
|
||||
chat_id=chat_id,
|
||||
sender_id=caller_id,
|
||||
text=text,
|
||||
created_at=created_at,
|
||||
)
|
||||
self._messages_by_chat[chat_id].append(msg)
|
||||
return msg
|
||||
|
||||
async def list_messages(
|
||||
self, caller_id: str, chat_id: str, limit: int = 50, cursor: str | None = None
|
||||
) -> tuple[list[MessageResponse], str | None]:
|
||||
async with self._lock:
|
||||
chat = self._chats_by_id.get(chat_id)
|
||||
if not chat or caller_id not in chat.member_ids:
|
||||
raise NotFoundError("Чат не найден")
|
||||
|
||||
all_msgs = self._messages_by_chat.get(chat_id, [])
|
||||
# Сортировка по (created_at, id) по возрастанию
|
||||
sorted_msgs = sorted(all_msgs, key=lambda x: (x.created_at, x.id))
|
||||
|
||||
start_idx = 0
|
||||
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 = c_data.get("created_at")
|
||||
c_id = c_data.get("id")
|
||||
if (
|
||||
not isinstance(c_created, str)
|
||||
or not isinstance(c_id, str)
|
||||
or not c_created.strip()
|
||||
or not c_id.strip()
|
||||
):
|
||||
raise InvalidRequestError("Поврежденный курсор")
|
||||
|
||||
start_idx = len(sorted_msgs)
|
||||
for idx, msg in enumerate(sorted_msgs):
|
||||
if (msg.created_at, msg.id) > (c_created, c_id):
|
||||
start_idx = idx
|
||||
break
|
||||
|
||||
items = sorted_msgs[start_idx : start_idx + limit]
|
||||
has_next = (start_idx + limit) < len(sorted_msgs)
|
||||
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 = InMemoryStorage()
|
||||
Reference in New Issue
Block a user