From fce99d5ca17876751144412b684a49cde728dc89 Mon Sep 17 00:00:00 2001 From: remimd Date: Sat, 14 Nov 2026 17:47:52 +0100 Subject: [PATCH] feat!: Move the default router to cq.default Importing cq no longer builds the default router nor registers the buses in the DI container: this only happens when cq.default is imported. The default router is exposed there as router. ContextCommandPipeline() now raises a RuntimeError instead of an AttributeError when it has no adapter and cq.default was not imported. BREAKING CHANGE: __router__, command_handler, event_handler, query_handler, new_command_bus, new_event_bus and new_query_bus are no longer exported by cq. Import them from cq.default instead, where __router__ is renamed to router. Co-Authored-By: Claude Opus 5.5 --- cq/__init__.py | 30 ------------ cq/_core/routing/command_pipeline.py | 9 +++- cq/default.py | 37 ++++++++++++++ docs/index.md | 3 +- docs/routing/configuring.md | 3 +- docs/routing/di.md | 7 +-- docs/routing/messages.md | 24 +++++---- docs/routing/multiple_commands.md | 2 +- tests/core/routing/test_command_pipeline.py | 14 ++++++ tests/test_default.py | 54 +++++++++++++++++++++ 10 files changed, 137 insertions(+), 46 deletions(-) create mode 100644 cq/default.py create mode 100644 tests/test_default.py diff --git a/cq/__init__.py b/cq/__init__.py index 0a887ab..f653ef3 100644 --- a/cq/__init__.py +++ b/cq/__init__.py @@ -50,37 +50,7 @@ "Queue", "RelatedEvents", "Router", - "__router__", - "command_handler", "dispatch_sequentially", - "event_handler", - "new_command_bus", - "new_event_bus", - "new_query_bus", - "query_handler", "resolve_handler_source", "through_middlewares", ) - - -try: - from .ext.injection import InjectionAdapter - -except ImportError: # pragma: no cover - __router__ = Router() - -else: - __router__ = Router(InjectionAdapter()) - del InjectionAdapter - -__router__.register_defaults() - -command_handler = __router__.command_handler -event_handler = __router__.event_handler -query_handler = __router__.query_handler - -new_command_bus = __router__.new_command_bus -new_event_bus = __router__.new_event_bus -new_query_bus = __router__.new_query_bus - -ContextCommandPipeline._set_default_di(__router__.di) diff --git a/cq/_core/routing/command_pipeline.py b/cq/_core/routing/command_pipeline.py index 526de4b..01d595e 100644 --- a/cq/_core/routing/command_pipeline.py +++ b/cq/_core/routing/command_pipeline.py @@ -21,7 +21,14 @@ class ContextCommandPipeline[C: Command](ContextPipeline[C]): __default_di: ClassVar[DIAdapter] def __init__(self, di: DIAdapter | None = None, /) -> None: - di = di or self.__default_di + try: + di = di or self.__default_di + except AttributeError as exc: + raise RuntimeError( + "No DI adapter: import `cq.default` to use the default router, " + "or build the pipeline with `router.command_pipeline()`." + ) from exc + super().__init__(LazyDispatcher(CommandBus, di)) self.__query_dispatcher = LazyDispatcher(QueryBus, di) diff --git a/cq/default.py b/cq/default.py new file mode 100644 index 0000000..5f1926a --- /dev/null +++ b/cq/default.py @@ -0,0 +1,37 @@ +from contextlib import suppress + +from ._core.routing.command_pipeline import ContextCommandPipeline +from ._core.routing.di import DIAdapter +from ._core.routing.router import Router + +__all__ = ( + "command_handler", + "event_handler", + "new_command_bus", + "new_event_bus", + "new_query_bus", + "query_handler", + "router", +) + + +def __detect_di_adapter() -> DIAdapter | None: + with suppress(ImportError): + from .ext.injection import InjectionAdapter + + return InjectionAdapter() + + return None # pragma: no cover + + +router = Router(__detect_di_adapter()).register_defaults() + +command_handler = router.command_handler +event_handler = router.event_handler +query_handler = router.query_handler + +new_command_bus = router.new_command_bus +new_event_bus = router.new_event_bus +new_query_bus = router.new_query_bus + +ContextCommandPipeline._set_default_di(router.di) diff --git a/docs/index.md b/docs/index.md index 4440e77..1094a82 100644 --- a/docs/index.md +++ b/docs/index.md @@ -52,7 +52,8 @@ pip install python-cq ```python import asyncio -from cq import CommandBus, command_handler +from cq import CommandBus +from cq.default import command_handler from dataclasses import dataclass from injection import inject diff --git a/docs/routing/configuring.md b/docs/routing/configuring.md index 201fcf2..f786939 100644 --- a/docs/routing/configuring.md +++ b/docs/routing/configuring.md @@ -6,7 +6,8 @@ The buses resolved by default have no listeners and no middlewares of your own. To customize one, write a factory that builds the bus with `new_command_bus()`, `new_query_bus()`, or `new_event_bus()`, configures it, and registers it in the DI container: ```python -from cq import CommandBus, new_command_bus +from cq import CommandBus +from cq.default import new_command_bus from injection import injectable diff --git a/docs/routing/di.md b/docs/routing/di.md index fb512ce..3accb0e 100644 --- a/docs/routing/di.md +++ b/docs/routing/di.md @@ -7,9 +7,9 @@ ## The `Router` class -`Router` ties the handler registries to a DI adapter. The decorators (`command_handler`, `event_handler`, `query_handler`) and bus factories (`new_command_bus`, `new_event_bus`, `new_query_bus`) exported by `cq` are bound to a default `Router` built at import time, which uses python-injection when the extra is installed. +`Router` ties the handler registries to a DI adapter. The decorators (`command_handler`, `event_handler`, `query_handler`) and bus factories (`new_command_bus`, `new_event_bus`, `new_query_bus`) exported by `cq.default` are bound to a default `Router`, which uses python-injection when the extra is installed. This router is only built, and its buses only registered in the container, when `cq.default` is imported: importing `cq` alone registers nothing. -To use your own adapter, create a `Router` with it and use its methods in place of the module-level ones: +To use your own adapter, create a `Router` with it and use its methods in place of the ones from `cq.default`, which you then never import: ```python from cq import Router @@ -145,7 +145,8 @@ class CommandScopeMiddleware: Command handlers then receive the events as their second parameter (of `handle` for a class), instead of as a constructor dependency: ```python -from cq import RelatedEvents, command_handler +from cq import RelatedEvents +from cq.default import command_handler from typing import NamedTuple diff --git a/docs/routing/messages.md b/docs/routing/messages.md index 8402dbe..1c52281 100644 --- a/docs/routing/messages.md +++ b/docs/routing/messages.md @@ -20,10 +20,10 @@ There is no base class to inherit from. `Command`, `Query`, and `Event` exported ## Handlers -A handler is either a class with an async `handle` method, or an async function. In both cases, the message is the first parameter. It is registered with one of the three decorators: `@command_handler`, `@query_handler`, or `@event_handler`. +A handler is either a class with an async `handle` method, or an async function. In both cases, the message is the first parameter. It is registered with one of the three decorators: `@command_handler`, `@query_handler`, or `@event_handler`, exported by `cq.default`. ```python -from cq import command_handler +from cq.default import command_handler @command_handler @@ -35,12 +35,17 @@ The decorator reads the annotation of the first parameter (of `handle` for a cla For a class, a new handler instance is built for every dispatch, through the configured DI adapter, so constructor dependencies are injected each time the handler runs. +!!! warning "Registration happens at import time" + `cq` exports the types and building blocks, while `cq.default` exports the ready-to-use decorators and bus factories, bound to a default router. That router, and the buses it registers in the DI container, only exist once `cq.default` has been imported. + + The same goes for handlers: a handler is registered when the module that defines it is imported. In an application split into several modules, make sure every module containing handlers is imported at startup, before the first dispatch. Otherwise, `dispatch` does not raise: it returns the `NotImplemented` sentinel (see [When no handler is registered](dispatching.md#when-no-handler-is-registered)). + ### Function handlers A handler that needs no dependency can be written as a plain async function: ```python -from cq import command_handler +from cq.default import command_handler @command_handler @@ -58,7 +63,7 @@ A command or a query accepts a single handler: registering a second one for the Defining a handler as a `NamedTuple` (or a frozen `dataclass`) gives a concise, immutable declaration of its dependencies: ```python -from cq import command_handler +from cq.default import command_handler from typing import NamedTuple @@ -90,7 +95,7 @@ The decorator only accepts a handler class or a function. Applying `@command_han A handler registered for a base class also receives every subclass of that type. This lets you write a single handler for a family of related messages: ```python -from cq import event_handler +from cq.default import event_handler from dataclasses import dataclass @@ -118,7 +123,7 @@ When several handlers match through the MRO, a command or a query goes to the mo Command handlers change the state of the system and may return a value, typically an identifier or a small result object. ```python -from cq import command_handler +from cq.default import command_handler from dataclasses import dataclass from typing import NamedTuple @@ -143,7 +148,8 @@ class CreateUserHandler(NamedTuple): A command handler can inject `RelatedEvents` to publish events as part of the command's execution: ```python -from cq import RelatedEvents, command_handler +from cq import RelatedEvents +from cq.default import command_handler @command_handler @@ -170,7 +176,7 @@ If an event handler raises, the command handler is cancelled if it is still runn Query handlers read state and must not produce side effects. ```python -from cq import query_handler +from cq.default import query_handler from dataclasses import dataclass from typing import NamedTuple @@ -193,7 +199,7 @@ class GetUserByIdHandler(NamedTuple): Event handlers react to something that has already happened. An event can have zero, one, or many handlers, which makes events the right tool for loose coupling between components. ```python -from cq import event_handler +from cq.default import event_handler from dataclasses import dataclass from typing import NamedTuple diff --git a/docs/routing/multiple_commands.md b/docs/routing/multiple_commands.md index 5f19c94..802027f 100644 --- a/docs/routing/multiple_commands.md +++ b/docs/routing/multiple_commands.md @@ -71,7 +71,7 @@ class PaymentContext: Annotate the pipeline with `ClassVar`: if the context is a dataclass, a plain annotation would turn the pipeline into a field. -The pipeline resolves `CommandBus` and `QueryBus` from the DI container each time it dispatches a message, not when it is created, so the buses you configure in your container are the ones it uses. With a bus factory registered as `@injectable`, each message is therefore dispatched by a new bus. If you manage your own `Router` (see [Custom DI adapter](di.md)), build the pipeline with `router.command_pipeline()` instead. +The pipeline resolves `CommandBus` and `QueryBus` from the DI container each time it dispatches a message, not when it is created, so the buses you configure in your container are the ones it uses. With a bus factory registered as `@injectable`, each message is therefore dispatched by a new bus. `ContextCommandPipeline()` resolves them through the router of `cq.default`, so that module must be imported before the pipeline is created. If you manage your own `Router` (see [Custom DI adapter](di.md)), build the pipeline with `router.command_pipeline()` instead. ### Steps diff --git a/tests/core/routing/test_command_pipeline.py b/tests/core/routing/test_command_pipeline.py index ab7b186..6a08258 100644 --- a/tests/core/routing/test_command_pipeline.py +++ b/tests/core/routing/test_command_pipeline.py @@ -1,3 +1,5 @@ +import pytest + from cq import ContextCommandPipeline, Router @@ -80,3 +82,15 @@ class Context: await Context.pipeline.dispatch(_CreateCommand()) assert queries == [query] + + def test_init_without_adapter_nor_default_router_raises_runtime_error( + self, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + monkeypatch.delattr( + ContextCommandPipeline, + "_ContextCommandPipeline__default_di", + ) + + with pytest.raises(RuntimeError, match=r"cq\.default"): + ContextCommandPipeline() diff --git a/tests/test_default.py b/tests/test_default.py new file mode 100644 index 0000000..be50bc6 --- /dev/null +++ b/tests/test_default.py @@ -0,0 +1,54 @@ +from typing import ClassVar + +from injection import mod + +from cq import AnyCommandBus, Bus, ContextCommandPipeline +from cq.default import command_handler, new_command_bus + + +class _CreateCommand: ... + + +class _PublishCommand: ... + + +class _Published: ... + + +def test_import_with_injection_registers_buses_in_default_module() -> None: + assert isinstance(mod().find_instance(AnyCommandBus), Bus) + + +async def test_new_command_bus_with_command_handler_returns_bus_dispatching_to_handler() -> ( + None +): + @command_handler + async def handler(command: _CreateCommand) -> str: + return "command handled" + + bus = new_command_bus() + + assert await bus.dispatch(_CreateCommand()) == "command handled" + + +async def test_context_command_pipeline_without_adapter_dispatches_through_default_router() -> ( + None +): + @command_handler + async def handler(command: _PublishCommand) -> _Published: + return _Published() + + class Context: + published: _Published + + pipeline: ClassVar[ContextCommandPipeline[_PublishCommand]] = ( + ContextCommandPipeline() + ) + + @pipeline.step + def _(self, published: _Published) -> None: + self.published = published + + context = await Context.pipeline(_PublishCommand()) + + assert isinstance(context.published, _Published)