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
20 changes: 19 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1625,14 +1625,23 @@ To get started quickly using Nexus with Temporal, see the Python Nexus sample:
https://github.com/temporalio/samples-python/tree/nexus/hello_nexus.


Two types of Nexus operation are supported, each using a decorator:
Nexus operation handlers can use one of these decorators:

- `@temporalio.nexus.workflow_run_operation`: a Nexus operation that is backed by a Temporal workflow. The operation
handler you write will start the handler workflow and then respond with a token indicating that the handler workflow
is in progress. When the handler workflow completes, Temporal server will automatically deliver the result (success or
failure) to the caller workflow.
- `@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.

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
current handler invocation, such as a request timeout. Worker Nexus inbound interceptors can read incoming headers from
`input.ctx.headers`.

The following steps are an overview of the [Python Nexus sample](
https://github.com/temporalio/samples-python/tree/nexus/hello_nexus).
Expand All @@ -1655,6 +1664,7 @@ https://github.com/temporalio/samples-python/tree/nexus/hello_nexus).
class MyNexusService:
my_sync_operation: nexusrpc.Operation[MyInput, MyOutput]
my_workflow_run_operation: nexusrpc.Operation[MyInput, MyOutput]
my_temporal_operation: nexusrpc.Operation[MyInput, MyOutput]
```

3. Implement your operation handlers in a service handler:
Expand All @@ -1676,6 +1686,14 @@ https://github.com/temporalio/samples-python/tree/nexus/hello_nexus).
input,
id=str(uuid.uuid4()),
)

