Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions modern_di_faststream/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ def setup_di(

container.providers_registry.add_providers(faststream_message_provider)
app.context.set_global("di_container", container)
# FastStream's lifecycle is callback-based, so the root container can't be
# wrapped in ``async with``. Reopen it on startup (before the broker consumes)
# to pair with the shutdown close, so a broker restart works instead of
# raising ContainerClosedError. Reopening an already-open container is a no-op.
app.on_startup(container.open)
app.after_shutdown(container.close_async)
# _DIMiddlewareFactory.__call__ ParamSpec doesn't structurally match BrokerMiddleware[Any, Any].
app.broker.add_middleware(_DIMiddlewareFactory(container)) # ty: ignore[invalid-argument-type]
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ classifiers = [
"Typing :: Typed",
"Topic :: Software Development :: Libraries",
]
dependencies = ["faststream>=0.7,<0.8", "modern-di>=2.16.1,<3"]
dependencies = ["faststream>=0.7,<0.8", "modern-di>=2.19.0,<3"]
version = "0"

[project.urls]
Expand Down
36 changes: 36 additions & 0 deletions tests/test_lifespan.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import typing

import faststream
from faststream import TestApp
from faststream.nats import NatsBroker, TestNatsBroker

from modern_di_faststream import FromDI, fetch_di_container
from tests.dependencies import Dependencies, SimpleCreator


TEST_SUBJECT = "test"


async def test_startup_reopens_container_across_cycles(app: faststream.FastStream) -> None:
broker = typing.cast(NatsBroker, app.broker)
container = fetch_di_container(app)

@broker.subscriber(TEST_SUBJECT)
async def index_subscriber(
message: str,
instance: typing.Annotated[SimpleCreator, FromDI(Dependencies.app_factory)],
) -> None:
assert message == "test"
assert isinstance(instance, SimpleCreator)

async with TestNatsBroker(broker) as br:
# First lifecycle: after_shutdown closes the root container.
async with TestApp(app):
await br.publish("test", TEST_SUBJECT)
assert container.closed

# Second lifecycle: on_startup must reopen the same container, so the
# middleware can build a request child instead of raising ContainerClosedError.
async with TestApp(app):
assert not container.closed
await br.publish("test", TEST_SUBJECT)
Loading