Skip to content

Commit d352802

Browse files
authored
Adopt the modern-di integration kit (#9)
* docs: add adopt-integration-kit change spec Carries the design spec authored during the earlier planning session onto this branch so Task 5 can finalize it. * chore: bump modern-di floor to 2.28.0 for the integration kit * refactor: compose integrations.bind and Container's async-with in _di_middleware * refactor: compose integrations.Marker/from_di/parse_markers/resolve_markers for FromDI and inject * docs: promote the integration-kit internals into architecture/ * docs: finalize adopt-integration-kit change summary
1 parent 7e1cff1 commit d352802

7 files changed

Lines changed: 137 additions & 55 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,4 @@ dist/
1919
.python-version
2020
.venv
2121
uv.lock
22+
.superpowers/

‎architecture/container-lifecycle.md‎

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,22 @@ one type, so:
3838
`_di_middleware` (`@web.middleware`) runs for every request. It:
3939

4040
1. Detects a WebSocket upgrade with `web.WebSocketResponse().can_prepare(request).ok`
41-
(checks the handshake without starting it or raising).
42-
2. Opens a `Scope.SESSION` child for a WebSocket, else a `Scope.REQUEST` child,
43-
with `{web.Request: request}` injected as context.
44-
3. Stashes the child on the request under `_CONTAINER_REQUEST_KEY`.
45-
4. `close_async`s the child when the handler returns (for a WebSocket that is
46-
when the socket closes, since the handler owns the socket's whole lifetime).
41+
(checks the handshake without starting it or raising) and picks
42+
`aiohttp_websocket_provider` or `aiohttp_request_provider` accordingly — this
43+
probe is aiohttp's own; `modern_di.integrations.classify_connection`'s
44+
isinstance-over-tuple dispatch can't do it, since both providers bind
45+
`web.Request`.
46+
2. Derives the child's scope and context from the picked provider via
47+
`modern_di.integrations.bind(provider, request)` — `Scope.SESSION` for a
48+
WebSocket, else `Scope.REQUEST`, with `{web.Request: request}` injected as
49+
context.
50+
3. Opens the child as an `async with` block — `Container.build_child_container`
51+
returns a container that is already open, so entering it is a no-op — and
52+
stashes it on the request under `_CONTAINER_REQUEST_KEY` for the duration of
53+
the block.
54+
4. Exiting the block closes the child (`close_async`), including on the
55+
exception path — for a WebSocket that is when the socket closes, since the
56+
handler owns the socket's whole lifetime.
4757

4858
Per-message work inside a WebSocket handler opens a nested `Scope.REQUEST` child
4959
of the SESSION container (`session_container.build_child_container(scope=Scope.REQUEST)`).

‎architecture/dependency-resolution.md‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,23 @@ uses an inert marker plus a decorator (the decorator path from modern-di's
66

77
## FromDI
88

9-
`FromDI(dependency)` marks a handler parameter for injection inside an
9+
`FromDI` is `modern_di.integrations.from_di`, re-exported directly — this
10+
package does not wrap it. It marks a handler parameter for injection inside an
1011
`Annotated` hint:
1112

1213
service: typing.Annotated[Service, FromDI(Deps.service)]
1314

14-
It returns `typing.cast(T, _FromDI(dependency))`: type checkers see the resolved
15-
type `T`, while at runtime it is a frozen `_FromDI` marker the decorator detects.
16-
The argument is a provider (`AbstractProvider`) or a bare type — resolution
15+
It returns `typing.cast(T, Marker(dependency))`: type checkers see the resolved
16+
type `T`, while at runtime it is a frozen `Marker` the decorator detects. The
17+
argument is a provider (`AbstractProvider`) or a bare type — resolution
1718
handles both (`resolve_provider` vs `resolve`).
1819

1920
## @inject
2021

21-
`inject` wraps a handler. At decoration time it reads
22+
`inject` wraps a handler. At decoration time it calls
23+
`modern_di.integrations.parse_markers(func)`, which reads
2224
`typing.get_type_hints(func, include_extras=True)` and collects the parameters
23-
whose `Annotated` metadata holds a `_FromDI`. aiohttp calls a handler with just
25+
whose `Annotated` metadata holds a `Marker`. aiohttp calls a handler with just
2426
the request (`handler(request)`) and does not introspect its signature, so — unlike
2527
a CLI integration — no signature rewrite is needed.
2628

@@ -29,7 +31,8 @@ At call time the wrapper:
2931
1. Reads the per-connection child container from `request[_CONTAINER_REQUEST_KEY]`
3032
(put there by `_di_middleware`); a missing key raises a `RuntimeError` pointing
3133
at `setup_di`.
32-
2. Resolves each marked parameter.
34+
2. Resolves each marked parameter via
35+
`modern_di.integrations.resolve_markers(child_container, markers)`.
3336
3. Calls the handler with the request plus the resolved parameters by keyword.
3437

3538
The `web.Request` a provider receives as DI context is the same object aiohttp

‎architecture/glossary.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,6 @@ A `ContextProvider` exposing the connection `web.Request`: `aiohttp_request_prov
1818
(REQUEST, by type) and the reference-only `aiohttp_websocket_provider` (SESSION).
1919

2020
**FromDI marker**:
21-
The inert `Annotated` metadata (`_FromDI`) that flags a handler parameter for
22-
resolution by `@inject`.
21+
The inert `Annotated` metadata (`modern_di.integrations.Marker`) that flags a
22+
handler parameter for resolution by `@inject`.
2323
_Avoid_: Depends (that is FastAPI's mechanism).

‎modern_di_aiohttp/main.py‎

Lines changed: 15 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,12 @@
11
"""modern-di integration for aiohttp."""
22

3-
import dataclasses
4-
import enum
53
import functools
64
import typing
75

86
from aiohttp import web
9-
from modern_di import Container, Scope, providers
7+
from modern_di import Container, Scope, integrations, providers
108

119

12-
T_co = typing.TypeVar("T_co", covariant=True)
1310
T = typing.TypeVar("T")
1411

1512

@@ -61,16 +58,19 @@ async def _di_middleware(
6158
handler: typing.Callable[[web.Request], typing.Awaitable[web.StreamResponse]],
6259
) -> web.StreamResponse:
6360
# `can_prepare` never raises and does not start the handshake; it only checks
64-
# whether the request is a valid WebSocket upgrade.
65-
connection_scope: enum.IntEnum = Scope.SESSION if web.WebSocketResponse().can_prepare(request).ok else Scope.REQUEST
66-
child_container = fetch_di_container(request.app).build_child_container(
67-
context={web.Request: request}, scope=connection_scope
61+
# whether the request is a valid WebSocket upgrade. Both connection providers
62+
# bind `web.Request`, so `integrations.classify_connection`'s isinstance
63+
# dispatch can't tell them apart — this probe is what picks the provider;
64+
# `integrations.bind` only derives the scope+context once it's picked.
65+
provider = (
66+
aiohttp_websocket_provider if web.WebSocketResponse().can_prepare(request).ok else aiohttp_request_provider
6867
)
69-
request[_CONTAINER_REQUEST_KEY] = child_container
70-
try:
68+
match = integrations.bind(provider, request)
69+
async with fetch_di_container(request.app).build_child_container(
70+
scope=match.scope, context=match.context
71+
) as child_container:
72+
request[_CONTAINER_REQUEST_KEY] = child_container
7173
return await handler(request)
72-
finally:
73-
await child_container.close_async()
7474

7575

7676
def setup_di(app: web.Application, container: Container) -> Container:
@@ -82,39 +82,15 @@ def setup_di(app: web.Application, container: Container) -> Container:
8282
return container
8383

8484

85-
@dataclasses.dataclass(slots=True, frozen=True)
86-
class _FromDI(typing.Generic[T_co]):
87-
dependency: providers.AbstractProvider[T_co] | type[T_co]
88-
89-
90-
def FromDI(dependency: providers.AbstractProvider[T_co] | type[T_co]) -> T_co: # noqa: N802
91-
return typing.cast(T_co, _FromDI(dependency))
92-
93-
94-
def _parse_inject_params(func: typing.Callable[..., typing.Any]) -> dict[str, _FromDI[typing.Any]]:
95-
hints = typing.get_type_hints(func, include_extras=True)
96-
di_params: dict[str, _FromDI[typing.Any]] = {}
97-
for name, hint in hints.items():
98-
if name == "return":
99-
continue
100-
if typing.get_origin(hint) is typing.Annotated:
101-
for meta in typing.get_args(hint)[1:]:
102-
if isinstance(meta, _FromDI):
103-
di_params[name] = meta
104-
break
105-
return di_params
106-
107-
108-
def _resolve_di_params(container: Container, di_params: dict[str, _FromDI[typing.Any]]) -> dict[str, typing.Any]:
109-
return {name: container.resolve_dependency(marker.dependency) for name, marker in di_params.items()}
85+
FromDI = integrations.from_di
11086

11187

11288
def inject(func: typing.Callable[..., typing.Awaitable[T]]) -> typing.Callable[..., typing.Awaitable[T]]:
113-
di_params = _parse_inject_params(func)
89+
markers = integrations.parse_markers(func)
11490

11591
@functools.wraps(func)
11692
async def wrapper(request: web.Request) -> T:
11793
child_container = fetch_request_container(request)
118-
return await func(request, **_resolve_di_params(child_container, di_params))
94+
return await func(request, **integrations.resolve_markers(child_container, markers))
11995

12096
return wrapper
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
---
2+
summary: modern_di_aiohttp/main.py now composes modern_di.integrations (bind for scope/context derivation — the can_prepare() provider probe stays aiohttp's own — Marker/from_di/parse_markers/resolve_markers, Container's async-with) instead of hand-rolling them; no public-API or test change.
3+
---
4+
5+
# Design: Adopt the modern-di integration kit
6+
7+
## Summary
8+
9+
`modern-di` 2.28.0 shipped `modern_di.integrations` — the framework-agnostic
10+
primitives that formalize what this package's `_di_middleware` and
11+
`@inject`/`FromDI` already hand-roll. This change swaps the hand-rolled
12+
internals for kit calls. Public API and runtime behavior are unchanged; every
13+
existing test asserts on public behavior only.
14+
15+
## Motivation
16+
17+
Fourth of the 13 adapter conversions surveyed by the kit's own design — see
18+
[modern-di's decision record](https://github.com/modern-python/modern-di/blob/main/planning/decisions/2026-07-13-integration-kit-shape.md).
19+
This repo is one of the two adapters the decision record calls out by name:
20+
aiohttp's `aiohttp_request_provider` and `aiohttp_websocket_provider` both
21+
bind `web.Request` (a WebSocket is an upgraded HTTP request at middleware
22+
entry, not a distinct connection type), so `integrations.classify_connection`'s
23+
isinstance-over-tuple dispatch **cannot** distinguish them — aiohttp keeps its
24+
own `can_prepare()` handshake probe to pick the provider. What the kit *does*
25+
replace is the derivation step once the provider is known:
26+
`integrations.bind(provider, connection) -> ConnectionMatch` produces the
27+
same `{web.Request: request}` context dict and scope aiohttp already
28+
hand-writes, from whichever provider `can_prepare()` selected. This mirrors
29+
the [FromDI]/`@inject` conversion already validated in
30+
[`modern-di-starlette`](https://github.com/modern-python/modern-di-starlette/pull/8)
31+
(same non-native-DI shape: `_FromDI`, `_parse_inject_params`,
32+
`_resolve_di_params` all map onto the kit byte-for-byte).
33+
34+
## Design
35+
36+
In `modern_di_aiohttp/main.py`:
37+
38+
- Import `integrations` from `modern_di`.
39+
- `_di_middleware`: keep the `can_prepare()` probe to select
40+
`aiohttp_websocket_provider` or `aiohttp_request_provider`, then replace the
41+
hand-written scope/context with
42+
`match = integrations.bind(provider, request)`. Open the child via
43+
`async with fetch_di_container(request.app).build_child_container(scope=match.scope, context=match.context) as child_container:` —
44+
replacing the manual `try`/`finally: await child_container.close_async()`.
45+
`bind()` never returns `None` (unlike `classify_connection`), so no
46+
fallback branch is needed here.
47+
- Delete `_FromDI`; replace `FromDI`'s body with a direct assignment:
48+
`FromDI = integrations.from_di`.
49+
- Delete `_parse_inject_params`/`_resolve_di_params`; `inject` calls
50+
`integrations.parse_markers(func)` at decoration time and
51+
`integrations.resolve_markers(child_container, markers)` at call time.
52+
- Drop now-unused imports: `enum` (only used for the old
53+
`connection_scope: enum.IntEnum` annotation) and `dataclasses` and the
54+
`T_co` TypeVar (only `_FromDI` used them).
55+
56+
`__init__.py`'s re-exports are untouched — every public name keeps its exact
57+
signature and behavior. No test constructs `_FromDI` directly (unlike
58+
`modern-di-litestar`'s `_Dependency` — verified by reading all four test
59+
files), so no test-file edit is expected here.
60+
61+
## Non-goals
62+
63+
- Any change to `setup_di`, `_on_startup`/`_on_cleanup`, or connection-provider
64+
registration — none of that is part of the kit.
65+
- The `can_prepare()` handshake probe itself — this is exactly the outlier
66+
case the kit's design deliberately does not absorb (a hypothetical seam
67+
used by only one adapter); it stays aiohttp's own code.
68+
- Any test rewrite. The existing suite asserts on public behavior only
69+
(`FromDI`, `inject`, `setup_di`, `fetch_di_container`,
70+
`fetch_request_container`, the two connection providers, and the internal
71+
`_CONTAINER_REQUEST_KEY`/`_on_startup`/`_on_cleanup` names some tests import
72+
directly — none of it references `_FromDI` or the scope-derivation
73+
internals being replaced).
74+
75+
## Testing
76+
77+
- `just test-ci` — 100% line coverage, all existing tests green with zero
78+
test-file changes.
79+
- `just lint-ci` — ruff (`select=ALL`), `ty check`, `check-planning`.
80+
81+
## Risk
82+
83+
- **Version-floor bump breaks on an environment still resolving `<2.28`**
84+
(low likelihood — semver-compatible; low impact — `pyproject.toml` pins the
85+
floor explicitly).
86+
- **`bind()` derives a different context dict than the hand-written
87+
`{web.Request: request}`** (low likelihood — `bind(provider, connection)`
88+
returns `context={provider.context_type: connection}`; both
89+
`aiohttp_request_provider` and `aiohttp_websocket_provider` have
90+
`context_type=web.Request`, so the key is identical regardless of which
91+
provider `can_prepare()` selects — verified against the provider
92+
declarations before writing this spec).

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ classifiers = [
1717
"Typing :: Typed",
1818
"Topic :: Software Development :: Libraries",
1919
]
20-
dependencies = ["aiohttp>=3.9,<4", "modern-di>=2.25.0,<3"]
20+
dependencies = ["aiohttp>=3.9,<4", "modern-di>=2.28.0,<3"]
2121
version = "0"
2222

2323
[project.urls]

0 commit comments

Comments
 (0)