117 lines
3.0 KiB
Python
117 lines
3.0 KiB
Python
from __future__ import annotations
|
|
|
|
import logging
|
|
from contextlib import asynccontextmanager
|
|
from uuid import uuid4
|
|
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.exceptions import RequestValidationError
|
|
from psycopg import InterfaceError, OperationalError
|
|
from psycopg.errors import LockNotAvailable, QueryCanceled
|
|
from psycopg_pool import PoolTimeout, TooManyRequests
|
|
from starlette.exceptions import HTTPException
|
|
|
|
from app.cache import close_cache
|
|
from app.instance import INSTANCE_ID
|
|
from app.db import close_db, open_db
|
|
from app.errors import ApiError, error_response, invalid, not_found
|
|
from app.routers import attachments, chats, health, messages, sessions, users
|
|
|
|
|
|
logger = logging.getLogger("messenger.api")
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
try:
|
|
await open_db()
|
|
yield
|
|
finally:
|
|
await close_cache()
|
|
await close_db()
|
|
|
|
|
|
app = FastAPI(
|
|
title="Replicated PostgreSQL messenger — Lab 3",
|
|
docs_url=None,
|
|
redoc_url=None,
|
|
openapi_url=None,
|
|
lifespan=lifespan,
|
|
)
|
|
|
|
|
|
@app.middleware("http")
|
|
async def request_middleware(request: Request, call_next):
|
|
request.state.request_id = str(uuid4())
|
|
|
|
try:
|
|
response = await call_next(request)
|
|
|
|
except ApiError as exc:
|
|
response = error_response(request, exc)
|
|
|
|
except (
|
|
OperationalError,
|
|
InterfaceError,
|
|
PoolTimeout,
|
|
TooManyRequests,
|
|
QueryCanceled,
|
|
LockNotAvailable,
|
|
) as exc:
|
|
logger.warning(
|
|
"Database unavailable request_id=%s error_type=%s",
|
|
request.state.request_id,
|
|
type(exc).__name__,
|
|
)
|
|
response = error_response(
|
|
request,
|
|
ApiError(
|
|
503,
|
|
"unavailable",
|
|
"Сервис временно недоступен",
|
|
),
|
|
)
|
|
|
|
except Exception as exc:
|
|
logger.error(
|
|
"Unhandled error request_id=%s error_type=%s",
|
|
request.state.request_id,
|
|
type(exc).__name__,
|
|
)
|
|
response = error_response(
|
|
request,
|
|
ApiError(
|
|
500,
|
|
"internal_error",
|
|
"Внутренняя ошибка сервера",
|
|
),
|
|
)
|
|
|
|
response.headers["X-Request-Id"] = request.state.request_id
|
|
response.headers["X-Instance-Id"] = INSTANCE_ID
|
|
return response
|
|
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def validation_error_handler(request: Request, exc):
|
|
return error_response(request, invalid())
|
|
|
|
|
|
@app.exception_handler(HTTPException)
|
|
async def http_error_handler(request: Request, exc: HTTPException):
|
|
if exc.status_code == 404:
|
|
error = not_found()
|
|
else:
|
|
error = invalid("Недопустимый HTTP-запрос")
|
|
|
|
return error_response(request, error)
|
|
|
|
|
|
app.include_router(health.router)
|
|
app.include_router(users.router)
|
|
app.include_router(sessions.router)
|
|
app.include_router(chats.router)
|
|
app.include_router(messages.router)
|
|
|
|
app.include_router(attachments.router)
|