Skip to content

Commit c74a507

Browse files
feat(fastapi): accept a MetricsInstrumentatorConfig as the entrypoint's metrics argument (#113)
1 parent e51a741 commit c74a507

5 files changed

Lines changed: 126 additions & 25 deletions

File tree

‎docs/adapters/fastapi.md‎

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ Everything operational lives under one prefix, so it is trivial to keep off your
3434
| --- | --- |
3535
| `/system/health/livez` | liveness probe |
3636
| `/system/health/readyz` | readiness probe (503 when unhealthy) |
37-
| `/system/metrics` | in-app Prometheus metrics (when `metrics=True`) |
37+
| `/system/metrics` | in-app Prometheus metrics (when `metrics` is `True` or a config) |
3838
| `/system/docs` | Swagger UI |
3939
| `/system/redoc` | ReDoc |
4040
| `/system/openapi.json` | the schema |
@@ -68,7 +68,7 @@ FastApiEntrypoint(
6868
| `exception_handlers` | `{ExceptionType: handler}`, appended after the defaults. |
6969
| `default_exception_handlers` | Install the built-in handlers. |
7070
| `error_renderer` | Wire-format renderer; `None` means RFC 9457. See [Errors](../concepts/errors.md#own-the-wire-format). |
71-
| `metrics` | Expose in-app request metrics at `/system/metrics`. |
71+
| `metrics` | Expose in-app request metrics at `/system/metrics`: `True` with the defaults, or a `MetricsInstrumentatorConfig` to tune them. See [Metrics](#metrics). |
7272
| `configure_app` | `(app, ctx) -> None`, the final hook after everything is wired. |
7373
| `kind`, `essential` | Telemetry label and failure semantics. See [Entrypoints](../concepts/entrypoints.md#kind-and-essential). |
7474

@@ -370,22 +370,33 @@ This is independent of the standalone exposition server that the
370370
[Prometheus backend](observability-backends.md#prometheus-metrics) starts when
371371
`settings.metrics.enabled` is true. Both write into the same registry.
372372

373-
To tune the instrumentator, wire it yourself:
374-
375-
```python
376-
from servicewright.adapters.fastapi import MetricsInstrumentatorConfig, setup_metrics_instrumentator
373+
To tune the instrumentator, pass a `MetricsInstrumentatorConfig` instead of `True`. The
374+
instrumentator then sits at the same place in the middleware stack as with `True`.
377375

376+
The default latency buckets suit fast APIs. `http_request_duration_seconds`, the histogram
377+
labelled by handler and method, stops at 1 second, and `http_request_duration_highr_seconds`,
378+
which has no labels, at 60 seconds. LLM calls, long polls and SSE streams then all land in
379+
`+Inf`. Set your own buckets through `instrument_kwargs`:
378380

379-
def configure_app(app, ctx) -> None:
380-
setup_metrics_instrumentator(
381-
app,
382-
config=MetricsInstrumentatorConfig(init_kwargs={"should_group_status_codes": False}),
383-
)
384-
381+
```python
382+
from servicewright.adapters.fastapi import MetricsInstrumentatorConfig
385383

386-
FastApiEntrypoint(metrics=False, configure_app=configure_app)
384+
FastApiEntrypoint(
385+
metrics=MetricsInstrumentatorConfig(
386+
instrument_kwargs={
387+
"latency_lowr_buckets": (0.1, 0.5, 1, 5, 30, 120, 600),
388+
"latency_highr_buckets": (0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120, 300, 600),
389+
},
390+
),
391+
)
387392
```
388393

394+
`latency_lowr_buckets` are the buckets of `http_request_duration_seconds` and
395+
`latency_highr_buckets` those of `http_request_duration_highr_seconds`; `+Inf` is added to both.
396+
Keep the first list short, since every bucket is repeated for each handler and method. Both only
397+
shape the default set of metrics: with `instrumentations` given, pass `buckets=` to
398+
`metrics.latency()` instead.
399+
389400
`MetricsInstrumentatorConfig` is a pass-through, one field per call the wrapper makes: `init_kwargs`
390401
to `Instrumentator(...)`, `instrumentations` to `.add(...)`, `instrument_kwargs` to
391402
`.instrument(...)` and `expose_kwargs` to `.expose(...)`.

‎docs/agents.md‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,12 @@ Entrypoint constructors, all keyword-only:
327327

328328
* `FastApiEntrypoint(config=None, routers=(), routes_registerer=None, middlewares=None,
329329
exception_handlers=None, default_exception_handlers=True, error_renderer=None,
330-
metrics=False, configure_app=None, kind="http", essential=True)`. `HttpConfig` defaults:
330+
metrics=False, configure_app=None, kind="http", essential=True)`. `metrics` is a `bool` or a
331+
`MetricsInstrumentatorConfig`: `True` installs the instrumentator with its defaults, a config
332+
installs it with that config at the same place. Latency buckets go in the config's
333+
`instrument_kwargs`: `latency_lowr_buckets` for `http_request_duration_seconds` (default
334+
0.1, 0.5 and 1 s), `latency_highr_buckets` for `http_request_duration_highr_seconds`
335+
(default up to 60 s). `HttpConfig` defaults:
331336
`host="0.0.0.0"`, `port=8000`, `graceful_timeout=30.0`, probes at
332337
`/system/health/livez` and `/system/health/readyz`, docs at `/system/docs`,
333338
`redirect_slashes=False`. `MiddlewareConfig` defaults have unit scope, context, sentry,
@@ -467,7 +472,8 @@ Each `*Plugin` takes exactly the same arguments as its entrypoint and exposes `.
467472
distribution, incompatible majors; the only public difference is `coalesce` (`bool` in
468473
3.x, `CoalescePolicy` in 4.x).
469474
19. **The FastAPI `metrics=` flag and `settings.metrics.enabled` are different things.**
470-
`FastApiEntrypoint(metrics=True)` adds the in-app `/system/metrics` route;
475+
`FastApiEntrypoint(metrics=True)`, or a `MetricsInstrumentatorConfig` in its place, adds the
476+
in-app `/system/metrics` route;
471477
`settings.metrics.enabled` starts the sink's own standalone exposition server on its own
472478
port. Neither implies the other. `MetricsSettings` rejects `port=0` unless
473479
`allow_ephemeral_port=True`: the sink has no bound-port readback, so an ephemeral

‎docs/operations/runbooks.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,8 @@ Also check `settings.tracing.excluded_urls` and remember that `/system/*` is exc
234234

235235
### Metrics endpoint returns 404
236236

237-
`FastApiEntrypoint(metrics=True)` exposes `/system/metrics`. The standalone server on
237+
`FastApiEntrypoint(metrics=True)`, or `metrics=MetricsInstrumentatorConfig(...)`, exposes
238+
`/system/metrics`; `metrics=False`, the default, does not. The standalone server on
238239
`settings.metrics.port` is a *different* endpoint, enabled by `settings.metrics.enabled`. A
239240
socket-less worker needs the second one.
240241

‎servicewright/adapters/fastapi/entrypoint.py‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
from ...core.contracts import ServerEntrypoint
3232
from .._uvicorn import UvicornRunner
3333
from ._imports import FastAPI
34-
from .config import HttpConfig, MiddlewareConfig
34+
from .config import HttpConfig, MetricsInstrumentatorConfig, MiddlewareConfig
3535
from .configurators import setup_exception_handlers, setup_health_routes, setup_middleware_stack
3636
from .metrics import setup_metrics_instrumentator
3737
from .observability import instrument_fastapi_app
@@ -71,6 +71,10 @@ class FastApiEntrypoint(ServerEntrypoint):
7171
localization) across every default handler.
7272
metrics: Expose in-app Prometheus metrics at ``/system/metrics`` via
7373
``prometheus-fastapi-instrumentator`` (requires servicewright[fastapi]).
74+
``False`` installs nothing, ``True`` the default
75+
``MetricsInstrumentatorConfig``, and a config instance is used as
76+
given: ``latency_lowr_buckets`` in its ``instrument_kwargs`` sets the
77+
buckets of ``http_request_duration_seconds``.
7478
configure_app: Final hook called with ``(app, ctx)`` after wiring.
7579
kind: Telemetry label (default ``"http"``).
7680
essential: Whether the entrypoint's exit/failure stops the process.
@@ -86,7 +90,7 @@ def __init__(
8690
exception_handlers: dict[type[Exception], ExceptionHandler] | None = None,
8791
default_exception_handlers: bool = True,
8892
error_renderer: HttpErrorRendererProtocol | None = None,
89-
metrics: bool = False,
93+
metrics: bool | MetricsInstrumentatorConfig = False,
9094
configure_app: ConfigureApp | None = None,
9195
kind: str = "http",
9296
essential: bool = True,
@@ -98,7 +102,12 @@ def __init__(
98102
self._exception_handlers: dict[type[Exception], ExceptionHandler] = dict(exception_handlers or {})
99103
self._default_exception_handlers = default_exception_handlers
100104
self._error_renderer = error_renderer
101-
self._metrics = metrics
105+
if isinstance(metrics, MetricsInstrumentatorConfig):
106+
self._metrics: MetricsInstrumentatorConfig | None = metrics
107+
elif metrics:
108+
self._metrics = MetricsInstrumentatorConfig()
109+
else:
110+
self._metrics = None
102111
self._configure_app = configure_app
103112
self.kind = kind
104113
self.essential = essential
@@ -176,8 +185,8 @@ async def build_app(self, ctx: ServiceContext[Any, Any]) -> FastAPI:
176185

177186
await self._register_routes(app, ctx)
178187

179-
if self._metrics:
180-
setup_metrics_instrumentator(app)
188+
if self._metrics is not None:
189+
setup_metrics_instrumentator(app, config=self._metrics)
181190

182191
if self._configure_app is not None:
183192
self._configure_app(app, ctx)
@@ -246,7 +255,7 @@ def __init__(
246255
exception_handlers: dict[type[Exception], ExceptionHandler] | None = None,
247256
default_exception_handlers: bool = True,
248257
error_renderer: HttpErrorRendererProtocol | None = None,
249-
metrics: bool = False,
258+
metrics: bool | MetricsInstrumentatorConfig = False,
250259
configure_app: ConfigureApp | None = None,
251260
kind: str = "http",
252261
essential: bool = True,

‎tests/unit/test_fastapi.py‎

Lines changed: 77 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,17 @@
1010
import asyncio
1111
import contextlib
1212
import logging
13+
import re
1314
import socket
15+
from collections.abc import Iterator
1416
from typing import Any, cast
1517
from unittest.mock import MagicMock
1618

1719
import pytest
1820
from deadline_budget import DeadlineExceededError
1921
from fastapi import APIRouter, FastAPI, HTTPException
2022
from fastapi.testclient import TestClient
21-
from prometheus_client import CollectorRegistry
23+
from prometheus_client import REGISTRY, CollectorRegistry
2224
from prometheus_fastapi_instrumentator import metrics
2325

2426
from servicewright import (
@@ -764,6 +766,17 @@ class MyMiddleware(BaseHTTPMiddleware):
764766
# --------------------------------------------------------------------------- #
765767
# Metrics
766768
# --------------------------------------------------------------------------- #
769+
@pytest.fixture
770+
def default_registry() -> Iterator[None]:
771+
# metrics=True instruments into the process-wide REGISTRY, where a second
772+
# instrumented app would collide on the same series: drop what the test added.
773+
registered_before = set(REGISTRY._collector_to_names)
774+
yield
775+
for collector in set(REGISTRY._collector_to_names) - registered_before:
776+
REGISTRY.unregister(collector)
777+
778+
779+
@pytest.mark.usefixtures("default_registry")
767780
async def test__metrics_endpoint__enabled__is_exposed() -> None:
768781
ep = FastApiEntrypoint(config=HttpConfig(port=0), metrics=True)
769782
client = await _build_client(ep, _make_service_ctx(FakeContainer()))
@@ -811,20 +824,81 @@ def _private_registry_config(registry: CollectorRegistry, **fields: Any) -> Metr
811824
)
812825

813826

814-
async def _build_instrumented_client(config: MetricsInstrumentatorConfig) -> TestClient:
827+
def _ping_router() -> APIRouter:
815828
router = APIRouter()
816829

817830
@router.get("/ping")
818831
async def ping() -> dict[str, str]:
819832
return {"pong": "ok"}
820833

834+
return router
835+
836+
837+
async def _build_instrumented_client(config: MetricsInstrumentatorConfig) -> TestClient:
821838
def configure(app: FastAPI, ctx: ServiceContext) -> None:
822839
setup_metrics_instrumentator(app, config=config)
823840

824-
ep = FastApiEntrypoint(config=HttpConfig(port=0), routers=(router,), configure_app=configure)
841+
ep = FastApiEntrypoint(config=HttpConfig(port=0), routers=(_ping_router(),), configure_app=configure)
825842
return await _build_client(ep, _make_service_ctx(FakeContainer()))
826843

827844

845+
async def _metrics_after_one_ping(ep: FastApiEntrypoint) -> str:
846+
client = await _build_client(ep, _make_service_ctx(FakeContainer()))
847+
client.get("/ping")
848+
return client.get("/system/metrics").text
849+
850+
851+
def _ping_latency_buckets(metrics_body: str) -> list[str]:
852+
return re.findall(
853+
r'^http_request_duration_seconds_bucket\{handler="/ping",le="([^"]+)",method="GET"\}',
854+
metrics_body,
855+
re.MULTILINE,
856+
)
857+
858+
859+
@pytest.fixture
860+
def long_request_metrics(metrics_registry: CollectorRegistry) -> MetricsInstrumentatorConfig:
861+
return _private_registry_config(metrics_registry, instrument_kwargs={"latency_lowr_buckets": (1, 60, 600)})
862+
863+
864+
async def test__metrics_endpoint__instrumentator_config_given__uses_its_latency_buckets(
865+
long_request_metrics: MetricsInstrumentatorConfig,
866+
) -> None:
867+
# Arrange
868+
ep = FastApiEntrypoint(config=HttpConfig(port=0), routers=(_ping_router(),), metrics=long_request_metrics)
869+
870+
# Act
871+
body = await _metrics_after_one_ping(ep)
872+
873+
# Assert
874+
assert _ping_latency_buckets(body) == ["1.0", "60.0", "600.0", "+Inf"]
875+
876+
877+
async def test__fastapi_plugin__instrumentator_config_given__forwards_it_to_the_entrypoint(
878+
long_request_metrics: MetricsInstrumentatorConfig,
879+
) -> None:
880+
# Arrange
881+
plugin = FastApiPlugin(config=HttpConfig(port=0), routers=(_ping_router(),), metrics=long_request_metrics)
882+
883+
# Act
884+
body = await _metrics_after_one_ping(plugin.entrypoint)
885+
886+
# Assert
887+
assert _ping_latency_buckets(body) == ["1.0", "60.0", "600.0", "+Inf"]
888+
889+
890+
@pytest.mark.usefixtures("default_registry")
891+
async def test__metrics_endpoint__enabled__keeps_the_default_latency_buckets() -> None:
892+
# Arrange
893+
ep = FastApiEntrypoint(config=HttpConfig(port=0), routers=(_ping_router(),), metrics=True)
894+
895+
# Act
896+
body = await _metrics_after_one_ping(ep)
897+
898+
# Assert
899+
assert _ping_latency_buckets(body) == ["0.1", "0.5", "1.0", "+Inf"]
900+
901+
828902
async def test__metrics_instrumentator__instrumentations_configured__emit_their_series(
829903
metrics_registry: CollectorRegistry,
830904
) -> None:

0 commit comments

Comments
 (0)