-
Notifications
You must be signed in to change notification settings - Fork 230
Expand file tree
/
Copy pathtest_temporal_operation.py
More file actions
1737 lines (1511 loc) · 60.8 KB
/
Copy pathtest_temporal_operation.py
File metadata and controls
1737 lines (1511 loc) · 60.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import uuid
from dataclasses import dataclass
from datetime import timedelta
import nexusrpc
import pytest
from nexusrpc import HandlerErrorType, Operation, service
from nexusrpc.handler import (
CancelOperationContext,
OperationTaskCancellation,
operation_handler,
service_handler,
)
from typing_extensions import override
import temporalio.exceptions
from temporalio import activity, nexus, workflow
from temporalio.api.activity.v1 import ActivityExecutionInfo
from temporalio.api.common.v1 import Link
from temporalio.client import (
ActivityExecutionStatus,
Client,
NexusOperationFailureError,
WorkflowExecutionStatus,
WorkflowFailureError,
)
from temporalio.common import (
NexusOperationExecutionStatus,
RetryPolicy,
WorkflowIDConflictPolicy,
)
from temporalio.nexus._token import OperationToken, OperationTokenType
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker
from tests.helpers import EventType, assert_event_subsequence, assert_eventually
from tests.helpers.nexus import (
assert_links_match,
expected_nexus_operation_link,
make_nexus_endpoint_name,
)
# Cloud CI's namespace credentials cannot manage Nexus endpoints.
# See https://github.com/temporalio/sdk-python/issues/1704.
pytestmark = pytest.mark.requires_local_server
@dataclass
class Input:
value: str
task_queue: str
update_value: str = ""
update_id: str = ""
expect_sync_response: bool = False
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"
with pytest.raises(ValueError, match="exactly one of value or token"):
nexus.TemporalOperationResult()
with pytest.raises(ValueError, match="exactly one of value or token"):
nexus.TemporalOperationResult(value="value", token="token")
def test_temporal_operation_result_validates_token() -> None:
with pytest.raises(ValueError, match="non-empty string"):
nexus.TemporalOperationResult.async_token("")
with pytest.raises(ValueError, match="non-empty string"):
nexus.TemporalOperationResult(token="")
with pytest.raises(ValueError, match="non-empty string"):
nexus.TemporalOperationResult(token=123) # type: ignore
@workflow.defn
class EchoWorkflow:
@workflow.run
async def run(self, input: Input) -> str:
return input.value
@activity.defn
async def echo_activity(input: Input) -> str:
return input.value
@activity.defn
async def raise_error_activity() -> None:
raise temporalio.exceptions.ApplicationError(
"test-activity-error-message",
type="test-activity-error-type",
non_retryable=True,
)
@activity.defn
async def wait_for_cancel_activity() -> None:
# Heartbeat in a loop so the activity receives cancellation. Letting the
# resulting CancelledError bubble out transitions the activity to CANCELED.
while True:
await asyncio.sleep(0.3)
activity.heartbeat()
@service
class TestService:
echo: Operation[Input, str]
blocking: Operation[None, None]
double_start: Operation[Input, None]
concurrent_start: Operation[Input, str]
retry_after_failed_start: Operation[Input, str]
sync_result: Operation[Input, str]
custom_cancel: Operation[str, None]
update_op: Operation[Input, str]
query_op: Operation[str, bool]
echo_activity: Operation[Input, str]
error_activity: Operation[Input, None]
blocking_activity: Operation[str, None]
custom_cancel_activity: Operation[str, None]
double_start_activity: Operation[Input, None]
mixed_start: Operation[Input, None]
@service_handler(service=TestService)
class TestServiceHandler:
# tell Pytest this is not a test class
__test__ = False
def __init__(self) -> None:
self.started_custom_cancel_workflow = asyncio.Event()
self.started_custom_cancel_activity = asyncio.Event()
self.custom_cancel_activity_called = asyncio.Event()
@nexus.temporal_operation
async def echo(
self,
_ctx: nexus.TemporalStartOperationContext,
client: nexus.TemporalNexusClient,
input: Input,
) -> nexus.TemporalOperationResult[str]:
return await client.start_workflow(
EchoWorkflow.run, input, id=f"echo-{input.value}"
)
@nexus.temporal_operation
async def blocking(
self,
_ctx: nexus.TemporalStartOperationContext,
client: nexus.TemporalNexusClient,
_input: None,
) -> nexus.TemporalOperationResult[None]:
return await client.start_workflow(
BlockingWorkflow.run, id=f"blocking-{uuid.uuid4()}"
)
@nexus.temporal_operation
async def double_start(
self,
_ctx: nexus.TemporalStartOperationContext,
client: nexus.TemporalNexusClient,
input: Input,
) -> nexus.TemporalOperationResult[None]:
await client.start_workflow(
EchoWorkflow.run, input, id=f"double-start-{uuid.uuid4()}"
)
await client.start_workflow(
EchoWorkflow.run, input, id=f"double-start-{uuid.uuid4()}"
)
return nexus.TemporalOperationResult.sync(None)
@nexus.temporal_operation
async def concurrent_start(
self,
_ctx: nexus.TemporalStartOperationContext,
client: nexus.TemporalNexusClient,
input: Input,
) -> nexus.TemporalOperationResult[str]:
results = await asyncio.gather(
client.start_workflow(
EchoWorkflow.run,
input,
id=f"concurrent-start-1-{uuid.uuid4()}",
),
client.start_workflow(
EchoWorkflow.run,
input,
id=f"concurrent-start-2-{uuid.uuid4()}",
),
return_exceptions=True,
)
async_results: list[nexus.TemporalOperationResult[str]] = []
handler_errors: list[nexusrpc.HandlerError] = []
for result in results:
if isinstance(result, nexus.TemporalOperationResult):
async_results.append(result)
elif isinstance(result, nexusrpc.HandlerError):
handler_errors.append(result)
elif isinstance(result, BaseException):
raise result
else:
raise RuntimeError(f"Unexpected concurrent start result: {result}")
if (
len(async_results) == 1
and len(handler_errors) == 1
and handler_errors[0].type == HandlerErrorType.BAD_REQUEST
):
return async_results[0]
raise RuntimeError(
"Expected one async workflow start and one BAD_REQUEST HandlerError, "
f"got {len(async_results)} starts and {len(handler_errors)} handler errors"
)
@nexus.temporal_operation
async def retry_after_failed_start(
self,
_ctx: nexus.TemporalStartOperationContext,
client: nexus.TemporalNexusClient,
input: Input,
) -> nexus.TemporalOperationResult[str]:
try:
await client.start_workflow(
BlockingWorkflow.run,
id=input.value,
id_conflict_policy=WorkflowIDConflictPolicy.FAIL,
)
except temporalio.exceptions.WorkflowAlreadyStartedError:
return await client.start_workflow(
EchoWorkflow.run,
input,
id=f"retry-after-failed-start-{uuid.uuid4()}",
)
raise RuntimeError("Expected first workflow start to fail")
@nexus.temporal_operation
async def sync_result(
self,
_ctx: nexus.TemporalStartOperationContext,
_client: nexus.TemporalNexusClient,
input: Input,
) -> nexus.TemporalOperationResult[str]:
return nexus.TemporalOperationResult.sync(input.value)
@operation_handler
def custom_cancel(self) -> nexus.TemporalOperationHandler[str, None]:
event = self.started_custom_cancel_workflow
class CustomCancelNexusOpHandler(nexus.TemporalOperationHandler[str, None]):
@override
async def start_operation(
self,
ctx: nexus.TemporalStartOperationContext,
client: nexus.TemporalNexusClient,
input: str,
) -> nexus.TemporalOperationResult[None]:
result = await client.start_workflow(BlockingWorkflow.run, id=input)
event.set()
return result
@override
async def cancel_workflow_run(
self,
ctx: nexus.TemporalCancelOperationContext,
options: nexus.CancelWorkflowRunOptions,
):
# get a handle to the workflow
handle = nexus.client().get_workflow_handle(options.workflow_id)
# cancel the workflow
await handle.cancel()
return CustomCancelNexusOpHandler()
@nexus.temporal_operation
async def update_op(
self,
_ctx: nexus.TemporalStartOperationContext,
client: nexus.TemporalNexusClient,
input: Input,
) -> nexus.TemporalOperationResult[str]:
# input.value carries the target workflow_id, input.update_value has actual update
return await client.start_workflow_update(
input.value,
UpdatableWorkflow.do_update,
input.update_value,
update_id=input.update_id,
)
@nexus.temporal_operation
async def query_op(
self,
_ctx: nexus.TemporalStartOperationContext,
client: nexus.TemporalNexusClient,
input: str,
) -> nexus.TemporalOperationResult[bool]:
handle = client.client.get_workflow_handle(input)
result = await handle.query(BlockingWorkflow.query_done)
return nexus.TemporalOperationResult.sync(result)
@nexus.temporal_operation
async def echo_activity(
self,
_ctx: nexus.TemporalStartOperationContext,
client: nexus.TemporalNexusClient,
input: Input,
) -> nexus.TemporalOperationResult[str]:
return await client.start_activity(
echo_activity,
input,
id=f"echo_activity-{uuid.uuid4()}",
start_to_close_timeout=timedelta(seconds=5),
)
@nexus.temporal_operation
async def error_activity(
self,
_ctx: nexus.TemporalStartOperationContext,
client: nexus.TemporalNexusClient,
_input: Input,
) -> nexus.TemporalOperationResult[None]:
# The activity raises immediately. With a single permitted attempt it
# fails the backing activity, which in turn fails the Nexus operation.
return await client.start_activity(
raise_error_activity,
id=f"error_activity-{uuid.uuid4()}",
start_to_close_timeout=timedelta(seconds=5),
retry_policy=RetryPolicy(maximum_attempts=1),
)
@nexus.temporal_operation
async def blocking_activity(
self,
_ctx: nexus.TemporalStartOperationContext,
client: nexus.TemporalNexusClient,
input: str,
) -> nexus.TemporalOperationResult[None]:
return await client.start_activity(
wait_for_cancel_activity,
id=input,
start_to_close_timeout=timedelta(seconds=30),
heartbeat_timeout=timedelta(seconds=1),
)
@nexus.temporal_operation
async def double_start_activity(
self,
_ctx: nexus.TemporalStartOperationContext,
client: nexus.TemporalNexusClient,
input: Input,
) -> nexus.TemporalOperationResult[None]:
await client.start_activity(
echo_activity,
input,
id=f"double-start-activity-{uuid.uuid4()}",
start_to_close_timeout=timedelta(seconds=5),
)
await client.start_activity(
echo_activity,
input,
id=f"double-start-activity-{uuid.uuid4()}",
start_to_close_timeout=timedelta(seconds=5),
)
return nexus.TemporalOperationResult.sync(None)
@nexus.temporal_operation
async def mixed_start(
self,
_ctx: nexus.TemporalStartOperationContext,
client: nexus.TemporalNexusClient,
input: Input,
) -> nexus.TemporalOperationResult[None]:
# Starting a workflow reserves the single async start, so the subsequent
# start_activity must hit the same guard and raise a BAD_REQUEST error.
await client.start_workflow(
EchoWorkflow.run, input, id=f"mixed-start-{uuid.uuid4()}"
)
await client.start_activity(
echo_activity,
input,
id=f"mixed-start-{uuid.uuid4()}",
start_to_close_timeout=timedelta(seconds=5),
)
return nexus.TemporalOperationResult.sync(None)
@operation_handler
def custom_cancel_activity(self) -> nexus.TemporalOperationHandler[str, None]:
started = self.started_custom_cancel_activity
cancel_called = self.custom_cancel_activity_called
class CustomCancelActivityNexusOpHandler(
nexus.TemporalOperationHandler[str, None]
):
@override
async def start_operation(
self,
ctx: nexus.TemporalStartOperationContext,
client: nexus.TemporalNexusClient,
input: str,
) -> nexus.TemporalOperationResult[None]:
result = await client.start_activity(
wait_for_cancel_activity,
id=input,
start_to_close_timeout=timedelta(seconds=30),
heartbeat_timeout=timedelta(seconds=1),
)
started.set()
return result
@override
async def cancel_activity(
self,
ctx: nexus.TemporalCancelOperationContext,
options: nexus.CancelActivityOptions,
):
# record that the custom override ran
cancel_called.set()
# get a handle to the activity and cancel it
handle = nexus.client().get_activity_handle(options.activity_id)
await handle.cancel()
return CustomCancelActivityNexusOpHandler()
@workflow.defn
class EchoWorkflowCaller:
@workflow.run
async def run(self, input: Input) -> str:
client = workflow.create_nexus_client(
service=TestService, endpoint=make_nexus_endpoint_name(input.task_queue)
)
return await client.execute_operation(TestService.echo, input)
async def test_temporal_operation_start_workflow(
client: Client, env: WorkflowEnvironment
):
task_queue = str(uuid.uuid4())
endpoint_name = make_nexus_endpoint_name(task_queue)
await env.create_nexus_endpoint(endpoint_name, task_queue)
async with Worker(
env.client,
task_queue=task_queue,
nexus_service_handlers=[TestServiceHandler()],
workflows=[EchoWorkflow, EchoWorkflowCaller],
):
wf_handle = await client.start_workflow(
EchoWorkflowCaller.run,
Input(value="test", task_queue=task_queue),
task_queue=task_queue,
id=str(uuid.uuid4()),
)
result = await wf_handle.result()
assert result == "test"
await assert_event_subsequence(
wf_handle,
[
EventType.EVENT_TYPE_NEXUS_OPERATION_SCHEDULED,
EventType.EVENT_TYPE_NEXUS_OPERATION_STARTED,
EventType.EVENT_TYPE_NEXUS_OPERATION_COMPLETED,
],
)
async def test_temporal_operation_update_workflow(
client: Client, env: WorkflowEnvironment
) -> None:
if (
env.supports_time_skipping
): # time skipping server uses different dynamic configs
pytest.skip("Update workflow tests don't work with time-skipping server")
task_queue = str(uuid.uuid4())
endpoint_name = make_nexus_endpoint_name(task_queue)
await env.create_nexus_endpoint(endpoint_name, task_queue)
async with Worker(
env.client,
task_queue=task_queue,
nexus_service_handlers=[TestServiceHandler()],
workflows=[UpdatableWorkflow, UpdateWorkflowCaller],
):
update_workflow_id = f"updatable-workflow-{uuid.uuid4()}"
target_handle = await client.start_workflow(
UpdatableWorkflow.run, id=update_workflow_id, task_queue=task_queue
)
async def check_simple_update_and_links():
"""Run an update, check state changes from pending to created, verify forward and back links are correct"""
wf_handle = await client.start_workflow(
UpdateWorkflowCaller.run,
Input(
value=update_workflow_id,
task_queue=task_queue,
update_value="Created",
),
task_queue=task_queue,
id=f"update-workflow-caller-created-{uuid.uuid4()}",
)
result = await wf_handle.result()
assert result == "Updated workflow status from Pending to Created"
# assert expected events are in expected sequence in caller history
await assert_event_subsequence(
wf_handle,
[
EventType.EVENT_TYPE_NEXUS_OPERATION_SCHEDULED,
EventType.EVENT_TYPE_NEXUS_OPERATION_STARTED,
EventType.EVENT_TYPE_NEXUS_OPERATION_COMPLETED,
],
)
# now, check the links
caller_history = await wf_handle.fetch_history()
handler_history = await target_handle.fetch_history()
scheduled_event = next(
e
for e in caller_history.events
if e.event_type == EventType.EVENT_TYPE_NEXUS_OPERATION_SCHEDULED
)
caller_request_id = (
scheduled_event.nexus_operation_scheduled_event_attributes.request_id
)
assert target_handle.result_run_id is not None
# from caller ns to target ns
expected_forward_link = Link(
workflow_event=Link.WorkflowEvent(
namespace=client.namespace,
workflow_id=update_workflow_id,
run_id=target_handle.result_run_id,
request_id_ref=Link.WorkflowEvent.RequestIdReference(
request_id=caller_request_id,
event_type=EventType.EVENT_TYPE_WORKFLOW_EXECUTION_UPDATE_ACCEPTED,
),
)
)
assert wf_handle.result_run_id is not None
# from target ns back to caller ns
expected_backward_link = Link(
workflow_event=Link.WorkflowEvent(
namespace=client.namespace,
workflow_id=wf_handle.id,
run_id=wf_handle.result_run_id,
event_ref=Link.WorkflowEvent.EventReference(
event_id=scheduled_event.event_id,
event_type=EventType.EVENT_TYPE_NEXUS_OPERATION_SCHEDULED,
),
)
)
caller_links = [
link
for e in caller_history.events
if e.event_type == EventType.EVENT_TYPE_NEXUS_OPERATION_STARTED
for link in e.links
]
handler_links = [
link
for e in handler_history.events
if e.event_type
== EventType.EVENT_TYPE_WORKFLOW_EXECUTION_UPDATE_ACCEPTED
for link in e.links
]
assert expected_forward_link in caller_links
assert expected_backward_link in handler_links
async def check_sequential_updates_consistent():
"""Run updates back-to-back, verify update isnt re-processed"""
stable_update_id = "sequential-update"
wf_handle = await client.start_workflow(
UpdateWorkflowCaller.run,
Input(
value=update_workflow_id,
task_queue=task_queue,
update_value="Processed",
update_id=stable_update_id,
),
task_queue=task_queue,
id="sequential-update-workflow-caller-processed-0",
)
result = await wf_handle.result()
assert result == "Updated workflow status from Created to Processed"
# same update_id -> wont be processed again, receives a sync result
wf_handle = await client.start_workflow(
UpdateWorkflowCaller.run,
Input(
value=update_workflow_id,
task_queue=task_queue,
update_value="Processed",
update_id=stable_update_id,
expect_sync_response=True,
),
task_queue=task_queue,
id="sequential-update-workflow-caller-processed-1",
)
result = await wf_handle.result()
assert result == "Updated workflow status from Created to Processed"
async def check_parallel_updates_idempotent_and_finish():
"""Run multiple updates in parallel, verify they are idempotent and finish with same result"""
stable_id = "parallel-updates-id"
num_parallel = 3
gate = asyncio.Event()
async def run_update(i: int) -> str:
await gate.wait()
wf_handle = await client.start_workflow(
UpdateWorkflowCaller.run,
Input(
value=update_workflow_id,
task_queue=task_queue,
update_value="Completed",
update_id=stable_id,
),
task_queue=task_queue,
id=f"parallel-update-workflow-caller-completed-{i}",
)
return await wf_handle.result()
tasks = [asyncio.create_task(run_update(i)) for i in range(num_parallel)]
gate.set()
results = await asyncio.gather(*tasks)
for result in results:
assert result == "Updated workflow status from Processed to Completed"
async def check_updates_on_completed_workflows_fail():
"""The handler workflow already finished at this point, further updaes should just fail"""
wf_handle = await client.start_workflow(
UpdateWorkflowCaller.run,
Input(
value=update_workflow_id,
task_queue=task_queue,
update_value="dummy, will fail anyway",
),
task_queue=task_queue,
id=f"{uuid.uuid4()}",
)
with pytest.raises(WorkflowFailureError):
await wf_handle.result()
await check_simple_update_and_links()
await check_sequential_updates_consistent()
await check_parallel_updates_idempotent_and_finish()
await check_updates_on_completed_workflows_fail()
async def test_temporal_operation_update_workflow_delayed(
client: Client, env: WorkflowEnvironment
) -> None:
if (
env.supports_time_skipping
): # time skipping server uses different dynamic configs
pytest.skip("Update workflow tests don't work with time-skipping server")
task_queue = str(uuid.uuid4())
endpoint_name = make_nexus_endpoint_name(task_queue)
await env.create_nexus_endpoint(endpoint_name, task_queue)
update_workflow_id = f"another-updatable-workflow-{uuid.uuid4()}"
# start both caller and handler without starting worker
wf_handle = await client.start_workflow(
UpdateWorkflowCaller.run,
Input(
value=update_workflow_id,
task_queue=task_queue,
update_value="Completed",
),
task_queue=task_queue,
id=f"update-workflow-caller-created-{uuid.uuid4()}",
)
target_handle = await client.start_workflow(
UpdatableWorkflow.run, id=update_workflow_id, task_queue=task_queue
)
# now, start the worker, it should process both the handler
# and the caller and finish the enqueued update
async with Worker(
env.client,
task_queue=task_queue,
nexus_service_handlers=[TestServiceHandler()],
workflows=[UpdatableWorkflow, UpdateWorkflowCaller],
):
result = await wf_handle.result()
assert result == "Updated workflow status from Pending to Completed"
await assert_event_subsequence(
wf_handle,
[
EventType.EVENT_TYPE_NEXUS_OPERATION_SCHEDULED,
EventType.EVENT_TYPE_NEXUS_OPERATION_STARTED,
EventType.EVENT_TYPE_NEXUS_OPERATION_COMPLETED,
],
)
caller_history = await wf_handle.fetch_history()
handler_history = await target_handle.fetch_history()
scheduled_event = next(
e
for e in caller_history.events
if e.event_type == EventType.EVENT_TYPE_NEXUS_OPERATION_SCHEDULED
)
caller_request_id = (
scheduled_event.nexus_operation_scheduled_event_attributes.request_id
)
assert target_handle.result_run_id is not None
expected_forward_link = Link(
workflow_event=Link.WorkflowEvent(
namespace=client.namespace,
workflow_id=update_workflow_id,
run_id=target_handle.result_run_id,
request_id_ref=Link.WorkflowEvent.RequestIdReference(
request_id=caller_request_id,
event_type=EventType.EVENT_TYPE_WORKFLOW_EXECUTION_UPDATE_ACCEPTED,
),
)
)
assert wf_handle.result_run_id is not None
expected_backward_link = Link(
workflow_event=Link.WorkflowEvent(
namespace=client.namespace,
workflow_id=wf_handle.id,
run_id=wf_handle.result_run_id,
event_ref=Link.WorkflowEvent.EventReference(
event_id=scheduled_event.event_id,
event_type=EventType.EVENT_TYPE_NEXUS_OPERATION_SCHEDULED,
),
)
)
caller_links = [
link
for e in caller_history.events
if e.event_type == EventType.EVENT_TYPE_NEXUS_OPERATION_STARTED
for link in e.links
]
handler_links = [
link
for e in handler_history.events
if e.event_type == EventType.EVENT_TYPE_WORKFLOW_EXECUTION_UPDATE_ACCEPTED
for link in e.links
]
assert expected_forward_link in caller_links
assert expected_backward_link in handler_links
async def test_temporal_operation_cancel_rejects_unknown_tokens():
class FakeNexusTaskCancellation(OperationTaskCancellation):
def is_cancelled(self) -> bool:
return False
def cancellation_reason(self) -> str | None:
return None
def wait_until_cancelled_sync(self, timeout: float | None = None) -> bool:
return False
async def wait_until_cancelled(self) -> None:
return None
def cancel(self, _reason: str) -> bool:
return False
cancel_ctx = CancelOperationContext(
service="TestService",
operation="echo",
headers={},
task_cancellation=FakeNexusTaskCancellation(),
)
service_handler = TestServiceHandler()
# Use a factory style operation form the handler to allow calling cancel directly
op_handler = service_handler.custom_cancel()
# Invalid token type
token = OperationToken(type=30, namespace="default") # type: ignore
with pytest.raises(nexusrpc.HandlerError) as err:
await op_handler.cancel(cancel_ctx, token.encode())
assert err.value.type == HandlerErrorType.INTERNAL
assert not err.value.retryable
underlying = err.value.__cause__
assert isinstance(underlying, TypeError)
assert "unknown token type, got 30" in str(underlying)
# Workflow ID missing from workflow type
token = OperationToken(type=OperationTokenType.WORKFLOW, namespace="default")
with pytest.raises(nexusrpc.HandlerError) as err:
await op_handler.cancel(cancel_ctx, token.encode())
assert err.value.type == HandlerErrorType.INTERNAL
assert not err.value.retryable
underlying = err.value.__cause__
assert isinstance(underlying, TypeError)
assert "expected non-empty workflow id for token type `WORKFLOW`" in str(underlying)
# Activity ID missing from activity type
token = OperationToken(type=OperationTokenType.ACTIVITY, namespace="default")
with pytest.raises(nexusrpc.HandlerError) as err:
await op_handler.cancel(cancel_ctx, token.encode())
assert err.value.type == HandlerErrorType.INTERNAL
assert not err.value.retryable
underlying = err.value.__cause__
assert isinstance(underlying, TypeError)
assert "expected non-empty activity id for token type `ACTIVITY`" in str(underlying)
activity_op_handler = service_handler.custom_cancel_activity()
for run_id in (None, ""):
token = OperationToken(
type=OperationTokenType.ACTIVITY,
namespace="default",
activity_id="activity-id",
run_id=run_id,
)
with pytest.raises(nexusrpc.HandlerError) as err:
await activity_op_handler.cancel(cancel_ctx, token.encode())
assert err.value.type == HandlerErrorType.INTERNAL
assert not err.value.retryable
assert not service_handler.custom_cancel_activity_called.is_set()
@workflow.defn
class BlockingWorkflow:
def __init__(self) -> None:
self.done: bool = False
@workflow.run
async def run(self) -> None:
await workflow.wait_condition(lambda: self.done)
@workflow.update
async def unblock(self):
self.done = True
@workflow.query
def query_done(self) -> bool:
return self.done
@workflow.defn
class QueryWorkflowCaller:
@workflow.run
async def run(self, input: Input) -> bool:
client = workflow.create_nexus_client(
service=TestService, endpoint=make_nexus_endpoint_name(input.task_queue)
)
return await client.execute_operation(TestService.query_op, input.value)
async def test_temporal_operation_query_workflow(
client: Client, env: WorkflowEnvironment
) -> None:
task_queue = str(uuid.uuid4())
endpoint_name = make_nexus_endpoint_name(task_queue)
await env.create_nexus_endpoint(endpoint_name, task_queue)
target_workflow_id = f"query-target-{uuid.uuid4()}"
async with Worker(
env.client,
task_queue=task_queue,
nexus_service_handlers=[TestServiceHandler()],
workflows=[BlockingWorkflow, QueryWorkflowCaller],
):
target_handle = await client.start_workflow(
BlockingWorkflow.run,
id=target_workflow_id,
task_queue=task_queue,
)
caller_handle = await client.start_workflow(
QueryWorkflowCaller.run,
Input(value=target_workflow_id, task_queue=task_queue),
id=f"query-caller-{uuid.uuid4()}",
task_queue=task_queue,
)
try:
assert not await caller_handle.result()
caller_history = await caller_handle.fetch_history()
completed_event = next(
event
for event in caller_history.events
if event.event_type == EventType.EVENT_TYPE_NEXUS_OPERATION_COMPLETED
)
target_history = await target_handle.fetch_history()
assert not any(event.links for event in target_history.events)
if not completed_event.links:
pytest.skip("server did not return a Workflow Query response link")
assert target_handle.result_run_id is not None
assert Link(
workflow=Link.Workflow(
namespace=client.namespace,
workflow_id=target_workflow_id,
run_id=target_handle.result_run_id,
reason="Query processed",
)
) in list(completed_event.links)
finally:
await target_handle.cancel()
@workflow.defn
class CancelBlockingWorkflowCaller:
op_started = False
@workflow.run
async def run(self, input: Input) -> None:
client = workflow.create_nexus_client(
service=TestService, endpoint=make_nexus_endpoint_name(input.task_queue)
)
op_handle = await client.start_operation(TestService.blocking, None)
self.op_started = True
return await op_handle
@workflow.update
async def wait_operation_started(self):
await workflow.wait_condition(lambda: self.op_started)
async def test_temporal_operation_cancel_workflow(
client: Client, env: WorkflowEnvironment
):
task_queue = str(uuid.uuid4())
endpoint_name = make_nexus_endpoint_name(task_queue)
await env.create_nexus_endpoint(endpoint_name, task_queue)
async with Worker(
env.client,
task_queue=task_queue,
nexus_service_handlers=[TestServiceHandler()],
workflows=[BlockingWorkflow, CancelBlockingWorkflowCaller],
):
wf_handle = await client.start_workflow(
CancelBlockingWorkflowCaller.run,
Input(value="test", task_queue=task_queue),
task_queue=task_queue,
id=f"blocking-{uuid.uuid4()}",
)
await wf_handle.execute_update(
CancelBlockingWorkflowCaller.wait_operation_started
)
await wf_handle.cancel()
await assert_event_subsequence(
wf_handle,
[
EventType.EVENT_TYPE_NEXUS_OPERATION_CANCEL_REQUESTED,
EventType.EVENT_TYPE_NEXUS_OPERATION_CANCEL_REQUEST_COMPLETED,
EventType.EVENT_TYPE_NEXUS_OPERATION_CANCELED,
],
)
async def test_customized_temporal_operation_cancel_workflow(
client: Client, env: WorkflowEnvironment
):
if env.supports_time_skipping:
pytest.skip(
"Standalone Nexus Operation tests don't work with time-skipping server"
)
task_queue = str(uuid.uuid4())
endpoint_name = make_nexus_endpoint_name(task_queue)
await env.create_nexus_endpoint(endpoint_name, task_queue)
service_handler = TestServiceHandler()
async with Worker(
env.client,
task_queue=task_queue,
nexus_service_handlers=[service_handler],
workflows=[BlockingWorkflow, CancelBlockingWorkflowCaller],
):
nexus_client = client.create_nexus_client(TestService, endpoint_name)
wf_id = f"custom-cancel-{uuid.uuid4()}"
op_handle = await nexus_client.start_operation(
TestService.custom_cancel, wf_id, id=str(uuid.uuid4())
)
await service_handler.started_custom_cancel_workflow.wait()
await op_handle.cancel()
async def check_cancelled():
wf_handle = client.get_workflow_handle(wf_id)
wf_desc = await wf_handle.describe()
assert wf_desc.status is WorkflowExecutionStatus.CANCELED
op_desc = await op_handle.describe()
assert op_desc.status is NexusOperationExecutionStatus.CANCELED
await assert_eventually(check_cancelled)
@workflow.defn
class DoubleStartWorkflowCaller: