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
30 changes: 0 additions & 30 deletions cq/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
9 changes: 8 additions & 1 deletion cq/_core/routing/command_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
37 changes: 37 additions & 0 deletions cq/default.py
Original file line number Diff line number Diff line change
@@ -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)
3 changes: 2 additions & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 2 additions & 1 deletion docs/routing/configuring.md
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
7 changes: 4 additions & 3 deletions docs/routing/di.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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


Expand Down
24 changes: 15 additions & 9 deletions docs/routing/messages.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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


Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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

Expand All @@ -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
Expand All @@ -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

Expand All @@ -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

Expand Down
2 changes: 1 addition & 1 deletion docs/routing/multiple_commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
14 changes: 14 additions & 0 deletions tests/core/routing/test_command_pipeline.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import pytest

from cq import ContextCommandPipeline, Router


Expand Down Expand Up @@ -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()
54 changes: 54 additions & 0 deletions tests/test_default.py
Original file line number Diff line number Diff line change
@@ -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)
Loading