Skip to content

Commit dc08d1f

Browse files
fix: four defects the agents page turned up (#44)
1 parent b2bd264 commit dc08d1f

10 files changed

Lines changed: 126 additions & 43 deletions

File tree

‎.github/PULL_REQUEST_TEMPLATE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
- [ ] Tests added or updated
1616
- [ ] `make check` passes locally (`ruff` + `mypy`)
17-
- [ ] `CHANGELOG.md` updated under `[Unreleased]`
17+
- [ ] `CHANGELOG.md` left alone — Release Please generates it from the Conventional Commit subjects (and from the PR title on a squash merge)
1818
- [ ] Documentation updated (if the public API changed), `docs/agents.md` included
1919

2020
## Related issues

‎docs/adapters/infrastructure.md‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -79,16 +79,20 @@ not make the pod unready on its own. Register your own check if your service dis
7979

8080
## Import paths
8181

82-
Import from the **submodule**, as shown above. The package-level convenience imports fall back to
83-
`None` when an extra is missing:
82+
Both spellings work and give you the same class:
8483

8584
```python
86-
from servicewright.adapters.warmers import KafkaProducerWarmer # None without [kafka]
87-
from servicewright.adapters.warmers.kafka import KafkaProducerWarmer # ImportError, as it should
85+
from servicewright.adapters.warmers import KafkaProducerWarmer
86+
from servicewright.adapters.warmers.kafka import KafkaProducerWarmer
8887
```
8988

90-
`servicewright.adapters.health` exports nothing at package level for the same reason — importing
91-
it never requires an extra.
89+
Neither requires the extra to be *importable*. The warmers are duck-typed on the client you pass
90+
in and soft-import their SDK, so the extra is what gives you a client to hand them, not what makes
91+
the module load. `PostgresWarmer` is the one exception: SQLAlchemy is what builds its probe query,
92+
so without `[postgres]` it raises `PostgresWarmupError` at construction.
93+
94+
`servicewright.adapters.health` exports nothing at package level; import each check from its
95+
submodule, which raises `ImportError` naming the extra at construction.
9296

9397
## Writing your own
9498

‎docs/agents.md‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,7 @@ unless a row says otherwise.
196196
| `run_sync` | `run_sync(service, settings, *, loop="auto")` | `"auto"` / `"asyncio"` / `"uvloop"` |
197197
| `event_loop_factory` | `event_loop_factory(loop="auto")` | the `loop_factory` for `asyncio.run`, or `None` |
198198
| `Host` | `Host(spec)` | `.run(settings, entrypoints=(), *, plugins=(), stop=None)`, `.add_entrypoint(ep)`, `.bootstrap(settings)` |
199+
| `install_signal_handlers` | `install_signal_handlers(stop_event)` | the installer the Host uses on the unowned path; returns an idempotent remover. Only useful when you pass `stop=` yourself — see rule 8 |
199200

200201
### Describing a service
201202

@@ -298,7 +299,9 @@ see `None`, and nothing is exported.
298299
### Adapters
299300

300301
Each subpackage needs its extra; importing one without it raises `ImportError` naming what
301-
to install.
302+
to install. `servicewright.adapters.warmers` and `.health` are the exception: they are
303+
duck-typed on the client you pass in and soft-import their SDK, so they import with no extra
304+
installed and raise (or degrade) at construction instead.
302305

303306
| Import | Public names |
304307
|---|---|
@@ -309,7 +312,7 @@ to install.
309312
| `servicewright.adapters.dishka` | `DishkaContainer`, `DishkaScope` |
310313
| `servicewright.adapters.settings` | `BaseServiceSettings`, `LoggingSettings`, `MetricsSettings`, `TracingSettings`, `ErrorTrackingSettings` |
311314
| `servicewright.adapters.observability` | ABCs `MetricsSink`, `TracingSink`, `ErrorTrackingSink`, `LoggingSink`; backends `PrometheusMetricsSink`, `OtelTracingSink`, `SentryErrorTrackingSink`, `StructlogLoggingSink`, `StdlibLoggingSink` (each imported lazily on first access) |
312-
| `servicewright.adapters.warmers` | `RedisWarmer`, `PostgresWarmer`, `KafkaProducerWarmer` — all `(client, …, timeout=10.0, priority=0, raise_on_failure=True)` |
315+
| `servicewright.adapters.warmers` | `RedisWarmer`, `PostgresWarmer`, `KafkaProducerWarmer` — all `(client, …, timeout=10.0, priority=0, raise_on_failure=True)`; the package and the submodules both export them, extra or no extra, and `PostgresWarmer` is the only one that needs its SDK (`PostgresWarmupError` at construction without it) |
313316
| `servicewright.adapters.health.postgres` / `.redis` | `PostgresHealthCheck(session_maker, timeout=5.0)`, `RedisHealthCheck(client, timeout=5.0)` — import from the submodule, not the package |
314317
| `servicewright.testing` | `FakeContainer`, `FakeScope`, `FakeSettings`, `FakeEntrypoint` |
315318

@@ -370,8 +373,9 @@ Each `*Plugin` takes exactly the same arguments as its entrypoint and exposes `.
370373
not want taking the API down.
371374
8. **Signals are installed only when you do not pass `stop`.** `await service.run(settings,
372375
stop=my_event)` installs none — that is the embedding and test path, and you own
373-
SIGINT/SIGTERM. A second signal on the owned path exits immediately with `128 + signum`,
374-
skipping every remaining cleanup step.
376+
SIGINT/SIGTERM. Call `install_signal_handlers(my_event)` yourself to get the same handlers
377+
back, and its return value to remove them. A second signal on the owned path exits
378+
immediately with `128 + signum`, skipping every remaining cleanup step.
375379
9. **Which base class you extend decides who opens the unit scope.** `ServerEntrypoint`
376380
exposes no `unit_scope` at all, because the transport adapter's middleware or interceptor
377381
opens it per request. `ScopedEntrypoint.unit_scope()` is the only sanctioned per-unit API

‎docs/concepts/lifecycle.md‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,20 @@ stop = asyncio.Event()
151151
await service.run(settings, stop=stop) # you own the signals
152152
```
153153

154-
This is the embedding path, and the one tests use.
154+
This is the embedding path, and the one tests use. If what you wanted was the runtime's own
155+
handlers on a stop event you also control, `install_signal_handlers` is the installer the Host
156+
uses, exported from the top level:
157+
158+
```python
159+
from servicewright import install_signal_handlers
160+
161+
stop = asyncio.Event()
162+
uninstall = install_signal_handlers(stop) # returns an idempotent remover
163+
try:
164+
await service.run(settings, stop=stop)
165+
finally:
166+
uninstall()
167+
```
155168

156169
## Exit codes
157170

‎docs/concepts/observability.md‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -71,11 +71,26 @@ The gates are:
7171
| tracing | `settings.tracing is not None` |
7272
| metrics | `settings.metrics is not None` |
7373

74-
!!! note "The default manager selects nothing"
74+
!!! warning "The default manager selects nothing — but `ObsConfig()` selects everything"
7575

7676
`ObservabilityManager()` with no `ObsConfig` disables everything — a bare `AppSpec` runs with
77-
zero observability side effects. `ObsConfig()` on its own, however, defaults to
78-
`prometheus` / `otel` / `sentry` / `structlog`. Pass it explicitly when you want them.
77+
zero observability side effects.
78+
79+
`ObsConfig()` on its own is the opposite: its field defaults are `prometheus` / `otel` /
80+
`sentry` / `structlog`, so a bare one selects all four. Against `BaseServiceSettings()`
81+
defaults — `logging` and `metrics` sections present, `tracing` `None`, `error_tracking`
82+
without a DSN — that makes `ObservabilityManager(ObsConfig())` a service that will not
83+
start without `servicewright[observability,metrics]`:
84+
85+
```
86+
ImportError: structlog logging requires servicewright[observability]; install it.
87+
```
88+
89+
Name the concerns you want and pass `None` for the rest:
90+
91+
```python
92+
ObsConfig(metrics="prometheus", logging="structlog", tracing=None, error_tracking=None)
93+
```
7994

8095
## How it degrades
8196

@@ -200,7 +215,7 @@ from servicewright import ChainRedactor, KeyRedactor, ObservabilityManager, Valu
200215
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+")
201216

202217
observability = ObservabilityManager(
203-
ObsConfig(),
218+
ObsConfig(logging="structlog", error_tracking="sentry", metrics=None, tracing=None),
204219
redactor=ChainRedactor(KeyRedactor(), ValueRedactor(lambda v: EMAIL.sub("<email>", v))),
205220
)
206221
```
@@ -220,7 +235,7 @@ cross-cutting `redactor` on their surface:
220235

221236
```python
222237
observability = ObservabilityManager(
223-
ObsConfig(),
238+
ObsConfig(logging="structlog", error_tracking="sentry", metrics=None, tracing=None),
224239
redactor=KeyRedactor(), # every surface: cheap, name-based
225240
error_redactor=ChainRedactor( # error path only: add the ML masker
226241
KeyRedactor(),

‎servicewright/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@
6060
current_context,
6161
event_loop_factory,
6262
get_context_value,
63+
install_signal_handlers,
6364
is_safe_context_id,
6465
mask_private_error,
6566
perform_warmup,
@@ -130,6 +131,7 @@
130131
"current_context",
131132
"event_loop_factory",
132133
"get_context_value",
134+
"install_signal_handlers",
133135
"is_safe_context_id",
134136
"mask_private_error",
135137
"perform_warmup",

‎servicewright/adapters/warmers/__init__.py‎

Lines changed: 8 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,13 @@
1-
"""Infrastructure warmers (async)."""
1+
"""Infrastructure warmers (async).
22
3-
from typing import TYPE_CHECKING
3+
Every warmer is duck-typed on the client it is handed and soft-imports its SDK,
4+
so importing this package never requires the ``kafka``, ``postgres`` or ``redis``
5+
extra and the three names are always the classes themselves.
6+
"""
47

5-
if TYPE_CHECKING:
6-
from .kafka import KafkaProducerWarmer
7-
from .postgres import PostgresWarmer
8-
from .redis import RedisWarmer
9-
else:
10-
# Optional kafka
11-
try:
12-
from .kafka import KafkaProducerWarmer
13-
except ImportError:
14-
KafkaProducerWarmer = None
15-
16-
# Optional postgres
17-
try:
18-
from .postgres import PostgresWarmer
19-
except ImportError:
20-
PostgresWarmer = None
21-
22-
# Optional redis
23-
try:
24-
from .redis import RedisWarmer
25-
except ImportError:
26-
RedisWarmer = None
8+
from .kafka import KafkaProducerWarmer as KafkaProducerWarmer
9+
from .postgres import PostgresWarmer as PostgresWarmer
10+
from .redis import RedisWarmer as RedisWarmer
2711

2812
__all__ = [
2913
"KafkaProducerWarmer",

‎servicewright/adapters/warmers/kafka.py‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,18 @@
44
import logging
55
from typing import Any
66

7-
from aiokafka.errors import KafkaError
8-
97
from ...core.contracts.warmer import AsyncWarmer
108
from ...core.exceptions import KafkaProducerWarmupError
119

10+
# Optional dependency: aiokafka, needed only to tell a broker failure from any
11+
# other one. Without it every failure takes the KafkaError branch of warmup().
12+
try:
13+
from aiokafka.errors import KafkaError as _KafkaError
14+
15+
KafkaError: Any = _KafkaError
16+
except ImportError:
17+
KafkaError = Exception
18+
1219
logger = logging.getLogger(__name__)
1320

1421
DEFAULT_WARMUP_TIMEOUT = 10.0

‎tests/unit/test_signals.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
import pytest
1212

13+
import servicewright
1314
from servicewright.core import signals as signals_mod
1415
from servicewright.core.signals import SIGNAL_EXIT_CODE_BASE, install_signal_handlers
1516

@@ -219,3 +220,16 @@ async def test__install_signal_handlers__registration_always_fails__does_not_rai
219220

220221
# Assert
221222
assert stop.is_set() is False
223+
224+
225+
def test__install_signal_handlers__imported_from_the_package_root__is_the_core_function() -> None:
226+
assert servicewright.install_signal_handlers is install_signal_handlers
227+
228+
229+
def test__servicewright__public_names_of_core__are_all_re_exported_at_the_top_level() -> None:
230+
"""`install_signal_handlers` was the one name in ``core.__all__`` the package root dropped."""
231+
# Act
232+
missing = set(servicewright.core.__all__) - set(servicewright.__all__)
233+
234+
# Assert
235+
assert missing == set()

‎tests/unit/test_warmup_engine.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,3 +422,43 @@ def test__redis_warmer_module__imported_without_redis__raises_with_the_install_h
422422
finally:
423423
# Restore
424424
importlib.reload(redis_mod)
425+
426+
427+
def test__kafka_warmer_module__imported_without_aiokafka__falls_back_to_a_bare_exception() -> None:
428+
kafka_mod = importlib.import_module("servicewright.adapters.warmers.kafka")
429+
430+
try:
431+
with patch.dict("sys.modules", {"aiokafka": None, "aiokafka.errors": None}):
432+
importlib.reload(kafka_mod)
433+
assert kafka_mod.KafkaError is Exception
434+
finally:
435+
# Restore
436+
importlib.reload(kafka_mod)
437+
438+
439+
@pytest.mark.parametrize(
440+
("name", "module_name", "absent_sdk"),
441+
[
442+
("KafkaProducerWarmer", "servicewright.adapters.warmers.kafka", ("aiokafka", "aiokafka.errors")),
443+
("PostgresWarmer", "servicewright.adapters.warmers.postgres", ("sqlalchemy",)),
444+
("RedisWarmer", "servicewright.adapters.warmers.redis", ("redis",)),
445+
],
446+
)
447+
def test__warmers_package__its_extra_is_missing__still_exports_the_warmer_class(
448+
name: str,
449+
module_name: str,
450+
absent_sdk: tuple[str, ...],
451+
) -> None:
452+
warmers_pkg = importlib.import_module("servicewright.adapters.warmers")
453+
warmer_mod = importlib.import_module(module_name)
454+
455+
try:
456+
with patch.dict("sys.modules", dict.fromkeys(absent_sdk)):
457+
importlib.reload(warmer_mod)
458+
importlib.reload(warmers_pkg)
459+
460+
assert getattr(warmers_pkg, name) is getattr(warmer_mod, name)
461+
finally:
462+
# Restore
463+
importlib.reload(warmer_mod)
464+
importlib.reload(warmers_pkg)

0 commit comments

Comments
 (0)