diff --git a/README.md b/README.md index f281abf..4ae5de9 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,51 @@ class MyNexusServiceHandler: return MyOutput(message=f"Hello {input.name}!") ``` +### Implementing and registering a dynamic Operation handler + +A dynamic Operation handler handles requests whose operation name is not registered with a service handler. Named Operations take precedence. A service handler can have one dynamic handler, with or without named Operations. + +The handler receives the requested operation name through `ctx.operation` and raw input as +`nexusrpc.LazyValue`. Decode the input with `await input.consume(as_type=...)`. Do not use the input after the handler returns. The handler can be sync or async. + +```python +from typing import Any + +import nexusrpc.handler + + +class MyDynamicOperation(nexusrpc.handler.OperationHandler[nexusrpc.LazyValue, Any]): + # Dynamic handler that simply echoes the input back synchronously. + async def start( + self, ctx: nexusrpc.handler.StartOperationContext, input: nexusrpc.LazyValue + ) -> nexusrpc.handler.StartOperationResultSync[Any]: + value = await input.consume(as_type=str) + return nexusrpc.handler.StartOperationResultSync(value) + + async def cancel( + self, ctx: nexusrpc.handler.CancelOperationContext, token: str + ) -> None: + raise NotImplementedError("An operation that responded synchronously cannot be cancelled.") +``` + +Register the handler with `@nexusrpc.handler.operation_handler(dynamic=True)` on your Nexus service handler. Each service can have maximum 1 dynamic handler. The registration will error if: + +* A name is provided for the dynamic handler +* A dynamic handler is already defined on this service handler + +```python +@nexusrpc.handler.service_handler(name="example-service") +class MyDynamicServiceHandler: + @nexusrpc.handler.operation_handler(dynamic=True) + def forward(self) -> nexusrpc.handler.OperationHandler[nexusrpc.LazyValue, Any]: + return MyDynamicOperation() + + +handler = nexusrpc.handler.Handler([MyDynamicServiceHandler()]) +``` + +Middleware applies to dynamic handlers as it does to named Operations and receives the undecoded `nexusrpc.LazyValue` on start. + --- _Versions 1.0.1 and earlier of the `nexus-rpc` package on PyPI belong to an unrelated diff --git a/src/nexusrpc/_util.py b/src/nexusrpc/_util.py index 7e89137..ae68869 100644 --- a/src/nexusrpc/_util.py +++ b/src/nexusrpc/_util.py @@ -11,13 +11,14 @@ if TYPE_CHECKING: import nexusrpc - from nexusrpc import InputT, OutputT + from nexusrpc import InputT, LazyValueT, OutputT from nexusrpc._common import ServiceT from nexusrpc.handler._operation_handler import OperationHandler _NEXUS_SERVICE_DEFINITION_ATTR_NAME = "__nexus_service_definition__" _NEXUS_OPERATION_ATTR_NAME = "__nexus_operation__" _NEXUS_OPERATION_FACTORY_ATTR_NAME = "__nexus_operation_factory__" +_NEXUS_DYNAMIC_OPERATION_FACTORY_ATTR_NAME = "__nexus_dynamic_operation_factory__" def get_service_definition( @@ -82,7 +83,7 @@ def get_operation_factory( if factory := getattr(obj, _NEXUS_OPERATION_FACTORY_ATTR_NAME, None): # obj was a decorated operation start method return factory - if get_operation(obj): + if get_operation(obj) or is_dynamic_operation_factory(obj): # obj was the desired factory return obj return None @@ -99,6 +100,18 @@ def set_operation_factory( setattr(obj, _NEXUS_OPERATION_FACTORY_ATTR_NAME, operation_factory) +def is_dynamic_operation_factory(obj: Any) -> bool: + """Return whether the operation handler factory is the dynamic fallback.""" + return bool(getattr(obj, _NEXUS_DYNAMIC_OPERATION_FACTORY_ATTR_NAME, False)) + + +def set_dynamic_operation_factory( + operation_factory: Callable[[Any], OperationHandler[LazyValueT, Any]], +) -> None: + """Mark an operation handler factory as the dynamic fallback.""" + setattr(operation_factory, _NEXUS_DYNAMIC_OPERATION_FACTORY_ATTR_NAME, True) + + # Copied from https://github.com/modelcontextprotocol/python-sdk # # Copyright (c) 2024 Anthropic, PBC. diff --git a/src/nexusrpc/handler/_core.py b/src/nexusrpc/handler/_core.py index 68c832b..10d7e1f 100644 --- a/src/nexusrpc/handler/_core.py +++ b/src/nexusrpc/handler/_core.py @@ -121,7 +121,7 @@ from ._operation_handler import ( MiddlewareSafeOperationHandler, OperationHandler, - collect_operation_handler_factories_by_method_name, + collect_operation_handler_factories, ) @@ -285,8 +285,12 @@ async def start_operation( service_handler = self._get_service_handler(ctx.service) op_handler = self._get_operation_handler(ctx, service_handler, ctx.operation) - op_defn = service_handler.service.operation_definitions[ctx.operation] - deserialized_input = await input.consume(as_type=op_defn.input_type) + op_defn = service_handler.service.operation_definitions.get(ctx.operation) + deserialized_input = ( + input + if op_defn is None + else await input.consume(as_type=op_defn.input_type) + ) return await op_handler.start(ctx, deserialized_input) async def cancel_operation(self, ctx: CancelOperationContext, token: str) -> None: @@ -317,7 +321,10 @@ def _get_operation_handler( def _validate_all_operation_handlers_are_async(self) -> None: for service_handler in self.service_handlers.values(): - for op_handler in service_handler.operation_handlers.values(): + handlers = list(service_handler.operation_handlers.values()) + if service_handler.dynamic_handler is not None: + handlers.append(service_handler.dynamic_handler) + for op_handler in handlers: _ = self._assert_async_callable(op_handler.start) _ = self._assert_async_callable(op_handler.cancel) @@ -353,6 +360,8 @@ class ServiceHandler: service: ServiceDefinition operation_handlers: dict[str, OperationHandler[Any, Any]] + dynamic_handler: Optional[OperationHandler[LazyValueT, Any]] = None + """The handler for operation names with no named handler, if configured.""" @classmethod def from_user_instance(cls, user_instance: Any) -> Self: @@ -368,21 +377,28 @@ def from_user_instance(cls, user_instance: Any) -> Self: # Construct a map of operation handlers keyed by the op name from the service # definition (i.e. by the name by which the operation can be requested) - factories_by_method_name = collect_operation_handler_factories_by_method_name( + factories_by_method_name, dynamic_factory = collect_operation_handler_factories( user_instance.__class__, service ) op_handlers = { name: factories_by_method_name[defn.method_name](user_instance) for name, defn in service.operation_definitions.items() } + dynamic_handler = None + if dynamic_factory is not None: + dynamic_handler = dynamic_factory(user_instance) + return cls( service=service, operation_handlers=op_handlers, + dynamic_handler=dynamic_handler, ) def get_operation_handler(self, operation_name: str) -> OperationHandler[Any, Any]: - """Return an operation handler, given the operation name.""" + """Return a named handler, or the dynamic handler for an unknown name.""" if operation_name not in self.service.operation_definitions: + if self.dynamic_handler is not None: + return self.dynamic_handler raise HandlerError( f"Nexus service definition '{self.service.name}' has no operation " f"'{operation_name}'. There are {len(self.service.operation_definitions)} operations " diff --git a/src/nexusrpc/handler/_decorators.py b/src/nexusrpc/handler/_decorators.py index 1ec9320..cd259ba 100644 --- a/src/nexusrpc/handler/_decorators.py +++ b/src/nexusrpc/handler/_decorators.py @@ -7,11 +7,13 @@ import nexusrpc.handler._syncio from nexusrpc._common import InputT, OutputT, ServiceHandlerT +from nexusrpc._serializer import LazyValue, LazyValueT from nexusrpc._service import Operation from nexusrpc._util import ( get_callable_name, get_service_definition, is_async_callable, + set_dynamic_operation_factory, set_operation, set_operation_factory, set_service_definition, @@ -25,7 +27,7 @@ OperationHandler, SyncOperationHandler, bind_operation_handler_methods_to_service, - collect_operation_handler_factories_by_method_name, + collect_operation_handler_factories, service_definition_from_operation_handler_methods, validate_operation_handler_methods, ) @@ -105,9 +107,7 @@ def decorator(cls: type[ServiceHandlerT]) -> type[ServiceHandlerT]: ) if not _name: raise ValueError("Service name must not be empty.") - factories_by_method_name = collect_operation_handler_factories_by_method_name( - cls, _service - ) + factories_by_method_name, _ = collect_operation_handler_factories(cls, _service) service = _service or service_definition_from_operation_handler_methods( _name, factories_by_method_name ) @@ -135,7 +135,7 @@ def operation_handler( @overload def operation_handler( - *, name: Optional[str] = None + *, name: Optional[str] = None, dynamic: bool = False ) -> Callable[[OperationHandlerFactoryT], OperationHandlerFactoryT]: ... @@ -143,6 +143,7 @@ def operation_handler( method: Optional[OperationHandlerFactoryT] = None, *, name: Optional[str] = None, + dynamic: bool = False, ) -> Union[ OperationHandlerFactoryT, Callable[[OperationHandlerFactoryT], OperationHandlerFactoryT], @@ -156,8 +157,17 @@ def operation_handler( Args: method: The method to decorate. name: Optional name for the operation. If not provided, the method name will be used. + dynamic: Use this factory for the unnamed fallback. Cannot specify name. + The handler must accept raw nexusrpc.LazyValue input. + + .. warning:: + Dynamic operation handler (setting dynamic=True) is experimental and may change in + the future. """ + if dynamic and name is not None: + raise ValueError("A dynamic operation handler cannot specify name") + def decorator( method: OperationHandlerFactoryT, ) -> OperationHandlerFactoryT: @@ -176,6 +186,14 @@ def decorator( f"but operation {method.__name__} has {len(type_args)} type parameters: {type_args}" ) + if dynamic: + if input_type not in (LazyValue, LazyValueT): + raise TypeError( + "A dynamic operation handler must accept nexusrpc.LazyValue" + ) + set_dynamic_operation_factory(method) + return method + op: Operation[Any, Any] = Operation( name=name or method.__name__, input_type=input_type, diff --git a/src/nexusrpc/handler/_operation_handler.py b/src/nexusrpc/handler/_operation_handler.py index b1b47d0..0b0bb9b 100644 --- a/src/nexusrpc/handler/_operation_handler.py +++ b/src/nexusrpc/handler/_operation_handler.py @@ -7,6 +7,7 @@ from typing import Any, Callable, Generic, Optional from nexusrpc._common import InputT, OutputT, ServiceHandlerT +from nexusrpc._serializer import LazyValueT from nexusrpc._service import Operation, OperationDefinition, ServiceDefinition from nexusrpc._util import ( _NEXUS_OPERATION_FACTORY_ATTR_NAME, # pyright: ignore[reportPrivateUsage] @@ -14,6 +15,7 @@ get_operation_factory, is_async_callable, is_callable, + is_dynamic_operation_factory, set_operation, set_operation_factory, ) @@ -132,14 +134,20 @@ async def cancel(self, ctx: CancelOperationContext, token: str) -> None: ... -def collect_operation_handler_factories_by_method_name( +def collect_operation_handler_factories( user_service_cls: type[ServiceHandlerT], service: Optional[ServiceDefinition], -) -> dict[str, Callable[[ServiceHandlerT], OperationHandler[Any, Any]]]: - """ - Collect operation handler methods from a user service handler class. +) -> tuple[ + dict[str, Callable[[ServiceHandlerT], OperationHandler[Any, Any]]], + Optional[Callable[[ServiceHandlerT], OperationHandler[LazyValueT, Any]]], +]: + """Collect named factories by method name and the optional dynamic factory. + + Validate duplicate handlers, including inherited ones, and named methods against + the service definition when provided. """ factories: dict[str, Callable[[ServiceHandlerT], OperationHandler[Any, Any]]] = {} + dynamic_factory = None service_method_names = ( {op_defn.method_name for op_defn in service.operation_definitions.values()} if service @@ -148,7 +156,14 @@ def collect_operation_handler_factories_by_method_name( seen = set() for _, method in inspect.getmembers(user_service_cls, is_callable): if factory := get_operation_factory(method): - if op := get_operation(factory): + if is_dynamic_operation_factory(factory): + if dynamic_factory is not None: + raise RuntimeError( + f"Service '{user_service_cls.__name__}' has more than one " + f"dynamic operation handler." + ) + dynamic_factory = factory + elif op := get_operation(factory): if op.name in seen: raise RuntimeError( f"Operation '{op.name}' in service '{user_service_cls.__name__}' " @@ -169,7 +184,7 @@ def collect_operation_handler_factories_by_method_name( ) factories[op.method_name] = factory seen.add(op.name) - return factories + return factories, dynamic_factory def validate_operation_handler_methods( diff --git a/tests/handler/test_dynamic_decorator.py b/tests/handler/test_dynamic_decorator.py new file mode 100644 index 0000000..b37605f --- /dev/null +++ b/tests/handler/test_dynamic_decorator.py @@ -0,0 +1,454 @@ +import asyncio +from concurrent.futures import ThreadPoolExecutor +from typing import Any + +import pytest + +import nexusrpc +from nexusrpc._util import get_operation_factory, set_operation_factory +from nexusrpc.handler import ( + CancelOperationContext, + Handler, + MiddlewareSafeOperationHandler, + OperationContext, + OperationHandler, + OperationHandlerMiddleware, + StartOperationContext, + StartOperationResultAsync, + StartOperationResultSync, + operation_handler, + service_handler, + sync_operation, +) +from nexusrpc.handler._core import ServiceHandler +from tests.helpers import DummySerializer, TestOperationTaskCancellation + + +def start_context(name: str, service: str = "tools") -> StartOperationContext: + return StartOperationContext( + service=service, + operation=name, + headers={}, + request_id="req", + task_cancellation=TestOperationTaskCancellation(), + ) + + +def cancel_context(name: str, service: str = "tools") -> CancelOperationContext: + return CancelOperationContext( + service=service, + operation=name, + headers={}, + task_cancellation=TestOperationTaskCancellation(), + ) + + +class Dynamic(OperationHandler[nexusrpc.LazyValue, Any]): + def __init__(self) -> None: + self.tools = {"echo"} + self.cancelled: list[tuple[str, str]] = [] + + async def start( + self, ctx: StartOperationContext, input: nexusrpc.LazyValue + ) -> StartOperationResultSync[Any] | StartOperationResultAsync: + assert isinstance(input, nexusrpc.LazyValue) + value = await input.consume(as_type=dict) + if ctx.operation not in self.tools: + raise nexusrpc.HandlerError( + "Unknown tool", type=nexusrpc.HandlerErrorType.NOT_FOUND + ) + if value.get("async"): + return StartOperationResultAsync(f"{ctx.operation}:{value['id']}") + return StartOperationResultSync((ctx.operation, ctx.request_id, value)) + + async def cancel(self, ctx: CancelOperationContext, token: str) -> None: + self.cancelled.append((ctx.operation, token)) + + +class Named(OperationHandler[None, str]): + def __init__(self) -> None: + self.cancelled: list[tuple[str, str]] = [] + + async def start( + self, ctx: StartOperationContext, input: None + ) -> StartOperationResultSync[str]: + assert input is None + return StartOperationResultSync("manifest") + + async def cancel(self, ctx: CancelOperationContext, token: str) -> None: + self.cancelled.append((ctx.operation, token)) + + +@service_handler(name="tools") +class Tools: + def __init__(self) -> None: + self.dynamic = Dynamic() + self.named = Named() + + @operation_handler + def list_tools(self) -> OperationHandler[None, str]: + return self.named + + @operation_handler(dynamic=True) + def forward(self) -> OperationHandler[nexusrpc.LazyValue, Any]: + return self.dynamic + + +# Named handlers keep precedence, while the fallback receives raw input and can return either result kind. +@pytest.mark.asyncio +@pytest.mark.parametrize( + ["operation", "value", "expected"], + [ + pytest.param("list_tools", None, "manifest", id="named"), + pytest.param("echo", {"id": 5}, ("echo", "req", {"id": 5}), id="dynamic-sync"), + pytest.param("echo", {"id": 5, "async": True}, "echo:5", id="dynamic-async"), + ], +) +async def test_dynamic_decorator_routes_raw_input_and_preserves_named_handlers( + operation: str, value: Any, expected: Any +): + tools = Tools() + handler = Handler([tools]) + result = await handler.start_operation( + start_context(operation), nexusrpc.LazyValue(DummySerializer(value), {}) + ) + if operation == "echo" and value.get("async"): + assert isinstance(result, StartOperationResultAsync) + assert result.token == expected + else: + assert isinstance(result, StartOperationResultSync) + assert result.value == expected + service = handler.service_handlers["tools"] + assert service.get_operation_handler(operation) is ( + tools.named if operation == "list_tools" else tools.dynamic + ) + assert set(service.operation_handlers) == {"list_tools"} + assert nexusrpc.get_operation(Tools.forward) is None + assert get_operation_factory(Tools.forward) is Tools.forward + + +# Removing a tool prevents new starts but does not prevent cancellation of its existing token. +@pytest.mark.asyncio +async def test_dynamic_cancel_after_tool_removal(): + tools = Tools() + handler = Handler([tools]) + result = await handler.start_operation( + start_context("echo"), + nexusrpc.LazyValue(DummySerializer({"id": 5, "async": True}), {}), + ) + assert isinstance(result, StartOperationResultAsync) + tools.dynamic.tools.remove("echo") + with pytest.raises(nexusrpc.HandlerError) as error: + _ = await handler.start_operation( + start_context("echo"), nexusrpc.LazyValue(DummySerializer({}), {}) + ) + assert error.value.type == nexusrpc.HandlerErrorType.NOT_FOUND + await handler.cancel_operation(cancel_context("echo"), result.token) + assert tools.dynamic.cancelled == [("echo", "echo:5")] + + +# Cancellation selects the named handler before falling back for an unmatched name. +@pytest.mark.asyncio +@pytest.mark.parametrize("operation", ["list_tools", "removed"]) +async def test_named_cancel_takes_precedence(operation: str): + tools = Tools() + handler = Handler([tools]) + await handler.cancel_operation(cancel_context(operation), "token") + expected = [(operation, "token")] + assert tools.named.cancelled == (expected if operation == "list_tools" else []) + assert tools.dynamic.cancelled == (expected if operation == "removed" else []) + + +# A fallback never receives start or cancel requests for an unknown service. +@pytest.mark.asyncio +@pytest.mark.parametrize("method", ["start", "cancel"]) +async def test_dynamic_handler_does_not_handle_unknown_services(method: str): + tools = Tools() + handler = Handler([tools]) + with pytest.raises(nexusrpc.HandlerError) as error: + if method == "start": + _ = await handler.start_operation( + start_context("echo", "missing"), + nexusrpc.LazyValue(DummySerializer({}), {}), + ) + else: + await handler.cancel_operation(cancel_context("echo", "missing"), "token") + assert error.value.type == nexusrpc.HandlerErrorType.NOT_FOUND + assert tools.dynamic.cancelled == [] + + +# A fallback cannot specify a name, including an empty string. +@pytest.mark.parametrize("name", ["named", ""]) +def test_dynamic_handler_rejects_name(name: str): + with pytest.raises(ValueError, match="cannot specify name"): + _ = operation_handler(name=name, dynamic=True) + + +# An inherited fallback cannot be combined with a second fallback. +def test_dynamic_handler_rejects_duplicates(): + with pytest.raises(RuntimeError, match="more than one dynamic"): + + @service_handler(name="duplicate") + class _Duplicate(Tools): + @operation_handler(dynamic=True) + def other(self) -> OperationHandler[nexusrpc.LazyValue, Any]: + return Dynamic() + + _ = _Duplicate + + +# Two dynamic handlers declared on the same service are rejected. +def test_dynamic_handler_rejects_duplicates_on_same_class(): + with pytest.raises(RuntimeError, match="more than one dynamic"): + + @service_handler(name="duplicate") + class _Duplicate: + @operation_handler(dynamic=True) + def first(self) -> OperationHandler[nexusrpc.LazyValue, Any]: + return Dynamic() + + @operation_handler(dynamic=True) + def second(self) -> OperationHandler[nexusrpc.LazyValue, Any]: + return Dynamic() + + _ = _Duplicate + + +# A fallback must accept raw input rather than a decoded value. +def test_dynamic_handler_requires_raw_input(): + with pytest.raises(TypeError, match="LazyValue"): + + @service_handler(name="decoded") + class _Decoded: + @operation_handler(dynamic=True) + def forward(self) -> OperationHandler[dict[str, Any], Any]: + raise AssertionError("Reject decoded input before creating the handler") + + _ = _Decoded + + +# An explicit service definition can have a fallback without declaring any named operations. +@pytest.mark.asyncio +async def test_dynamic_handler_with_explicit_service_and_no_named_operations(): + @nexusrpc.service(name="empty") + class Empty: + pass + + @service_handler(service=Empty) + class CatchAll: + @operation_handler(dynamic=True) + def forward(self) -> OperationHandler[nexusrpc.LazyValue, Any]: + return Dynamic() + + instance = CatchAll() + service = ServiceHandler.from_user_instance(instance) + assert not service.operation_handlers + handler = Handler([instance]) + result = await handler.start_operation( + start_context("echo", "empty"), nexusrpc.LazyValue(DummySerializer({}), {}) + ) + assert isinstance(result, StartOperationResultSync) and result.value[0] == "echo" + + +# Custom start-method decorators can attach a dynamic factory without an Operation. +@pytest.mark.asyncio +async def test_dynamic_factory_attached_to_start_method(): + @operation_handler(dynamic=True) + def factory(_self: Any) -> OperationHandler[nexusrpc.LazyValue, Any]: + return Dynamic() + + @service_handler(name="tools") + class CustomService: + async def forward(self) -> None: + raise AssertionError("The start method must not be called as a factory") + + set_operation_factory(forward, factory) + + handler = Handler([CustomService()]) + assert not handler.service_handlers["tools"].operation_handlers + assert nexusrpc.get_operation(CustomService.forward) is None + assert get_operation_factory(CustomService.forward) is factory + result = await handler.start_operation( + start_context("echo"), nexusrpc.LazyValue(DummySerializer({"id": 5}), {}) + ) + assert isinstance(result, StartOperationResultSync) + assert result.value == ("echo", "req", {"id": 5}) + + +# A fallback can also accompany named operations from an explicit service definition. +@pytest.mark.asyncio +async def test_dynamic_handler_with_explicit_named_service(): + @nexusrpc.service(name="explicit") + class Definition: + list_tools: nexusrpc.Operation[None, str] + + @service_handler(service=Definition) + class ExplicitTools(Tools): + pass + + handler = Handler([ExplicitTools()]) + named = await handler.start_operation( + start_context("list_tools", "explicit"), + nexusrpc.LazyValue(DummySerializer(None), {}), + ) + dynamic = await handler.start_operation( + start_context("echo", "explicit"), + nexusrpc.LazyValue(DummySerializer({}), {}), + ) + assert isinstance(named, StartOperationResultSync) and named.value == "manifest" + assert isinstance(dynamic, StartOperationResultSync) and dynamic.value[0] == "echo" + + +# Blocking fallback methods require an executor and still receive raw input when one is supplied. +@pytest.mark.asyncio +async def test_blocking_dynamic_handler_requires_an_executor(): + class Blocking(OperationHandler[nexusrpc.LazyValue, Any]): + def start( + self, ctx: StartOperationContext, input: nexusrpc.LazyValue + ) -> StartOperationResultSync[Any]: # type: ignore[override] + return StartOperationResultSync(asyncio.run(input.consume(as_type=dict))) + + async def cancel(self, ctx: CancelOperationContext, token: str) -> None: + pass + + @service_handler(name="tools") + class BlockingService: + @operation_handler(dynamic=True) + def forward(self) -> OperationHandler[nexusrpc.LazyValue, Any]: + return Blocking() + + with pytest.raises(RuntimeError, match="executor"): + _ = Handler([BlockingService()]) + with ThreadPoolExecutor() as executor: + handler = Handler([BlockingService()], executor=executor) + result = await handler.start_operation( + start_context("echo"), nexusrpc.LazyValue(DummySerializer({"id": 5}), {}) + ) + assert isinstance(result, StartOperationResultSync) and result.value == { + "id": 5 + } + + +class RecordingMiddleware(OperationHandlerMiddleware): + def __init__(self) -> None: + self.calls: list[tuple[str, str, Any]] = [] + + def intercept( + self, ctx: OperationContext, next: MiddlewareSafeOperationHandler + ) -> MiddlewareSafeOperationHandler: + return RecordingOperationHandler(next, self) + + +class RecordingOperationHandler(MiddlewareSafeOperationHandler): + def __init__( + self, next: MiddlewareSafeOperationHandler, middleware: RecordingMiddleware + ) -> None: + self._next = next + self._middleware = middleware + + async def start( + self, ctx: StartOperationContext, input: Any + ) -> StartOperationResultSync[Any] | StartOperationResultAsync: + self._middleware.calls.append(("start", ctx.operation, input)) + return await self._next.start(ctx, input) + + async def cancel(self, ctx: CancelOperationContext, token: str) -> None: + self._middleware.calls.append(("cancel", ctx.operation, token)) + return await self._next.cancel(ctx, token) + + +# Middleware sees the original name, raw start input, and cancellation token for the fallback. +@pytest.mark.asyncio +async def test_middleware_runs_for_dynamic_handler(): + middleware = RecordingMiddleware() + tools = Tools() + handler = Handler([tools], middleware=[middleware]) + raw = nexusrpc.LazyValue(DummySerializer({"id": 1, "async": True}), {}) + result = await handler.start_operation(start_context("echo"), raw) + assert isinstance(result, StartOperationResultAsync) + await handler.cancel_operation(cancel_context("echo"), result.token) + assert middleware.calls == [ + ("start", "echo", raw), + ("cancel", "echo", "echo:1"), + ] + assert tools.dynamic.cancelled == [("echo", "echo:1")] + + +# A NOT_FOUND raised by the fallback is returned unchanged for start and cancel. +@pytest.mark.asyncio +@pytest.mark.parametrize("method", ["start", "cancel"]) +async def test_not_found_from_dynamic_handler_is_final(method: str): + class RejectingDynamic(Dynamic): + async def cancel(self, ctx: CancelOperationContext, token: str) -> None: + raise nexusrpc.HandlerError( + "Unknown tool", type=nexusrpc.HandlerErrorType.NOT_FOUND + ) + + tools = Tools() + tools.dynamic = RejectingDynamic() + tools.dynamic.tools.clear() + handler = Handler([tools]) + with pytest.raises(nexusrpc.HandlerError) as error: + if method == "start": + _ = await handler.start_operation( + start_context("echo"), nexusrpc.LazyValue(DummySerializer({}), {}) + ) + else: + await handler.cancel_operation(cancel_context("echo"), "token") + assert error.value.type == nexusrpc.HandlerErrorType.NOT_FOUND + assert str(error.value) == "Unknown tool" + + +# A named handler's NOT_FOUND must not trigger a second attempt through the fallback. +@pytest.mark.asyncio +@pytest.mark.parametrize("method", ["start", "cancel"]) +async def test_named_not_found_does_not_use_fallback(method: str): + rejection = nexusrpc.HandlerError( + "Named rejection", type=nexusrpc.HandlerErrorType.NOT_FOUND + ) + + class RejectingNamed(Named): + async def start( + self, ctx: StartOperationContext, input: None + ) -> StartOperationResultSync[str]: + raise rejection + + async def cancel(self, ctx: CancelOperationContext, token: str) -> None: + raise rejection + + tools = Tools() + tools.named = RejectingNamed() + tools.dynamic.tools.add("list_tools") + handler = Handler([tools]) + with pytest.raises(nexusrpc.HandlerError) as error: + if method == "start": + _ = await handler.start_operation( + start_context("list_tools"), + nexusrpc.LazyValue(DummySerializer(None), {}), + ) + else: + await handler.cancel_operation(cancel_context("list_tools"), "token") + assert error.value is rejection + assert tools.dynamic.cancelled == [] + + +# Without a fallback, unmatched start and cancel requests still return NOT_FOUND. +@pytest.mark.asyncio +@pytest.mark.parametrize("method", ["start", "cancel"]) +async def test_unknown_operation_without_dynamic_handler_is_not_found(method: str): + @service_handler(name="named") + class NamedOnly: + @sync_operation + async def list_tools(self, _ctx: StartOperationContext, _input: None) -> str: + return "manifest" + + handler = Handler([NamedOnly()]) + with pytest.raises(nexusrpc.HandlerError) as error: + if method == "start": + _ = await handler.start_operation( + start_context("echo", "named"), + nexusrpc.LazyValue(DummySerializer({}), {}), + ) + else: + await handler.cancel_operation(cancel_context("echo", "named"), "token") + assert error.value.type == nexusrpc.HandlerErrorType.NOT_FOUND diff --git a/tests/handler/test_service_handler_decorator_results_in_correctly_functioning_operation_factories.py b/tests/handler/test_service_handler_decorator_results_in_correctly_functioning_operation_factories.py index cd7570a..9adc9c3 100644 --- a/tests/handler/test_service_handler_decorator_results_in_correctly_functioning_operation_factories.py +++ b/tests/handler/test_service_handler_decorator_results_in_correctly_functioning_operation_factories.py @@ -21,7 +21,7 @@ ) from nexusrpc.handler._decorators import operation_handler from nexusrpc.handler._operation_handler import ( - collect_operation_handler_factories_by_method_name, + collect_operation_handler_factories, ) from tests.helpers import TestOperationTaskCancellation @@ -77,9 +77,10 @@ async def test_collected_operation_factories_match_service_definition( service = get_service_definition(test_case.Service) assert isinstance(service, nexusrpc.ServiceDefinition) assert service.name == "Service" - operation_factories = collect_operation_handler_factories_by_method_name( + operation_factories, dynamic_factory = collect_operation_handler_factories( test_case.Service, service ) + assert dynamic_factory is None assert operation_factories.keys() == test_case.expected_operation_factories.keys() ctx = StartOperationContext( service="Service",