Files
mtusi2026lab4-Leskovskiy/src/main.py
T

48 lines
1.7 KiB
Python

import uuid
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from . import config
from .db import engine, Base
from .errors import ApiError, api_error_handler, unhandled_handler
from .s3 import ensure_bucket
from .routers import health, users, sessions, chats, messages, attachments
@asynccontextmanager
async def lifespan(app: FastAPI):
# create_all is not idempotent under parallel startup: two replicas
# may race and one hits UniqueViolation on pg_type. Catch and re-run
# once after a short delay; by then the other replica has finished.
import asyncio
from sqlalchemy.exc import IntegrityError, OperationalError
for attempt in range(5):
try:
Base.metadata.create_all(engine)
break
except (IntegrityError, OperationalError) as exc:
print(f"WARN: create_all attempt {attempt+1} failed: {exc}")
await asyncio.sleep(1.0)
else:
print("WARN: create_all failed after 5 attempts; continuing")
try:
ensure_bucket()
except Exception as exc:
print(f"WARN: ensure_bucket failed: {exc}")
yield
app = FastAPI(lifespan=lifespan)
app.add_exception_handler(ApiError, api_error_handler)
app.add_exception_handler(Exception, unhandled_handler)
@app.middleware("http")
async def add_request_id(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
response.headers["X-Instance-Id"] = config.INSTANCE_ID
return response
for r in (health, users, sessions, chats, messages, attachments):
app.include_router(r.router)