@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}!")
)
```

4. Register your service handler with a Temporal worker.
Expand Down
1 change: 1 addition & 0 deletions changelog/changed/curious-nexus-tern.md
Original file line number Diff line number Diff line change
@@ -0,0 +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.
2 changes: 0 additions & 2 deletions temporalio/client/_nexus.py
Original file line number Diff line number Diff line change
Expand Up @@ -664,7 +664,6 @@ async def start_operation(
operation: Callable[
[
NexusServiceType,
temporalio.nexus.TemporalStartOperationContext,
temporalio.nexus.TemporalNexusClient,
InputT,
],
Expand Down Expand Up @@ -941,7 +940,6 @@ async def execute_operation(
operation: Callable[
[
NexusServiceType,
temporalio.nexus.TemporalStartOperationContext,
temporalio.nexus.TemporalNexusClient,
InputT,
],
Expand Down
6 changes: 2 additions & 4 deletions temporalio/nexus/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@
Info,
LoggerAdapter,
NexusCallback,
TemporalCancelOperationContext,
TemporalStartOperationContext,
OperationCancellationToken,
WorkflowRunOperationContext,
client,
in_operation,
Expand Down Expand Up @@ -46,9 +45,8 @@
"Info",
"LoggerAdapter",
"NexusCallback",
"OperationCancellationToken",
"WorkflowRunOperationContext",
"TemporalCancelOperationContext",
"TemporalStartOperationContext",
"client",
"create_completion_callback",
"in_operation",
Expand Down
27 changes: 6 additions & 21 deletions temporalio/nexus/_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,7 @@
)
from temporalio.types import NexusServiceType

from ._operation_context import (
TemporalStartOperationContext,
WorkflowRunOperationContext,
)
from ._operation_context import WorkflowRunOperationContext
from ._operation_handlers import (
TemporalOperationHandler,
WorkflowRunOperationHandler,
Expand Down Expand Up @@ -148,7 +145,6 @@ async def _start(
TemporalOperationStartHandlerFunc: TypeAlias = Callable[
[
NexusServiceType,
TemporalStartOperationContext,
TemporalNexusClient,
InputT,
],
Expand Down Expand Up @@ -184,7 +180,9 @@ def temporal_operation(
TemporalOperationStartHandlerFunc[NexusServiceType, InputT, OutputT],
]
):
"""Decorator marking a method as the start method for an operation that interacts with Temporal.
"""Decorate an async ``(self, client, input)`` Nexus start method.

Return a :py:class:`TemporalOperationResult` and use :py:func:`info` for invocation information.

.. warning::
This API is experimental and unstable.
Expand All @@ -204,29 +202,16 @@ def decorator(
) = get_temporal_operation_start_method_input_and_output_type_annotations(start)

def operation_handler_factory(
self: NexusServiceType,
instance: NexusServiceType,
) -> OperationHandler[InputT, OutputT]:
async def _start(
ctx: TemporalStartOperationContext,
client: TemporalNexusClient,
input: InputT,
) -> TemporalOperationResult[OutputT]:
return await start(
self,
ctx,
client,
input,
)

class _TemporalOperationHandler(TemporalOperationHandler):
@override
async def start_operation(
self,
ctx: TemporalStartOperationContext,
client: TemporalNexusClient,
input: InputT,
) -> TemporalOperationResult[OutputT]:
return await _start(ctx, client, input)
return await start(instance, client, input)

_TemporalOperationHandler.start_operation.__doc__ = start.__doc__
return _TemporalOperationHandler()
Expand Down
7 changes: 1 addition & 6 deletions temporalio/nexus/_notification.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,7 @@
import temporalio.converter

from . import notifications
from ._operation_context import (
TemporalStartOperationContext,
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 @@ -257,7 +254,6 @@ def create_completion_callback(
operation: Callable[
[
Any,
TemporalStartOperationContext,
TemporalNexusClient,
notifications.OnCompleteRequest[
temporalio.common.RawValue, HandlerSourceContextT
Expand All @@ -276,7 +272,6 @@ def create_completion_callback(
operation: Callable[
[
Any,
TemporalStartOperationContext,
TemporalNexusClient,
notifications.OnCompleteRequest[HandlerOutputT, HandlerSourceContextT],
],
Expand Down
112 changes: 77 additions & 35 deletions temporalio/nexus/_operation_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@
from nexusrpc.handler import (
CancelOperationContext,
OperationContext,
OperationTaskCancellation,
StartOperationContext,
)
from typing_extensions import Self

import temporalio.api.common.v1
import temporalio.api.nexus.v1
Expand Down Expand Up @@ -114,6 +114,38 @@ def reserve(self) -> Generator[None]:
)


class OperationCancellationToken:
"""Observe cancellation of the current Nexus handler invocation.

A request to cancel the Nexus operation itself is delivered separately to the
handler's cancel method. Get this token from :py:attr:`Info.cancellation_token`.
"""

def __init__(self, task_cancellation: OperationTaskCancellation) -> None:
"""Initialize the token. Obtain one from the operation info."""
self.__task_cancellation = task_cancellation

def is_cancelled(self) -> bool:
"""Return whether cancellation of the handler invocation was requested."""
return self.__task_cancellation.is_cancelled()

def cancellation_reason(self) -> str | None:
"""Return the reason for cancellation, if available."""
return self.__task_cancellation.cancellation_reason()

async def wait_until_cancelled(self) -> None:
"""Wait for cancellation of this invocation.

Async handlers can receive :py:class:`asyncio.CancelledError` at an await.
The worker records the cancellation reason before interrupting the handler.
"""
await self.__task_cancellation.wait_until_cancelled()

def wait_until_cancelled_sync(self, timeout: float | None = None) -> bool:
"""Return whether cancellation occurred within the given timeout in seconds."""
return self.__task_cancellation.wait_until_cancelled_sync(timeout)


@dataclass(frozen=True)
class Info:
"""Information about the running Nexus operation.
Expand All @@ -130,6 +162,44 @@ class Info:
task_queue: str
"""The task queue of the worker handling this Nexus operation."""

service: str
"""The service name for the current Nexus request."""

operation: str
"""The operation name for the current Nexus request."""

request_id: str | None
"""Opaque ID shared by retries of the same start request, if available.

Cancel invocations have no start request ID.
"""

cancellation_token: OperationCancellationToken
"""Read-only token for observing cancellation of this handler invocation."""

@classmethod
def _from_operation_context(
cls,
context: OperationContext,
*,
endpoint: str,
namespace: str,
task_queue: str,
) -> Info:
return cls(
endpoint=endpoint,
namespace=namespace,
task_queue=task_queue,
service=context.service,
operation=context.operation,
request_id=(
(context.request_id or None)
if isinstance(context, StartOperationContext)
else None
),
cancellation_token=OperationCancellationToken(context.task_cancellation),
)


def in_operation() -> bool:
"""Whether the current code is inside a Nexus operation."""
Expand All @@ -138,7 +208,7 @@ def in_operation() -> bool:

def info() -> Info:
"""Get the current Nexus operation information."""
return _temporal_context().info()
return _temporal_context().info


def client() -> temporalio.client.Client:
Expand Down Expand Up @@ -226,7 +296,7 @@ def _current_propagated_nexus_serialization_context() -> ( # pyright: ignore[re
if nexus_ctx is None:
return None
return temporalio.api.nexus.v1.PropagatedSerializationContext(
endpoint=nexus_ctx.info().endpoint,
endpoint=nexus_ctx.info.endpoint,
service=nexus_ctx.nexus_context.service,
operation=nexus_ctx.nexus_context.operation,
)
Expand All @@ -253,7 +323,7 @@ class _TemporalOperationCtx(Generic[_OperationCtxT]):
client: temporalio.client.Client
"""The Temporal client in use by the worker handling the current Nexus operation."""

info: Callable[[], Info]
info: Info
"""Temporal information about the running Nexus operation."""

nexus_context: _OperationCtxT
Expand All @@ -270,7 +340,7 @@ def metric_meter(self) -> temporalio.common.MetricMeter:
{
"nexus_service": self.nexus_context.service,
"nexus_operation": self.nexus_context.operation,
"task_queue": self.info().task_queue,
"task_queue": self.info.task_queue,
}
)
return self._metric_meter
Expand Down Expand Up @@ -642,34 +712,6 @@ def set(self) -> None:
_temporal_cancel_operation_context.set(self)


class TemporalStartOperationContext(StartOperationContext):
"""Context received by a Temporal Nexus operation when it is started.

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

@classmethod
def _from_start_operation_context(cls, ctx: StartOperationContext) -> Self:
return cls(
**{f.name: getattr(ctx, f.name) for f in dataclasses.fields(ctx)},
)


class TemporalCancelOperationContext(CancelOperationContext):
"""Context received by a Temporal Nexus operation when it is canceled.

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

@classmethod
def _from_cancel_operation_context(cls, ctx: CancelOperationContext) -> Self:
return cls(
**{f.name: getattr(ctx, f.name) for f in dataclasses.fields(ctx)},
)


class LoggerAdapter(logging.LoggerAdapter):
"""Logger adapter that adds Nexus operation context information."""

Expand All @@ -685,7 +727,7 @@ def process(
if tctx := _try_temporal_context():
extra["service"] = tctx.nexus_context.service
extra["operation"] = tctx.nexus_context.operation
extra["task_queue"] = tctx.info().task_queue
extra["task_queue"] = tctx.info.task_queue
kwargs["extra"] = extra | kwargs.get("extra", {})
return msg, kwargs

Expand Down Expand Up @@ -737,7 +779,7 @@ async def _start_nexus_backing_workflow(
arg=arg,
args=args,
id=id,
task_queue=task_queue or temporal_context.info().task_queue,
task_queue=task_queue or temporal_context.info.task_queue,
result_type=result_type,
execution_timeout=execution_timeout,
run_timeout=run_timeout,
Expand Down
Loading
Loading