69 lines
2.2 KiB
Python
69 lines
2.2 KiB
Python
import uuid
|
|
import base64
|
|
from typing import Optional
|
|
from fastapi import FastAPI, Request, status
|
|
from fastapi.exceptions import RequestValidationError
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
from contextlib import asynccontextmanager
|
|
|
|
from .exceptions import make_error_response, ApiException
|
|
from .db import get_pool, init_db, close_db
|
|
from .routes.router import api_v1_router
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
|
|
await init_db()
|
|
yield
|
|
await close_db()
|
|
|
|
app = FastAPI(title='MTUCI messanger', lifespan=lifespan)
|
|
|
|
|
|
|
|
@app.middleware("http")
|
|
async def request_id_middleware(request: Request, call_next):
|
|
req_id = request.headers.get("X-Request-Id")
|
|
if not req_id or not req_id.strip():
|
|
req_id = str(uuid.uuid4())
|
|
request.state.request_id = req_id
|
|
|
|
response = await call_next(request)
|
|
response.headers["X-Request-Id"] = req_id
|
|
return response
|
|
|
|
@app.exception_handler(ApiException)
|
|
async def api_exception_handler(request: Request, exc: ApiException):
|
|
req_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
|
return make_error_response(exc.status_code, exc.code, exc.message, req_id, exc.headers)
|
|
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
|
req_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
|
return make_error_response(400, "invalid_request", "Invalid request body", req_id)
|
|
|
|
|
|
@app.exception_handler(StarletteHTTPException)
|
|
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
|
req_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
|
return make_error_response(exc.status_code, "invalid_request", str(exc.detail), req_id)
|
|
|
|
|
|
@app.exception_handler(Exception)
|
|
async def general_exception_handler(request: Request, exc: Exception):
|
|
req_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
|
return make_error_response(500, "internal_error", "Internal server error", req_id)
|
|
|
|
@app.get("/health/live")
|
|
async def health_live():
|
|
return {"status": "ok"}
|
|
|
|
|
|
@app.get("/health/ready")
|
|
async def health_ready():
|
|
return {"status": "ok"}
|
|
|
|
|
|
app.include_router(api_v1_router)
|