Skip to content

Commit ebc2c05

Browse files
fix(core): make the observability section protocols read-only so narrowed settings satisfy them (#13)
The four section protocols (logging / error-tracking / tracing / metrics) declared their members as mutable attributes, which are invariant: a settings model that narrows a field — a Literal-typed log level, a non-optional dsn, a bounded sample ratio — was rejected against BaseServiceSettingsProtocol even though nothing in the library ever writes to a section. The members are now read-only properties, matching the container protocol that returns them; plain attributes, dataclass and pydantic fields still satisfy them, narrowed ones start to. Pinned by a mypy-driven test that type-checks the issue's reproduction. Closes #8
1 parent b434a21 commit ebc2c05

3 files changed

Lines changed: 207 additions & 18 deletions

File tree

‎docs/concepts/settings.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,22 @@ Sentry for something else does not touch your settings class.
6868
| `profiles_sample_rate` | `float` | Profiling sampling |
6969
| `debug` | `bool` | SDK debug mode |
7070

71+
### Narrowing a section
72+
73+
Sections may declare types **narrower** than the tables above: a `Literal` level, a bounded
74+
`sample_ratio`, a `port` newtype. Section members are read-only properties and nothing in
75+
servicewright writes to them, so a narrowed model still satisfies the protocol. `LogLevelStr` is
76+
exported for the log level:
77+
78+
```python
79+
from servicewright.core.observability import LogLevelStr
80+
81+
82+
class LoggingSettings(BaseModel):
83+
level: LogLevelStr = "INFO"
84+
use_json: bool = True
85+
```
86+
7187
### Optional extras
7288

7389
- `settings.environment` — if present, it is used as the environment for observability setup.

‎servicewright/core/observability/protocols.py‎

Lines changed: 52 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,11 @@
44
never by vendor — which backend consumes a section is decided by
55
:class:`~servicewright.core.observability.config.ObsConfig`. Each protocol
66
declares only the minimal shape the built-in sinks need; backends are free to
7-
read extra fields off the same section via ``getattr``.
7+
read extra fields off the same section via ``getattr``. Members are read-only
8+
properties rather than mutable attributes because nothing in the library ever
9+
writes to a section, so a settings model is free to NARROW what it declares — a
10+
``Literal`` log level, a bounded sample ratio, a ``port`` newtype — and still
11+
satisfy the protocol.
812
"""
913

1014
from __future__ import annotations
@@ -17,38 +21,68 @@
1721
class LoggingSettingsProtocol(Protocol):
1822
"""Logging concern: root level and rendering format."""
1923

20-
level: LogLevelStr | str
21-
use_json: bool
24+
@property
25+
def level(self) -> LogLevelStr | str: ...
26+
27+
@property
28+
def use_json(self) -> bool: ...
2229

2330

2431
class ErrorTrackingSettingsProtocol(Protocol):
2532
"""Error-tracking concern: reporting endpoint and sampling."""
2633

27-
dsn: str | None
28-
environment: str
29-
traces_sample_rate: float
30-
profiles_sample_rate: float
31-
debug: bool
34+
@property
35+
def dsn(self) -> str | None: ...
36+
37+
@property
38+
def environment(self) -> str: ...
39+
40+
@property
41+
def traces_sample_rate(self) -> float: ...
42+
43+
@property
44+
def profiles_sample_rate(self) -> float: ...
45+
46+
@property
47+
def debug(self) -> bool: ...
3248

3349

3450
class TracingSettingsProtocol(Protocol):
3551
"""Tracing concern: exporter endpoint and sampling."""
3652

37-
service_name: str
38-
collector_url: str | None
39-
sample_ratio: float
40-
insecure: bool
41-
enable_console_exporter: bool
42-
excluded_urls: str | None
53+
@property
54+
def service_name(self) -> str: ...
55+
56+
@property
57+
def collector_url(self) -> str | None: ...
58+
59+
@property
60+
def sample_ratio(self) -> float: ...
61+
62+
@property
63+
def insecure(self) -> bool: ...
64+
65+
@property
66+
def enable_console_exporter(self) -> bool: ...
67+
68+
@property
69+
def excluded_urls(self) -> str | None: ...
4370

4471

4572
class MetricsSettingsProtocol(Protocol):
4673
"""Metrics concern: standalone exposition endpoint."""
4774

48-
enabled: bool
49-
port: int
50-
host: str
51-
prefix: str | None
75+
@property
76+
def enabled(self) -> bool: ...
77+
78+
@property
79+
def port(self) -> int: ...
80+
81+
@property
82+
def host(self) -> str: ...
83+
84+
@property
85+
def prefix(self) -> str | None: ...
5286

5387

5488
__all__ = [

‎tests/unit/test_settings_typing.py‎

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
"""Type-level tests: a settings model may narrow its observability sections.
2+
3+
The section protocols are structural, and a mutable attribute matches
4+
invariantly — so a narrowed field (issue #8) can only be pinned by running a
5+
type checker over a reproduction and reading its verdict.
6+
"""
7+
8+
from __future__ import annotations
9+
10+
import subprocess
11+
import sys
12+
from pathlib import Path
13+
14+
import pytest
15+
16+
mypy = pytest.importorskip("mypy")
17+
18+
pytestmark = pytest.mark.unit
19+
20+
ROOT = Path(__file__).resolve().parents[2]
21+
22+
_TEMPLATE = """\
23+
from typing import Literal
24+
25+
from servicewright import BaseServiceSettingsProtocol
26+
27+
{sections}
28+
29+
class Settings:
30+
{fields}
31+
32+
def get_app_version(self) -> str:
33+
return "1.0.0"
34+
35+
36+
def takes_protocol(settings: BaseServiceSettingsProtocol) -> None: ...
37+
38+
39+
takes_protocol(Settings())
40+
"""
41+
42+
_NARROWED_LOGGING = _TEMPLATE.format(
43+
sections="""\
44+
class Logging:
45+
level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO"
46+
use_json: bool = True
47+
""",
48+
fields="""\
49+
logging: Logging = Logging()
50+
metrics: None = None
51+
error_tracking: None = None
52+
tracing: None = None\
53+
""",
54+
)
55+
56+
_NARROWED_ERROR_TRACKING = _TEMPLATE.format(
57+
sections="""\
58+
class ErrorTracking:
59+
dsn: str = "https://key@example.invalid/1"
60+
environment: Literal["local", "prod"] = "local"
61+
traces_sample_rate: float = 0.1
62+
profiles_sample_rate: float = 0.0
63+
debug: bool = False
64+
""",
65+
fields="""\
66+
logging: None = None
67+
metrics: None = None
68+
error_tracking: ErrorTracking = ErrorTracking()
69+
tracing: None = None\
70+
""",
71+
)
72+
73+
_WIDE_LOGGING = _TEMPLATE.format(
74+
sections="""\
75+
class Logging:
76+
level: str = "INFO"
77+
use_json: bool = True
78+
""",
79+
fields="""\
80+
logging: Logging = Logging()
81+
metrics: None = None
82+
error_tracking: None = None
83+
tracing: None = None\
84+
""",
85+
)
86+
87+
_INCOMPLETE_LOGGING = _TEMPLATE.format(
88+
sections="""\
89+
class Logging:
90+
level: str = "INFO"
91+
""",
92+
fields="""\
93+
logging: Logging = Logging()
94+
metrics: None = None
95+
error_tracking: None = None
96+
tracing: None = None\
97+
""",
98+
)
99+
100+
101+
def _run_mypy(source: str, tmp_path: Path) -> subprocess.CompletedProcess[str]:
102+
snippet = tmp_path / "settings_snippet.py"
103+
snippet.write_text(source)
104+
105+
return subprocess.run( # noqa: S603 - fixed argv, only the snippet path varies
106+
[sys.executable, "-m", "mypy", "--config-file", str(ROOT / "pyproject.toml"), str(snippet)],
107+
cwd=ROOT,
108+
capture_output=True,
109+
text=True,
110+
check=False,
111+
)
112+
113+
114+
@pytest.mark.parametrize(
115+
"source",
116+
[
117+
pytest.param(_NARROWED_LOGGING, id="literal-log-level"),
118+
pytest.param(_NARROWED_ERROR_TRACKING, id="non-optional-dsn-and-literal-environment"),
119+
pytest.param(_WIDE_LOGGING, id="wide-str-log-level"),
120+
],
121+
)
122+
def test__settings_model__sections_declare_types_at_least_as_narrow__satisfies_the_protocol(
123+
source: str,
124+
tmp_path: Path,
125+
) -> None:
126+
# Act
127+
result = _run_mypy(source, tmp_path)
128+
129+
# Assert
130+
assert result.returncode == 0, result.stdout
131+
assert "Success:" in result.stdout, result.stdout
132+
133+
134+
def test__settings_model__section_missing_a_declared_member__fails_the_protocol(tmp_path: Path) -> None:
135+
# Act
136+
result = _run_mypy(_INCOMPLETE_LOGGING, tmp_path)
137+
138+
# Assert
139+
assert result.returncode != 0, result.stdout

0 commit comments

Comments
 (0)