diff --git a/README.md b/README.md index 461f79094..a04488c5a 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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. diff --git a/changelog/changed/curious-nexus-tern.md b/changelog/changed/curious-nexus-tern.md index d548884f5..28fd76f03 100644 --- a/changelog/changed/curious-nexus-tern.md +++ b/changelog/changed/curious-nexus-tern.md @@ -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. diff --git a/temporalio/client/_nexus.py b/temporalio/client/_nexus.py index ac449cbc5..7e6526b95 100644 --- a/temporalio/client/_nexus.py +++ b/temporalio/client/_nexus.py @@ -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( @@ -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, @@ -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( @@ -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, diff --git a/temporalio/nexus/_decorators.py b/temporalio/nexus/_decorators.py index 3baa64bdf..324879638 100644 --- a/temporalio/nexus/_decorators.py +++ b/temporalio/nexus/_decorators.py @@ -2,6 +2,7 @@ from collections.abc import Awaitable, Callable from typing import ( + Any, TypeAlias, overload, ) @@ -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 ( @@ -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, @@ -143,19 +144,19 @@ 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 @@ -163,55 +164,66 @@ 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() diff --git a/temporalio/nexus/_notification.py b/temporalio/nexus/_notification.py index 35d4e6848..044c0f5d4 100644 --- a/temporalio/nexus/_notification.py +++ b/temporalio/nexus/_notification.py @@ -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 @@ -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, @@ -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, diff --git a/temporalio/nexus/_util.py b/temporalio/nexus/_util.py index cb7dbe24a..168128cb5 100644 --- a/temporalio/nexus/_util.py +++ b/temporalio/nexus/_util.py @@ -2,6 +2,8 @@ import functools import inspect +import sys +import types import typing import warnings from collections.abc import Awaitable, Callable @@ -9,11 +11,15 @@ Any, ) +if sys.version_info >= (3, 12): + from typing import TypeAliasType + import nexusrpc from nexusrpc import ( InputT, OutputT, ) +from nexusrpc.handler import StartOperationResultAsync, StartOperationResultSync from temporalio.nexus._operation_context import WorkflowRunOperationContext from temporalio.nexus._temporal_client import ( @@ -48,35 +54,63 @@ def get_workflow_run_start_method_input_and_output_type_annotations( ) -def get_temporal_operation_start_method_input_and_output_type_annotations( - start: Callable[ - [ - NexusServiceType, - TemporalNexusClient, - InputT, - ], - Awaitable[TemporalOperationResult[OutputT]], - ], -) -> tuple[ - type[InputT] | None, - type[OutputT] | None, -]: - """Return operation input and output types. - - ``start`` must be a type-annotated start method that returns a - :py:class:`temporalio.nexus.TemporalOperationResult`. - """ +def get_temporal_operation_start_method_types( + start: Callable[..., Any], +) -> tuple[type[Any] | None, type[Any] | None, bool]: + """Return the input type, payload type, and whether the annotation requires a wrapper.""" try: inspect.signature(start).bind(None, None, None) except TypeError as err: raise TypeError( f"@temporal_operation method {start} must accept (self, client, input)." ) from err - return _get_wrapped_start_method_input_and_output_type_annotations( - start, - expected_param_types=(TemporalNexusClient,), - expected_return_origin=TemporalOperationResult, + + input_type, return_type = _get_start_method_input_and_output_type_annotations( + start, expected_param_types=(TemporalNexusClient,) + ) + if sys.version_info >= (3, 12): + aliases: set[TypeAliasType] = set() + while ( + isinstance(return_type, TypeAliasType) and not return_type.__type_params__ + ): + if return_type in aliases: + raise TypeError( + f"@temporal_operation method {start} has a cyclic return type alias." + ) + aliases.add(return_type) + value = return_type.__value__ + return_type = type(None) if value is None else value + + if return_type is None or return_type is Any: + return input_type, None, True + + origin = typing.get_origin(return_type) or return_type + if isinstance(origin, type) and issubclass(origin, TemporalOperationResult): + args = typing.get_args(return_type) + return input_type, args[0] if len(args) == 1 else None, True + + result_types = ( + (typing.get_origin(arg) or arg for arg in typing.get_args(return_type)) + if origin in (typing.Union, types.UnionType) # pyright: ignore[reportDeprecated] + else (origin,) ) + if any( + isinstance(result_type, type) + and issubclass( + result_type, + ( + TemporalOperationResult, + StartOperationResultSync, + StartOperationResultAsync, + ), + ) + for result_type in result_types + ): + raise TypeError( + f"@temporal_operation method {start} must declare a payload type or " + "TemporalOperationResult with the payload type inside the wrapper." + ) + return input_type, return_type, False def _get_wrapped_start_method_input_and_output_type_annotations( diff --git a/temporalio/workflow/_nexus.py b/temporalio/workflow/_nexus.py index c58e90e1b..660891b0d 100644 --- a/temporalio/workflow/_nexus.py +++ b/temporalio/workflow/_nexus.py @@ -217,7 +217,7 @@ async def start_operation( event_groups: Sequence[EventGroup] | None = None, ) -> NexusOperationHandle[OutputT]: ... - # Overload for temporal_operation methods + # Overloads for temporal_operation methods @overload @abstractmethod async def start_operation( @@ -242,6 +242,30 @@ async def start_operation( event_groups: Sequence[EventGroup] | None = None, ) -> NexusOperationHandle[OutputT]: ... + @overload + @abstractmethod + async def start_operation( + self, + operation: Callable[ + [ + NexusServiceType, + temporalio.nexus.TemporalNexusClient, + InputT, + ], + Awaitable[OutputT], + ], + input: InputT, + *, + output_type: type[OutputT] | None = None, + schedule_to_close_timeout: timedelta | None = None, + schedule_to_start_timeout: timedelta | None = None, + start_to_close_timeout: timedelta | None = None, + cancellation_type: NexusOperationCancellationType = NexusOperationCancellationType.WAIT_COMPLETED, + headers: Mapping[str, str] | None = None, + summary: str | None = None, + event_groups: Sequence[EventGroup] | None = None, + ) -> NexusOperationHandle[OutputT]: ... + @abstractmethod async def start_operation( self, @@ -403,7 +427,7 @@ async def execute_operation( event_groups: Sequence[EventGroup] | None = None, ) -> OutputT: ... - # Overload for temporal_operation methods + # Overloads for temporal_operation methods @overload @abstractmethod async def execute_operation( @@ -428,6 +452,30 @@ async def execute_operation( event_groups: Sequence[EventGroup] | None = None, ) -> OutputT: ... + @overload + @abstractmethod + async def execute_operation( + self, + operation: Callable[ + [ + NexusServiceType, + temporalio.nexus.TemporalNexusClient, + InputT, + ], + Awaitable[OutputT], + ], + input: InputT, + *, + output_type: type[OutputT] | None = None, + schedule_to_close_timeout: timedelta | None = None, + schedule_to_start_timeout: timedelta | None = None, + start_to_close_timeout: timedelta | None = None, + cancellation_type: NexusOperationCancellationType = NexusOperationCancellationType.WAIT_COMPLETED, + headers: Mapping[str, str] | None = None, + summary: str | None = None, + event_groups: Sequence[EventGroup] | None = None, + ) -> OutputT: ... + @abstractmethod async def execute_operation( self, diff --git a/tests/nexus/test_handler_operation_definitions.py b/tests/nexus/test_handler_operation_definitions.py index 7a3e0e91d..3ef5bea67 100644 --- a/tests/nexus/test_handler_operation_definitions.py +++ b/tests/nexus/test_handler_operation_definitions.py @@ -3,8 +3,10 @@ and input/output types. """ +import typing import warnings from dataclasses import dataclass +from inspect import Signature from typing import Any, ClassVar, cast import nexusrpc.handler @@ -188,6 +190,79 @@ async def op( assert op.output_type == Output +@pytest.mark.parametrize( + ("annotation", "output_type"), + [ + (Signature.empty, None), + (Any, None), + (nexus.TemporalOperationResult, None), + (nexus.TemporalOperationResult[None], type(None)), + ], +) +async def test_temporal_operation_preserves_explicit_result_modes( + annotation: Any, output_type: type | None +): + result = nexus.TemporalOperationResult[None].sync(None) + + class Handler: + async def start(self, _client: nexus.TemporalNexusClient, _input: None) -> Any: + return result + + if annotation is Signature.empty: + del Handler.start.__annotations__["return"] + else: + Handler.start.__annotations__["return"] = annotation + + method = nexus.temporal_operation(Handler.start) + op = nexusrpc.get_operation(method) + assert op + assert op.output_type is output_type + handler = getattr(method, "__nexus_operation_factory__")(Handler()) + client = cast(nexus.TemporalNexusClient, object()) + assert await handler.start_operation(client, None) is result + + +async def test_temporal_operation_rejects_missing_explicit_result(): + class Handler: + @nexus.temporal_operation + async def start( + self, _client: nexus.TemporalNexusClient, _input: None + ) -> nexus.TemporalOperationResult[None]: + return cast(nexus.TemporalOperationResult[None], cast(object, None)) + + handler = getattr(Handler.start, "__nexus_operation_factory__")(Handler()) + client = cast(nexus.TemporalNexusClient, object()) + with pytest.raises(TypeError, match="must return a TemporalOperationResult"): + await handler.start_operation(client, None) + + +def test_temporal_operation_resolves_direct_payload_alias(): + alias_type = getattr(typing, "TypeAliasType", None) + if alias_type is None: + pytest.skip("Native type aliases require Python 3.12") + + class Handler: + async def echo(self, _client: nexus.TemporalNexusClient, value: str) -> str: + return value + + Handler.echo.__annotations__["return"] = alias_type("Payload", str) + method = nexus.temporal_operation(Handler.echo) + _, operation = get_operation_factory(method) + assert operation is not None + assert operation.output_type is str + + +def test_temporal_operation_rejects_mixed_return_modes(): + class Handler: + async def start( + self, _client: nexus.TemporalNexusClient, _input: None + ) -> nexus.TemporalOperationResult[None] | None: + return None + + with pytest.raises(TypeError, match="must declare a payload type or"): + nexus.temporal_operation(Handler.start) + + def test_temporal_operation_rejects_old_context_parameter(): async def start( _self: object, diff --git a/tests/nexus/test_nexus_type_errors.py b/tests/nexus/test_nexus_type_errors.py index 39956548c..82239f0f5 100644 --- a/tests/nexus/test_nexus_type_errors.py +++ b/tests/nexus/test_nexus_type_errors.py @@ -5,7 +5,7 @@ from dataclasses import dataclass from datetime import timedelta -from typing import Any, TypeAlias +from typing import Any, TypeAlias, assert_type from unittest.mock import Mock import nexusrpc @@ -708,6 +708,37 @@ async def my_temporal_operation( ) -> temporalio.nexus.TemporalOperationResult[None]: raise NotImplementedError + @temporalio.nexus.temporal_operation(name="direct_temporal_operation") + async def direct_temporal_operation( + self, + _client: temporalio.nexus.TemporalNexusClient, + _input: MyInput, + ) -> MyOutput | None: + return None + + +async def direct_temporal_operation_types(client: Client) -> None: + service = MyServiceHandlerWithoutServiceDefinition + operation = service.direct_temporal_operation + workflow_client = workflow.create_nexus_client(service=service, endpoint="endpoint") + assert_type( + await workflow_client.start_operation(operation, MyInput()), + workflow.NexusOperationHandle[MyOutput | None], + ) + assert_type( + await workflow_client.execute_operation(operation, MyInput()), MyOutput | None + ) + + nexus_client = client.create_nexus_client(service, "endpoint") + assert_type( + await nexus_client.start_operation(operation, MyInput(), id="op"), + NexusOperationHandle[MyOutput | None], + ) + assert_type( + await nexus_client.execute_operation(operation, MyInput(), id="op"), + MyOutput | None, + ) + _handler: TemporalOperationStartHandlerFunc[ MyServiceHandler, diff --git a/tests/nexus/test_temporal_operation.py b/tests/nexus/test_temporal_operation.py index 307d7eb30..d1e840dbc 100644 --- a/tests/nexus/test_temporal_operation.py +++ b/tests/nexus/test_temporal_operation.py @@ -1,4 +1,5 @@ import asyncio +import typing import uuid from dataclasses import dataclass from datetime import timedelta @@ -64,6 +65,11 @@ class Input: expect_sync_response: bool = False +@dataclass +class DirectResult: + value: str + + def test_temporal_operation_result_validates_single_result_kind() -> None: assert nexus.TemporalOperationResult.sync(None).value is None assert nexus.TemporalOperationResult.async_token("token").token == "token" @@ -142,6 +148,7 @@ class TestService: concurrent_start: Operation[Input, str] retry_after_failed_start: Operation[Input, str] sync_result: Operation[Input, str] + direct_result: Operation[Input, list[DirectResult] | None] custom_cancel: Operation[str, None] update_op: Operation[Input, str] bad_update_stage_op: Operation[Input, str] @@ -281,6 +288,14 @@ async def sync_result( ) -> nexus.TemporalOperationResult[str]: return nexus.TemporalOperationResult.sync(input.value) + @nexus.temporal_operation(name="direct_result") + async def direct_result( + self, _client: nexus.TemporalNexusClient, input: Input + ) -> list[DirectResult] | None: + if input.value: + return [DirectResult(value=input.value)] + return None + @operation_handler def custom_cancel(self) -> nexus.TemporalOperationHandler[str, None]: service_handler = self @@ -1568,6 +1583,111 @@ async def test_temporal_operation_sync_result(client: Client, env: WorkflowEnvir ) +@workflow.defn +class DirectResultCaller: + @workflow.run + async def run(self, input: Input) -> list[DirectResult] | None: + client = workflow.create_nexus_client( + service=TestServiceHandler, + endpoint=make_nexus_endpoint_name(input.task_queue), + ) + result = await client.execute_operation( + TestServiceHandler.direct_result, + input, + schedule_to_close_timeout=timedelta(seconds=5), + ) + if result is not None: + assert type(result[0]) is DirectResult + return result + + +@pytest.mark.parametrize("sync", [True, False]) +async def test_temporal_operation_accepts_aliased_explicit_result( + client: Client, env: WorkflowEnvironment, sync: bool +) -> None: + alias_type = getattr(typing, "TypeAliasType", None) + if alias_type is None: + pytest.skip("Native type aliases require Python 3.12") + if env.supports_time_skipping_v1: + pytest.skip("Standalone Nexus Operation tests don't work with time skipping") + + @service + class AliasService: + echo: Operation[Input, str] + + class Handler: + async def echo( + self, client: nexus.TemporalNexusClient, input: Input + ) -> nexus.TemporalOperationResult[str]: + if sync: + return nexus.TemporalOperationResult.sync(input.value) + return await client.start_workflow( + EchoWorkflow.run, input, id=str(uuid.uuid4()) + ) + + Handler.echo.__annotations__["return"] = alias_type( + "Result", nexus.TemporalOperationResult[str] + ) + setattr(Handler, "echo", nexus.temporal_operation(Handler.echo)) + handler = service_handler(service=AliasService)(Handler) + task_queue = str(uuid.uuid4()) + endpoint = make_nexus_endpoint_name(task_queue) + await env.create_nexus_endpoint(endpoint, task_queue) + async with Worker( + client, + task_queue=task_queue, + workflows=[EchoWorkflow], + nexus_service_handlers=[handler()], + ): + nexus_client = client.create_nexus_client(AliasService, endpoint) + assert ( + await nexus_client.execute_operation( + AliasService.echo, + Input(value="echo", task_queue=task_queue), + id=str(uuid.uuid4()), + schedule_to_close_timeout=timedelta(seconds=5), + ) + == "echo" + ) + + +@pytest.mark.parametrize( + ("value", "expected"), [("test", [DirectResult("test")]), ("", None)] +) +async def test_temporal_operation_direct_result( + client: Client, + env: WorkflowEnvironment, + value: str, + expected: list[DirectResult] | None, +): + task_queue = str(uuid.uuid4()) + await env.create_nexus_endpoint(make_nexus_endpoint_name(task_queue), task_queue) + async with Worker( + client, + task_queue=task_queue, + nexus_service_handlers=[TestServiceHandler()], + workflows=[DirectResultCaller], + ): + handle = await client.start_workflow( + DirectResultCaller.run, + Input(value=value, task_queue=task_queue), + task_queue=task_queue, + id=str(uuid.uuid4()), + ) + assert await handle.result() == expected + nexus_events = [ + event.event_type + for event in (await handle.fetch_history()).events + if EventType.Name(event.event_type).startswith( + "EVENT_TYPE_NEXUS_OPERATION_" + ) + ] + assert nexus_events == [ + EventType.EVENT_TYPE_NEXUS_OPERATION_SCHEDULED, + EventType.EVENT_TYPE_NEXUS_OPERATION_COMPLETED, + ] + + async def test_temporal_operation_observes_invocation_timeout( client: Client, env: WorkflowEnvironment ) -> None: @@ -1583,7 +1703,7 @@ class TimeoutService: @nexus.temporal_operation async def wait_for_cancellation( self, _client: nexus.TemporalNexusClient, _input: None - ) -> nexus.TemporalOperationResult[None]: + ) -> None: token = nexus.info().cancellation_token assert not token.is_cancelled() assert token.cancellation_reason() is None @@ -1600,7 +1720,6 @@ async def wait_for_cancellation( await asyncio.wait_for(token.wait_until_cancelled(), timeout=1) observed.set_result(token) raise - return nexus.TemporalOperationResult.sync(None) task_queue = str(uuid.uuid4()) endpoint_name = make_nexus_endpoint_name(task_queue)