Files
mtusi2026lab2/app/main.py

165 lines
4.8 KiB
Python

import uuid
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from app.db import db
from app.migrations import apply_migrations
from app.storage import Storage
from app.session_store import make_session_store
from app.cache import make_cache
from app.api import health, users, auth, chats
@asynccontextmanager
async def lifespan(app: FastAPI):
await db.connect()
await apply_migrations(db.pool)
app.state.cache = make_cache()
app.state.storage = Storage(db.pool, app.state.cache)
app.state.session_store = make_session_store(db.pool)
await app.state.session_store.delete_expired()
yield
await app.state.cache.close()
await app.state.session_store.close()
await db.close()
app = FastAPI(title="MTUSI Messenger", version="1.3.0", lifespan=lifespan)
@app.middleware("http")
async def request_context(request: Request, call_next):
rid = request.headers.get("X-Request-Id") or uuid.uuid4().hex
request.state.request_id = rid
response = await call_next(request)
response.headers["X-Request-Id"] = rid
return response
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
rid = getattr(request.state, "request_id", uuid.uuid4().hex)
return JSONResponse(
status_code=400,
content={
"error": {
"code": "invalid_request",
"message": "validation error",
"request_id": rid,
}
},
headers={"X-Request-Id": rid},
)
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
rid = getattr(request.state, "request_id", uuid.uuid4().hex)
headers = {"X-Request-Id": rid}
if exc.headers:
headers.update(exc.headers)
code_map = {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
409: "conflict",
413: "payload_too_large",
415: "unsupported_media_type",
429: "rate_limited",
503: "unavailable",
}
code = code_map.get(exc.status_code, "internal_error")
message = exc.detail if isinstance(exc.detail, str) else "error"
return JSONResponse(
status_code=exc.status_code,
content={
"error": {
"code": code,
"message": message,
"request_id": rid,
}
},
headers=headers,
)
# PostgreSQL: ошибки соединения → 503
try:
from asyncpg.exceptions import (
PostgresConnectionError,
TooManyConnectionsError,
CannotConnectNowError,
ConnectionDoesNotExistError,
)
@app.exception_handler(PostgresConnectionError)
@app.exception_handler(TooManyConnectionsError)
@app.exception_handler(CannotConnectNowError)
@app.exception_handler(ConnectionDoesNotExistError)
async def postgres_unavailable_handler(request: Request, exc: Exception):
rid = getattr(request.state, "request_id", uuid.uuid4().hex)
return JSONResponse(
status_code=503,
content={
"error": {
"code": "unavailable",
"message": "database unavailable",
"request_id": rid,
}
},
headers={"X-Request-Id": rid},
)
except ImportError:
pass
# Redis: ошибки соединения → 503
try:
import redis.exceptions as redis_exceptions
@app.exception_handler(redis_exceptions.ConnectionError)
@app.exception_handler(redis_exceptions.TimeoutError)
async def redis_unavailable_handler(request: Request, exc: Exception):
rid = getattr(request.state, "request_id", uuid.uuid4().hex)
return JSONResponse(
status_code=503,
content={
"error": {
"code": "unavailable",
"message": "cache unavailable",
"request_id": rid,
}
},
headers={"X-Request-Id": rid},
)
except ImportError:
pass
@app.exception_handler(Exception)
async def generic_exception_handler(request: Request, exc: Exception):
rid = getattr(request.state, "request_id", uuid.uuid4().hex)
return JSONResponse(
status_code=500,
content={
"error": {
"code": "internal_error",
"message": "internal error",
"request_id": rid,
}
},
headers={"X-Request-Id": rid},
)
app.include_router(health.router)
app.include_router(users.router, prefix="/api/v1")
app.include_router(auth.router, prefix="/api/v1")
app.include_router(chats.router, prefix="/api/v1")