From c88388fa0b0ddac441c3b9dc18cb5919c5f1fd96 Mon Sep 17 00:00:00 2001 From: long-nt-tran Date: Thu, 12 Nov 2026 18:24:40 -0500 Subject: [PATCH 1/3] Add dynamic operation handler --- README.md | 45 +++ src/nexusrpc/_service.py | 2 + src/nexusrpc/handler/_core.py | 51 ++- src/nexusrpc/handler/_decorators.py | 11 +- src/nexusrpc/handler/_operation_handler.py | 39 +- tests/handler/test_dynamic_decorator.py | 426 +++++++++++++++++++++ 6 files changed, 553 insertions(+), 21 deletions(-) create mode 100644 tests/handler/test_dynamic_decorator.py 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/_service.py b/src/nexusrpc/_service.py index 468ac83..9f54098 100644 --- a/src/nexusrpc/_service.py +++ b/src/nexusrpc/_service.py @@ -46,6 +46,8 @@ class MyNexusService: """ name: str + dynamic: bool = dataclasses.field(default=False, kw_only=True) + """Whether this describes the unnamed handler fallback.""" method_name: Optional[str] = dataclasses.field(default=None, init=False) input_type: Optional[type[InputT]] = dataclasses.field(default=None) output_type: Optional[type[OutputT]] = dataclasses.field(default=None) diff --git a/src/nexusrpc/handler/_core.py b/src/nexusrpc/handler/_core.py index 68c832b..f5828b3 100644 --- a/src/nexusrpc/handler/_core.py +++ b/src/nexusrpc/handler/_core.py @@ -109,7 +109,7 @@ from nexusrpc._common import HandlerError, HandlerErrorType from nexusrpc._serializer import LazyValueT from nexusrpc._service import ServiceDefinition -from nexusrpc._util import get_service_definition, is_async_callable +from nexusrpc._util import get_operation, get_service_definition, is_async_callable from ._common import ( CancelOperationContext, @@ -283,10 +283,14 @@ async def start_operation( input: The input to the operation, as a LazyValue. """ 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) + handler = service_handler.get_operation_handler(ctx.operation) + op_handler = self._get_operation_handler(ctx, handler) + definition = service_handler.service.operation_definitions.get(ctx.operation) + deserialized_input = ( + input + if definition is None + else await input.consume(as_type=definition.input_type) + ) return await op_handler.start(ctx, deserialized_input) async def cancel_operation(self, ctx: CancelOperationContext, token: str) -> None: @@ -297,17 +301,20 @@ async def cancel_operation(self, ctx: CancelOperationContext, token: str) -> Non token: The operation token. """ service_handler = self._get_service_handler(ctx.service) - op_handler = self._get_operation_handler(ctx, service_handler, ctx.operation) + handler = service_handler.get_operation_handler(ctx.operation) + op_handler = self._get_operation_handler(ctx, handler) return await op_handler.cancel(ctx, token) def _get_operation_handler( - self, ctx: OperationContext, service_handler: ServiceHandler, operation: str + self, + ctx: OperationContext, + handler: OperationHandler[Any, Any], ) -> MiddlewareSafeOperationHandler: """ - Get the specified handler for the specified operation from the given service_handler and apply all middleware. + Wrap the resolved handler for the specified operation and apply all middleware. """ op_handler: MiddlewareSafeOperationHandler = _EnsuredAwaitableOperationHandler( - self.executor, service_handler.get_operation_handler(operation) + self.executor, handler ) for middleware in reversed(self._middleware): @@ -317,7 +324,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 +363,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: @@ -375,29 +387,40 @@ def from_user_instance(cls, user_instance: Any) -> Self: name: factories_by_method_name[defn.method_name](user_instance) for name, defn in service.operation_definitions.items() } + + dynamic_handler = None + for factory in factories_by_method_name.values(): + operation = get_operation(factory) + if operation is not None and operation.dynamic: + dynamic_handler = factory(user_instance) + break + 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 " f"in the definition.", type=HandlerErrorType.NOT_FOUND, ) - operation_handler = self.operation_handlers.get(operation_name) - if operation_handler is None: + handler = self.operation_handlers.get(operation_name) + if handler is None: raise HandlerError( f"Nexus service implementation '{self.service.name}' has no handler for " f"operation '{operation_name}'. There are {len(self.operation_handlers)} " f"available operation handlers.", type=HandlerErrorType.NOT_FOUND, ) - return operation_handler + return handler class _Executor: diff --git a/src/nexusrpc/handler/_decorators.py b/src/nexusrpc/handler/_decorators.py index 1ec9320..ba04ace 100644 --- a/src/nexusrpc/handler/_decorators.py +++ b/src/nexusrpc/handler/_decorators.py @@ -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,13 @@ 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. """ + if dynamic and name is not None: + raise ValueError("A dynamic operation handler cannot specify name") + def decorator( method: OperationHandlerFactoryT, ) -> OperationHandlerFactoryT: @@ -177,7 +183,8 @@ def decorator( ) op: Operation[Any, Any] = Operation( - name=name or method.__name__, + name="" if dynamic else name or method.__name__, + dynamic=dynamic, input_type=input_type, output_type=output_type, ) diff --git a/src/nexusrpc/handler/_operation_handler.py b/src/nexusrpc/handler/_operation_handler.py index b1b47d0..010912e 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 LazyValue, LazyValueT from nexusrpc._service import Operation, OperationDefinition, ServiceDefinition from nexusrpc._util import ( _NEXUS_OPERATION_FACTORY_ATTR_NAME, # pyright: ignore[reportPrivateUsage] @@ -146,15 +147,35 @@ def collect_operation_handler_factories_by_method_name( else set() ) seen = set() + has_dynamic = False for _, method in inspect.getmembers(user_service_cls, is_callable): if factory := get_operation_factory(method): if op := get_operation(factory): + if op.dynamic: + if op.name: + raise ValueError( + "A dynamic operation handler cannot have a name" + ) + if op.input_type not in (LazyValue, LazyValueT): + raise TypeError( + "A dynamic operation handler must accept nexusrpc.LazyValue" + ) + if has_dynamic: + raise RuntimeError( + f"Service '{user_service_cls.__name__}' has more than one " + f"dynamic operation handler." + ) + has_dynamic = True if op.name in seen: raise RuntimeError( f"Operation '{op.name}' in service '{user_service_cls.__name__}' " f"is defined multiple times." ) - if service and op.method_name not in service_method_names: + if ( + service + and not op.dynamic + and op.method_name not in service_method_names + ): _names = ", ".join(f"'{s}'" for s in sorted(service_method_names)) msg = ( f"Operation method name '{op.method_name}' in service handler {user_service_cls} " @@ -189,9 +210,15 @@ def validate_operation_handler_methods( 2. The input and output types of the handler method must exactly match the types declared in the service definition. """ - operation_handler_factories_by_method_name = ( - operation_handler_factories_by_method_name.copy() - ) + named_factories = {} + for name, handler_factory in operation_handler_factories_by_method_name.items(): + # The service contract lists only named operations. Exclude the dynamic fallback + # so validation does not reject it as an extra operation. + operation = get_operation(handler_factory) + if operation is not None and operation.dynamic: + continue + named_factories[name] = handler_factory + operation_handler_factories_by_method_name = named_factories for op_defn in service_definition.operation_definitions.values(): factory = operation_handler_factories_by_method_name.pop( op_defn.method_name, None @@ -329,6 +356,8 @@ def service_definition_from_operation_handler_methods( f"method with an operation handler decorator such as " f"@nexusrpc.handler.sync_operation?" ) - op_defns[op.name] = OperationDefinition.from_operation(op) + # The dynamic fallback has no fixed name, so it is not part of the service contract. + if not op.dynamic: + op_defns[op.name] = OperationDefinition.from_operation(op) return ServiceDefinition(name=service_name, operation_definitions=op_defns) diff --git a/tests/handler/test_dynamic_decorator.py b/tests/handler/test_dynamic_decorator.py new file mode 100644 index 0000000..651fe4f --- /dev/null +++ b/tests/handler/test_dynamic_decorator.py @@ -0,0 +1,426 @@ +import asyncio +from concurrent.futures import ThreadPoolExecutor +from typing import Any + +import pytest + +import nexusrpc +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"} + + +# 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" + + +# 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 From 50d1fb642004e0a6a719650043f8eb8f3225da1e Mon Sep 17 00:00:00 2001 From: long-nt-tran Date: Fri, 20 Nov 2026 10:34:23 -0500 Subject: [PATCH 2/3] Address PR feedback, remove some cosmetic-only changes --- src/nexusrpc/_service.py | 2 - src/nexusrpc/_util.py | 17 ++++- src/nexusrpc/handler/_core.py | 41 +++++------- src/nexusrpc/handler/_decorators.py | 23 +++++-- src/nexusrpc/handler/_operation_handler.py | 66 ++++++++----------- tests/handler/test_dynamic_decorator.py | 28 ++++++++ ...rrectly_functioning_operation_factories.py | 5 +- 7 files changed, 106 insertions(+), 76 deletions(-) diff --git a/src/nexusrpc/_service.py b/src/nexusrpc/_service.py index 9f54098..468ac83 100644 --- a/src/nexusrpc/_service.py +++ b/src/nexusrpc/_service.py @@ -46,8 +46,6 @@ class MyNexusService: """ name: str - dynamic: bool = dataclasses.field(default=False, kw_only=True) - """Whether this describes the unnamed handler fallback.""" method_name: Optional[str] = dataclasses.field(default=None, init=False) input_type: Optional[type[InputT]] = dataclasses.field(default=None) output_type: Optional[type[OutputT]] = dataclasses.field(default=None) 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 f5828b3..10d7e1f 100644 --- a/src/nexusrpc/handler/_core.py +++ b/src/nexusrpc/handler/_core.py @@ -109,7 +109,7 @@ from nexusrpc._common import HandlerError, HandlerErrorType from nexusrpc._serializer import LazyValueT from nexusrpc._service import ServiceDefinition -from nexusrpc._util import get_operation, get_service_definition, is_async_callable +from nexusrpc._util import get_service_definition, is_async_callable from ._common import ( CancelOperationContext, @@ -121,7 +121,7 @@ from ._operation_handler import ( MiddlewareSafeOperationHandler, OperationHandler, - collect_operation_handler_factories_by_method_name, + collect_operation_handler_factories, ) @@ -283,13 +283,13 @@ async def start_operation( input: The input to the operation, as a LazyValue. """ service_handler = self._get_service_handler(ctx.service) - handler = service_handler.get_operation_handler(ctx.operation) - op_handler = self._get_operation_handler(ctx, handler) - definition = service_handler.service.operation_definitions.get(ctx.operation) + op_handler = self._get_operation_handler(ctx, service_handler, ctx.operation) + + op_defn = service_handler.service.operation_definitions.get(ctx.operation) deserialized_input = ( input - if definition is None - else await input.consume(as_type=definition.input_type) + if op_defn is None + else await input.consume(as_type=op_defn.input_type) ) return await op_handler.start(ctx, deserialized_input) @@ -301,20 +301,17 @@ async def cancel_operation(self, ctx: CancelOperationContext, token: str) -> Non token: The operation token. """ service_handler = self._get_service_handler(ctx.service) - handler = service_handler.get_operation_handler(ctx.operation) - op_handler = self._get_operation_handler(ctx, handler) + op_handler = self._get_operation_handler(ctx, service_handler, ctx.operation) return await op_handler.cancel(ctx, token) def _get_operation_handler( - self, - ctx: OperationContext, - handler: OperationHandler[Any, Any], + self, ctx: OperationContext, service_handler: ServiceHandler, operation: str ) -> MiddlewareSafeOperationHandler: """ - Wrap the resolved handler for the specified operation and apply all middleware. + Get the specified handler for the specified operation from the given service_handler and apply all middleware. """ op_handler: MiddlewareSafeOperationHandler = _EnsuredAwaitableOperationHandler( - self.executor, handler + self.executor, service_handler.get_operation_handler(operation) ) for middleware in reversed(self._middleware): @@ -380,20 +377,16 @@ 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 - for factory in factories_by_method_name.values(): - operation = get_operation(factory) - if operation is not None and operation.dynamic: - dynamic_handler = factory(user_instance) - break + if dynamic_factory is not None: + dynamic_handler = dynamic_factory(user_instance) return cls( service=service, @@ -412,15 +405,15 @@ def get_operation_handler(self, operation_name: str) -> OperationHandler[Any, An f"in the definition.", type=HandlerErrorType.NOT_FOUND, ) - handler = self.operation_handlers.get(operation_name) - if handler is None: + operation_handler = self.operation_handlers.get(operation_name) + if operation_handler is None: raise HandlerError( f"Nexus service implementation '{self.service.name}' has no handler for " f"operation '{operation_name}'. There are {len(self.operation_handlers)} " f"available operation handlers.", type=HandlerErrorType.NOT_FOUND, ) - return handler + return operation_handler class _Executor: diff --git a/src/nexusrpc/handler/_decorators.py b/src/nexusrpc/handler/_decorators.py index ba04ace..95f2748 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 ) @@ -159,6 +159,10 @@ def operation_handler( 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) are experimental and may change in + the future. """ if dynamic and name is not None: @@ -182,9 +186,16 @@ 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="" if dynamic else name or method.__name__, - dynamic=dynamic, + name=name or method.__name__, input_type=input_type, output_type=output_type, ) diff --git a/src/nexusrpc/handler/_operation_handler.py b/src/nexusrpc/handler/_operation_handler.py index 010912e..0b0bb9b 100644 --- a/src/nexusrpc/handler/_operation_handler.py +++ b/src/nexusrpc/handler/_operation_handler.py @@ -7,7 +7,7 @@ from typing import Any, Callable, Generic, Optional from nexusrpc._common import InputT, OutputT, ServiceHandlerT -from nexusrpc._serializer import LazyValue, LazyValueT +from nexusrpc._serializer import LazyValueT from nexusrpc._service import Operation, OperationDefinition, ServiceDefinition from nexusrpc._util import ( _NEXUS_OPERATION_FACTORY_ATTR_NAME, # pyright: ignore[reportPrivateUsage] @@ -15,6 +15,7 @@ get_operation_factory, is_async_callable, is_callable, + is_dynamic_operation_factory, set_operation, set_operation_factory, ) @@ -133,49 +134,42 @@ 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 else set() ) seen = set() - has_dynamic = False for _, method in inspect.getmembers(user_service_cls, is_callable): if factory := get_operation_factory(method): - if op := get_operation(factory): - if op.dynamic: - if op.name: - raise ValueError( - "A dynamic operation handler cannot have a name" - ) - if op.input_type not in (LazyValue, LazyValueT): - raise TypeError( - "A dynamic operation handler must accept nexusrpc.LazyValue" - ) - if has_dynamic: - raise RuntimeError( - f"Service '{user_service_cls.__name__}' has more than one " - f"dynamic operation handler." - ) - has_dynamic = True + 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__}' " f"is defined multiple times." ) - if ( - service - and not op.dynamic - and op.method_name not in service_method_names - ): + if service and op.method_name not in service_method_names: _names = ", ".join(f"'{s}'" for s in sorted(service_method_names)) msg = ( f"Operation method name '{op.method_name}' in service handler {user_service_cls} " @@ -190,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( @@ -210,15 +204,9 @@ def validate_operation_handler_methods( 2. The input and output types of the handler method must exactly match the types declared in the service definition. """ - named_factories = {} - for name, handler_factory in operation_handler_factories_by_method_name.items(): - # The service contract lists only named operations. Exclude the dynamic fallback - # so validation does not reject it as an extra operation. - operation = get_operation(handler_factory) - if operation is not None and operation.dynamic: - continue - named_factories[name] = handler_factory - operation_handler_factories_by_method_name = named_factories + operation_handler_factories_by_method_name = ( + operation_handler_factories_by_method_name.copy() + ) for op_defn in service_definition.operation_definitions.values(): factory = operation_handler_factories_by_method_name.pop( op_defn.method_name, None @@ -356,8 +344,6 @@ def service_definition_from_operation_handler_methods( f"method with an operation handler decorator such as " f"@nexusrpc.handler.sync_operation?" ) - # The dynamic fallback has no fixed name, so it is not part of the service contract. - if not op.dynamic: - op_defns[op.name] = OperationDefinition.from_operation(op) + op_defns[op.name] = OperationDefinition.from_operation(op) return ServiceDefinition(name=service_name, operation_definitions=op_defns) diff --git a/tests/handler/test_dynamic_decorator.py b/tests/handler/test_dynamic_decorator.py index 651fe4f..b37605f 100644 --- a/tests/handler/test_dynamic_decorator.py +++ b/tests/handler/test_dynamic_decorator.py @@ -5,6 +5,7 @@ import pytest import nexusrpc +from nexusrpc._util import get_operation_factory, set_operation_factory from nexusrpc.handler import ( CancelOperationContext, Handler, @@ -122,6 +123,8 @@ async def test_dynamic_decorator_routes_raw_input_and_preserves_named_handlers( 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. @@ -247,6 +250,31 @@ def forward(self) -> OperationHandler[nexusrpc.LazyValue, Any]: 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(): 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", From f28bba319faad5fd10eb1fc73c095d7af55c38f7 Mon Sep 17 00:00:00 2001 From: long-nt-tran Date: Mon, 23 Nov 2026 12:58:43 -0500 Subject: [PATCH 3/3] Update docstring --- src/nexusrpc/handler/_decorators.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/nexusrpc/handler/_decorators.py b/src/nexusrpc/handler/_decorators.py index 95f2748..cd259ba 100644 --- a/src/nexusrpc/handler/_decorators.py +++ b/src/nexusrpc/handler/_decorators.py @@ -161,7 +161,7 @@ def operation_handler( The handler must accept raw nexusrpc.LazyValue input. .. warning:: - Dynamic operation handler (setting dynamic=True) are experimental and may change in + Dynamic operation handler (setting dynamic=True) is experimental and may change in the future. """