Skip to content

Commit 7d51a43

Browse files
feat!: MetricsSettings rejects port=0 unless allow_ephemeral_port=True
`0` on the shipped model only ever arrives from configuration (`METRICS__PORT`), and in a pod it is a silent outage: the exposition server binds whatever the OS hands it, the sink logs `port: 0` and has no bound-port readback, and the pod quietly stops being scraped. The model now carries `allow_ephemeral_port` (default False) and an after-validator that rejects `port=0` unless it is set, with a message naming both. `MetricsSettingsProtocol` does not change. Twin of bedrock-python/grpc-server-kit#24, where the same decision landed on `BaseGrpcServerSettings.port`. BREAKING CHANGE: `MetricsSettings(port=0)` now raises `ValidationError`; pass `allow_ephemeral_port=True` (or `METRICS__ALLOW_EPHEMERAL_PORT=true`) to bind an ephemeral exposition port on purpose.
1 parent 02062df commit 7d51a43

4 files changed

Lines changed: 60 additions & 3 deletions

File tree

‎docs/agents.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -457,7 +457,9 @@ Each `*Plugin` takes exactly the same arguments as its entrypoint and exposes `.
457457
19. **The FastAPI `metrics=` flag and `settings.metrics.enabled` are different things.**
458458
`FastApiEntrypoint(metrics=True)` adds the in-app `/system/metrics` route;
459459
`settings.metrics.enabled` starts the sink's own standalone exposition server on its own
460-
port. Neither implies the other.
460+
port. Neither implies the other. `MetricsSettings` rejects `port=0` unless
461+
`allow_ephemeral_port=True`: the sink has no bound-port readback, so an ephemeral
462+
exposition port is one nothing scrapes, and `METRICS__PORT=0` in a pod is a silent outage.
461463
20. **gRPC reflection and channelz are off by default and unauthenticated when on**, on the
462464
same port as production traffic. The effective gRPC drain is
463465
`min(host drain_grace_seconds, config.grace_period)`.

‎docs/concepts/settings.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ your own that uses them behaves exactly like the shipped one.
4343
| `enabled` | `bool` | `False` | Start a standalone exposition server |
4444
| `host` | `str` | `"0.0.0.0"` | Bind host for that server |
4545
| `port` | `int` | `9090` | Bind port for that server |
46+
| `allow_ephemeral_port` | `bool` | `False` | Accept `port=0`; validated by the shipped model, not read by the backend |
4647
| `prefix` | `str \| None` | `None` | Metric name prefix, for backends that use one |
4748

4849
`host` and `port` are read only when `enabled` is true and have no backend fallback; their
@@ -173,6 +174,15 @@ The models validate what the backends assume: the log level must be one of `LogL
173174
(case-insensitively, so `LOGGING__LEVEL=debug` is fine while `warn` is a load-time error rather
174175
than a silent `INFO`), the sample ratios are bounded to `[0, 1]`, the metrics port to a port.
175176

177+
`MetricsSettings` also rejects `port=0` unless `allow_ephemeral_port=True`. `0` binds an
178+
ephemeral port, which is what a test wants and, in a pod, what a scraper pointed at a fixed port
179+
never finds; the sink has no bound-port readback, so nothing in the process knows either, and `0`
180+
only ever arrives from configuration (`METRICS__PORT`, one keystroke from `9090`). Say it in code
181+
for a service that means it, or set `METRICS__ALLOW_EPHEMERAL_PORT=true` next to `METRICS__PORT=0`
182+
when the port comes from the environment: a section is built afresh from its variables, so a
183+
default instance on the settings class is replaced, not merged, once one `METRICS__*` variable is
184+
set.
185+
176186
### Disabling and narrowing
177187

178188
Exactly as with a hand-written class: a section annotated `None` is off, a section model can be

‎servicewright/adapters/settings/models.py‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ class Settings(BaseServiceSettings):
3535
from ...core.observability import LogLevelStr
3636

