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
4 changes: 2 additions & 2 deletions cq/_core/routing/command_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ def __init__(self, di: DIAdapter | None = None, /) -> None:
"or build the pipeline with `router.command_pipeline()`."
) from exc

super().__init__(LazyDispatcher(CommandBus, di))
self.__query_dispatcher = LazyDispatcher(QueryBus, di)
super().__init__(LazyDispatcher(CommandBus, di)) # type: ignore[arg-type]
self.__query_dispatcher = LazyDispatcher(QueryBus, di) # type: ignore[arg-type]

def add_static_query_step[Q: Query](self, query: Q, /) -> Self:
return self.add_static_step(query, dispatcher=self.__query_dispatcher)
Expand Down
22 changes: 12 additions & 10 deletions cq/_core/routing/di.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
from collections.abc import Awaitable, Callable
from typing import TYPE_CHECKING, Any, Concatenate, Protocol, runtime_checkable

from typing_extensions import TypeForm

if TYPE_CHECKING: # pragma: no cover
from cq import Command, CommandBus, EventBus, Middleware, QueryBus

Expand Down Expand Up @@ -38,11 +40,11 @@ def command_scope(self) -> Middleware[Concatenate[Command, ...], Any] | None:
return None

@abstractmethod
def lazy[T](self, tp: type[T]) -> Callable[[], Awaitable[T]]:
def lazy[T](self, type_: TypeForm[T]) -> Callable[[], Awaitable[T]]:
"""
Return a callable that resolves an instance of ``tp`` in two steps.
Return a callable that resolves an instance of ``type_`` in two steps.

1. ``lazy(tp)`` obtains a resolver from the DI framework for ``tp``.
1. ``lazy(type_)`` obtains a resolver from the DI framework for ``type_``.
2. Calling and awaiting the returned callable performs the actual
resolution and returns the instance.
"""
Expand All @@ -69,9 +71,9 @@ def register_defaults(
return

@abstractmethod
def wire[T](self, tp: type[T]) -> Callable[..., Awaitable[T]]:
def wire[T](self, type_: type[T]) -> Callable[..., Awaitable[T]]:
"""
Return an async factory that instantiates ``tp`` with injected
Return an async factory that instantiates ``type_`` with injected
dependencies.

Used internally to build handler instances whose dependencies are
Expand All @@ -84,14 +86,14 @@ def wire[T](self, tp: type[T]) -> Callable[..., Awaitable[T]]:
class NoDI(DIAdapter):
__slots__ = ()

def lazy[T](self, tp: type[T], /) -> Callable[[], Awaitable[T]]:
tp_str = getattr(tp, "__name__", str(tp))
def lazy[T](self, type_: TypeForm[T], /) -> Callable[[], Awaitable[T]]:
type_str = getattr(type_, "__name__", str(type_))
raise RuntimeError(
f"Can't lazily resolve {tp_str}: no DI container configured."
f"Can't lazily resolve {type_str}: no DI container configured."
)

def wire[T](self, tp: type[T], /) -> Callable[..., Awaitable[T]]:
def wire[T](self, type_: type[T], /) -> Callable[..., Awaitable[T]]:
async def factory() -> T:
return tp()
return type_()

return factory
11 changes: 3 additions & 8 deletions cq/_core/routing/dispatchers/bus.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import sys
from abc import ABC, abstractmethod
from collections.abc import Awaitable, Callable, Iterator
from typing import Any, Concatenate, Protocol, Self, runtime_checkable

import anyio
from anyio.abc import TaskGroup
from typing_extensions import TypeForm, deprecated

from cq._core.middleware import Middleware
from cq._core.routing.dispatchers.abc import BaseDispatcher, Dispatcher
Expand All @@ -15,11 +15,6 @@
SingleHandlerRegistry,
)

if sys.version_info >= (3, 13): # pragma: no cover
from warnings import deprecated
else: # pragma: no cover
from typing_extensions import deprecated

type Listener[T] = Callable[[T], Awaitable[Any]]


Expand All @@ -43,7 +38,7 @@ def add_middlewares(self, *middlewares: Middleware[Concatenate[I, ...], O]) -> S
@abstractmethod
def subscribe(
self,
message_type: type[I],
message_type: TypeForm[I],
function: Callable[Concatenate[I, ...], Awaitable[O]],
fail_silently: bool = ...,
) -> Self:
Expand All @@ -67,7 +62,7 @@ def add_listeners(self, *listeners: Listener[I]) -> Self:

def subscribe(
self,
message_type: type[I],
message_type: TypeForm[I],
function: Callable[Concatenate[I, ...], Awaitable[O]],
fail_silently: bool = False,
) -> Self:
Expand Down
8 changes: 4 additions & 4 deletions cq/_core/routing/dispatchers/lazy.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from collections.abc import Awaitable, Callable
from types import GenericAlias
from typing import TypeAliasType

from typing_extensions import TypeForm

from cq._core.routing.di import DIAdapter
from cq._core.routing.dispatchers.abc import Dispatcher
Expand All @@ -13,11 +13,11 @@ class LazyDispatcher[I, O](Dispatcher[I, O]):

def __init__(
self,
dispatcher_type: type[Dispatcher[I, O]] | TypeAliasType | GenericAlias,
dispatcher_type: TypeForm[Dispatcher[I, O]],
/,
di: DIAdapter,
) -> None:
self.__resolve = di.lazy(dispatcher_type) # type: ignore[arg-type]
self.__resolve = di.lazy(dispatcher_type)

async def dispatch(self, message: I, /) -> O:
dispatcher = await self.__resolve()
Expand Down
29 changes: 21 additions & 8 deletions cq/_core/routing/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
)

from type_analyzer import MatchingTypesConfig, iter_matching_types, matching_types
from typing_extensions import TypeForm

from cq._core.common.typing import Decorator
from cq._core.routing.di import DIAdapter, NoDI
Expand Down Expand Up @@ -92,7 +93,7 @@ def handlers_from(
@abstractmethod
def subscribe(
self,
message_type: type[I],
message_type: TypeForm[I],
entry: HandlerEntry[Concatenate[I, ...], O],
) -> Self:
raise NotImplementedError
Expand All @@ -118,7 +119,7 @@ def handlers_from(

def subscribe(
self,
message_type: type[I],
message_type: TypeForm[I],
entry: HandlerEntry[Concatenate[I, ...], O],
) -> Self:
for key_type in _build_key_types(message_type):
Expand Down Expand Up @@ -149,7 +150,7 @@ def handlers_from(

def subscribe(
self,
message_type: type[I],
message_type: TypeForm[I],
entry: HandlerEntry[Concatenate[I, ...], O],
) -> Self:
entries = {key_type: entry for key_type in _build_key_types(message_type)}
Expand All @@ -171,10 +172,19 @@ class HandlerDecorator[I, O]:

if TYPE_CHECKING: # pragma: no cover

@overload
def __call__[T: HandlerType[..., Any]]( # type: ignore[overload-overlap]
self,
handler: T,
/,
*,
fail_silently: bool = ...,
) -> T: ...

@overload
def __call__(
self,
message_type: type[I],
message_type: TypeForm[I],
/,
*,
fail_silently: bool = ...,
Expand All @@ -200,7 +210,10 @@ def __call__(

def __call__[T](
self,
message_or_handler: type[I] | T | None = None,
message_or_handler: HandlerType[Concatenate[I, ...], O]
| TypeForm[I]
| T
| None = None,
/,
*,
fail_silently: bool = False,
Expand All @@ -219,7 +232,7 @@ def __decorator[T](
wrapped: T,
/,
*,
message_type: type[I] | None,
message_type: TypeForm[I] | None,
fail_silently: bool,
) -> T:
if not self.__try_subscribe(wrapped, message_type, fail_silently):
Expand All @@ -230,7 +243,7 @@ def __decorator[T](
def __try_subscribe(
self,
handler: Any,
message_type: type[I] | None,
message_type: TypeForm[I] | None,
fail_silently: bool,
) -> bool:
if isfunction(handler):
Expand Down Expand Up @@ -266,7 +279,7 @@ def _iter_key_types(message_type: Any) -> Iterator[Any]:

def _resolve_message_type[I, O](
handler: Callable[Concatenate[I, ...], Awaitable[O]],
) -> type[I]:
) -> TypeForm[I]:
signature = inspect_signature(handler, eval_str=True)

for parameter in signature.parameters.values():
Expand Down
13 changes: 7 additions & 6 deletions cq/ext/injection.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from injection import Module, adefine_scope, mod
from injection.exceptions import ScopeAlreadyDefinedError
from typing_extensions import TypeForm

from cq import (
AnyIORelatedEvents,
Expand Down Expand Up @@ -37,8 +38,8 @@ def command_scope(self) -> Middleware[Concatenate[Command, ...], Any]:
threadsafe=self.threadsafe,
)

def lazy[T](self, tp: type[T], /) -> Callable[[], Awaitable[T]]:
awaitable = self.module.aget_lazy_instance(tp, threadsafe=self.threadsafe)
def lazy[T](self, type_: TypeForm[T], /) -> Callable[[], Awaitable[T]]:
awaitable = self.module.aget_lazy_instance(type_, threadsafe=self.threadsafe)
return lambda: awaitable

def register_defaults(
Expand All @@ -47,7 +48,7 @@ def register_defaults(
event_bus: Callable[..., EventBus],
query_bus: Callable[..., QueryBus[Any]],
) -> None:
self.module.injectable(
self.module.injectable( # type: ignore[call-overload]
command_bus,
ignore_type_hint=True,
inject=False,
Expand All @@ -61,7 +62,7 @@ def register_defaults(
on=EventBus,
mode="fallback",
)
self.module.injectable(
self.module.injectable( # type: ignore[call-overload]
query_bus,
ignore_type_hint=True,
inject=False,
Expand All @@ -73,8 +74,8 @@ def register_defaults(
mode="fallback",
)(self.__new_related_events)

def wire[T](self, tp: type[T], /) -> Callable[..., Awaitable[T]]:
return self.module.make_async_factory(tp, self.threadsafe)
def wire[T](self, type_: type[T], /) -> Callable[..., Awaitable[T]]:
return self.module.make_async_factory(type_, self.threadsafe)

@staticmethod
async def __new_related_events(event_bus: EventBus) -> AsyncIterator[RelatedEvents]:
Expand Down
10 changes: 6 additions & 4 deletions docs/routing/di.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ from collections.abc import Awaitable, Callable
from cq import Command, CommandBus, DIAdapter, EventBus, Middleware, QueryBus, Router
from typing import Any, Concatenate

from typing_extensions import TypeForm


class MyDIAdapter(DIAdapter):
def command_scope(self) -> Middleware[Concatenate[Command, ...], Any] | None:
Expand All @@ -33,9 +35,9 @@ class MyDIAdapter(DIAdapter):
"""
...

def lazy[T](self, tp: type[T]) -> Callable[[], Awaitable[T]]:
def lazy[T](self, type_: TypeForm[T]) -> Callable[[], Awaitable[T]]:
"""
Return a callable that, when called and awaited, resolves `tp` from
Return a callable that, when called and awaited, resolves `type_` from
the container. Pipelines call the returned callable on every
message they dispatch, so that buses registered later in the import
graph are picked up.
Expand All @@ -56,9 +58,9 @@ class MyDIAdapter(DIAdapter):
"""
...

def wire[T](self, tp: type[T]) -> Callable[..., Awaitable[T]]:
def wire[T](self, type_: type[T]) -> Callable[..., Awaitable[T]]:
"""
Return an async factory that instantiates `tp` with its dependencies
Return an async factory that instantiates `type_` with its dependencies
injected. Called once per handler class at registration, and the factory
is awaited on every dispatch.
"""
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ classifiers = [
dependencies = [
"anyio",
"type-analyzer",
"typing-extensions; python_version < '3.13'",
"typing-extensions",
]

[project.optional-dependencies]
Expand Down
2 changes: 1 addition & 1 deletion tests/_core/routing/dispatchers/test_lazy.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class Handler:
async def handle(self, query: _Query) -> str:
return "query handled"

dispatcher = LazyDispatcher[_Query, Any](QueryBus, router.di)
dispatcher = LazyDispatcher[_Query, Any](QueryBus, router.di) # type: ignore[arg-type]
router.register_defaults()

assert await dispatcher.dispatch(_Query()) == "query handled"
6 changes: 3 additions & 3 deletions tests/_core/routing/test_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def test_handlers_from_with_unknown_message_type_returns_nothing(self) -> None:
def test_message_types_with_success_returns_subscribed_types(self) -> None:
registry = MultipleHandlerRegistry[Any, str]()
registry.subscribe(
_Message | _OtherMessage, # type: ignore[arg-type]
_Message | _OtherMessage,
HandlerEntry.from_function(_handle),
)

Expand Down Expand Up @@ -162,7 +162,7 @@ def test_subscribe_with_union_containing_subscribed_type_raises_runtime_error(
entry = HandlerEntry.from_function(_other_handle)

with pytest.raises(RuntimeError):
registry.subscribe(_OtherMessage | _Message, entry) # type: ignore[arg-type]
registry.subscribe(_OtherMessage | _Message, entry)

assert set(registry.message_types) == {_Message}

Expand All @@ -183,7 +183,7 @@ def test_handlers_from_with_unknown_message_type_returns_nothing(self) -> None:
def test_message_types_with_success_returns_subscribed_types(self) -> None:
registry = SingleHandlerRegistry[Any, str]()
registry.subscribe(
_Message | _OtherMessage, # type: ignore[arg-type]
_Message | _OtherMessage,
HandlerEntry.from_function(_handle),
)

Expand Down
2 changes: 1 addition & 1 deletion tests/ext/test_injection.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def test_register_defaults_with_success_registers_buses(
router.register_defaults()

for bus_type in (AnyCommandBus, EventBus, QueryBus[Any]):
assert isinstance(injection_module.find_instance(bus_type), Bus)
assert isinstance(injection_module.find_instance(bus_type), Bus) # type: ignore[arg-type]

async def test_command_scope_with_success_provides_related_events_to_command_handlers(
self,
Expand Down
Loading
Loading