Files
plba/src/app_runtime/http/http_app.py
T

38 lines
1.3 KiB
Python

from __future__ import annotations
import logging
import time
from collections.abc import Iterable
from fastapi import FastAPI, Request
from app_runtime.core.service_container import ServiceContainer
from app_runtime.http.base import HttpRouteRegistrar
LOGGER = logging.getLogger(__name__)
class HttpApplicationAppFactory:
def create(self, registrars: Iterable[HttpRouteRegistrar], services: ServiceContainer) -> FastAPI:
app = FastAPI(title="PLBA Application API")
self._register_middleware(app)
for registrar in registrars:
registrar.register(app, services)
return app
def _register_middleware(self, app: FastAPI) -> None:
@app.middleware("http")
async def track_request(request: Request, call_next): # type: ignore[no-untyped-def]
started = time.monotonic()
response = await call_next(request)
duration_ms = int((time.monotonic() - started) * 1000)
response.headers["X-Response-Time-Ms"] = str(duration_ms)
LOGGER.info(
"Application HTTP request handled: method=%s path=%s status=%s duration_ms=%s",
request.method,
request.url.path,
response.status_code,
duration_ms,
)
return response