Skip to content

Commit 9c3e23e

Browse files
feat: HttpServerSettings builds the FastAPI entrypoint's config from environment settings
One pydantic model per config dataclass in the FastAPI adapter — HttpServerSettings, HealthSettings, MiddlewareSettings and the four middleware settings — same fields and defaults, to_config() on each, plus UvicornSettings typing the operational uvicorn knobs behind HttpConfig.uvicorn_kwargs (None until set, forwarded only then; no workers, which Server.serve() ignores). Plain BaseModels, never a BaseSettings, nested under the name you choose; BaseServiceSettings stays transport-neutral. The members that are code — version, unit_scope, context_setters, custom — are arguments of to_config(). port=0 is rejected unless allow_ephemeral_port=True, as on MetricsSettings. Closes #61
1 parent 7e00bfd commit 9c3e23e

10 files changed

Lines changed: 1003 additions & 46 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ import-linter contract enforces the direction in CI: deleting `adapters/` leaves
119119
| `core.warmup` | Priority-grouped, fail-fast warmup before readiness flips | — |
120120
| `core.observability` | Sink protocols, NullObjects, backend registry, redaction | — |
121121
| `adapters.builtin` | `DaemonEntrypoint`, `OneShotEntrypoint` — zero-dependency | — |
122-
| `adapters.fastapi` | FastAPI entrypoint, middleware stack, problem-details handlers | `fastapi` |
122+
| `adapters.fastapi` | FastAPI entrypoint, middleware stack, problem-details handlers, its config as settings models | `fastapi` |
123123
| `adapters.litestar` | Litestar entrypoint | `litestar` |
124124
| `adapters.grpc` | gRPC entrypoint over grpc-server-kit, error mapping, health bridge | `grpc` |
125125
| `adapters.apscheduler4` / `apscheduler3` | Scheduler entrypoints with identical public surfaces | `apscheduler4` / `apscheduler3` |
@@ -133,7 +133,7 @@ import-linter contract enforces the direction in CI: deleting `adapters/` leaves
133133

134134
| Extra | Pulls in | Enables |
135135
| --- | --- | --- |
136-
| `fastapi` | fastapi, uvicorn, deadline-budget, prometheus-fastapi-instrumentator | `FastApiEntrypoint` + its middleware stack |
136+
| `fastapi` | fastapi, uvicorn, deadline-budget, prometheus-fastapi-instrumentator | `FastApiEntrypoint` + its middleware stack, `HttpServerSettings` |
137137
| `litestar` | litestar, uvicorn | `LitestarEntrypoint` |
138138
| `grpc` | grpc-server-kit[reflection,channelz,health] | `GrpcEntrypoint`, error mapping, health bridge |
139139
| `apscheduler4` / `apscheduler3` | apscheduler 4.x / 3.x | `SchedulerEntrypoint` (one major per environment) |

