diff --git a/.gitignore b/.gitignore index b5a7189..e6a53fe 100644 --- a/.gitignore +++ b/.gitignore @@ -25,6 +25,7 @@ bin/ obj/ coverage/ *.log +!evidence/*.log .DS_Store .idea/ .vscode/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..8701024 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,27 @@ +FROM python:3.12-slim + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + APP_HOST=0.0.0.0 \ + APP_PORT=8080 + +RUN groupadd -g 10001 appuser && \ + useradd -u 10001 -g appuser -s /sbin/nologin -M appuser + +WORKDIR /app + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY app/ ./app/ + +RUN chown -R appuser:appuser /app + +USER appuser + +EXPOSE 8080 + +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/live')" || exit 1 + +CMD ["python", "-m", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8080", "--timeout-graceful-shutdown", "10"] diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..6e6e089 --- /dev/null +++ b/app/__init__.py @@ -0,0 +1 @@ +"""Messenger application package.""" diff --git a/app/config.py b/app/config.py new file mode 100644 index 0000000..77c5f4b --- /dev/null +++ b/app/config.py @@ -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") diff --git a/app/dependencies.py b/app/dependencies.py new file mode 100644 index 0000000..4b3eae0 --- /dev/null +++ b/app/dependencies.py @@ -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 diff --git a/app/errors.py b/app/errors.py new file mode 100644 index 0000000..6966c8c --- /dev/null +++ b/app/errors.py @@ -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, + ) diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..96edbf8 --- /dev/null +++ b/app/main.py @@ -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, + ) diff --git a/app/middleware.py b/app/middleware.py new file mode 100644 index 0000000..765092a --- /dev/null +++ b/app/middleware.py @@ -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 diff --git a/app/routes/__init__.py b/app/routes/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/routes/chats.py b/app/routes/chats.py new file mode 100644 index 0000000..d59927f --- /dev/null +++ b/app/routes/chats.py @@ -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 diff --git a/app/routes/health.py b/app/routes/health.py new file mode 100644 index 0000000..b807f23 --- /dev/null +++ b/app/routes/health.py @@ -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") diff --git a/app/routes/messages.py b/app/routes/messages.py new file mode 100644 index 0000000..695b4a3 --- /dev/null +++ b/app/routes/messages.py @@ -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) diff --git a/app/routes/users.py b/app/routes/users.py new file mode 100644 index 0000000..61ee0d0 --- /dev/null +++ b/app/routes/users.py @@ -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 diff --git a/app/schemas.py b/app/schemas.py new file mode 100644 index 0000000..2fe3268 --- /dev/null +++ b/app/schemas.py @@ -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 diff --git a/app/storage.py b/app/storage.py new file mode 100644 index 0000000..84fbd21 --- /dev/null +++ b/app/storage.py @@ -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() diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..e279b86 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,4 @@ +[pytest] +pythonpath = . +asyncio_mode = auto +python_files = test_*.py *_test.py tests.py test.py diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..b528540 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +fastapi==0.141.1 +uvicorn[standard]==0.52.4 +pydantic==2.13.5 +pytest==9.1.1 +pytest-asyncio==1.4.0 +httpx==0.28.1 diff --git a/tests_student/conftest.py b/tests_student/conftest.py new file mode 100644 index 0000000..82d1cb2 --- /dev/null +++ b/tests_student/conftest.py @@ -0,0 +1,18 @@ +import os + +import pytest +from httpx import ASGITransport, AsyncClient + +from app.main import app + + +@pytest.fixture +async def client(): + base_url = os.getenv("BASE_URL", "http://testserver") + if base_url.startswith("http://testserver"): + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://testserver") as ac: + yield ac + else: + async with AsyncClient(base_url=base_url) as ac: + yield ac diff --git a/tests_student/tests.py b/tests_student/tests.py new file mode 100644 index 0000000..ba79c1e --- /dev/null +++ b/tests_student/tests.py @@ -0,0 +1,320 @@ +import asyncio +import uuid + +import pytest +from httpx import AsyncClient + + +@pytest.mark.asyncio +async def test_invalid_json_and_extra_fields(client: AsyncClient): + """Проверка невалидного JSON и запрета лишних полей (400 invalid_request).""" + # 1. Невалидный синтаксис JSON + res_malformed = await client.post( + "/api/v1/users", + content="not a valid json {", + headers={"Content-Type": "application/json"}, + ) + assert res_malformed.status_code == 400 + err_malformed = res_malformed.json() + assert err_malformed["error"]["code"] == "invalid_request" + assert "request_id" in err_malformed["error"] + assert ( + res_malformed.headers.get("X-Request-Id") + == err_malformed["error"]["request_id"] + ) + + # 2. Лишние поля (additionalProperties: false) + res_extra = await client.post( + "/api/v1/users", + json={ + "username": f"u_{uuid.uuid4().hex[:8]}", + "display_name": "test_user", + "unexpected_field": "hacker_payload", + }, + ) + assert res_extra.status_code == 400 + err_extra = res_extra.json() + assert err_extra["error"]["code"] == "invalid_request" + + # 3. Запрет завершающего перевода строки в username ("abc\n") + res_newline = await client.post( + "/api/v1/users", + json={"username": "abc\n", "display_name": "test_newline"}, + ) + assert res_newline.status_code == 400 + assert res_newline.json()["error"]["code"] == "invalid_request" + + # 4. Валидация курсора: не-dict JSON (W10= -> []) и пустой cursor= + user_res = ( + await client.post( + "/api/v1/users", + json={"username": f"u_{uuid.uuid4().hex[:8]}", "display_name": "test_cursor_val"}, + ) + ).json() + headers = {"X-User-Id": user_res["id"]} + + # cursor=W10= (декодируется в list [], а не dict) + res_w10 = await client.get("/api/v1/chats?cursor=W10=", headers=headers) + assert res_w10.status_code == 400 + assert res_w10.json()["error"]["code"] == "invalid_request" + + # пустой cursor= + res_empty_cursor = await client.get("/api/v1/chats?cursor=", headers=headers) + assert res_empty_cursor.status_code == 400 + assert res_empty_cursor.json()["error"]["code"] == "invalid_request" + + +@pytest.mark.asyncio +async def test_outsider_chat_access_is_404(client: AsyncClient): + """Проверка того, что доступ к чужому чату возвращает строго 404 (а не 403).""" + # Создаём двух участников чата + test_user1 = ( + await client.post( + "/api/v1/users", + json={"username": f"u1_{uuid.uuid4().hex[:8]}", "display_name": "test_user1"}, + ) + ).json() + test_user2 = ( + await client.post( + "/api/v1/users", + json={"username": f"u2_{uuid.uuid4().hex[:8]}", "display_name": "test_user2"}, + ) + ).json() + # Создаём стороннего пользователя + test_user3 = ( + await client.post( + "/api/v1/users", + json={"username": f"u3_{uuid.uuid4().hex[:8]}", "display_name": "test_user3"}, + ) + ).json() + + # Первый пользователь создаёт чат со вторым + chat = ( + await client.post( + "/api/v1/chats", + headers={"X-User-Id": test_user1["id"]}, + json={"title": "Private Chat", "member_ids": [test_user1["id"], test_user2["id"]]}, + ) + ).json() + + chat_id = chat["id"] + + # Сторонний пользователь пытается получить чат по ID -> 404 + res_chat = await client.get( + f"/api/v1/chats/{chat_id}", headers={"X-User-Id": test_user3["id"]} + ) + assert res_chat.status_code == 404 + assert res_chat.json()["error"]["code"] == "not_found" + + # Сторонний пользователь пытается отправить сообщение в чужой чат -> 404 + res_post = await client.post( + f"/api/v1/chats/{chat_id}/messages", + headers={"X-User-Id": test_user3["id"]}, + json={"text": "Привет извне"}, + ) + assert res_post.status_code == 404 + assert res_post.json()["error"]["code"] == "not_found" + + # Сторонний пользователь пытается прочитать сообщения чужого чата -> 404 + res_msgs = await client.get( + f"/api/v1/chats/{chat_id}/messages", headers={"X-User-Id": test_user3["id"]} + ) + assert res_msgs.status_code == 404 + assert res_msgs.json()["error"]["code"] == "not_found" + + +@pytest.mark.asyncio +async def test_empty_and_whitespace_message(client: AsyncClient): + """Проверка отправки пустого сообщения или сообщения только из пробелов (400).""" + user = ( + await client.post( + "/api/v1/users", + json={"username": f"u_{uuid.uuid4().hex[:8]}", "display_name": "test_user"}, + ) + ).json() + chat = ( + await client.post( + "/api/v1/chats", + headers={"X-User-Id": user["id"]}, + json={"title": "Chat", "member_ids": [user["id"]]}, + ) + ).json() + + # Пустая строка + res_empty = await client.post( + f"/api/v1/chats/{chat['id']}/messages", + headers={"X-User-Id": user["id"]}, + json={"text": ""}, + ) + assert res_empty.status_code == 400 + assert res_empty.json()["error"]["code"] == "invalid_request" + + # Только пробелы и переводы строк + res_spaces = await client.post( + f"/api/v1/chats/{chat['id']}/messages", + headers={"X-User-Id": user["id"]}, + json={"text": " \t \n "}, + ) + assert res_spaces.status_code == 400 + assert res_spaces.json()["error"]["code"] == "invalid_request" + + +@pytest.mark.asyncio +async def test_duplicate_username_conflict(client: AsyncClient): + """Проверка регистрации пользователя с уже занятым username (409).""" + uname = f"unique_{uuid.uuid4().hex[:8]}" + res1 = await client.post( + "/api/v1/users", json={"username": uname, "display_name": "test_user1"} + ) + assert res1.status_code == 201 + + res2 = await client.post( + "/api/v1/users", json={"username": uname, "display_name": "test_user2"} + ) + assert res2.status_code == 409 + err = res2.json() + assert err["error"]["code"] == "conflict" + + +@pytest.mark.asyncio +async def test_multi_page_cursor_pagination(client: AsyncClient): + """Проверка обхода нескольких страниц по keyset-курсору.""" + user = ( + await client.post( + "/api/v1/users", + json={"username": f"pag_{uuid.uuid4().hex[:8]}", "display_name": "test_user"}, + ) + ).json() + chat = ( + await client.post( + "/api/v1/chats", + headers={"X-User-Id": user["id"]}, + json={"title": "Pagination Chat", "member_ids": [user["id"]]}, + ) + ).json() + chat_id = chat["id"] + + # Отправляем 5 сообщений + sent_texts = [f"Message #{i}" for i in range(1, 6)] + created_messages = [] + for txt in sent_texts: + res = await client.post( + f"/api/v1/chats/{chat_id}/messages", + headers={"X-User-Id": user["id"]}, + json={"text": txt}, + ) + assert res.status_code == 201 + created_messages.append(res.json()) + + # Страница 1: limit=2 + p1 = ( + await client.get( + f"/api/v1/chats/{chat_id}/messages?limit=2", + headers={"X-User-Id": user["id"]}, + ) + ).json() + assert len(p1["items"]) == 2 + assert p1["next_cursor"] is not None + + # Страница 2: limit=2 с курсором со страницы 1 + p2 = ( + await client.get( + f"/api/v1/chats/{chat_id}/messages?limit=2&cursor={p1['next_cursor']}", + headers={"X-User-Id": user["id"]}, + ) + ).json() + assert len(p2["items"]) == 2 + assert p2["next_cursor"] is not None + + # Страница 3: limit=2 с курсором со страницы 2 -> остался 1 элемент, next_cursor == None + p3 = ( + await client.get( + f"/api/v1/chats/{chat_id}/messages?limit=2&cursor={p2['next_cursor']}", + headers={"X-User-Id": user["id"]}, + ) + ).json() + assert len(p3["items"]) == 1 + assert p3["next_cursor"] is None + + # Проверяем, что все 5 сообщений собраны без повторов и потерь + all_retrieved = p1["items"] + p2["items"] + p3["items"] + assert len(all_retrieved) == 5 + assert [m["id"] for m in all_retrieved] == [m["id"] for m in created_messages] + + +@pytest.mark.asyncio +async def test_concurrency_race_condition(client: AsyncClient): + """ + Защита состояния от гонок: + Параллельно отправляем 100 сообщений от 10 клиентов, + затем получаем ровно 100 уникальных сообщений без повреждений. + """ + # 1. Создаём 10 клиентов + users = [] + for i in range(10): + u = ( + await client.post( + "/api/v1/users", + json={ + "username": f"conc_{i}_{uuid.uuid4().hex[:6]}", + "display_name": f"test_user_{i}", + }, + ) + ).json() + users.append(u) + + user_ids = [u["id"] for u in users] + + # 2. Создаём чат со всеми 10 участниками + chat = ( + await client.post( + "/api/v1/chats", + headers={"X-User-Id": user_ids[0]}, + json={"title": "Highload Concurrency Chat", "member_ids": user_ids}, + ) + ).json() + chat_id = chat["id"] + + # 3. Каждый из 10 клиентов отправляет по 10 сообщений параллельно (итого 100 сообщений) + async def send_batch(user, client_idx): + tasks = [] + for msg_idx in range(10): + text = f"client-{client_idx}-msg-{msg_idx}" + tasks.append( + client.post( + f"/api/v1/chats/{chat_id}/messages", + headers={"X-User-Id": user["id"]}, + json={"text": text}, + ) + ) + return await asyncio.gather(*tasks) + + # Запускаем отправку от всех 10 клиентов одновременно + batch_results = await asyncio.gather(*[send_batch(users[i], i) for i in range(10)]) + + # Проверяем, что все 100 запросов завершились со статусом 201 Created + all_responses = [resp for batch in batch_results for resp in batch] + assert len(all_responses) == 100 + for resp in all_responses: + assert resp.status_code == 201 + + # 4. Читаем все сообщения из чата (limit=100) + history_res = await client.get( + f"/api/v1/chats/{chat_id}/messages?limit=100", + headers={"X-User-Id": user_ids[0]}, + ) + assert history_res.status_code == 200 + history = history_res.json() + items = history["items"] + + # параллельно отправим 100 сообщений от 10 клиентов, затем получаем ровно 100 уникальных сообщений + assert len(items) == 100, f"Expected 100 messages, received {len(items)}" + unique_ids = {m["id"] for m in items} + assert len(unique_ids) == 100, "Found duplicate message IDs" + + # Проверяем монотонную сортировку (created_at, id) + for idx in range(len(items) - 1): + assert (items[idx]["created_at"], items[idx]["id"]) <= ( + items[idx + 1]["created_at"], + items[idx + 1]["id"], + )