3737
try:
38-
from pydantic import BaseModel, Field, field_validator
38+
from pydantic import BaseModel, Field, field_validator, model_validator
3939
from pydantic_settings import BaseSettings, SettingsConfigDict
4040
except ImportError as exc: # pragma: no cover - exercised only without the extra
4141
raise ImportError("Settings models require servicewright[settings]; install it.") from exc
@@ -65,14 +65,29 @@ class MetricsSettings(BaseModel):
6565
Satisfies :class:`~servicewright.core.observability.MetricsSettingsProtocol`.
6666
A present section activates the metrics sink; ``enabled`` only decides whether
6767
the sink also serves ``/metrics`` on its own port (the FastAPI entrypoint
68-
serves ``/system/metrics`` regardless).
68+
serves ``/system/metrics`` regardless). ``port=0`` is rejected unless
69+
``allow_ephemeral_port`` says so: the sink has no bound-port readback, so an
70+
ephemeral exposition port is one nothing scrapes.
6971
"""
7072

7173
enabled: bool = Field(default=False, description="Start a standalone exposition server")
7274
host: str = Field(default="0.0.0.0", description="Bind host of that server")
7375
port: int = Field(default=9090, ge=0, le=65535, description="Bind port of that server")
76+
allow_ephemeral_port: bool = Field(
77+
default=False,
78+
description="Accept port=0 (ephemeral); off by default, a scraper targeting a fixed port cannot reach one",
79+
)
7480
prefix: str | None = Field(default=None, description="Metric name prefix, for backends that apply one globally")
7581

82+
@model_validator(mode="after")
83+
def _validate_port(self) -> MetricsSettings:
84+
if self.port == 0 and not self.allow_ephemeral_port:
85+
raise ValueError(
86+
"metrics port=0 binds an ephemeral port and a scraper targeting a fixed port will not reach it; "
87+
"set allow_ephemeral_port=True if that is intended"
88+
)
89+
return self
90+
7691

7792
class TracingSettings(BaseModel):
7893
"""``settings.tracing``: exporter endpoint and sampling.

‎tests/unit/test_settings_models.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,36 @@ def test__section_models__value_outside_what_the_backend_accepts__is_rejected_at
225225
model(**{field: value})
226226

227227

228+
def test__metrics_settings__port_zero__rejected_naming_the_flag() -> None:
229+
# 0 only ever arrives from configuration, and a pod on an ephemeral port is one nothing scrapes.
230+
with pytest.raises(ValidationError, match=r"ephemeral port.*allow_ephemeral_port=True"):
231+
MetricsSettings(port=0)
232+
233+
234+
def test__metrics_settings__port_zero_with_allow_ephemeral_port__accepted() -> None:
235+
assert MetricsSettings(port=0, allow_ephemeral_port=True).port == 0
236+
237+
238+
@pytest.mark.parametrize("allow_ephemeral_port", [False, True])
239+
def test__metrics_settings__fixed_port__unaffected_by_allow_ephemeral_port(allow_ephemeral_port: bool) -> None:
240+
assert MetricsSettings(port=9090, allow_ephemeral_port=allow_ephemeral_port).port == 9090
241+
242+
243+
def test__base_service_settings__metrics_port_zero_from_environment__behaves_as_kwargs(
244+
monkeypatch: pytest.MonkeyPatch,
245+
) -> None:
246+
monkeypatch.setenv("METRICS__PORT", "0")
247+
248+
with pytest.raises(ValidationError, match=r"allow_ephemeral_port=True"):
249+
BaseServiceSettings()
250+
251+
monkeypatch.setenv("METRICS__ALLOW_EPHEMERAL_PORT", "true")
252+
settings = BaseServiceSettings()
253+
254+
assert settings.metrics is not None
255+
assert settings.metrics.port == 0
256+
257+
228258
# --------------------------------------------------------------------------- #
229259
# As overridable as a hand-written class
230260
# --------------------------------------------------------------------------- #

0 commit comments

Comments
 (0)