121 lines
4.2 KiB
Python
121 lines
4.2 KiB
Python
import logging
|
|
import time
|
|
import uuid
|
|
from typing import Annotated
|
|
|
|
from fastapi import Depends, FastAPI, Request
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.responses import JSONResponse
|
|
from redis.exceptions import RedisError
|
|
from sqlalchemy import select
|
|
from sqlalchemy.exc import DBAPIError
|
|
from sqlalchemy.exc import TimeoutError as DatabaseTimeoutError
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
|
|
from src.api.router import router as api_router
|
|
from src.core import cache
|
|
from src.core.callback import lifespan
|
|
from src.core.db.session import get_db_session
|
|
from src.core.errors import ApiError, error_response
|
|
from src.core.request_limits import RequestLimitsMiddleware
|
|
from src.core.settings import settings
|
|
|
|
logging.basicConfig(level=settings.log_level, format=settings.log_format)
|
|
|
|
app = FastAPI(lifespan=lifespan)
|
|
app.add_middleware(RequestLimitsMiddleware)
|
|
app.include_router(api_router)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
@app.middleware("http")
|
|
async def add_request_id(request: Request, call_next):
|
|
request_id = str(uuid.uuid4())
|
|
request.state.request_id = request_id
|
|
started_at = time.perf_counter()
|
|
|
|
try:
|
|
response = await call_next(request)
|
|
except Exception:
|
|
logger.exception(
|
|
"Необработанная ошибка запроса",
|
|
extra={"request_id": request_id},
|
|
)
|
|
|
|
response = JSONResponse(
|
|
status_code=500,
|
|
content={
|
|
"error": {
|
|
"code": "internal_error",
|
|
"message": "Внутренняя ошибка сервера",
|
|
"request_id": request_id,
|
|
}
|
|
},
|
|
)
|
|
|
|
response.headers["X-Request-Id"] = request_id
|
|
if request.url.path.startswith("/api/v1/"):
|
|
response.headers["Cache-Control"] = "no-store"
|
|
response.headers["X-Content-Type-Options"] = "nosniff"
|
|
logger.info(
|
|
"ид_запроса=%s метод=%s путь=%r статус=%s длительность_мс=%.3f",
|
|
request_id,
|
|
request.method,
|
|
request.url.path,
|
|
response.status_code,
|
|
(time.perf_counter() - started_at) * 1000,
|
|
)
|
|
return response
|
|
|
|
|
|
@app.exception_handler(ApiError)
|
|
async def handle_api_error(request: Request, exc: ApiError) -> JSONResponse:
|
|
response = error_response(request, exc.status_code, exc.code, exc.message)
|
|
if exc.status_code == 401:
|
|
response.headers["WWW-Authenticate"] = (
|
|
'Basic realm="messenger", charset="UTF-8"'
|
|
if request.url.path == "/api/v1/auth/sessions"
|
|
else 'Bearer realm="messenger"'
|
|
)
|
|
return response
|
|
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def handle_validation_error(request: Request, exc: RequestValidationError) -> JSONResponse:
|
|
return error_response(request, 400, "invalid_request", "Некорректные параметры запроса")
|
|
|
|
|
|
@app.exception_handler(StarletteHTTPException)
|
|
async def handle_http_error(request: Request, exc: StarletteHTTPException) -> JSONResponse:
|
|
code = "not_found" if exc.status_code == 404 else "invalid_request"
|
|
message = "Объект не найден" if exc.status_code == 404 else "Некорректный запрос"
|
|
return error_response(request, exc.status_code, code, message)
|
|
|
|
|
|
@app.get("/health/live")
|
|
async def get_health():
|
|
return {
|
|
"status": "ok",
|
|
}
|
|
|
|
|
|
@app.get("/health/ready")
|
|
async def get_ready(session: Annotated[AsyncSession, Depends(get_db_session, scope="function")]):
|
|
from src.core.db.models import User
|
|
|
|
await session.scalar(select(User.id).limit(1))
|
|
await cache.get_client().ping()
|
|
return {
|
|
"status": "ok",
|
|
}
|
|
|
|
|
|
async def handle_database_error(request: Request, exc: Exception) -> JSONResponse:
|
|
logger.warning("Хранилище временно недоступно: тип_ошибки=%s", type(exc).__name__)
|
|
return error_response(request, 503, "unavailable", "Хранилище временно недоступно")
|
|
|
|
|
|
for error_type in (RedisError, DBAPIError, DatabaseTimeoutError, OSError, TimeoutError):
|
|
app.add_exception_handler(error_type, handle_database_error)
|