Files

118 lines
5.2 KiB
Python

"""FastAPI process: one stateless replica. No auto-migration on startup."""
import logging
import uuid
import time
from starlette.routing import Match
from opentelemetry.trace import SpanKind, Status, StatusCode
from . import telemetry as ot
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("lab5")
@asynccontextmanager
async def lifespan(app: FastAPI):
ot.init("api")
start()
try:
yield
finally:
stop()
ot.flush()
app = FastAPI(title="MTUCI Messenger Lab 6", 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):
# Match the registered template even when early authentication fails.
route = next((r.path for r in app.routes if r.matches(req.scope)[0] == Match.FULL), 'unmatched')
method = req.method if req.method in ('GET','POST','DELETE','PUT','PATCH','HEAD','OPTIONS') else 'OTHER'
attrs = {'method': method, 'route': route}
start_at = time.monotonic()
if route in ("/health/live", "/health/ready"):
response = await handle_request(req, call_next)
attrs["status_class"] = str(response.status_code//100)+"xx"
ot.count("lab_http_requests", attrs)
ot.observe("lab_http_duration", time.monotonic()-start_at, attrs)
return response
with ot.span(method+' '+route, kind=SpanKind.SERVER, attrs={'http.request.method':method,'http.route':route}) as span:
response = await handle_request(req, call_next)
attrs['status_class'] = str(response.status_code//100)+'xx'
span.set_attribute('http.response.status_code', response.status_code)
if response.status_code >= 500:
span.set_status(Status(StatusCode.ERROR))
ot.count('lab_http_requests', attrs)
ot.observe('lab_http_duration', time.monotonic()-start_at, attrs)
ot.event('http.completed', level=logging.ERROR if response.status_code >= 500 else logging.INFO,
request_id=request_id(req), route=route, method=method, status_code=response.status_code)
if ot.trace_id():
response.headers['X-Trace-Id'] = ot.trace_id()
return response
async def handle_request(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"))