|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from abc import abstractmethod |
| 4 | +from collections.abc import Awaitable, Callable |
| 5 | +from contextlib import nullcontext |
| 6 | +from typing import TYPE_CHECKING, Any, AsyncContextManager, Protocol, runtime_checkable |
| 7 | + |
| 8 | +if TYPE_CHECKING: |
| 9 | + from cq import CommandBus, EventBus, QueryBus |
| 10 | + |
| 11 | + |
| 12 | +@runtime_checkable |
| 13 | +class DIAdapter(Protocol): |
| 14 | + """ |
| 15 | + Protocol for integrating a dependency injection container with python-cq. |
| 16 | +
|
| 17 | + Implement this protocol to connect your DI framework to the CQ buses. |
| 18 | + A concrete implementation (``InjectionAdapter``) is provided via the |
| 19 | + ``python-cq[injection]`` extra for projects that use *python-injection*. |
| 20 | + """ |
| 21 | + |
| 22 | + __slots__ = () |
| 23 | + |
| 24 | + @abstractmethod |
| 25 | + def command_scope(self) -> AsyncContextManager[None]: |
| 26 | + """ |
| 27 | + Return an async context manager that delimits the lifetime of a |
| 28 | + command dispatch. |
| 29 | +
|
| 30 | + **Responsibilities** |
| 31 | +
|
| 32 | + The scope must at minimum manage the lifecycle of a ``RelatedEvents`` |
| 33 | + instance and register it so that it is resolvable via injection for |
| 34 | + the duration of the scope. |
| 35 | +
|
| 36 | + **Nested calls** |
| 37 | +
|
| 38 | + ``command_scope`` is entered in two distinct situations: |
| 39 | +
|
| 40 | + 1. Around a standard command dispatch (via |
| 41 | + ``CommandDispatchScopeMiddleware``). |
| 42 | + 2. Around each step of a ``ContextCommandPipeline``, which itself |
| 43 | + wraps a command dispatch. |
| 44 | +
|
| 45 | + This means two nested calls can occur for a single logical command. |
| 46 | + Implementations must detect re-entrant activation (e.g. a scope |
| 47 | + already active on the current task) and silently ignore the inner |
| 48 | + call instead of opening a second, conflicting scope. |
| 49 | + """ |
| 50 | + |
| 51 | + raise NotImplementedError |
| 52 | + |
| 53 | + @abstractmethod |
| 54 | + def lazy[T](self, tp: type[T]) -> Callable[[], Awaitable[T]]: |
| 55 | + """ |
| 56 | + Return a callable that resolves an instance of ``tp`` in two steps. |
| 57 | +
|
| 58 | + 1. ``lazy(tp)`` obtains a resolver from the DI framework for ``tp``. |
| 59 | + 2. Calling and awaiting the returned callable performs the actual |
| 60 | + resolution and returns the instance. |
| 61 | + """ |
| 62 | + |
| 63 | + raise NotImplementedError |
| 64 | + |
| 65 | + def register_defaults( |
| 66 | + self, |
| 67 | + command_bus: Callable[..., CommandBus[Any]], |
| 68 | + event_bus: Callable[..., EventBus], |
| 69 | + query_bus: Callable[..., QueryBus[Any]], |
| 70 | + ) -> None: |
| 71 | + """ |
| 72 | + Register the CQ buses as default providers in the DI container. |
| 73 | +
|
| 74 | + Called once during setup so that handlers and middlewares can |
| 75 | + declare ``CommandBus``, ``EventBus``, or ``QueryBus`` as |
| 76 | + constructor dependencies and receive the configured instances. |
| 77 | +
|
| 78 | + The default implementation is a no-op for adapters that do not |
| 79 | + need automatic bus registration. |
| 80 | + """ |
| 81 | + |
| 82 | + return |
| 83 | + |
| 84 | + @abstractmethod |
| 85 | + def wire[T](self, tp: type[T]) -> Callable[..., Awaitable[T]]: |
| 86 | + """ |
| 87 | + Return an async factory that instantiates ``tp`` with injected |
| 88 | + dependencies. |
| 89 | +
|
| 90 | + Used internally to build handler instances whose dependencies are |
| 91 | + resolved by the container. |
| 92 | + """ |
| 93 | + |
| 94 | + raise NotImplementedError |
| 95 | + |
| 96 | + |
| 97 | +class NoDI(DIAdapter): |
| 98 | + __slots__ = () |
| 99 | + |
| 100 | + def command_scope(self) -> AsyncContextManager[None]: |
| 101 | + return nullcontext() |
| 102 | + |
| 103 | + def lazy[T](self, tp: type[T], /) -> Callable[[], Awaitable[T]]: |
| 104 | + tp_str = getattr(tp, "__name__", str(tp)) |
| 105 | + raise RuntimeError( |
| 106 | + f"Can't lazily resolve {tp_str}: no DI container configured." |
| 107 | + ) |
| 108 | + |
| 109 | + def wire[T](self, tp: type[T], /) -> Callable[..., Awaitable[T]]: |
| 110 | + async def factory() -> T: |
| 111 | + return tp() |
| 112 | + |
| 113 | + return factory |
0 commit comments