Реализация лабораторной работы 4 на 4
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
from .api import app as api_endpoints
|
||||
from .api import health_router as health_endpoints
|
||||
|
||||
__all__ = ["api_endpoints", "health_endpoints"]
|
||||
@@ -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 basic_credentials, bearer_token
|
||||
|
||||
__all__ = ["get_current_user", "basic_credentials", "bearer_token"]
|
||||
@@ -0,0 +1,15 @@
|
||||
from fastapi import Depends
|
||||
|
||||
from domain import UserSchema
|
||||
from infrastructure.dependencies import ServiceCreator
|
||||
from infrastructure.services import AuthService
|
||||
|
||||
from .security import bearer_token
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
token: str | None = Depends(bearer_token),
|
||||
service: AuthService = Depends(ServiceCreator.get_auth_service),
|
||||
) -> UserSchema:
|
||||
"""Владелец действующей Bearer-сессии; X-User-Id не учитывается; иначе 401"""
|
||||
return await service.authenticate(token)
|
||||
@@ -0,0 +1,52 @@
|
||||
import base64
|
||||
import binascii
|
||||
|
||||
from fastapi import Depends
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from fastapi.security.http import HTTPBase
|
||||
|
||||
from domain import BasicCredentialsSchema
|
||||
from domain.errors import InvalidCredentialsError
|
||||
|
||||
BASIC_SCHEME = "basic"
|
||||
|
||||
basic_scheme = HTTPBase(
|
||||
scheme=BASIC_SCHEME,
|
||||
scheme_name="basicAuth",
|
||||
description="Только для POST /auth/sessions",
|
||||
auto_error=False,
|
||||
)
|
||||
|
||||
bearer_scheme = HTTPBearer(
|
||||
scheme_name="bearerAuth",
|
||||
bearerFormat="opaque session token",
|
||||
auto_error=False,
|
||||
)
|
||||
|
||||
|
||||
async def basic_credentials(
|
||||
authorization: HTTPAuthorizationCredentials | None = Depends(basic_scheme),
|
||||
) -> BasicCredentialsSchema:
|
||||
"""
|
||||
Authorization: Basic base64(username:password)
|
||||
|
||||
username — до первого двоеточия, остальное — пароль
|
||||
Любая ошибка формата — тот же 401, что и неверный пароль.
|
||||
"""
|
||||
if authorization is None or authorization.scheme.lower() != BASIC_SCHEME:
|
||||
raise InvalidCredentialsError()
|
||||
try:
|
||||
decoded = base64.b64decode(authorization.credentials, validate=True)
|
||||
username, separator, password = decoded.decode("utf-8").partition(":")
|
||||
except (binascii.Error, UnicodeDecodeError):
|
||||
raise InvalidCredentialsError() from None
|
||||
if not separator or not username.isascii():
|
||||
raise InvalidCredentialsError()
|
||||
return BasicCredentialsSchema(username=username, password=password)
|
||||
|
||||
|
||||
async def bearer_token(
|
||||
authorization: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
|
||||
) -> str | None:
|
||||
"""Токен из Authorization: Bearer; другие схемы (Basic) — как отсутствие"""
|
||||
return authorization.credentials if authorization is not None else None
|
||||
@@ -0,0 +1,3 @@
|
||||
from .exceptions import register_exception_handlers
|
||||
|
||||
__all__ = ["register_exception_handlers"]
|
||||
@@ -0,0 +1,61 @@
|
||||
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,
|
||||
error.headers,
|
||||
)
|
||||
|
||||
|
||||
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,36 @@
|
||||
from fastapi import APIRouter, Depends, Request, status
|
||||
|
||||
from domain import HealthSchema
|
||||
from domain.errors import UnavailableError
|
||||
from infrastructure.dependencies import DatabasePoolManager, get_database
|
||||
|
||||
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, database: DatabasePoolManager = Depends(get_database)
|
||||
) -> HealthSchema:
|
||||
"""
|
||||
Приложение не завершается и PostgreSQL отвечает. Valkey не критичен:
|
||||
без него сессии читаются из PostgreSQL, поэтому он не влияет на готовность.
|
||||
"""
|
||||
if not getattr(request.app.state, "is_ready", False):
|
||||
raise UnavailableError()
|
||||
if not await database.check():
|
||||
raise UnavailableError("бд недоступна")
|
||||
return HealthSchema()
|
||||
@@ -0,0 +1,3 @@
|
||||
from .request_context import RequestContextMiddleware
|
||||
|
||||
__all__ = ["RequestContextMiddleware"]
|
||||
@@ -0,0 +1,71 @@
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from fastapi import Request, Response
|
||||
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
|
||||
|
||||
from application.api.utils import INSTANCE_ID_HEADER, REQUEST_ID_HEADER, error_response
|
||||
from config import INSTANCE_ID, LOGGER
|
||||
from domain.errors import AppError
|
||||
|
||||
HEALTH_PATH_PREFIX = "/health/"
|
||||
|
||||
INCOMING_REQUEST_ID = re.compile(r"^[0-9a-f]{32}$")
|
||||
|
||||
|
||||
class RequestContextMiddleware(BaseHTTPMiddleware):
|
||||
"""
|
||||
X-Request-Id и X-Instance-Id в каждом ответе, журнал запросов и защита
|
||||
от необработанных ошибок.
|
||||
|
||||
X-Request-Id берётся у балансировщика (nginx выставляет $request_id),
|
||||
поэтому одна строка access-лога LB и журнал реплики связаны одним ID.
|
||||
В лог попадают метод, путь, статус и длительность — без тел запросов,
|
||||
query-параметров и текста сообщений.
|
||||
"""
|
||||
|
||||
async def dispatch(
|
||||
self, request: Request, call_next: RequestResponseEndpoint
|
||||
) -> Response:
|
||||
request_id = self._request_id(request)
|
||||
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
|
||||
response.headers[INSTANCE_ID_HEADER] = INSTANCE_ID
|
||||
if getattr(request.app.state, "is_draining", False):
|
||||
response.headers["Connection"] = "close"
|
||||
self._log_request(request, response, request_id, started)
|
||||
return response
|
||||
|
||||
@staticmethod
|
||||
def _request_id(request: Request) -> str:
|
||||
incoming = request.headers.get(REQUEST_ID_HEADER, "")
|
||||
if INCOMING_REQUEST_ID.fullmatch(incoming):
|
||||
return incoming
|
||||
return uuid.uuid4().hex
|
||||
|
||||
@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,17 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from .auth import auth_router
|
||||
from .chats import chats_router
|
||||
from .messages import messages_router
|
||||
from .users import users_router
|
||||
from .attachments.endpoints import attachments_router
|
||||
|
||||
app = APIRouter(prefix="/v1")
|
||||
|
||||
app.include_router(users_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(chats_router)
|
||||
app.include_router(messages_router)
|
||||
app.include_router(attachments_router)
|
||||
|
||||
__all__ = ["app"]
|
||||
@@ -0,0 +1,2 @@
|
||||
from .endpoints import attachments_router
|
||||
__all__ = ["attachments_router"]
|
||||
@@ -0,0 +1,58 @@
|
||||
import tempfile
|
||||
import os
|
||||
import hashlib
|
||||
from uuid import UUID
|
||||
from fastapi import APIRouter, Depends, Request, Query, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
from application.api.dependencies import get_current_user
|
||||
from domain import UserSchema, AttachmentSchema
|
||||
from infrastructure.dependencies import ServiceCreator
|
||||
from infrastructure.services import AttachmentService
|
||||
from infrastructure.services.attachment_service.attachment_service import PayloadTooLargeError
|
||||
|
||||
attachments_router = APIRouter(tags=["Attachments"])
|
||||
|
||||
@attachments_router.post("/chats/{chat_id}/attachments", status_code=status.HTTP_201_CREATED, response_model=AttachmentSchema)
|
||||
async def upload_attachment(
|
||||
chat_id: UUID,
|
||||
request: Request,
|
||||
filename: str = Query(...),
|
||||
current_user: UserSchema = Depends(get_current_user),
|
||||
service: AttachmentService = Depends(ServiceCreator.get_attachment_service)
|
||||
) -> AttachmentSchema:
|
||||
temp_file = tempfile.NamedTemporaryFile(delete=False)
|
||||
temp_path = temp_file.name
|
||||
try:
|
||||
size = 0
|
||||
hasher = hashlib.sha256()
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > 10 * 1024 * 1024:
|
||||
temp_file.close()
|
||||
raise PayloadTooLargeError()
|
||||
hasher.update(chunk)
|
||||
temp_file.write(chunk)
|
||||
temp_file.close()
|
||||
|
||||
return await service.process_and_save(temp_path, filename, chat_id, current_user.id, size, hasher.hexdigest())
|
||||
finally:
|
||||
if os.path.exists(temp_path):
|
||||
os.remove(temp_path)
|
||||
|
||||
@attachments_router.get("/attachments/{attachment_id}", status_code=status.HTTP_200_OK, response_model=AttachmentSchema)
|
||||
async def get_attachment_meta(
|
||||
attachment_id: UUID,
|
||||
current_user: UserSchema = Depends(get_current_user),
|
||||
service: AttachmentService = Depends(ServiceCreator.get_attachment_service)
|
||||
) -> AttachmentSchema:
|
||||
return await service.get_attachment_meta(attachment_id, current_user.id)
|
||||
|
||||
@attachments_router.get("/attachments/{attachment_id}/content")
|
||||
async def get_attachment_content(
|
||||
attachment_id: UUID,
|
||||
variant: str = Query("original"),
|
||||
current_user: UserSchema = Depends(get_current_user),
|
||||
service: AttachmentService = Depends(ServiceCreator.get_attachment_service)
|
||||
):
|
||||
stream_gen, mime = await service.get_attachment_stream(attachment_id, current_user.id)
|
||||
return StreamingResponse(stream_gen, media_type=mime)
|
||||
@@ -0,0 +1,3 @@
|
||||
from .endpoints import auth_router
|
||||
|
||||
__all__ = ["auth_router"]
|
||||
@@ -0,0 +1,35 @@
|
||||
from fastapi import APIRouter, Depends, Response, status
|
||||
|
||||
from application.api.dependencies import basic_credentials, bearer_token
|
||||
from domain import BasicCredentialsSchema, SessionSchema
|
||||
from infrastructure.dependencies import ServiceCreator
|
||||
from infrastructure.services import AuthService
|
||||
|
||||
auth_router = APIRouter(prefix="/auth/sessions", tags=["Auth"])
|
||||
|
||||
|
||||
@auth_router.post(
|
||||
"",
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
response_model=SessionSchema,
|
||||
)
|
||||
async def create_session(
|
||||
credentials: BasicCredentialsSchema = Depends(basic_credentials),
|
||||
service: AuthService = Depends(ServiceCreator.get_auth_service),
|
||||
) -> SessionSchema:
|
||||
"""Вход по Basic, без JSON body; возвращает Bearer-токен"""
|
||||
return await service.login(credentials)
|
||||
|
||||
|
||||
@auth_router.delete(
|
||||
"/current",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
response_class=Response,
|
||||
)
|
||||
async def revoke_session(
|
||||
token: str | None = Depends(bearer_token),
|
||||
service: AuthService = Depends(ServiceCreator.get_auth_service),
|
||||
) -> Response:
|
||||
"""Logout: текущий токен перестаёт действовать; повтор — 401"""
|
||||
await service.logout(token)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -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,63 @@
|
||||
from typing import Annotated
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, Header, Query, status
|
||||
|
||||
from application.api.dependencies import get_current_user
|
||||
from domain import (
|
||||
IDEMPOTENCY_KEY_MAX_LENGTH,
|
||||
IDEMPOTENCY_KEY_PATTERN,
|
||||
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(...)],
|
||||
idempotency_key: Annotated[
|
||||
str,
|
||||
Header(
|
||||
alias="Idempotency-Key",
|
||||
min_length=1,
|
||||
max_length=IDEMPOTENCY_KEY_MAX_LENGTH,
|
||||
pattern=IDEMPOTENCY_KEY_PATTERN,
|
||||
),
|
||||
],
|
||||
current_user: UserSchema = Depends(get_current_user),
|
||||
service: MessageService = Depends(ServiceCreator.get_message_service),
|
||||
) -> MessageSchema:
|
||||
"""
|
||||
Idempotency-Key обязателен: повтор того же тела возвращает тот же 201
|
||||
и то же сообщение, другое тело с тем же ключом — 409. Нет/неверный ключ — 400.
|
||||
"""
|
||||
return await service.send_message(current_user, chat_id, body, idempotency_key)
|
||||
|
||||
|
||||
@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,13 @@
|
||||
from .errors import (
|
||||
INSTANCE_ID_HEADER,
|
||||
REQUEST_ID_HEADER,
|
||||
error_response,
|
||||
get_request_id,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"REQUEST_ID_HEADER",
|
||||
"INSTANCE_ID_HEADER",
|
||||
"error_response",
|
||||
"get_request_id",
|
||||
]
|
||||
@@ -0,0 +1,33 @@
|
||||
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"
|
||||
INSTANCE_ID_HEADER = "X-Instance-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