Skip to content
Draft
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
13 changes: 6 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1634,9 +1634,10 @@ Nexus operation handlers can use one of these decorators:
- `@nexusrpc.handler.sync_operation`: an operation that responds synchronously. It may be `def` or `async def` and it
may do network I/O, but it must respond within 10 seconds.
- `@temporalio.nexus.temporal_operation`: an experimental decorator for an `async def` that receives a
`TemporalNexusClient` and the operation input. Return `TemporalOperationResult.sync(value)` for a synchronous
Nexus response. To start a Workflow, Workflow Update, or Activity that completes the Nexus operation later,
return the `TemporalOperationResult` from the corresponding client method.
`TemporalNexusClient` and the operation input. Return the declared output directly for a synchronous Nexus response.
To start a Workflow, Workflow Update, or Activity that completes the Nexus operation later, return the
`TemporalOperationResult` from the corresponding client method. An explicit `TemporalOperationResult.sync(value)`
also completes synchronously.

In a Temporal operation handler, `nexus.info()` provides the service, operation, endpoint, worker namespace and task
queue, and the opaque start request ID when available. `nexus.info().cancellation_token` observes cancellation of the
Expand Down Expand Up @@ -1690,10 +1691,8 @@ https://github.com/temporalio/samples-python/tree/nexus/hello_nexus).
@nexus.temporal_operation
async def my_temporal_operation(
self, client: nexus.TemporalNexusClient, input: MyInput
) -> nexus.TemporalOperationResult[MyOutput]:
return nexus.TemporalOperationResult.sync(
MyOutput(message=f"Hello {input.name} from {nexus.info().operation}!")
)
) -> MyOutput:
return MyOutput(message=f"Hello {input.name} from {nexus.info().operation}!")
```

4. Register your service handler with a Temporal worker.
Expand Down
2 changes: 1 addition & 1 deletion changelog/changed/curious-nexus-tern.md
Original file line number Diff line number Diff line change
@@ -1 +1 @@
Experimental Temporal Nexus start handlers now accept `(client, input)` and typed cancel overrides accept only their options. Use `temporalio.nexus.info()` for invocation metadata and a read-only cancellation token.
Experimental Temporal Nexus start handlers now accept `(client, input)` and typed cancel overrides accept only their options. Use `temporalio.nexus.info()` for invocation metadata and a read-only cancellation token, and return a typed payload directly from `@temporal_operation` for synchronous completion.
64 changes: 62 additions & 2 deletions temporalio/client/_nexus.py
Original file line number Diff line number Diff line change
Expand Up @@ -656,7 +656,7 @@ async def start_operation(
rpc_timeout: timedelta | None = None,
) -> NexusOperationHandle[OutputT]: ...

# Overload for temporal_operation methods
# Overloads for temporal_operation methods
@overload
@abstractmethod
async def start_operation(
Expand Down Expand Up @@ -687,6 +687,36 @@ async def start_operation(
rpc_timeout: timedelta | None = None,
) -> NexusOperationHandle[OutputT]: ...

@overload
@abstractmethod
async def start_operation(
self,
operation: Callable[
[
NexusServiceType,
temporalio.nexus.TemporalNexusClient,
InputT,
],
Awaitable[OutputT],
],
arg: InputT,
*,
id: str,
id_reuse_policy: temporalio.common.NexusOperationIDReusePolicy = temporalio.common.NexusOperationIDReusePolicy.ALLOW_DUPLICATE,
id_conflict_policy: temporalio.common.NexusOperationIDConflictPolicy = temporalio.common.NexusOperationIDConflictPolicy.FAIL,
schedule_to_close_timeout: timedelta | None = None,
schedule_to_start_timeout: timedelta | None = None,
start_to_close_timeout: timedelta | None = None,
search_attributes: temporalio.common.TypedSearchAttributes | None = None,
summary: str | None = None,
headers: Mapping[str, str] | None = None,
completion_callbacks: Sequence[
temporalio.nexus.CompletionCallback[OutputT]
] = (),
rpc_metadata: Mapping[str, str | bytes] = {},
rpc_timeout: timedelta | None = None,
) -> NexusOperationHandle[OutputT]: ...

@abstractmethod
async def start_operation(
self,
Expand Down Expand Up @@ -932,7 +962,7 @@ async def execute_operation(
rpc_timeout: timedelta | None = None,
) -> OutputT: ...

# Overload for temporal_operation methods
# Overloads for temporal_operation methods
@overload
@abstractmethod
async def execute_operation(
Expand Down Expand Up @@ -963,6 +993,36 @@ async def execute_operation(
rpc_timeout: timedelta | None = None,
) -> OutputT: ...

@overload
@abstractmethod
async def execute_operation(
self,
operation: Callable[
[
NexusServiceType,
temporalio.nexus.TemporalNexusClient,
InputT,
],
Awaitable[OutputT],
],
arg: InputT,
*,
id: str,
id_reuse_policy: temporalio.common.NexusOperationIDReusePolicy = temporalio.common.NexusOperationIDReusePolicy.ALLOW_DUPLICATE,
id_conflict_policy: temporalio.common.NexusOperationIDConflictPolicy = temporalio.common.NexusOperationIDConflictPolicy.FAIL,
schedule_to_close_timeout: timedelta | None = None,
schedule_to_start_timeout: timedelta | None = None,
start_to_close_timeout: timedelta | None = None,
search_attributes: temporalio.common.TypedSearchAttributes | None = None,
summary: str | None = None,
headers: Mapping[str, str] | None = None,
completion_callbacks: Sequence[
temporalio.nexus.CompletionCallback[OutputT]
] = (),
rpc_metadata: Mapping[str, str | bytes] = {},
rpc_timeout: timedelta | None = None,
) -> OutputT: ...

@abstractmethod
async def execute_operation(
self,
Expand Down
68 changes: 40 additions & 28 deletions temporalio/nexus/_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from collections.abc import Awaitable, Callable
from typing import (
Any,
TypeAlias,
overload,
)
Expand All @@ -18,7 +19,7 @@
TemporalNexusClient,
TemporalOperationResult,
)
from temporalio.types import NexusServiceType
from temporalio.types import NexusServiceType, ReturnType

from ._operation_context import WorkflowRunOperationContext
from ._operation_handlers import (
Expand All @@ -28,7 +29,7 @@
from ._token import WorkflowHandle
from ._util import (
get_callable_name,
get_temporal_operation_start_method_input_and_output_type_annotations,
get_temporal_operation_start_method_types,
get_workflow_run_start_method_input_and_output_type_annotations,
is_async_callable,
set_operation_factory,
Expand Down Expand Up @@ -143,75 +144,86 @@ async def _start(


TemporalOperationStartHandlerFunc: TypeAlias = Callable[
[
NexusServiceType,
TemporalNexusClient,
InputT,
],
Awaitable[TemporalOperationResult[OutputT]],
[NexusServiceType, TemporalNexusClient, InputT],
Awaitable[TemporalOperationResult[OutputT] | OutputT],
]

_TemporalOperationMethod: TypeAlias = Callable[
[NexusServiceType, TemporalNexusClient, InputT], Awaitable[ReturnType]
]


@overload
def temporal_operation(
start: TemporalOperationStartHandlerFunc[NexusServiceType, InputT, OutputT],
) -> TemporalOperationStartHandlerFunc[NexusServiceType, InputT, OutputT]: ...
start: _TemporalOperationMethod[NexusServiceType, InputT, ReturnType],
) -> _TemporalOperationMethod[NexusServiceType, InputT, ReturnType]: ...


@overload
def temporal_operation(
*,
name: str | None = None,
) -> Callable[
[TemporalOperationStartHandlerFunc[NexusServiceType, InputT, OutputT]],
TemporalOperationStartHandlerFunc[NexusServiceType, InputT, OutputT],
[_TemporalOperationMethod[NexusServiceType, InputT, ReturnType]],
_TemporalOperationMethod[NexusServiceType, InputT, ReturnType],
]: ...


def temporal_operation(
start: None
| TemporalOperationStartHandlerFunc[NexusServiceType, InputT, OutputT] = None,
start: None | _TemporalOperationMethod[NexusServiceType, InputT, ReturnType] = None,
*,
name: str | None = None,
) -> (
TemporalOperationStartHandlerFunc[NexusServiceType, InputT, OutputT]
_TemporalOperationMethod[NexusServiceType, InputT, ReturnType]
| Callable[
[TemporalOperationStartHandlerFunc[NexusServiceType, InputT, OutputT]],
TemporalOperationStartHandlerFunc[NexusServiceType, InputT, OutputT],
[_TemporalOperationMethod[NexusServiceType, InputT, ReturnType]],
_TemporalOperationMethod[NexusServiceType, InputT, ReturnType],
]
):
"""Decorate an async ``(self, client, input)`` Nexus start method.

Return a :py:class:`TemporalOperationResult` and use :py:func:`info` for invocation information.
Declare and return the payload type to complete the Nexus operation synchronously.
Declare :py:class:`TemporalOperationResult` with the payload type to return an
explicit synchronous result or an asynchronous operation token. A method with an
unspecified return type, such as ``Any`` or no annotation, must return an explicit result.

Use :py:func:`info` to access information about the current invocation.

.. warning::
This API is experimental and unstable.
"""

def decorator(
start: TemporalOperationStartHandlerFunc[NexusServiceType, InputT, OutputT],
) -> TemporalOperationStartHandlerFunc[NexusServiceType, InputT, OutputT]:
start: _TemporalOperationMethod[NexusServiceType, InputT, ReturnType],
) -> _TemporalOperationMethod[NexusServiceType, InputT, ReturnType]:
if not is_async_callable(start):
raise RuntimeError(
f"{start} is not an `async def` method. "
"@temporal_operation must decorate an `async def` start method."
)
(
input_type,
output_type,
) = get_temporal_operation_start_method_input_and_output_type_annotations(start)
input_type, output_type, returns_wrapper = (
get_temporal_operation_start_method_types(start)
)

def operation_handler_factory(
instance: NexusServiceType,
) -> OperationHandler[InputT, OutputT]:
class _TemporalOperationHandler(TemporalOperationHandler):
) -> OperationHandler[InputT, Any]:
class _TemporalOperationHandler(TemporalOperationHandler[Any, Any]):
@override
async def start_operation(
self,
client: TemporalNexusClient,
input: InputT,
) -> TemporalOperationResult[OutputT]:
return await start(instance, client, input)
) -> TemporalOperationResult[Any]:
result = await start(instance, client, input)
if not returns_wrapper:
return TemporalOperationResult.sync(result)
if not isinstance(result, TemporalOperationResult):
raise TypeError(
f"@temporal_operation method {start} must return a "
"TemporalOperationResult."
)
return result

_TemporalOperationHandler.start_operation.__doc__ = start.__doc__
return _TemporalOperationHandler()
Expand Down
14 changes: 11 additions & 3 deletions temporalio/nexus/_notification.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
import temporalio.converter

from . import notifications
from ._operation_context import WorkflowRunOperationContext
from ._operation_context import (
WorkflowRunOperationContext,
)
from ._temporal_client import TemporalNexusClient, TemporalOperationResult
from ._token import WorkflowHandle
from ._util import get_operation_factory
Expand Down Expand Up @@ -259,7 +261,10 @@ def create_completion_callback(
temporalio.common.RawValue, HandlerSourceContextT
],
],
Awaitable[TemporalOperationResult[notifications.OnCompleteResponse]],
Awaitable[
notifications.OnCompleteResponse
| TemporalOperationResult[notifications.OnCompleteResponse]
],
],
task_queue: str,
source_context: HandlerSourceContextT,
Expand All @@ -275,7 +280,10 @@ def create_completion_callback(
TemporalNexusClient,
notifications.OnCompleteRequest[HandlerOutputT, HandlerSourceContextT],
],
Awaitable[TemporalOperationResult[notifications.OnCompleteResponse]],
Awaitable[
notifications.OnCompleteResponse
| TemporalOperationResult[notifications.OnCompleteResponse]
],
],
task_queue: str,
source_context: HandlerSourceContextT,
Expand Down
Loading
Loading