diff --git a/docs/integrations/injection.md b/docs/integrations/injection.md index afa3c82..d09dab3 100644 --- a/docs/integrations/injection.md +++ b/docs/integrations/injection.md @@ -63,7 +63,7 @@ async def related_events_factory( ## Custom module -To register everything in another python-injection module than the default one, build a `Router` with your own `InjectionAdapter`, as described in [Custom DI adapter](../routing/di.md#the-router-class): +To register everything in another python-injection module than the default one, build a `Router` with your own `InjectionAdapter`, as described in [Creating your own router](../routing/router.md#creating-your-own-router): ```python from cq import Router diff --git a/docs/routing/di.md b/docs/routing/di.md index 3accb0e..a4efe67 100644 --- a/docs/routing/di.md +++ b/docs/routing/di.md @@ -5,38 +5,9 @@ **python-cq** does not depend on a specific dependency injection container. It talks to DI through the `DIAdapter` protocol: implement it once and the library works with the container you already use. -## The `Router` class +## Using your adapter -`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 ones from `cq.default`, which you then never import: - -```python -from cq import Router - -router = Router(MyDIAdapter()).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 -``` - -`register_defaults()` hands the bus factories to the adapter so that `CommandBus`, `EventBus`, and `QueryBus` can be resolved from the container. Call it once per router. - -A router also lists the message types its handlers are registered for, through `command_types`, `event_types`, and `query_types`. - -Pipelines follow the same rule. Build them from your router so they resolve the buses through your adapter: - -```python -class PaymentContext: - pipeline: ClassVar[ContextCommandPipeline[ValidateCartCommand]] = ( - router.command_pipeline() - ) -``` +An adapter is used by passing it to a `Router`, whose decorators and bus factories then replace the ones of `cq.default`. See [Creating your own router](router.md#creating-your-own-router). ## Implementing a `DIAdapter` @@ -97,6 +68,8 @@ class MyDIAdapter(DIAdapter): router = Router(MyDIAdapter()).register_defaults() ``` +The reference implementation for python-injection lives in `cq.ext.injection.InjectionAdapter`. It is a good starting point to model your own adapter on a working example. + ### The command scope `AnyIORelatedEvents` is the ready-made `RelatedEvents` implementation. It is an async context manager that takes the function used to emit each event, usually an `EventBus`, and waits for every scheduled event on exit. A command scope typically opens one per dispatch and exposes it to the container: @@ -161,9 +134,3 @@ class CreateUserHandler(NamedTuple): ``` The middlewares you add to the bus are not affected: they sit outside the command scope (see [Execution order](middlewares.md#execution-order)) and only receive the command. - -## Without an adapter - -`Router()` without argument uses a minimal adapter: handler classes are instantiated with no arguments, there is no command scope, and anything that needs to resolve a bus lazily (such as a pipeline) raises a `RuntimeError` as soon as it is created. This is also what the default router uses when the `[injection]` extra is not installed. - -The reference implementation for python-injection lives in `cq.ext.injection.InjectionAdapter`. It is a good starting point to model your own adapter on a working example. diff --git a/docs/routing/messages.md b/docs/routing/messages.md index 1c52281..73637ed 100644 --- a/docs/routing/messages.md +++ b/docs/routing/messages.md @@ -36,7 +36,7 @@ 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. + `cq` exports the types and building blocks, while `cq.default` exports the ready-to-use decorators and bus factories, bound to a default [router](router.md). 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)). diff --git a/docs/routing/multiple_commands.md b/docs/routing/multiple_commands.md index 802027f..178ed16 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. `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. +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 [Creating your own router](router.md#creating-your-own-router)), build the pipeline with `router.command_pipeline()` instead. ### Steps diff --git a/docs/routing/router.md b/docs/routing/router.md new file mode 100644 index 0000000..d20a827 --- /dev/null +++ b/docs/routing/router.md @@ -0,0 +1,79 @@ +# The router + +`Router` is the object that connects everything in the routing part of the library. Handlers are registered on a router, buses are built by a router, and a router is what links both to your DI container. + +## What a router holds + +A router owns two things: + +* **three handler registries**, one per message type. The command and query registries accept a single handler per message type, the event registry accepts any number; +* **a DI adapter**, used to instantiate handler classes, to open the command scope, and to register the buses in the container. + +Everything else is derived from these two: + +| Member | Role | +|----------------------------------------------------|--------------------------------------------------------------------------------| +| `command_handler`, `event_handler`, `query_handler` | Decorators that register a handler in the matching registry | +| `new_command_bus`, `new_event_bus`, `new_query_bus` | Factories that build a new bus reading from the matching registry | +| `command_pipeline()` | Builds a `ContextCommandPipeline` that resolves the buses through the adapter | +| `register_defaults()` | Registers the three bus factories in the DI container | +| `command_types`, `event_types`, `query_types` | The message types that have at least one registered handler | +| `di` | The DI adapter of the router | + +A bus only knows the handlers of the router that built it. A handler registered with the decorator of one router is never reached by a bus built by another. + +There are two ways to get a router: + +* **the default router** of `cq.default`, ready to use, built on python-injection. Nothing to set up; +* **your own router**, built with the adapter you choose. Everything is explicit: you decide which container the handlers and buses live in, and nothing is registered by importing a module of the library. + +## The default router + +`cq.default` builds a router when it is imported, and exports its members as module-level names: + +```python +from cq.default import command_handler, new_command_bus, router +``` + +`command_handler` is `router.command_handler`, `new_command_bus` is `router.new_command_bus`, and so on. This is why the guides import the decorators and bus factories from `cq.default`. + +When it is built, the default router: + +1. picks `cq.ext.injection.InjectionAdapter` as its DI adapter if the `[injection]` extra is installed, or a minimal adapter otherwise (see [Without an adapter](#without-an-adapter)); +2. calls `register_defaults()`, so that `CommandBus`, `EventBus`, and `QueryBus` can be resolved from the container; +3. becomes the router used by `ContextCommandPipeline()` when no adapter is given. + +None of this happens when importing `cq` alone. `cq` only exports types and building blocks, so the default router, and the buses it registers, only exist once `cq.default` has been imported. + +## Creating your own router + +Your own router gives you control over where things are registered. Its handlers and buses are isolated from the default router and from its container: they live in the adapter you pass, which can be an `InjectionAdapter` bound to a python-injection module of your own (see [python-injection](../integrations/injection.md#custom-module)) or an adapter for another container (see [Custom DI adapter](di.md)). + +Build it with the adapter, call `register_defaults()` once, and use its members everywhere the guides use the ones of `cq.default`, which you then never import: + +```python +from cq import Router + +router = Router(MyDIAdapter()).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 +``` + +Pipelines follow the same rule. Build them from your router so they resolve the buses through your adapter, since `ContextCommandPipeline()` without argument relies on `cq.default`: + +```python +class PaymentContext: + pipeline: ClassVar[ContextCommandPipeline[ValidateCartCommand]] = ( + router.command_pipeline() + ) +``` + +## Without an adapter + +`Router()` without argument uses a minimal adapter: handler classes are instantiated with no arguments, there is no command scope, and anything that needs to resolve a bus lazily (such as a pipeline) raises a `RuntimeError` as soon as it is created. This is also what the default router uses when the `[injection]` extra is not installed. diff --git a/mkdocs.yml b/mkdocs.yml index eb91c75..3b3f00b 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -19,6 +19,7 @@ nav: - Home: index.md - Routing: - Messages and handlers: routing/messages.md + - The router: routing/router.md - Dispatching messages: routing/dispatching.md - Configuring a bus: routing/configuring.md - Middlewares: routing/middlewares.md