Skip to content

Commit 55a62db

Browse files
feat: ship the settings contract as pydantic-settings models (#23)
* feat: ship the settings contract as pydantic-settings models The settings contract was documented as field tables plus a pydantic-settings example that every consumer transcribed by hand, and nothing checked the copy: a field could become required (tracing.service_name), a misspelled one fell back to a default nobody could see, and the defaults themselves were guesswork. servicewright.adapters.settings, behind the new `settings` extra, is the contract written down once: LoggingSettings, MetricsSettings, TracingSettings and ErrorTrackingSettings with exactly the protocols' fields and the sinks' own fallbacks as defaults (validated instead of silently coerced), and BaseServiceSettings composing them with `environment`, `app_version` and get_app_version(), loading from the environment with `__` nesting. Subclasses narrow or disable sections exactly as a hand-written class does. The docs tables gain the defaults, the blueprints import the models instead of restating them, and the mypy-driven typing test now asserts the shipped models satisfy BaseServiceSettingsProtocol. Closes #22 * test: make the shipped-models typing cases fail when the module is unresolvable With ignore_missing_imports on, mypy types a missing module as Any and the protocol check passes vacuously; revealing a member of the shipped models turns that into a failure.
1 parent 4455ad7 commit 55a62db

17 files changed

Lines changed: 685 additions & 119 deletions

File tree

‎ARCHITECTURE.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,8 @@ concrete framework binding.**
5454
contract surface, the `Host` loop-kernel, the lifecycle state machine, observability
5555
seam-specs/orchestration, warmup orchestration, the health registry.
5656
- **`adapters/`** holds the implementation: one subpackage per `(framework, major)` for
57-
entrypoints, the DI binding, the concrete warmers, the concrete health-checkers, and the
58-
add-on backend implementations.
57+
entrypoints, the DI binding, the concrete warmers, the concrete health-checkers, the
58+
add-on backend implementations, and the pydantic-settings models of the settings contract.
5959

6060
**Dependency rule (CI-enforced via import-linter):** `adapters → core → stdlib`; never
6161
`core → adapters`; never `adapter → adapter`. **Litmus:** *deleting `adapters/` must leave

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ import-linter contract enforces the direction in CI: deleting `adapters/` leaves
115115
| `adapters.grpc` | gRPC entrypoint over grpc-server-kit, error mapping, health bridge | `grpc` |
116116
| `adapters.apscheduler4` / `apscheduler3` | Scheduler entrypoints with identical public surfaces | `apscheduler4` / `apscheduler3` |
117117
| `adapters.dishka` | dishka ⇄ core scope binding | `dishka` |
118+
| `adapters.settings` | pydantic-settings models of the settings contract | `settings` |
118119
| `adapters.observability` | prometheus / OpenTelemetry / Sentry / structlog / stdlib sinks | see below |
119120
| `adapters.warmers`, `adapters.health` | Redis / Postgres / Kafka warmers and checks | `redis`, `postgres`, `kafka` |
120121
| `servicewright.testing` | `FakeContainer`, `FakeEntrypoint`, `FakeScope`, `FakeSettings` | — |
@@ -128,6 +129,7 @@ import-linter contract enforces the direction in CI: deleting `adapters/` leaves
128129
| `grpc` | grpc-server-kit[reflection,channelz,health] | `GrpcEntrypoint`, error mapping, health bridge |
129130
| `apscheduler4` / `apscheduler3` | apscheduler 4.x / 3.x | `SchedulerEntrypoint` (one major per environment) |
130131
| `dishka` | dishka | `DishkaContainer` |
132+
| `settings` | pydantic-settings | `BaseServiceSettings` + the four section models, with the sinks' defaults |
131133
| `observability` | opentelemetry-sdk, OTLP gRPC exporter, structlog | `otel` tracing + `structlog` logging sinks |
132134
| `fastapi-tracing` | the above + opentelemetry-instrumentation-fastapi | HTTP request spans |
133135
| `metrics` | prometheus-client | `prometheus` metrics sink + `/system/metrics` |

‎docs/adapters/overview.md‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
Everything that touches a third-party library lives in `servicewright.adapters`, behind an extra.
44
The kernel never imports any of it.
55

6-
There are four families.
6+
There are five families.
77

88
## Entrypoint adapters
99

@@ -43,6 +43,16 @@ observability stack and the shutdown.
4343
Any other container works by implementing
4444
[two methods](../concepts/dependency-injection.md#the-contract).
4545

46+
## Settings
47+
48+
| Adapter | Class | Extra |
49+
| --- | --- | --- |
50+
| [Settings models](../concepts/settings.md#shipped-models) | `BaseServiceSettings` | `settings` |
51+
52+
The settings contract as pydantic-settings models: one model per section, carrying the defaults
53+
the backends fall back to, and a composite that loads them from the environment. Any object with
54+
the right attributes still works.
55+
4656
## Observability backends
4757

4858
| Concern | Backend | Extra |

‎docs/blueprints/http-api.md‎

Lines changed: 9 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -28,19 +28,9 @@ flowchart LR
2828

2929
```python title="runtime/settings.py"
3030
from pydantic import BaseModel
31-
from pydantic_settings import BaseSettings, SettingsConfigDict
31+
from pydantic_settings import SettingsConfigDict
3232

33-
34-
class LoggingSettings(BaseModel):
35-
level: str = "INFO"
36-
use_json: bool = True
37-
38-
39-
class MetricsSettings(BaseModel):
40-
enabled: bool = False # the API exposes /system/metrics on its own port
41-
host: str = "0.0.0.0"
42-
port: int = 9090
43-
prefix: str | None = None
33+
from servicewright.adapters.settings import BaseServiceSettings
4434

4535

4636
class HttpSettings(BaseModel):
@@ -49,23 +39,19 @@ class HttpSettings(BaseModel):
4939
cors_origins: list[str] = []
5040

5141

52-
class Settings(BaseSettings):
53-
model_config = SettingsConfigDict(env_nested_delimiter="__", env_file=".env")
42+
class Settings(BaseServiceSettings):
43+
model_config = SettingsConfigDict(env_file=".env")
5444

55-
app_version: str = "0.0.0"
56-
environment: str = "local"
5745
database_dsn: str
5846

5947
http: HttpSettings = HttpSettings()
60-
logging: LoggingSettings = LoggingSettings()
61-
metrics: MetricsSettings = MetricsSettings()
62-
tracing: None = None
63-
error_tracking: None = None
64-
65-
def get_app_version(self) -> str:
66-
return self.app_version
6748
```
6849

50+
The observability sections come from `BaseServiceSettings` (`servicewright[settings]`): logging
51+
on, the metrics sink on with no standalone server (the API exposes `/system/metrics` on its own
52+
port), tracing and error tracking off until `TRACING__COLLECTOR_URL` / `ERROR_TRACKING__DSN` are
53+
set. See [Settings](../concepts/settings.md#shipped-models).
54+
6955
## 2. Container
7056

7157
```python title="infra/di/providers.py"

‎docs/blueprints/project-layout.md‎

Lines changed: 4 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -108,41 +108,22 @@ Four small files, each with one job.
108108

109109
```python
110110
from pydantic import BaseModel
111-
from pydantic_settings import BaseSettings, SettingsConfigDict
111+
from pydantic_settings import SettingsConfigDict
112112

113-
114-
class LoggingSettings(BaseModel):
115-
level: str = "INFO"
116-
use_json: bool = True
117-
118-
119-
class MetricsSettings(BaseModel):
120-
enabled: bool = False
121-
host: str = "0.0.0.0"
122-
port: int = 9090
123-
prefix: str | None = None
113+
from servicewright.adapters.settings import BaseServiceSettings
124114

125115

126116
class HttpSettings(BaseModel):
127117
host: str = "0.0.0.0"
128118
port: int = 8000
129119

130120

131-
class Settings(BaseSettings):
132-
model_config = SettingsConfigDict(env_nested_delimiter="__", env_file=".env")
121+
class Settings(BaseServiceSettings):
122+
model_config = SettingsConfigDict(env_file=".env")
133123

134-
app_version: str = "0.0.0"
135-
environment: str = "local"
136124
database_dsn: str
137125

138126
http: HttpSettings = HttpSettings()
139-
logging: LoggingSettings = LoggingSettings()
140-
metrics: MetricsSettings = MetricsSettings()
141-
tracing: None = None
142-
error_tracking: None = None
143-
144-
def get_app_version(self) -> str:
145-
return self.app_version
146127
```
147128

148129
=== "container.py"

‎docs/concepts/architecture.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ preference — it is what makes `pip install servicewright` cost you nothing.
9696
| `adapters.grpc` | gRPC entrypoint, error mapping, health bridge | `grpc` |
9797
| `adapters.apscheduler4` / `apscheduler3` | Scheduler entrypoints with identical surfaces | `apscheduler4` / `apscheduler3` |
9898
| `adapters.dishka` | dishka ⇄ core scope binding | `dishka` |
99+
| `adapters.settings` | pydantic-settings models of the settings contract | `settings` |
99100
| `adapters.observability` | Prometheus / OTel / Sentry / structlog / stdlib sinks | varies |
100101
| `adapters.warmers`, `adapters.health` | Redis / Postgres / Kafka warmers and checks | `redis`, `postgres`, `kafka` |
101102
| `servicewright.testing` | In-memory doubles for your own tests | — |

‎docs/concepts/settings.md‎

Lines changed: 98 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
# Settings
22

33
servicewright reads a small, fixed set of things off a settings object that **you** own and
4-
construct. It never loads a `.env`, never reads `os.environ`, and never defines a settings class
5-
you have to inherit from.
4+
construct. The kernel never loads a `.env`, never reads `os.environ`, and never defines a class
5+
you have to inherit from: it checks shape, not ancestry. The `settings` extra ships that shape as
6+
ready-made [pydantic-settings models](#shipped-models), so you do not have to transcribe it.
67

78
## The protocol
89

@@ -24,21 +25,28 @@ Sentry for something else does not touch your settings class.
2425

2526
## The sections
2627

28+
Each table lists the **default** the built-in backend falls back to when the field is missing
29+
from your section. The [shipped models](#shipped-models) carry the same values, so a model of
30+
your own that uses them behaves exactly like the shipped one.
31+
2732
### `logging`
2833

29-
| Field | Type | Meaning |
30-
| --- | --- | --- |
31-
| `level` | `str` | Root log level: `DEBUG`, `INFO`, ... |
32-
| `use_json` | `bool` | JSON lines vs human-readable console output |
34+
| Field | Type | Default | Meaning |
35+
| --- | --- | --- | --- |
36+
| `level` | `str` | `"INFO"` | Root log level: `DEBUG`, `INFO`, ... |
37+
| `use_json` | `bool` | `True` | JSON lines vs human-readable console output |
3338

3439
### `metrics`
3540

36-
| Field | Type | Meaning |
37-
| --- | --- | --- |
38-
| `enabled` | `bool` | Start a standalone exposition server |
39-
| `host` | `str` | Bind host for that server |
40-
| `port` | `int` | Bind port for that server |
41-
| `prefix` | `str \| None` | Metric name prefix, for backends that use one |
41+
| Field | Type | Default | Meaning |
42+
| --- | --- | --- | --- |
43+
| `enabled` | `bool` | `False` | Start a standalone exposition server |
44+
| `host` | `str` | `"0.0.0.0"` | Bind host for that server |
45+
| `port` | `int` | `9090` | Bind port for that server |
46+
| `prefix` | `str \| None` | `None` | Metric name prefix, for backends that use one |
47+
48+
`host` and `port` are read only when `enabled` is true and have no backend fallback; their
49+
defaults are the shipped model's.
4250

4351
!!! note
4452

@@ -49,24 +57,24 @@ Sentry for something else does not touch your settings class.
4957

5058
### `tracing`
5159

52-
| Field | Type | Meaning |
53-
| --- | --- | --- |
54-
| `service_name` | `str` | Resource service name (falls back to `AppSpec.service_name`) |
55-
| `collector_url` | `str \| None` | OTLP endpoint; `None` means no exporter |
56-
| `sample_ratio` | `float` | Ratio for the parent-based sampler |
57-
| `insecure` | `bool` | Plaintext OTLP connection |
58-
| `enable_console_exporter` | `bool` | Also print spans to stdout |
59-
| `excluded_urls` | `str \| None` | Comma-separated paths to skip |
60+
| Field | Type | Default | Meaning |
61+
| --- | --- | --- | --- |
62+
| `service_name` | `str` | `""` | Resource service name; empty falls back to `AppSpec.service_name` |
63+
| `collector_url` | `str \| None` | `None` | OTLP endpoint; `None` means no exporter |
64+
| `sample_ratio` | `float` | `1.0` | Ratio for the parent-based sampler |
65+
| `insecure` | `bool` | `True` | Plaintext OTLP connection |
66+
| `enable_console_exporter` | `bool` | `False` | Also print spans to stdout |
67+
| `excluded_urls` | `str \| None` | `None` | Comma-separated paths to skip |
6068

6169
### `error_tracking`
6270

63-
| Field | Type | Meaning |
64-
| --- | --- | --- |
65-
| `dsn` | `str \| None` | Reporting endpoint; **empty means the concern is off** |
66-
| `environment` | `str` | Environment tag |
67-
| `traces_sample_rate` | `float` | Performance-trace sampling |
68-
| `profiles_sample_rate` | `float` | Profiling sampling |
69-
| `debug` | `bool` | SDK debug mode |
71+
| Field | Type | Default | Meaning |
72+
| --- | --- | --- | --- |
73+
| `dsn` | `str \| None` | `None` | Reporting endpoint; **empty means the concern is off** |
74+
| `environment` | `str` | `""` | Environment tag; empty falls back to `settings.environment` |
75+
| `traces_sample_rate` | `float` | `0.0` | Performance-trace sampling |
76+
| `profiles_sample_rate` | `float` | `0.0` | Profiling sampling |
77+
| `debug` | `bool` | `False` | SDK debug mode |
7078

7179
### Narrowing a section
7280

@@ -111,59 +119,87 @@ Your code never has to check whether metrics are configured.
111119

112120
Error tracking is special: the section may exist while `dsn` is empty, which also counts as off.
113121

114-
## With pydantic-settings
122+
## Shipped models
123+
124+
Install the `settings` extra and the four sections plus the composite come as pydantic models,
125+
carrying the defaults above:
115126

116-
Anything with the right attribute names works. A typical real service:
127+
```bash
128+
pip install "servicewright[settings]"
129+
```
117130

118131
```python
119-
from pydantic import BaseModel
120-
from pydantic_settings import BaseSettings, SettingsConfigDict
132+
from pydantic_settings import SettingsConfigDict
121133

134+
from servicewright.adapters.settings import BaseServiceSettings
122135

123-
class LoggingSettings(BaseModel):
124-
level: str = "INFO"
125-
use_json: bool = True
126136

137+
class Settings(BaseServiceSettings):
138+
model_config = SettingsConfigDict(env_file=".env")
139+
140+
app_version: str = "1.4.0"
141+
database_dsn: str
142+
```
143+
144+
```bash
145+
LOGGING__LEVEL=DEBUG TRACING__COLLECTOR_URL=otel:4317 python main.py
146+
```
127147

128-
class MetricsSettings(BaseModel):
129-
enabled: bool = False
130-
host: str = "0.0.0.0"
131-
port: int = 9090
132-
prefix: str | None = None
148+
`BaseServiceSettings` is a `pydantic_settings.BaseSettings` with `env_nested_delimiter="__"`, the
149+
four sections, `environment` (default `"local"`), `app_version` (default `"0.0.0"`) and a
150+
`get_app_version()` returning it. Your `model_config` is merged with the base one, so an
151+
`env_file` or an `env_prefix` of yours keeps the `__` nesting.
133152

153+
### What is on by default
134154

135-
class TracingSettings(BaseModel):
136-
service_name: str = ""
137-
collector_url: str | None = None
138-
sample_ratio: float = 1.0
139-
insecure: bool = True
140-
enable_console_exporter: bool = False
141-
excluded_urls: str | None = None
155+
| Section | Default | Why |
156+
| --- | --- | --- |
157+
| `logging` | `LoggingSettings()` — `INFO`, JSON | you want logs |
158+
| `metrics` | `MetricsSettings()` — sink on, exposition server off | inert until something records |
159+
| `error_tracking` | `ErrorTrackingSettings()` — no `dsn`, so off | switches on from `ERROR_TRACKING__DSN` alone |
160+
| `tracing` | `None` | a present section installs a tracer provider; `TRACING__COLLECTOR_URL=...` creates it |
142161

162+
A section typed `TracingSettings | None` is built from its nested variables the moment one is
163+
set, so `TRACING__COLLECTOR_URL=otel:4317` is all it takes to switch tracing on.
143164

144-
class Settings(BaseSettings):
145-
model_config = SettingsConfigDict(env_nested_delimiter="__", env_file=".env")
165+
A present section still activates its backend at bootstrap, which needs that backend's extra
166+
installed — `observability` for `structlog` and `otel`, `metrics` for `prometheus`. Otherwise set
167+
the section to `None` or select another backend in [`ObsConfig`](observability.md). The `settings`
168+
extra itself pulls in nothing but pydantic-settings.
146169

147-
app_version: str = "0.0.0"
148-
environment: str = "local"
170+
### Validation instead of silent fallbacks
149171

150-
logging: LoggingSettings = LoggingSettings()
151-
metrics: MetricsSettings = MetricsSettings()
152-
tracing: TracingSettings | None = None
153-
error_tracking: None = None
172+
The models validate what the backends assume: the log level must be one of `LogLevelStr`
173+
(case-insensitively, so `LOGGING__LEVEL=debug` is fine while `warn` is a load-time error rather
174+
than a silent `INFO`), the sample ratios are bounded to `[0, 1]`, the metrics port to a port.
154175

155-
def get_app_version(self) -> str:
156-
return self.app_version
157-
```
176+
### Disabling and narrowing
158177

159-
```bash
160-
LOGGING__LEVEL=DEBUG METRICS__PORT=9100 python main.py
178+
Exactly as with a hand-written class: a section annotated `None` is off, a section model can be
179+
subclassed to narrow or extend it, and a default can be replaced:
180+
181+
```python
182+
from typing import Literal
183+
184+
from servicewright.adapters.settings import BaseServiceSettings, LoggingSettings, TracingSettings
185+
186+
187+
class StrictLogging(LoggingSettings):
188+
level: Literal["INFO", "WARNING", "ERROR"] = "INFO"
189+
190+
191+
class Settings(BaseServiceSettings):
192+
logging: StrictLogging = StrictLogging()
193+
tracing: TracingSettings = TracingSettings(sample_ratio=0.1) # on, sampling 10 %
194+
metrics: None = None # off
161195
```
162196

163-
!!! note
197+
### Writing your own
164198

165-
servicewright never imports pydantic. The example above works because the attributes line up,
166-
not because of any integration.
199+
Anything with the right attribute names still works — a frozen dataclass, a plain class, a
200+
pydantic-settings class of your own; [Your first service](../getting-started/first-service.md)
201+
shows the smallest one. The kernel never imports pydantic: the models live in
202+
`servicewright.adapters.settings`, behind their extra, like every other binding.
167203

168204
## What is *not* in settings
169205

‎docs/getting-started/first-service.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@ see [Settings](../concepts/settings.md).
3232
!!! tip
3333

3434
Any object with these attributes works: a `pydantic-settings` model, a dataclass, a plain
35-
class. servicewright checks shape, not inheritance.
35+
class. servicewright checks shape, not inheritance. The `settings` extra ships the shape as
36+
ready-made models — see [Settings](../concepts/settings.md#shipped-models).
3637

3738
## 2. A dependency container
3839

‎docs/getting-started/installation.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,12 @@ pip install "servicewright[fastapi,grpc,metrics,observability]"
4242

4343
The `stdlib` logging backend needs no extra.
4444

45-
### Infrastructure and DI
45+
### Infrastructure, DI and settings
4646

4747
| Extra | Pulls in | Gives you |
4848
| --- | --- | --- |
4949
| `dishka` | dishka | [`DishkaContainer`](../adapters/dishka.md) |
50+
| `settings` | pydantic-settings | [`BaseServiceSettings`](../concepts/settings.md#shipped-models) and the four section models |
5051
| `redis` | redis | `RedisWarmer`, `RedisHealthCheck` |
5152
| `postgres` | `sqlalchemy[asyncio]` | `PostgresWarmer`, `PostgresHealthCheck` |
5253
| `kafka` | aiokafka | `KafkaProducerWarmer` |

0 commit comments

Comments
 (0)