feat: функционал первой лабы перенос
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from .health import health_router
|
||||
from .routers import app as v1_endpoints
|
||||
|
||||
app = APIRouter(prefix="/api")
|
||||
|
||||
app.include_router(v1_endpoints)
|
||||
|
||||
__all__ = ["app", "health_router"]
|
||||
@@ -0,0 +1,4 @@
|
||||
from .auth import get_current_user
|
||||
from .security import USER_ID_HEADER, user_id_header
|
||||
|
||||
__all__ = ["get_current_user", "user_id_header", "USER_ID_HEADER"]
|
||||
@@ -0,0 +1,15 @@
|
||||
from fastapi import Depends
|
||||
|
||||
from domain import UserSchema
|
||||
from infrastructure.dependencies import ServiceCreator
|
||||
from infrastructure.services import UserService
|
||||
|
||||
from .security import user_id_header
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
raw_user_id: str | None = Depends(user_id_header),
|
||||
service: UserService = Depends(ServiceCreator.get_user_service),
|
||||
) -> UserSchema:
|
||||
"""Текущий пользователь из X-User-Id; иначе 401"""
|
||||
return await service.authenticate(raw_user_id)
|
||||
@@ -0,0 +1,10 @@
|
||||
from fastapi.security import APIKeyHeader
|
||||
|
||||
USER_ID_HEADER = "X-User-Id"
|
||||
|
||||
user_id_header = APIKeyHeader(
|
||||
name=USER_ID_HEADER,
|
||||
scheme_name="devUser",
|
||||
description="uuid существующего пользователя",
|
||||
auto_error=False,
|
||||
)
|
||||
@@ -0,0 +1,3 @@
|
||||
from .exceptions import register_exception_handlers
|
||||
|
||||
__all__ = ["register_exception_handlers"]
|
||||
@@ -0,0 +1,57 @@
|
||||
from http import HTTPStatus
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from application.api.utils import error_response, get_request_id
|
||||
from domain.errors import AppError, ErrorCode, InvalidRequestError, NotFoundError
|
||||
|
||||
|
||||
async def app_error_handler(request: Request, error: Exception) -> JSONResponse:
|
||||
"""Доменные ошибки сервисов и репозиториев"""
|
||||
assert isinstance(error, AppError)
|
||||
return error_response(
|
||||
get_request_id(request), error.status_code, error.code, error.message
|
||||
)
|
||||
|
||||
|
||||
async def validation_error_handler(request: Request, error: Exception) -> JSONResponse:
|
||||
"""Malformed JSON, лишние поля, неверные типы, uuid и limit — 400"""
|
||||
assert isinstance(error, RequestValidationError)
|
||||
return error_response(
|
||||
get_request_id(request),
|
||||
InvalidRequestError.status_code,
|
||||
InvalidRequestError.code,
|
||||
_describe_validation_error(error),
|
||||
)
|
||||
|
||||
|
||||
async def http_error_handler(request: Request, error: Exception) -> JSONResponse:
|
||||
"""Ошибки маршрутизации неизвестный путь, неподдерживаемый метод"""
|
||||
assert isinstance(error, StarletteHTTPException)
|
||||
if error.status_code == HTTPStatus.NOT_FOUND:
|
||||
code, message = NotFoundError.code, NotFoundError.default_message
|
||||
elif error.status_code >= HTTPStatus.INTERNAL_SERVER_ERROR:
|
||||
code, message = AppError.code, AppError.default_message
|
||||
else:
|
||||
code, message = ErrorCode.INVALID_REQUEST, HTTPStatus(error.status_code).phrase
|
||||
return error_response(
|
||||
get_request_id(request), error.status_code, code, message, error.headers
|
||||
)
|
||||
|
||||
|
||||
def _describe_validation_error(error: RequestValidationError) -> str:
|
||||
"""Безопасное описание: только тип и путь поля, без присланного значения"""
|
||||
first = error.errors()[0]
|
||||
if first.get("type") == "json_invalid":
|
||||
return "Некорректный JSON в теле запроса"
|
||||
location = ".".join(str(part) for part in first.get("loc", ()))
|
||||
return f"Некорректное значение: {location}"
|
||||
|
||||
|
||||
def register_exception_handlers(app: FastAPI) -> None:
|
||||
app.add_exception_handler(AppError, app_error_handler)
|
||||
app.add_exception_handler(RequestValidationError, validation_error_handler)
|
||||
app.add_exception_handler(StarletteHTTPException, http_error_handler)
|
||||
@@ -0,0 +1,3 @@
|
||||
from .endpoints import health_router
|
||||
|
||||
__all__ = ["health_router"]
|
||||
@@ -0,0 +1,28 @@
|
||||
from fastapi import APIRouter, Request, status
|
||||
|
||||
from domain import HealthSchema
|
||||
from domain.errors import UnavailableError
|
||||
|
||||
health_router = APIRouter(prefix="/health", tags=["Health"])
|
||||
|
||||
|
||||
@health_router.get(
|
||||
"/live",
|
||||
status_code=status.HTTP_200_OK,
|
||||
response_model=HealthSchema,
|
||||
)
|
||||
async def liveness() -> HealthSchema:
|
||||
"""Процесс жив и обрабатывает хттп"""
|
||||
return HealthSchema()
|
||||
|
||||
|
||||
@health_router.get(
|
||||
"/ready",
|
||||
status_code=status.HTTP_200_OK,
|
||||
response_model=HealthSchema,
|
||||
)
|
||||
async def readiness(request: Request) -> HealthSchema:
|
||||
"""Хранилище создано и приложение не завершается"""
|
||||
if not getattr(request.app.state, "is_ready", False):
|
||||
raise UnavailableError()
|
||||
return HealthSchema()
|
||||
@@ -0,0 +1,3 @@
|
||||
from .request_context import RequestContextMiddleware
|
||||
|
||||
__all__ = ["RequestContextMiddleware"]
|
||||
@@ -0,0 +1,55 @@
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from fastapi import Request, Response
|
||||
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
|
||||
|
||||
from application.api.utils import REQUEST_ID_HEADER, error_response
|
||||
from config import LOGGER
|
||||
from domain.errors import AppError
|
||||
|
||||
HEALTH_PATH_PREFIX = "/health/"
|
||||
|
||||
|
||||
class RequestContextMiddleware(BaseHTTPMiddleware):
|
||||
"""
|
||||
X-Request-Id в каждом ответе, журнал запросов и защита от необработанных ошибок.
|
||||
|
||||
В лог попадают метод, путь, статус и длительность — без тел запросов,
|
||||
query-параметров и текста сообщений.
|
||||
"""
|
||||
|
||||
async def dispatch(
|
||||
self, request: Request, call_next: RequestResponseEndpoint
|
||||
) -> Response:
|
||||
request_id = uuid.uuid4().hex
|
||||
request.state.request_id = request_id
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except Exception:
|
||||
LOGGER.exception(f"Необработанная ошибка | request_id={request_id}")
|
||||
error = AppError()
|
||||
response = error_response(
|
||||
request_id, error.status_code, error.code, error.message
|
||||
)
|
||||
response.headers[REQUEST_ID_HEADER] = request_id
|
||||
self._log_request(request, response, request_id, started)
|
||||
return response
|
||||
|
||||
@staticmethod
|
||||
def _log_request(
|
||||
request: Request, response: Response, request_id: str, started: float
|
||||
) -> None:
|
||||
duration_ms = (time.perf_counter() - started) * 1000
|
||||
if response.status_code >= 500:
|
||||
level = "ERROR"
|
||||
elif request.url.path.startswith(HEALTH_PATH_PREFIX):
|
||||
level = "DEBUG"
|
||||
else:
|
||||
level = "INFO"
|
||||
LOGGER.log(
|
||||
level,
|
||||
f"{request.method} {request.url.path} -> {response.status_code} "
|
||||
f"| {duration_ms:.1f} ms | request_id={request_id}",
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from .chats import chats_router
|
||||
from .messages import messages_router
|
||||
from .users import users_router
|
||||
|
||||
app = APIRouter(prefix="/v1")
|
||||
|
||||
app.include_router(users_router)
|
||||
app.include_router(chats_router)
|
||||
app.include_router(messages_router)
|
||||
|
||||
__all__ = ["app"]
|
||||
@@ -0,0 +1,3 @@
|
||||
from .endpoints import chats_router
|
||||
|
||||
__all__ = ["chats_router"]
|
||||
@@ -0,0 +1,58 @@
|
||||
from typing import Annotated
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, Query, status
|
||||
|
||||
from application.api.dependencies import get_current_user
|
||||
from domain import (
|
||||
ChatPageSchema,
|
||||
ChatSchema,
|
||||
CreateChatSchema,
|
||||
UserSchema,
|
||||
)
|
||||
from infrastructure.dependencies import ServiceCreator
|
||||
from infrastructure.services import ChatService
|
||||
|
||||
chats_router = APIRouter(prefix="/chats", tags=["Chats"])
|
||||
|
||||
|
||||
@chats_router.post(
|
||||
"",
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
response_model=ChatSchema,
|
||||
)
|
||||
async def create_chat(
|
||||
body: Annotated[CreateChatSchema, Body(...)],
|
||||
current_user: UserSchema = Depends(get_current_user),
|
||||
service: ChatService = Depends(ServiceCreator.get_chat_service),
|
||||
) -> ChatSchema:
|
||||
"""Вызывающий должен входить в member_ids"""
|
||||
return await service.create_chat(current_user, body)
|
||||
|
||||
|
||||
@chats_router.get(
|
||||
"",
|
||||
status_code=status.HTTP_200_OK,
|
||||
response_model=ChatPageSchema,
|
||||
)
|
||||
async def list_chats(
|
||||
limit: Annotated[int, Query(ge=1, le=100)] = 50,
|
||||
cursor: Annotated[str | None, Query(min_length=1)] = None,
|
||||
current_user: UserSchema = Depends(get_current_user),
|
||||
service: ChatService = Depends(ServiceCreator.get_chat_service),
|
||||
) -> ChatPageSchema:
|
||||
"""Чаты текущего пользователя по (created_at, id) по возрастанию"""
|
||||
return await service.list_chats(current_user, limit, cursor)
|
||||
|
||||
|
||||
@chats_router.get(
|
||||
"/{chat_id}",
|
||||
status_code=status.HTTP_200_OK,
|
||||
response_model=ChatSchema,
|
||||
)
|
||||
async def get_chat(
|
||||
chat_id: UUID,
|
||||
current_user: UserSchema = Depends(get_current_user),
|
||||
service: ChatService = Depends(ServiceCreator.get_chat_service),
|
||||
) -> ChatSchema:
|
||||
return await service.get_chat(current_user, chat_id)
|
||||
@@ -0,0 +1,3 @@
|
||||
from .endpoints import messages_router
|
||||
|
||||
__all__ = ["messages_router"]
|
||||
@@ -0,0 +1,48 @@
|
||||
from typing import Annotated
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, Query, status
|
||||
|
||||
from application.api.dependencies import get_current_user
|
||||
from domain import (
|
||||
CreateMessageSchema,
|
||||
MessagePageSchema,
|
||||
MessageSchema,
|
||||
UserSchema,
|
||||
)
|
||||
from infrastructure.dependencies import ServiceCreator
|
||||
from infrastructure.services import MessageService
|
||||
|
||||
messages_router = APIRouter(
|
||||
prefix="/chats/{chat_id}/messages", tags=["Messages"]
|
||||
)
|
||||
|
||||
|
||||
@messages_router.post(
|
||||
"",
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
response_model=MessageSchema,
|
||||
)
|
||||
async def send_message(
|
||||
chat_id: UUID,
|
||||
body: Annotated[CreateMessageSchema, Body(...)],
|
||||
current_user: UserSchema = Depends(get_current_user),
|
||||
service: MessageService = Depends(ServiceCreator.get_message_service),
|
||||
) -> MessageSchema:
|
||||
return await service.send_message(current_user, chat_id, body)
|
||||
|
||||
|
||||
@messages_router.get(
|
||||
"",
|
||||
status_code=status.HTTP_200_OK,
|
||||
response_model=MessagePageSchema,
|
||||
)
|
||||
async def list_messages(
|
||||
chat_id: UUID,
|
||||
limit: Annotated[int, Query(ge=1, le=100)] = 50,
|
||||
cursor: Annotated[str | None, Query(min_length=1)] = None,
|
||||
current_user: UserSchema = Depends(get_current_user),
|
||||
service: MessageService = Depends(ServiceCreator.get_message_service),
|
||||
) -> MessagePageSchema:
|
||||
"""История чата: keyset cursor по (created_at, id) по возрастанию"""
|
||||
return await service.list_messages(current_user, chat_id, limit, cursor)
|
||||
@@ -0,0 +1,3 @@
|
||||
from .endpoints import users_router
|
||||
|
||||
__all__ = ["users_router"]
|
||||
@@ -0,0 +1,33 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, status
|
||||
|
||||
from application.api.dependencies import get_current_user
|
||||
from domain import CreateUserSchema, UserSchema
|
||||
from infrastructure.dependencies import ServiceCreator
|
||||
from infrastructure.services import UserService
|
||||
|
||||
users_router = APIRouter(prefix="/users", tags=["Users"])
|
||||
|
||||
|
||||
@users_router.post(
|
||||
"",
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
response_model=UserSchema,
|
||||
openapi_extra={"security": []},
|
||||
)
|
||||
async def register_user(
|
||||
body: Annotated[CreateUserSchema, Body(...)],
|
||||
service: UserService = Depends(ServiceCreator.get_user_service),
|
||||
) -> UserSchema:
|
||||
"""Публичная регистрация; username уникален"""
|
||||
return await service.register(body)
|
||||
|
||||
|
||||
@users_router.get(
|
||||
"/me",
|
||||
status_code=status.HTTP_200_OK,
|
||||
response_model=UserSchema,
|
||||
)
|
||||
async def get_me(current_user: UserSchema = Depends(get_current_user)) -> UserSchema:
|
||||
return current_user
|
||||
@@ -0,0 +1,3 @@
|
||||
from .errors import REQUEST_ID_HEADER, error_response, get_request_id
|
||||
|
||||
__all__ = ["REQUEST_ID_HEADER", "error_response", "get_request_id"]
|
||||
@@ -0,0 +1,32 @@
|
||||
from collections.abc import Mapping
|
||||
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from domain.errors import ErrorBodySchema, ErrorCode, ErrorSchema
|
||||
|
||||
REQUEST_ID_HEADER = "X-Request-Id"
|
||||
|
||||
|
||||
def get_request_id(request: Request) -> str:
|
||||
"""ID запроса, назначенный RequestContextMiddleware"""
|
||||
request_id: str = request.state.request_id
|
||||
return request_id
|
||||
|
||||
|
||||
def error_response(
|
||||
request_id: str,
|
||||
status_code: int,
|
||||
code: ErrorCode,
|
||||
message: str,
|
||||
headers: Mapping[str, str] | None = None,
|
||||
) -> JSONResponse:
|
||||
"""Ответ в едином формате ошибки контракта"""
|
||||
body = ErrorSchema(
|
||||
error=ErrorBodySchema(code=code, message=message, request_id=request_id)
|
||||
)
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content=body.model_dump(mode="json"),
|
||||
headers={**(headers or {}), REQUEST_ID_HEADER: request_id},
|
||||
)
|
||||
Reference in New Issue
Block a user