Skip to content

Commit 060cc65

Browse files
authored
feat: add manage_lifespan to setup_di (#78)
1 parent 8590871 commit 060cc65

5 files changed

Lines changed: 99 additions & 7 deletions

File tree

‎CONTEXT.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ uses each in FastStream's sense. The three below are this package's own.
1717

1818
**Root container**:
1919
The `Container` handed to `setup_di` and stored on the app's `ContextRepo`; `fetch_di_container`
20-
reads it back. Its lifetime tracks the app's, reopened on startup and closed after shutdown.
20+
reads it back. By default its lifetime tracks the app's, reopened on startup and closed after shutdown;
21+
with `manage_lifespan=False` the user opens and closes it instead.
2122
_Avoid_: app container, app-scoped container — accurate but unnamed; the code calls it the root
2223
container, and one of the two names has to win.
2324

‎README.md‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,11 +71,27 @@ async def handle(name: str, handler: GreetingHandler = FromDI(Dependencies.handl
7171

7272
The current `StreamMessage` is resolvable within DI via the pre-built `faststream_message_provider` context provider.
7373

74+
### Sharing a container
75+
76+
By default the app opens the container on startup and closes it after shutdown, which runs every `APP`-scoped finalizer. When the container outlives the app, or other apps share it, pass `manage_lifespan=False` and open and close it yourself:
77+
78+
```python
79+
container = Container(groups=[Dependencies])
80+
setup_di(app, container, manage_lifespan=False)
81+
82+
83+
async def main() -> None:
84+
async with container:
85+
await app.run()
86+
```
87+
88+
When several apps share one container, exactly one of them should own its lifespan, or the first app to stop closes the container for the rest.
89+
7490
## API
7591

7692
| Symbol | Description |
7793
|---|---|
78-
| `setup_di(app, container)` | Stores the container in the app context and registers startup/shutdown lifecycle hooks. On startup it reopens the container and adds the DI middleware to every broker of the app, including one added via `app.add_broker` after `setup_di` or by an `on_startup` hook registered before `setup_di`. After shutdown it closes the container. Raises `RuntimeError` at startup if the app has no broker by then. Returns the container |
94+
| `setup_di(app, container, *, manage_lifespan=True)` | Stores the container in the app context and registers startup/shutdown lifecycle hooks. On startup it reopens the container and adds the DI middleware to every broker of the app, including one added via `app.add_broker` after `setup_di` or by an `on_startup` hook registered before `setup_di`. After shutdown it closes the container. With `manage_lifespan=False` it never opens or closes the container, and the middleware still builds and closes a request container per message. Raises `RuntimeError` at startup if the app has no broker by then. Returns the container |
7995
| `FromDI(dependency, *, use_cache=True, cast=False)` | FastStream `Depends` that resolves a provider (or type) from the request container. Raises `RuntimeError` naming `setup_di` when a message reaches it without the middleware installed |
8096
| `fetch_di_container(app)` | Returns the root container from the app context |
8197
| `faststream_message_provider` | `ContextProvider` for the current `faststream.StreamMessage` (`REQUEST` scope) |

‎modern_di_faststream/main.py‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,8 @@ def fetch_di_container(app_: faststream.FastStream | AsgiFastStream) -> Containe
7070
def setup_di(
7171
app: faststream.FastStream | AsgiFastStream,
7272
container: Container,
73+
*,
74+
manage_lifespan: bool = True,
7375
) -> Container:
7476
container.add_providers(faststream_message_provider)
7577
app.context.set_global(_ROOT_CONTAINER_KEY, container)
@@ -84,13 +86,14 @@ def install_middleware() -> None:
8486
if middleware_factory not in broker.config.broker_middlewares:
8587
broker.add_middleware(middleware_factory)
8688

89+
app.on_startup(install_middleware)
8790
# FastStream's lifecycle is callback-based, so the root container can't be
8891
# wrapped in ``async with``. Reopen it on startup (before the broker consumes)
8992
# to pair with the shutdown close, so a broker restart works instead of
9093
# raising ContainerClosedError. Reopening an already-open container is a no-op.
91-
app.on_startup(container.open)
92-
app.on_startup(install_middleware)
93-
app.after_shutdown(container.close_async)
94+
if manage_lifespan:
95+
app.on_startup(container.open)
96+
app.after_shutdown(container.close_async)
9497
return container
9598

9699

‎tests/dependencies.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,14 @@ class DependentCreator:
1515
dep1: SimpleCreator
1616

1717

18+
@dataclasses.dataclass(kw_only=True, slots=True)
19+
class Finalizable:
20+
finalized: int = 0
21+
22+
def finalize(self) -> None:
23+
self.finalized += 1
24+
25+
1826
def fetch_message_is_processed_from_request(message: StreamMessage[typing.Any] | None = None) -> bool:
1927
return message.processed if message else False
2028

@@ -24,3 +32,15 @@ class Dependencies(Group):
2432
request_factory = providers.Factory(scope=Scope.REQUEST, creator=DependentCreator, bound_type=None)
2533
action_factory = providers.Factory(scope=Scope.ACTION, creator=DependentCreator, bound_type=None)
2634
message_is_processed = providers.Factory(scope=Scope.REQUEST, creator=fetch_message_is_processed_from_request)
35+
app_finalizable = providers.Factory(
36+
scope=Scope.APP,
37+
creator=Finalizable,
38+
bound_type=None,
39+
cache=providers.CacheSettings(finalizer=Finalizable.finalize),
40+
)
41+
request_finalizable = providers.Factory(
42+
scope=Scope.REQUEST,
43+
creator=Finalizable,
44+
bound_type=None,
45+
cache=providers.CacheSettings(finalizer=Finalizable.finalize),
46+
)

‎tests/test_lifespan.py‎

Lines changed: 54 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@
33
import faststream
44
from faststream import TestApp
55
from faststream.nats import NatsBroker, TestNatsBroker
6+
from modern_di import Container
67

7-
from modern_di_faststream import FromDI, fetch_di_container
8-
from tests.dependencies import Dependencies, SimpleCreator
8+
from modern_di_faststream import FromDI, fetch_di_container, setup_di
9+
from tests.dependencies import Dependencies, Finalizable, SimpleCreator
910

1011

1112
TEST_SUBJECT = "test"
@@ -43,3 +44,54 @@ async def index_subscriber(
4344
async with TestApp(app):
4445
assert not container.closed
4546
await br.publish("test", TEST_SUBJECT)
47+
48+
49+
def _unmanaged_app() -> tuple[faststream.FastStream, NatsBroker, Container, list[Finalizable]]:
50+
broker = NatsBroker()
51+
app = faststream.FastStream(broker)
52+
container = setup_di(app, Container(groups=[Dependencies]), manage_lifespan=False)
53+
request_instances: list[Finalizable] = []
54+
55+
@broker.subscriber(TEST_SUBJECT)
56+
async def index_subscriber(
57+
message: str,
58+
app_instance: typing.Annotated[Finalizable, FromDI(Dependencies.app_finalizable)],
59+
request_instance: typing.Annotated[Finalizable, FromDI(Dependencies.request_finalizable)],
60+
) -> None:
61+
assert message == "test"
62+
assert app_instance is container.resolve_provider(Dependencies.app_finalizable)
63+
request_instances.append(request_instance)
64+
65+
return app, broker, container, request_instances
66+
67+
68+
async def test_manage_lifespan_false_leaves_the_root_open_after_shutdown() -> None:
69+
app, broker, container, _ = _unmanaged_app()
70+
71+
async with TestNatsBroker(broker) as br, TestApp(app):
72+
await br.publish("test", TEST_SUBJECT)
73+
74+
assert not container.closed
75+
assert container.resolve_provider(Dependencies.app_finalizable).finalized == 0
76+
77+
78+
async def test_manage_lifespan_false_still_builds_and_closes_the_request_container() -> None:
79+
app, broker, _, request_instances = _unmanaged_app()
80+
81+
async with TestNatsBroker(broker) as br, TestApp(app):
82+
await br.publish("test", TEST_SUBJECT)
83+
84+
assert [instance.finalized for instance in request_instances] == [1]
85+
86+
87+
async def test_manage_lifespan_false_lets_the_user_own_the_root() -> None:
88+
app, broker, container, _ = _unmanaged_app()
89+
90+
async with container:
91+
async with TestNatsBroker(broker) as br, TestApp(app):
92+
await br.publish("test", TEST_SUBJECT)
93+
app_instance = container.resolve_provider(Dependencies.app_finalizable)
94+
assert app_instance.finalized == 0
95+
96+
assert container.closed
97+
assert app_instance.finalized == 1

0 commit comments

Comments
 (0)