forked from mtusi2026/mtusi2026lab6
167 lines
7.0 KiB
Python
167 lines
7.0 KiB
Python
import uuid
|
|
import os
|
|
import socket
|
|
from contextlib import asynccontextmanager
|
|
import psycopg
|
|
from psycopg_pool import PoolTimeout, TooManyRequests
|
|
from starlette.concurrency import run_in_threadpool
|
|
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.responses import JSONResponse
|
|
from pydantic import ValidationError as PydanticValidationError
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
|
|
from src.models import ErrorResponse
|
|
from src.routes import chats, health, messages, users, attachments
|
|
from botocore.exceptions import BotoCoreError, ClientError
|
|
from src.storage import storage
|
|
|
|
|
|
def create_app() -> FastAPI:
|
|
"""Создать и настроить приложение FastAPI."""
|
|
@asynccontextmanager
|
|
async def lifespan(app):
|
|
await run_in_threadpool(storage.pool.open, wait=True)
|
|
try:
|
|
yield
|
|
finally:
|
|
await run_in_threadpool(storage.pool.close)
|
|
|
|
instance_id = os.getenv("INSTANCE_ID", socket.gethostname()) + "-" + uuid.uuid4().hex[:8]
|
|
app = FastAPI(title="MTUSI Messenger Lab6", version="1.6.0", lifespan=lifespan)
|
|
|
|
@app.exception_handler(BotoCoreError)
|
|
@app.exception_handler(ClientError)
|
|
@app.exception_handler(psycopg.OperationalError)
|
|
@app.exception_handler(psycopg.errors.QueryCanceled)
|
|
@app.exception_handler(psycopg.errors.LockNotAvailable)
|
|
@app.exception_handler(PoolTimeout)
|
|
@app.exception_handler(TooManyRequests)
|
|
async def dependency_error(request, exc):
|
|
return JSONResponse(status_code=503, content=ErrorResponse(error={
|
|
"code": "unavailable", "message": "хранилище временно недоступно",
|
|
"request_id": request.state.request_id}).model_dump(),
|
|
headers={"X-Request-Id": request.state.request_id})
|
|
|
|
@app.middleware("http")
|
|
async def add_request_id(request: Request, call_next):
|
|
"""Добавляет идентификаторы запроса и процесса, ограничивает очередь."""
|
|
request_id = request.headers.get("X-Request-Id", "") or str(uuid.uuid4())
|
|
request.state.request_id = request_id
|
|
|
|
# Ограничение числа обслуживаемых запросов в процессе.
|
|
if not storage.acquire_request_slot():
|
|
return JSONResponse(
|
|
status_code=503,
|
|
content=ErrorResponse(
|
|
error={
|
|
"code": "unavailable",
|
|
"message": "сервер перегружен, попробуйте позже",
|
|
"request_id": request_id,
|
|
}
|
|
).model_dump(),
|
|
headers={"X-Request-Id": request_id, "X-Instance-Id": instance_id},
|
|
)
|
|
|
|
try:
|
|
response = await call_next(request)
|
|
response.headers["X-Request-Id"] = request_id
|
|
response.headers["X-Instance-Id"] = instance_id
|
|
return response
|
|
finally:
|
|
storage.release_request_slot()
|
|
|
|
@app.exception_handler(StarletteHTTPException)
|
|
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
|
"""Обработчик HTTPException: возвращает ошибку в формате контракта {"error": ...}."""
|
|
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
|
if isinstance(exc.detail, dict) and "error" in exc.detail:
|
|
return JSONResponse(
|
|
status_code=exc.status_code,
|
|
content=exc.detail,
|
|
headers={"X-Request-Id": request_id, **(exc.headers or {})},
|
|
)
|
|
return JSONResponse(
|
|
status_code=exc.status_code,
|
|
content=ErrorResponse(
|
|
error={
|
|
"code": "internal_error",
|
|
"message": str(exc.detail),
|
|
"request_id": request_id,
|
|
}
|
|
).model_dump(),
|
|
headers={"X-Request-Id": request_id, "X-Instance-Id": instance_id},
|
|
)
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def request_validation_handler(request: Request, exc: RequestValidationError):
|
|
"""Перехватываем ошибки валидации запроса (422 -> 400 по контракту)."""
|
|
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
|
errors = exc.errors()
|
|
messages = []
|
|
for err in errors:
|
|
loc = ".".join(str(x) for x in err.get("loc", []))
|
|
messages.append(f"{loc}: {err.get('msg', 'invalid')}")
|
|
return JSONResponse(
|
|
status_code=400,
|
|
content=ErrorResponse(
|
|
error={
|
|
"code": "invalid_request",
|
|
"message": "; ".join(messages),
|
|
"request_id": request_id,
|
|
}
|
|
).model_dump(),
|
|
headers={"X-Request-Id": request_id, "X-Instance-Id": instance_id},
|
|
)
|
|
|
|
@app.exception_handler(PydanticValidationError)
|
|
async def validation_exception_handler(request: Request, exc: PydanticValidationError):
|
|
"""Перехватываем ошибки Pydantic (422 -> 400 по контракту)."""
|
|
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
|
errors = exc.errors()
|
|
messages = []
|
|
for err in errors:
|
|
loc = ".".join(str(x) for x in err.get("loc", []))
|
|
messages.append(f"{loc}: {err.get('msg', 'invalid')}")
|
|
return JSONResponse(
|
|
status_code=400,
|
|
content=ErrorResponse(
|
|
error={
|
|
"code": "invalid_request",
|
|
"message": "; ".join(messages),
|
|
"request_id": request_id,
|
|
}
|
|
).model_dump(),
|
|
headers={"X-Request-Id": request_id, "X-Instance-Id": instance_id},
|
|
)
|
|
|
|
@app.exception_handler(Exception)
|
|
async def generic_exception_handler(request: Request, exc: Exception):
|
|
"""Обработчик непредвиденных исключений: скрываем детали, возвращаем 500."""
|
|
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
|
return JSONResponse(
|
|
status_code=500,
|
|
content=ErrorResponse(
|
|
error={
|
|
"code": "internal_error",
|
|
"message": "внутренняя ошибка сервера",
|
|
"request_id": request_id,
|
|
}
|
|
).model_dump(),
|
|
headers={"X-Request-Id": request_id, "X-Instance-Id": instance_id},
|
|
)
|
|
|
|
# Подключаем роуты
|
|
app.include_router(health.router)
|
|
app.include_router(users.router)
|
|
app.include_router(chats.router)
|
|
app.include_router(messages.router)
|
|
app.include_router(attachments.router)
|
|
|
|
return app
|
|
|
|
|
|
# Экземпляр приложения для uvicorn
|
|
app = create_app()
|