feat: port lab3 backend foundation to lab4
This commit is contained in:
+86
@@ -0,0 +1,86 @@
|
||||
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 pathlib import Path
|
||||
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 instance_id=%s", settings.instance_id)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
engine.dispose()
|
||||
logger.info("Application shutdown instance_id=%s", settings.instance_id)
|
||||
|
||||
app = FastAPI(title=settings.app_name, version="1.3.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 response_headers(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
|
||||
response.headers["X-Instance-Id"] = settings.instance_id
|
||||
response.headers["X-Content-Type-Options"] = "nosniff"
|
||||
return response
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_exception_handler(request: Request, exc: HTTPException):
|
||||
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
||||
code = {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"}.get(exc.status_code, "internal_error")
|
||||
headers = dict(exc.headers or {})
|
||||
headers["X-Request-Id"] = request_id
|
||||
headers["X-Instance-Id"] = settings.instance_id
|
||||
return JSONResponse(status_code=exc.status_code, content={"error": {"code": code, "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 = getattr(request.state, "request_id", str(uuid.uuid4()))
|
||||
return JSONResponse(status_code=400, content={"error": {"code": "invalid_request", "message": "Validation error", "request_id": request_id}}, headers={"X-Request-Id": request_id, "X-Instance-Id": settings.instance_id})
|
||||
|
||||
@app.get("/health/live")
|
||||
def liveness():
|
||||
return {"status": "ok"}
|
||||
|
||||
DRAIN_FILE = Path("/tmp/api-draining")
|
||||
@app.get("/health/ready")
|
||||
def readiness():
|
||||
if DRAIN_FILE.exists():
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Instance is draining",
|
||||
)
|
||||
|
||||
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
|
||||
Reference in New Issue
Block a user