|
| 1 | +""" |
| 2 | +Caller workflow that demonstrates Nexus operation cancellation. |
| 3 | +
|
| 4 | +Fans out 5 concurrent Nexus hello operations (one per language), takes the first |
| 5 | +result, and cancels the rest using WAIT_REQUESTED cancellation semantics. |
| 6 | +""" |
| 7 | + |
| 8 | +import asyncio |
| 9 | +from datetime import timedelta |
| 10 | + |
| 11 | +from temporalio import workflow |
| 12 | +from temporalio.exceptions import CancelledError, NexusOperationError |
| 13 | + |
| 14 | +with workflow.unsafe.imports_passed_through(): |
| 15 | + from nexus_cancel.service import HelloInput, Language, NexusService |
| 16 | + |
| 17 | +NEXUS_ENDPOINT = "nexus-cancel-endpoint" |
| 18 | + |
| 19 | + |
| 20 | +@workflow.defn |
| 21 | +class HelloCallerWorkflow: |
| 22 | + def __init__(self) -> None: |
| 23 | + self.nexus_client = workflow.create_nexus_client( |
| 24 | + service=NexusService, |
| 25 | + endpoint=NEXUS_ENDPOINT, |
| 26 | + ) |
| 27 | + |
| 28 | + @workflow.run |
| 29 | + async def run(self, message: str) -> str: |
| 30 | + # Fan out 5 concurrent Nexus calls, one per language. |
| 31 | + # Each task starts and awaits its own operation so all race concurrently. |
| 32 | + async def run_operation(language: Language): |
| 33 | + handle = await self.nexus_client.start_operation( |
| 34 | + NexusService.hello, |
| 35 | + HelloInput(name=message, language=language), |
| 36 | + schedule_to_close_timeout=timedelta(seconds=10), |
| 37 | + cancellation_type=workflow.NexusOperationCancellationType.WAIT_REQUESTED, |
| 38 | + ) |
| 39 | + return await handle |
| 40 | + |
| 41 | + tasks = [asyncio.create_task(run_operation(lang)) for lang in Language] |
| 42 | + |
| 43 | + # Wait for the first operation to complete |
| 44 | + workflow.logger.info( |
| 45 | + f"Started {len(tasks)} operations, waiting for first to complete..." |
| 46 | + ) |
| 47 | + done, pending = await workflow.wait(tasks, return_when=asyncio.FIRST_COMPLETED) |
| 48 | + |
| 49 | + # Get the result from the first completed operation |
| 50 | + result = await done.pop() |
| 51 | + workflow.logger.info(f"First operation completed with: {result.message}") |
| 52 | + |
| 53 | + # Cancel all remaining operations |
| 54 | + workflow.logger.info(f"Cancelling {len(pending)} remaining operations...") |
| 55 | + for task in pending: |
| 56 | + task.cancel() |
| 57 | + |
| 58 | + # Wait for all cancellations to be acknowledged. |
| 59 | + # If the workflow completes before cancellation requests are delivered, |
| 60 | + # the server drops them. Waiting ensures all handlers receive the |
| 61 | + # cancellation. |
| 62 | + for task in pending: |
| 63 | + try: |
| 64 | + await task |
| 65 | + except (NexusOperationError, CancelledError): |
| 66 | + # Expected: the operation was cancelled |
| 67 | + workflow.logger.info("Operation was cancelled") |
| 68 | + |
| 69 | + return result.message |
0 commit comments