forked from mtusi2026/mtusi2026lab4
85 lines
3.5 KiB
Python
85 lines
3.5 KiB
Python
"""FastAPI process: one stateless replica. No auto-migration on startup."""
|
|
import logging
|
|
import uuid
|
|
from contextlib import asynccontextmanager
|
|
|
|
import psycopg
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.responses import JSONResponse
|
|
from starlette.concurrency import run_in_threadpool
|
|
from redis.exceptions import RedisError
|
|
|
|
from .api import router
|
|
from .attachments import router as attachment_router
|
|
from .auth import challenge, current_user
|
|
from .core import APIError, INSTANCE_ID, error_body, invalid, request_id
|
|
from .storage import start, stop
|
|
|
|
logging.basicConfig(level="INFO")
|
|
logger = logging.getLogger("lab3")
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
start()
|
|
try:
|
|
yield
|
|
finally:
|
|
stop()
|
|
|
|
app = FastAPI(title="MTUCI Messenger Lab 4", docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
|
|
app.include_router(router)
|
|
app.include_router(attachment_router)
|
|
|
|
PROTECTED = ("/api/v1/chats", "/api/v1/attachments", "/api/v1/users/me", "/api/v1/auth/sessions/current")
|
|
JSON_POST = ("/api/v1/users", "/api/v1/chats")
|
|
|
|
|
|
@app.middleware("http")
|
|
async def request_context(req: Request, call_next):
|
|
req.state.request_id = uuid.uuid4().hex
|
|
try:
|
|
path = req.url.path
|
|
# Authenticate before parsing the request body or resource-specific fields.
|
|
if any(path == p or path.startswith(p + "/") for p in PROTECTED):
|
|
req.state.actor = await run_in_threadpool(current_user, req)
|
|
if req.method == "POST" and (path in JSON_POST or (path.startswith("/api/v1/chats/") and path.endswith("/messages"))):
|
|
if req.headers.get("content-type", "").split(";", 1)[0].strip().lower() != "application/json":
|
|
raise APIError(415, "unsupported_media_type", "Content-Type must be application/json")
|
|
if req.method == "POST" and path == "/api/v1/auth/sessions" and await req.body():
|
|
raise invalid("Login body is not allowed")
|
|
response = await call_next(req)
|
|
except APIError as exc:
|
|
response = api_error(req, exc)
|
|
except (RedisError, psycopg.OperationalError, psycopg.InterfaceError):
|
|
response = api_error(req, APIError(503, "unavailable", "Dependency unavailable"))
|
|
except Exception:
|
|
logger.exception("unexpected request failure id=%s", request_id(req))
|
|
response = api_error(req, APIError(500, "internal_error", "Internal server error"))
|
|
response.headers["X-Request-Id"] = request_id(req)
|
|
response.headers["X-Instance-Id"] = INSTANCE_ID
|
|
return response
|
|
|
|
|
|
def api_error(req: Request, exc: APIError) -> JSONResponse:
|
|
headers = {"WWW-Authenticate": challenge(req)} if exc.status == 401 else {}
|
|
return JSONResponse(status_code=exc.status, content=error_body(req, exc.code, exc.message), headers=headers)
|
|
|
|
|
|
@app.exception_handler(APIError)
|
|
async def api_error_handler(req: Request, exc: APIError):
|
|
return api_error(req, exc)
|
|
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def validation_error_handler(req: Request, exc: RequestValidationError):
|
|
return api_error(req, invalid())
|
|
|
|
|
|
@app.exception_handler(Exception)
|
|
async def unexpected_error_handler(req: Request, exc: Exception):
|
|
logger.exception("handler failure id=%s", request_id(req))
|
|
if isinstance(exc, (psycopg.OperationalError, psycopg.InterfaceError, RedisError)):
|
|
return api_error(req, APIError(503, "unavailable", "Dependency unavailable"))
|
|
return api_error(req, APIError(500, "internal_error", "Internal server error"))
|