‎docs/adapters/fastapi.md‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,111 @@ FastApiEntrypoint(
8989
| `uvicorn_kwargs` | `{}` | Merged into the `uvicorn.Config(...)` call |
9090
| `health` | `HealthConfig()` | Probe routes: `enabled`, `liveness_path`, `readiness_path` |
9191

92+
### From settings
93+
94+
The environment-facing side of the same field set ships with the adapter: `HttpServerSettings`,
95+
one pydantic model per config dataclass — `HealthSettings`, `MiddlewareSettings` with its four
96+
middleware sections, `UvicornSettings` — same field names, same defaults, `to_config()` on each.
97+
Nest it in your settings object (`servicewright[settings]`'s `BaseServiceSettings`, or a
98+
`BaseSettings` of your own with `env_nested_delimiter="__"`) and the mapping lives here rather than
99+
in each service:
100+
101+
```python
102+
from servicewright.adapters.fastapi import FastApiEntrypoint, HttpServerSettings
103+
from servicewright.adapters.settings import BaseServiceSettings
104+
105+
106+
class Settings(BaseServiceSettings):
107+
server: HttpServerSettings = HttpServerSettings()
108+
109+
110+
settings = Settings()
111+
http = FastApiEntrypoint(
112+
config=settings.server.to_config(version=settings.app_version),
113+
middlewares=settings.server.middlewares.to_config(),
114+
routers=(router,),
115+
)
116+
```
117+
118+
```bash
119+
SERVER__PORT=8080
120+
SERVER__GRACEFUL_TIMEOUT=15
121+
SERVER__HEALTH__READINESS_PATH=/readyz
122+
SERVER__UVICORN__TIMEOUT_KEEP_ALIVE=30
123+
SERVER__UVICORN__FORWARDED_ALLOW_IPS=*
124+
SERVER__MIDDLEWARES__GZIP__ENABLED=false
125+
SERVER__MIDDLEWARES__CORS__ALLOW_ORIGINS='["https://app.example.com"]'
126+
```
127+
128+
Every model is a plain `BaseModel`, never a `BaseSettings`, so the only way into `server.port` is
129+
`SERVER__PORT`: a bare `PORT` or `HOST` in the pod cannot reach it. `HttpServerSettings().to_config()`
130+
equals `HttpConfig()` and `MiddlewareSettings().to_config()` equals `MiddlewareConfig()`, and a test
131+
asserts that each model names exactly the fields of its dataclass minus the members below, so a
132+
field added to a dataclass cannot leave the mapping silently incomplete. `MiddlewareConfig` is the
133+
entrypoint's own argument rather than part of `HttpConfig`, hence the second call.
134+
135+
The members that are code, not environment, are arguments of `to_config()` rather than fields:
136+
137+
| Argument | Of | Default | Why it is not read from settings |
138+
| --- | --- | --- | --- |
139+
| `version` | `HttpServerSettings.to_config` | `"0.0.0"` | The OpenAPI version is the application's, which `settings.app_version` carries once already |
140+
| `unit_scope` | `MiddlewareSettings.to_config` | `True` | Whether your DI integration owns the request scope is decided where it is wired |
141+
| `context_setters` | `MiddlewareSettings.to_config` | `None` | `ContextSetter` objects |
142+
| `custom` | `MiddlewareSettings.to_config` | `()` | Middleware classes and their kwargs |
143+
144+
`fastapi_kwargs` and `uvicorn_kwargs` stay dict fields, JSON in the environment
145+
(`SERVER__FASTAPI_KWARGS='{"debug": true}'`); anything that is not JSON — a `lifespan`, say — goes
146+
onto the returned config afterwards, `config.fastapi_kwargs["lifespan"] = lifespan`.
147+
148+
`port=0` is rejected unless `allow_ephemeral_port=True`, as on
149+
[`MetricsSettings`](../concepts/settings.md#validation-instead-of-silent-fallbacks): `0` only ever
150+
arrives here from configuration (`SERVER__PORT`, one keystroke from `8000`), and a pod on an
151+
ephemeral port is one no probe or load balancer reaches. `HttpConfig(port=0)` itself keeps working
152+
and reports what it got through `bound_port`. CORS `allow_credentials=True` with a `*` origin fails
153+
at load, with `server.middlewares.cors` in the error, rather than at construction.
154+
155+
#### The uvicorn knobs
156+
157+
`server.uvicorn` types the operational uvicorn arguments. Every field is `None` until set and only
158+
a set field is forwarded, so uvicorn's own defaults apply to the rest and the model pins none of
159+
them; `to_config()` puts exactly what was set into `HttpConfig.uvicorn_kwargs`, typed —
160+
`SERVER__UVICORN__TIMEOUT_KEEP_ALIVE=30` arrives as the integer `30`, where the same key under a
161+
`dict` field would arrive as the string `"30"`.
162+
163+
| Field | uvicorn's default | Meaning |
164+
| --- | --- | --- |
165+
| `proxy_headers` | `True` | Trust `X-Forwarded-*` from `forwarded_allow_ips` |
166+
| `forwarded_allow_ips` | `127.0.0.1` | A list, a comma-separated string or `*` |
167+
| `root_path` | `""` | ASGI root path, for an app served under a prefix |
168+
| `server_header`, `date_header` | `True` | The `Server` and `Date` response headers |
169+
| `timeout_keep_alive` | `5` | Seconds an idle keep-alive connection is held |
170+
| `backlog` | `2048` | Listen backlog |
171+
| `limit_concurrency` | none | Concurrent connections or tasks before new requests get a 503 |
172+
| `limit_max_requests` | none | Requests served before the server exits — and the Host stops the process |
173+
| `h11_max_incomplete_event_size` | h11's | Largest request line plus headers, bytes |
174+
| `access_log` | `True` | uvicorn's own access log; the logging middleware writes one line per request already |
175+
| `log_level` | none | Level of uvicorn's own loggers, `critical` … `trace`, any case |
176+
| `ssl_keyfile`, `ssl_certfile`, `ssl_keyfile_password`, `ssl_ca_certs`, `ssl_cert_reqs`, `ssl_ciphers` | none | TLS termination in the process; uvicorn wraps the socket the runner bound |
177+
178+
`uvicorn_kwargs` is the escape hatch for the rest of `uvicorn.Config`'s signature and wins on a
179+
collision, as it does on `HttpConfig` itself. A test asserts every typed field is a
180+
`uvicorn.Config` parameter and lands there under its own name.
181+
182+
Not typed, on purpose, because the runner pre-binds the socket and drives one `uvicorn.Server`
183+
directly:
184+
185+
| Parameter | Why |
186+
| --- | --- |
187+
| `workers` | Read only by `uvicorn.run()`'s multiprocess supervisor. `Server.serve()` is single-process, so a `workers` in `uvicorn_kwargs` is stored on the config and never consulted: one process per pod, always |
188+
| `host`, `port`, `timeout_graceful_shutdown` | `server.host`, `server.port`, `server.graceful_timeout` |
189+
| `log_config` | The Host owns logging; the runner passes `None` |
190+
| `loop` | `run_sync(loop=...)` owns the loop |
191+
| `reload*`, `uds`, `fd`, `env_file` | The development reloader, other ways to bind, another environment layer |
192+
193+
Not covered at all: cookie policy (`secure`, `httponly`, `samesite`) is an application concern and
194+
stays in your settings; `MetricsInstrumentatorConfig` is callables and library kwargs, wired in
195+
code as under [Metrics](#metrics); `LitestarConfig` has no settings model.
196+
92197
## Per-request dependency scope
93198

94199
`UnitScopeMiddleware` is installed automatically as the **outermost** middleware and opens one

‎docs/agents.md‎

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -311,7 +311,7 @@ installed and raise (or degrade) at construction instead.
311311

312312
| Import | Public names |
313313
|---|---|
314-
| `servicewright.adapters.fastapi` | `FastApiEntrypoint`, `FastApiPlugin`, `HttpConfig`, `MiddlewareConfig`, `HealthConfig`, `CORSMiddlewareConfig`, `LoggingMiddlewareConfig`, `GZipMiddlewareConfig`, `CorrelationIdMiddlewareConfig`, `MetricsInstrumentatorConfig`, `UnitScopeDep`, `UnitScopeMiddleware`, `get_unit_scope`, `current_unit_scope`, `setup_default_exception_handlers`, `setup_metrics_instrumentator`, `LivenessResponse`, `ReadinessResponse`, `ProblemDetails`, `XUserId`, `IdempotencyKey`, `AuthorizationHeader`, `XFingerprintHeader`, `OtelBaggageSetter`, `StructlogSetter`, `get_default_context_setters`, `RoutesRegisterer`, `ConfigureApp` |
314+
| `servicewright.adapters.fastapi` | `FastApiEntrypoint`, `FastApiPlugin`, `HttpConfig`, `MiddlewareConfig`, `HealthConfig`, `CORSMiddlewareConfig`, `LoggingMiddlewareConfig`, `GZipMiddlewareConfig`, `CorrelationIdMiddlewareConfig`, `MetricsInstrumentatorConfig`, `UnitScopeDep`, `UnitScopeMiddleware`, `get_unit_scope`, `current_unit_scope`, `setup_default_exception_handlers`, `setup_metrics_instrumentator`, `LivenessResponse`, `ReadinessResponse`, `ProblemDetails`, `XUserId`, `IdempotencyKey`, `AuthorizationHeader`, `XFingerprintHeader`, `OtelBaggageSetter`, `StructlogSetter`, `get_default_context_setters`, `RoutesRegisterer`, `ConfigureApp`; the config as settings models `HttpServerSettings`, `HealthSettings`, `MiddlewareSettings`, `LoggingMiddlewareSettings`, `CorrelationIdMiddlewareSettings`, `GZipMiddlewareSettings`, `CORSMiddlewareSettings`, `UvicornSettings` |
315315
| `servicewright.adapters.litestar` | `LitestarEntrypoint`, `LitestarPlugin`, `LitestarConfig`, `HealthConfig`, `build_health_routes`, `UnitScopeMiddleware`, `get_unit_scope`, `current_unit_scope`, `RouteRegisterer`, `ConfigureApp` |
316316
| `servicewright.adapters.grpc` | `GrpcEntrypoint`, `GrpcPlugin`, `GrpcConfig`, `ServicerRegisterer`, `InterceptorFactory`, `ServiceErrorInterceptor`, `UnhandledErrorInterceptor`, `GRPC_STATUS_BY_KIND`, `ERROR_CODE_TRAILING_METADATA`, `GrpcHealthBridge`, `UnitScopeInterceptor`, `current_unit_scope`, `GrpcServerMetricsRecorder`, `IDEMPOTENCY_KEY_METADATA`, `get_idempotency_key`, `get_client_ip`, `get_user_agent`, `get_client_context` |
317317
| `servicewright.adapters.apscheduler4` (and `.apscheduler3`) | `SchedulerEntrypoint`, `SchedulerPlugin`, `ScheduledJob`, `ScheduledJobFunc`, `SchedulerJobMetricsRecorder`, `SchedulerError`, `DuplicateScheduleError` |
@@ -331,6 +331,15 @@ Entrypoint constructors, all keyword-only:
331331
`/system/health/livez` and `/system/health/readyz`, docs at `/system/docs`,
332332
`redirect_slashes=False`. `MiddlewareConfig` defaults have unit scope, context, sentry,
333333
processing time, logging, correlation id, gzip and CORS all on.
334+
`HttpServerSettings` is `HttpConfig` as a settings model — a plain pydantic `BaseModel` the
335+
adapter exports; nest it as `server: HttpServerSettings = HttpServerSettings()` in your
336+
settings class and it is `SERVER__*` in the environment. Same fields and defaults, `health` and
337+
`middlewares` sections, the operational uvicorn knobs typed under `uvicorn` (`None` means
338+
uvicorn's default and only a set field is forwarded; there is no `workers`, since
339+
`Server.serve()` is single-process and ignores it). `settings.server.to_config(version="0.0.0")`
340+
is the `HttpConfig`, `settings.server.middlewares.to_config(unit_scope=True,
341+
context_setters=None, custom=())` the `MiddlewareConfig`; the keywords are the members no
342+
environment carries. `port=0` is rejected unless `allow_ephemeral_port=True`.
334343
* `LitestarEntrypoint(config=None, route_handlers=(), route_registerer=None,
335344
configure_app=None, kind="http", essential=True)`. `LitestarConfig` probes are
336345
`/system/livez` and `/system/readyz`; `unit_scope=True`.
@@ -416,7 +425,8 @@ Each `*Plugin` takes exactly the same arguments as its entrypoint and exposes `.
416425
12. **Settings are read structurally, never inherited.** The kernel reads `settings.logging`,
417426
`.metrics`, `.tracing`, `.error_tracking` and `get_app_version()` off whatever object you
418427
pass; a misspelled field silently becomes a default. `servicewright[settings]` ships the
419-
contract as pydantic models so it cannot drift.
428+
contract as pydantic models so it cannot drift, and the FastAPI adapter ships
429+
`HttpServerSettings` for its own config the same way.
420430
13. **Warmers run in priority groups — lower `priority` first, equal priorities in
421431
parallel** — and the Host always calls the engine with `raise_on_failure=True`. A warmer
422432
that must not abort startup sets `raise_on_failure=False` on **itself**; a failing group
@@ -543,6 +553,24 @@ async def sweep(scope: UnitScopeProtocol) -> None:
543553
await repo.delete_expired()
544554
```
545555

556+
```python
557+
# WRONG — a settings model of your own carrying HttpConfig's fields, copied across by hand
558+
class HttpSettings(BaseModel):
559+
host: str = "0.0.0.0"
560+
port: int = 8000
561+
timeout_keep_alive: int = 5
562+
563+
config = HttpConfig(host=settings.http.host, port=settings.http.port,
564+
uvicorn_kwargs={"timeout_keep_alive": settings.http.timeout_keep_alive})
565+
566+
# RIGHT — the adapter ships the model; nest it and translate once
567+
class Settings(BaseServiceSettings):
568+
server: HttpServerSettings = HttpServerSettings()
569+
570+
config = settings.server.to_config(version=settings.app_version)
571+
middlewares = settings.server.middlewares.to_config()
572+
```
573+
546574
```python
547575
# WRONG — passing a stop event and still expecting SIGTERM to be handled
548576
await service.run(settings, stop=asyncio.Event()) # no signal handlers are installed
@@ -599,7 +627,7 @@ Fetch a page when the task is the one named beside it.
599627
| [Observability](concepts/observability.md) | selecting backends, the four concerns, redaction, instruments |
600628
| [Plugins](concepts/plugins.md) | packaging wiring as `on_register` |
601629
| [Adapters overview](adapters/overview.md) | which adapter family solves the problem in front of you |
602-
| [FastAPI](adapters/fastapi.md) | the HTTP entrypoint, its middleware stack, probes, per-request scope |
630+
| [FastAPI](adapters/fastapi.md) | the HTTP entrypoint, its middleware stack, probes, per-request scope, `HttpServerSettings` |
603631
| [Litestar](adapters/litestar.md) | the lean HTTP entrypoint and how it differs from the FastAPI one |
604632
| [gRPC](adapters/grpc.md) | servicers, interceptors, the health bridge, error mapping, reflection, `GrpcConfig.from_settings` |
605633
| [Scheduler](adapters/scheduler.md) | cron and interval jobs, triggers, the 3.x/4.x split |

‎docs/blueprints/http-api.md‎

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ logs, Prometheus metrics, RFC 9457 errors and a Kubernetes-correct shutdown.
66
Copy it, rename it, delete what you do not need.
77

88
```bash
9-
pip install "servicewright[fastapi,dishka,postgres,metrics,observability]"
9+
pip install "servicewright[fastapi,dishka,postgres,metrics,observability,settings]"
1010
```
1111

1212
## What you are building
@@ -27,31 +27,31 @@ flowchart LR
2727
## 1. Settings
2828

2929
```python title="runtime/settings.py"
30-
from pydantic import BaseModel
3130
from pydantic_settings import SettingsConfigDict
3231

32+
from servicewright.adapters.fastapi import HttpServerSettings
3333
from servicewright.adapters.settings import BaseServiceSettings
3434

3535

36-
class HttpSettings(BaseModel):
37-
host: str = "0.0.0.0"
38-
port: int = 8000
39-
cors_origins: list[str] = []
40-
41-
4236
class Settings(BaseServiceSettings):
4337
model_config = SettingsConfigDict(env_file=".env")
4438

4539
database_dsn: str
4640

47-
http: HttpSettings = HttpSettings()
41+
server: HttpServerSettings = HttpServerSettings()
4842
```
4943

5044
The observability sections come from `BaseServiceSettings` (`servicewright[settings]`): logging
5145
on, the metrics sink on with no standalone server (the API exposes `/system/metrics` on its own
5246
port), tracing and error tracking off until `TRACING__COLLECTOR_URL` / `ERROR_TRACKING__DSN` are
5347
set. See [Settings](../concepts/settings.md#shipped-models).
5448

49+
`server` is the FastAPI adapter's `HttpServerSettings`: `HttpConfig`, its `HealthConfig` and the
50+
`MiddlewareConfig` as one nested model, the uvicorn knobs typed, so everything the entrypoint reads
51+
from the environment is `SERVER__*` — `SERVER__PORT`, `SERVER__UVICORN__TIMEOUT_KEEP_ALIVE`,
52+
`SERVER__MIDDLEWARES__CORS__ALLOW_ORIGINS`. See
53+
[From settings](../adapters/fastapi.md#from-settings).
54+
5555
## 2. Container
5656

5757
```python title="infra/di/providers.py"
@@ -212,25 +212,22 @@ def build_spec(settings: Settings) -> AppSpec:
212212
## 6. The entrypoint and main
213213

214214
```python title="runtime/entrypoints.py"
215-
from servicewright.adapters.fastapi import CORSMiddlewareConfig, FastApiEntrypoint, HttpConfig, MiddlewareConfig
215+
from servicewright.adapters.fastapi import FastApiEntrypoint
216216

217217

218218
def build_http(settings: Settings) -> FastApiEntrypoint:
219219
return FastApiEntrypoint(
220-
config=HttpConfig(
221-
host=settings.http.host,
222-
port=settings.http.port,
223-
version=settings.app_version,
224-
graceful_timeout=10.0,
225-
),
220+
config=settings.server.to_config(version=settings.app_version),
221+
middlewares=settings.server.middlewares.to_config(),
226222
routers=(orders_router,),
227-
middlewares=MiddlewareConfig(
228-
cors=CORSMiddlewareConfig(allow_origins=settings.http.cors_origins),
229-
),
230223
metrics=True,
231224
)
232225
```
233226

227+
`to_config()` is the whole mapping: host, port, the 10 s graceful timeout, the probe paths and
228+
whatever `SERVER__UVICORN__*` the deployment sets. `version` is the one thing it takes from you —
229+
the OpenAPI version is the application's.
230+
234231
```python title="api_main.py"
235232
import asyncio
236233

@@ -264,7 +261,7 @@ spec:
264261
env:
265262
- name: DATABASE_DSN
266263
valueFrom: { secretKeyRef: { name: orders-db, key: dsn } }
267-
- name: HTTP__CORS_ORIGINS
264+
- name: SERVER__MIDDLEWARES__CORS__ALLOW_ORIGINS
268265
value: '["https://app.example.com"]'
269266
livenessProbe:
270267
httpGet: { path: /system/health/livez, port: 8000 }

‎docs/blueprints/project-layout.md‎

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -107,23 +107,18 @@ Four small files, each with one job.
107107
=== "settings.py"
108108

109109
```python
110-
from pydantic import BaseModel
111110
from pydantic_settings import SettingsConfigDict
112111

112+
from servicewright.adapters.fastapi import HttpServerSettings
113113
from servicewright.adapters.settings import BaseServiceSettings
114114

115115

116-
class HttpSettings(BaseModel):
117-
host: str = "0.0.0.0"
118-
port: int = 8000
119-
120-
121116
class Settings(BaseServiceSettings):
122117
model_config = SettingsConfigDict(env_file=".env")
123118

124119
database_dsn: str
125120

126-
http: HttpSettings = HttpSettings()
121+
server: HttpServerSettings = HttpServerSettings()
127122
```
128123

129124
=== "container.py"
@@ -176,18 +171,14 @@ Four small files, each with one job.
176171
=== "entrypoints.py"
177172

178173
```python
179-
from servicewright.adapters.fastapi import FastApiEntrypoint, HttpConfig
174+
from servicewright.adapters.fastapi import FastApiEntrypoint
180175

181176
from orders_service.api.http.routers import orders_router
182177

183178

184179
def build_http(settings: Settings) -> FastApiEntrypoint:
185180
return FastApiEntrypoint(
186-
config=HttpConfig(
187-
host=settings.http.host,
188-
port=settings.http.port,
189-
version=settings.app_version,
190-
),
181+
config=settings.server.to_config(version=settings.app_version),
191182
routers=(orders_router,),
192183
metrics=True,
193184
)

0 commit comments

Comments
 (0)