Files
mtusi2026lab4/src/main.py
T
2026-10-20 17:24:32 +03:00

169 lines
5.4 KiB
Python

import asyncio
import logging
import sys
import time
from contextlib import asynccontextmanager
from uuid import uuid4
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
import uvicorn
from starlette.responses import JSONResponse, Response
from starlette.exceptions import HTTPException
from .errors import ApiError
from .cursor import configure_secret
from .models import ErrorDetails, ErrorResponse
from .config import load_settings
from .routes import router
from .attachments import router as attachment_router
from .storage.s3 import S3Settings, S3Store
from .storage.postgres import PostgresStore
def logger(name: str) -> logging.Logger:
result = logging.getLogger(name)
if result.handlers:
return result
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s"))
result.addHandler(handler)
result.setLevel(logging.INFO)
result.propagate = False
return result
access_logger = logger("messenger.access")
@asynccontextmanager
async def lifespan(application: FastAPI):
settings = load_settings()
configure_secret(settings.cursor_secret)
store = PostgresStore(settings.database_url)
await store.connect()
application.state.store = store
application.state.settings = settings
application.state.s3 = S3Store(S3Settings.load())
application.state.upload_slot = asyncio.Semaphore(1)
application.state.accepting_requests = True
try:
yield
finally:
application.state.accepting_requests = False
application.state.s3.client.close()
await store.close()
app = FastAPI(
title="MTUSI Messenger",
version="1.4.0",
redoc_url=None,
lifespan=lifespan,
)
@app.middleware("http")
async def add_request_id(request: Request, call_next) -> Response:
"""Добавляет ID запроса и пишет безопасную строку access-лога."""
request.state.request_id = str(uuid4())
started_at = time.monotonic()
status_code = 500
try:
response = await call_next(request)
status_code = response.status_code
response.headers["X-Request-Id"] = request.state.request_id
response.headers["X-Instance-Id"] = request.app.state.settings.instance_id
return response
finally:
access_logger.info(
"request_id=%s method=%s path=%s status=%s elapsed_ms=%.3f",
request.state.request_id,
request.method,
request.url.path,
status_code,
(time.monotonic() - started_at) * 1000,
)
def error_response(
request: Request, status_code: int, code: str, message: str, headers: dict[str, str] | None = None
) -> JSONResponse:
request_id = request.state.request_id
body = ErrorResponse(
error=ErrorDetails(code=code, message=message, request_id=request_id)
)
# Неожиданная ошибка обрабатывается за пределами HTTP-middleware.
# Поэтому её ответ тоже должен сам получить заголовок из контракта.
return JSONResponse(
status_code=status_code,
content=body.model_dump(),
headers={
"X-Request-Id": request_id,
"X-Instance-Id": request.app.state.settings.instance_id,
**(headers or {}),
},
)
@app.exception_handler(ApiError)
async def handle_api_error(request: Request, error: ApiError) -> JSONResponse:
"""Преобразует контролируемую ошибку API в стандартный JSON-ответ."""
return error_response(request, error.status_code, error.code, error.message, error.headers)
@app.exception_handler(RequestValidationError)
async def handle_validation_error(
request: Request, error: RequestValidationError
) -> JSONResponse:
"""Преобразует ошибки JSON и Pydantic в обязательный ответ 400."""
return error_response(request, 400, "invalid_request", "Некорректный запрос")
@app.exception_handler(HTTPException)
async def handle_http_error(request: Request, error: HTTPException) -> JSONResponse:
"""Включает ошибки декодирования тела, возникающие до Pydantic."""
codes = {
400: "invalid_request",
401: "unauthorized",
403: "forbidden",
404: "not_found",
405: "method_not_allowed",
503: "unavailable",
}
code = codes.get(error.status_code, "internal_error")
return error_response(
request, error.status_code, code,
"Некорректный запрос" if error.status_code < 500 else "Ошибка сервера",
error.headers,
)
@app.exception_handler(Exception)
async def handle_unexpected_error(request: Request, error: Exception) -> JSONResponse:
"""Не раскрывает внутренние детали при непредвиденной ошибке приложения."""
return error_response(request, 500, "internal_error", "Внутренняя ошибка сервера")
app.include_router(router)
app.include_router(attachment_router)
def main() -> None:
settings = load_settings()
uvicorn.run(
app,
host=settings.host,
port=settings.port,
access_log=False,
timeout_graceful_shutdown=8,
)
if __name__ == "__main__":
main()