forked from mtusi2026/mtusi2026lab2
150 lines
3.7 KiB
Python
150 lines
3.7 KiB
Python
import logging
|
|
import uuid
|
|
from contextlib import asynccontextmanager
|
|
|
|
from fastapi import FastAPI, HTTPException, Request
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.responses import JSONResponse
|
|
from sqlalchemy import text
|
|
from sqlalchemy.exc import SQLAlchemyError
|
|
|
|
from app.api.auth import router as auth_router
|
|
from app.api.users import router as users_router
|
|
from app.api.chats import router as chats_router
|
|
from app.api.messages import router as messages_router
|
|
from app.core.config import settings
|
|
from app.db.session import engine
|
|
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
|
)
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
logger.info("Application startup")
|
|
yield
|
|
engine.dispose()
|
|
logger.info("Application shutdown")
|
|
|
|
|
|
app = FastAPI(
|
|
title="Messenger API",
|
|
version="1.2.0",
|
|
lifespan=lifespan,
|
|
)
|
|
|
|
app.include_router(users_router)
|
|
app.include_router(auth_router)
|
|
app.include_router(chats_router)
|
|
app.include_router(messages_router)
|
|
|
|
|
|
@app.middleware("http")
|
|
async def add_request_id(request: Request, call_next):
|
|
request_id = str(uuid.uuid4())
|
|
request.state.request_id = request_id
|
|
|
|
try:
|
|
response = await call_next(request)
|
|
except Exception:
|
|
logger.exception(
|
|
"Unhandled request error; request_id=%s",
|
|
request_id,
|
|
)
|
|
response = JSONResponse(
|
|
status_code=500,
|
|
content={
|
|
"error": {
|
|
"code": "internal_error",
|
|
"message": "Unexpected error",
|
|
"request_id": request_id,
|
|
}
|
|
},
|
|
)
|
|
|
|
response.headers["X-Request-Id"] = request_id
|
|
return response
|
|
|
|
|
|
@app.exception_handler(HTTPException)
|
|
async def http_exception_handler(request: Request, exc: HTTPException):
|
|
request_id = request.state.request_id
|
|
|
|
error_code_map = {
|
|
400: "invalid_request",
|
|
401: "unauthorized",
|
|
404: "not_found",
|
|
409: "conflict",
|
|
413: "payload_too_large",
|
|
415: "unsupported_media_type",
|
|
429: "rate_limited",
|
|
500: "internal_error",
|
|
503: "unavailable",
|
|
}
|
|
|
|
headers = dict(exc.headers or {})
|
|
headers["X-Request-Id"] = request_id
|
|
|
|
return JSONResponse(
|
|
status_code=exc.status_code,
|
|
content={
|
|
"error": {
|
|
"code": error_code_map.get(
|
|
exc.status_code,
|
|
"internal_error",
|
|
),
|
|
"message": (
|
|
exc.detail
|
|
if isinstance(exc.detail, str)
|
|
else "Request failed"
|
|
),
|
|
"request_id": request_id,
|
|
}
|
|
},
|
|
headers=headers,
|
|
)
|
|
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def validation_exception_handler(
|
|
request: Request,
|
|
exc: RequestValidationError,
|
|
):
|
|
request_id = request.state.request_id
|
|
|
|
return JSONResponse(
|
|
status_code=400,
|
|
content={
|
|
"error": {
|
|
"code": "invalid_request",
|
|
"message": "Validation error",
|
|
"request_id": request_id,
|
|
}
|
|
},
|
|
headers={"X-Request-Id": request_id},
|
|
)
|
|
|
|
|
|
@app.get("/health/live")
|
|
def liveness():
|
|
return {"status": "ok"}
|
|
|
|
|
|
@app.get("/health/ready")
|
|
def readiness():
|
|
try:
|
|
with engine.connect() as connection:
|
|
connection.execute(text("SELECT 1"))
|
|
return {"status": "ok"}
|
|
|
|
except SQLAlchemyError:
|
|
logger.exception("PostgreSQL readiness check failed")
|
|
raise HTTPException(
|
|
status_code=503,
|
|
detail="Database unavailable",
|
|
) from None
|