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
45 changes: 45 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 15 additions & 2 deletions src/nexusrpc/_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down
28 changes: 22 additions & 6 deletions src/nexusrpc/handler/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@
from ._operation_handler import (
MiddlewareSafeOperationHandler,
OperationHandler,
collect_operation_handler_factories_by_method_name,
collect_operation_handler_factories,
)


Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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:
Expand All @@ -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 "
Expand Down
28 changes: 23 additions & 5 deletions src/nexusrpc/handler/_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
)
Expand Down Expand Up @@ -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
)
Expand Down Expand Up @@ -135,14 +135,15 @@ def operation_handler(

@overload
def operation_handler(
*, name: Optional[str] = None
*, name: Optional[str] = None, dynamic: bool = False
) -> Callable[[OperationHandlerFactoryT], OperationHandlerFactoryT]: ...


def operation_handler(
method: Optional[OperationHandlerFactoryT] = None,
*,
name: Optional[str] = None,
dynamic: bool = False,
) -> Union[
OperationHandlerFactoryT,
Callable[[OperationHandlerFactoryT], OperationHandlerFactoryT],
Expand All @@ -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:
Expand All @@ -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,
Expand Down
27 changes: 21 additions & 6 deletions src/nexusrpc/handler/_operation_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@
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]
get_operation,
get_operation_factory,
is_async_callable,
is_callable,
is_dynamic_operation_factory,
set_operation,
set_operation_factory,
)
Expand Down Expand Up @@ -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
Expand All @@ -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__}' "
Expand All @@ -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(
Expand Down
Loading
Loading