|
| 1 | +""" |
| 2 | +This file demonstrates how to implement a Nexus service. |
| 3 | +""" |
| 4 | + |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +import uuid |
| 8 | + |
| 9 | +import nexusrpc |
| 10 | +from temporalio import nexus |
| 11 | + |
| 12 | +from hello_nexus.handler.workflows import WorkflowStartedByNexusOperation |
| 13 | +from hello_nexus.service import MyInput, MyNexusService, MyOutput |
| 14 | + |
| 15 | + |
| 16 | +@nexusrpc.handler.service_handler(service=MyNexusService) |
| 17 | +class MyNexusServiceHandler: |
| 18 | + # You can create an __init__ method accepting what is needed by your operation |
| 19 | + # handlers to handle requests. You typically instantiate your service handler class |
| 20 | + # when starting your worker. See hello_nexus/basic/handler/worker.py. |
| 21 | + |
| 22 | + # This is a nexus operation that is backed by a Temporal workflow. The start method |
| 23 | + # starts a workflow, and returns a nexus operation token. Meanwhile, the workflow |
| 24 | + # executes in the background; Temporal server takes care of delivering the eventual |
| 25 | + # workflow result (success or failure) to the calling workflow. |
| 26 | + # |
| 27 | + # The token will be used by the caller if it subsequently wants to cancel the Nexus |
| 28 | + # operation. |
| 29 | + @nexus.workflow_run_operation |
| 30 | + async def my_workflow_run_operation( |
| 31 | + self, ctx: nexus.WorkflowRunOperationContext, input: MyInput |
| 32 | + ) -> nexus.WorkflowHandle[MyOutput]: |
| 33 | + return await ctx.start_workflow( |
| 34 | + WorkflowStartedByNexusOperation.run, |
| 35 | + input, |
| 36 | + id=str(uuid.uuid4()), |
| 37 | + ) |
| 38 | + |
| 39 | + # This is a Nexus operation that responds synchronously to all requests. That means |
| 40 | + # that unlike the workflow run operation above, in this case the `start` method |
| 41 | + # returns the final operation result. |
| 42 | + # |
| 43 | + # Sync operations are free to make arbitrary network calls, or perform CPU-bound |
| 44 | + # computations. Total execution duration must not exceed 10s. |
| 45 | + @nexusrpc.handler.sync_operation |
| 46 | + async def my_sync_operation( |
| 47 | + self, ctx: nexusrpc.handler.StartOperationContext, input: MyInput |
| 48 | + ) -> MyOutput: |
| 49 | + return MyOutput(message=f"Hello {input.name} from sync operation!") |
0 commit comments