-
Notifications
You must be signed in to change notification settings - Fork 198
Expand file tree
/
Copy path_impl.py
More file actions
1639 lines (1543 loc) · 66.2 KB
/
Copy path_impl.py
File metadata and controls
1639 lines (1543 loc) · 66.2 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
"""Client support for accessing Temporal."""
from __future__ import annotations
import asyncio
import inspect
import uuid
import warnings
from collections.abc import (
Callable,
Mapping,
)
from datetime import timedelta
from typing import (
TYPE_CHECKING,
Any,
cast,
)
from google.protobuf.internal.containers import MessageMap
import temporalio.api.common.v1
import temporalio.api.enums.v1
import temporalio.api.errordetails.v1
import temporalio.api.failure.v1
import temporalio.api.schedule.v1
import temporalio.api.taskqueue.v1
import temporalio.api.update.v1
import temporalio.api.workflowservice.v1
import temporalio.common
import temporalio.converter
import temporalio.exceptions
import temporalio.nexus
import temporalio.nexus._operation_context
from temporalio.activity import ActivityCancellationDetails
from temporalio.converter import (
ActivitySerializationContext,
StorageDriverActivityInfo,
StorageDriverStoreContext,
StorageDriverWorkflowInfo,
WorkflowSerializationContext,
)
from temporalio.service import (
RPCError,
RPCStatusCode,
)
from ..common import HeaderCodecBehavior
from ._activity import (
ActivityExecutionAsyncIterator,
ActivityExecutionCount,
ActivityExecutionDescription,
ActivityHandle,
AsyncActivityIDReference,
)
from ._exceptions import (
AsyncActivityCancelledError,
ScheduleAlreadyRunningError,
WorkflowQueryFailedError,
WorkflowQueryRejectedError,
WorkflowUpdateRPCTimeoutOrCancelledError,
)
from ._helpers import _apply_headers, _encode_user_metadata
from ._interceptor import (
BackfillScheduleInput,
CancelActivityInput,
CancelNexusOperationInput,
CancelWorkflowInput,
CompleteAsyncActivityInput,
CountActivitiesInput,
CountNexusOperationsInput,
CountWorkflowsInput,
CreateScheduleInput,
DeleteScheduleInput,
DescribeActivityInput,
DescribeNexusOperationInput,
DescribeScheduleInput,
DescribeWorkflowInput,
FailAsyncActivityInput,
FetchWorkflowHistoryEventsInput,
GetNexusOperationResultInput,
GetWorkerBuildIdCompatibilityInput,
GetWorkerTaskReachabilityInput,
HeartbeatAsyncActivityInput,
ListActivitiesInput,
ListNexusOperationsInput,
ListSchedulesInput,
ListWorkflowsInput,
OutboundInterceptor,
PauseScheduleInput,
QueryWorkflowInput,
ReportCancellationAsyncActivityInput,
SignalWorkflowInput,
StartActivityInput,
StartNexusOperationInput,
StartWorkflowInput,
StartWorkflowUpdateInput,
StartWorkflowUpdateWithStartInput,
TerminateActivityInput,
TerminateNexusOperationInput,
TerminateWorkflowInput,
TriggerScheduleInput,
UnpauseScheduleInput,
UpdateScheduleInput,
UpdateWithStartStartWorkflowInput,
UpdateWithStartUpdateWorkflowInput,
UpdateWorkerBuildIdCompatibilityInput,
)
from ._nexus import (
NexusOperationExecutionAsyncIterator,
NexusOperationExecutionCount,
NexusOperationExecutionDescription,
NexusOperationFailureError,
NexusOperationHandle,
)
from ._schedule import (
ScheduleAsyncIterator,
ScheduleDescription,
ScheduleHandle,
ScheduleUpdate,
ScheduleUpdateInput,
)
from ._worker_versioning import WorkerBuildIdVersionSets, WorkerTaskReachability
from ._workflow import (
WorkflowExecutionAsyncIterator,
WorkflowExecutionCount,
WorkflowExecutionDescription,
WorkflowExecutionStatus,
WorkflowHandle,
WorkflowHistoryEventAsyncIterator,
WorkflowUpdateHandle,
WorkflowUpdateStage,
)
if TYPE_CHECKING:
from ._client import Client
class _ClientImpl(OutboundInterceptor): # pyright: ignore[reportUnusedClass]
def __init__(self, client: Client) -> None: # type: ignore
# We are intentionally not calling the base class's __init__ here
self._client = client
### Workflow calls
async def start_workflow(
self, input: StartWorkflowInput
) -> WorkflowHandle[Any, Any]:
req: (
temporalio.api.workflowservice.v1.StartWorkflowExecutionRequest
| temporalio.api.workflowservice.v1.SignalWithStartWorkflowExecutionRequest
)
if input.start_signal is not None:
req = await self._build_signal_with_start_workflow_execution_request(input)
else:
req = await self._build_start_workflow_execution_request(input)
resp: (
temporalio.api.workflowservice.v1.StartWorkflowExecutionResponse
| temporalio.api.workflowservice.v1.SignalWithStartWorkflowExecutionResponse
)
first_execution_run_id = None
eagerly_started = False
try:
if isinstance(
req,
temporalio.api.workflowservice.v1.SignalWithStartWorkflowExecutionRequest,
):
resp = await self._client.workflow_service.signal_with_start_workflow_execution(
req,
retry=True,
metadata=input.rpc_metadata,
timeout=input.rpc_timeout,
)
else:
resp = await self._client.workflow_service.start_workflow_execution(
req,
retry=True,
metadata=input.rpc_metadata,
timeout=input.rpc_timeout,
)
first_execution_run_id = resp.run_id
eagerly_started = resp.HasField("eager_workflow_task")
except RPCError as err:
# If the status is ALREADY_EXISTS and the details can be extracted
# as already started, use a different exception
if err.status == RPCStatusCode.ALREADY_EXISTS and err.grpc_status.details:
details = temporalio.api.errordetails.v1.WorkflowExecutionAlreadyStartedFailure()
if err.grpc_status.details[0].Unpack(details):
raise temporalio.exceptions.WorkflowAlreadyStartedError(
input.id, input.workflow, run_id=details.run_id
)
raise
handle: WorkflowHandle[Any, Any] = WorkflowHandle(
self._client,
req.workflow_id,
result_run_id=resp.run_id,
first_execution_run_id=first_execution_run_id,
result_type=input.ret_type,
start_workflow_response=resp,
)
setattr(handle, "__temporal_eagerly_started", eagerly_started)
return handle
async def _build_start_workflow_execution_request(
self, input: StartWorkflowInput
) -> temporalio.api.workflowservice.v1.StartWorkflowExecutionRequest:
req = temporalio.api.workflowservice.v1.StartWorkflowExecutionRequest()
await self._populate_start_workflow_execution_request(req, input)
# _populate_start_workflow_execution_request is used for both StartWorkflowInput
# and UpdateWithStartStartWorkflowInput. UpdateWithStartStartWorkflowInput does
# not have the following two fields so they are handled here.
req.request_eager_execution = input.request_eager_start
if input.request_id:
req.request_id = input.request_id
# Server currently only supports workflow_event and batch_job
# link types. This filter should be removed or adapted as
# server-side support comes online.
# See https://github.com/temporalio/temporal/issues/10345
links = [
link
for link in input.links
if link.HasField("workflow_event") or link.HasField("batch_job")
]
req.completion_callbacks.extend(
temporalio.api.common.v1.Callback(
nexus=temporalio.api.common.v1.Callback.Nexus(
url=callback.url,
header=callback.headers,
),
links=links,
)
for callback in input.callbacks
)
# Links are duplicated on request for compatibility with older server versions.
req.links.extend(links)
if temporalio.nexus._operation_context._in_nexus_backing_workflow_start_context():
req.on_conflict_options.attach_request_id = True
req.on_conflict_options.attach_completion_callbacks = True
req.on_conflict_options.attach_links = True
return req
async def _build_signal_with_start_workflow_execution_request(
self, input: StartWorkflowInput
) -> temporalio.api.workflowservice.v1.SignalWithStartWorkflowExecutionRequest:
assert input.start_signal
data_converter = self._client.data_converter._with_contexts(
WorkflowSerializationContext(
namespace=self._client.namespace,
workflow_id=input.id,
),
StorageDriverStoreContext(
target=StorageDriverWorkflowInfo(
id=input.id, type=input.workflow, namespace=self._client.namespace
),
),
)
req = temporalio.api.workflowservice.v1.SignalWithStartWorkflowExecutionRequest(
signal_name=input.start_signal
)
if input.start_signal_args:
req.signal_input.payloads.extend(
await data_converter.encode(input.start_signal_args)
)
await self._populate_start_workflow_execution_request(req, input)
return req
async def _build_update_with_start_start_workflow_execution_request(
self, input: UpdateWithStartStartWorkflowInput
) -> temporalio.api.workflowservice.v1.StartWorkflowExecutionRequest:
req = temporalio.api.workflowservice.v1.StartWorkflowExecutionRequest()
await self._populate_start_workflow_execution_request(req, input)
return req
async def _populate_start_workflow_execution_request(
self,
req: (
temporalio.api.workflowservice.v1.StartWorkflowExecutionRequest
| temporalio.api.workflowservice.v1.SignalWithStartWorkflowExecutionRequest
),
input: StartWorkflowInput | UpdateWithStartStartWorkflowInput,
) -> None:
data_converter = self._client.data_converter._with_contexts(
WorkflowSerializationContext(
namespace=self._client.namespace,
workflow_id=input.id,
),
StorageDriverStoreContext(
target=StorageDriverWorkflowInfo(
id=input.id, type=input.workflow, namespace=self._client.namespace
),
),
)
req.namespace = self._client.namespace
req.workflow_id = input.id
req.workflow_type.name = input.workflow
req.task_queue.name = input.task_queue
if input.args:
req.input.payloads.extend(await data_converter.encode(input.args))
if input.execution_timeout is not None:
req.workflow_execution_timeout.FromTimedelta(input.execution_timeout)
if input.run_timeout is not None:
req.workflow_run_timeout.FromTimedelta(input.run_timeout)
if input.task_timeout is not None:
req.workflow_task_timeout.FromTimedelta(input.task_timeout)
req.identity = self._client.identity
req.request_id = str(uuid.uuid4())
req.workflow_id_reuse_policy = cast(
"temporalio.api.enums.v1.WorkflowIdReusePolicy.ValueType",
int(input.id_reuse_policy),
)
req.workflow_id_conflict_policy = cast(
"temporalio.api.enums.v1.WorkflowIdConflictPolicy.ValueType",
int(input.id_conflict_policy),
)
if input.retry_policy is not None:
input.retry_policy.apply_to_proto(req.retry_policy)
req.cron_schedule = input.cron_schedule
if input.memo is not None:
await data_converter._encode_memo_existing(input.memo, req.memo)
if input.search_attributes is not None:
temporalio.converter.encode_search_attributes(
input.search_attributes, req.search_attributes
)
metadata = await _encode_user_metadata(
data_converter, input.static_summary, input.static_details
)
if metadata is not None:
req.user_metadata.CopyFrom(metadata)
if input.start_delay is not None:
req.workflow_start_delay.FromTimedelta(input.start_delay)
if input.headers is not None: # type:ignore[reportUnnecessaryComparison]
await self._apply_headers(input.headers, req.header.fields)
if input.priority is not None: # type:ignore[reportUnnecessaryComparison]
req.priority.CopyFrom(input.priority._to_proto())
if input.versioning_override is not None:
req.versioning_override.CopyFrom(input.versioning_override._to_proto())
async def cancel_workflow(self, input: CancelWorkflowInput) -> None:
await self._client.workflow_service.request_cancel_workflow_execution(
temporalio.api.workflowservice.v1.RequestCancelWorkflowExecutionRequest(
namespace=self._client.namespace,
workflow_execution=temporalio.api.common.v1.WorkflowExecution(
workflow_id=input.id,
run_id=input.run_id or "",
),
identity=self._client.identity,
request_id=str(uuid.uuid4()),
first_execution_run_id=input.first_execution_run_id or "",
reason=input.reason,
),
retry=True,
metadata=input.rpc_metadata,
timeout=input.rpc_timeout,
)
async def describe_workflow(
self, input: DescribeWorkflowInput
) -> WorkflowExecutionDescription:
return await WorkflowExecutionDescription._from_raw_description(
await self._client.workflow_service.describe_workflow_execution(
temporalio.api.workflowservice.v1.DescribeWorkflowExecutionRequest(
namespace=self._client.namespace,
execution=temporalio.api.common.v1.WorkflowExecution(
workflow_id=input.id,
run_id=input.run_id or "",
),
),
retry=True,
metadata=input.rpc_metadata,
timeout=input.rpc_timeout,
),
namespace=self._client.namespace,
converter=self._client.data_converter.with_context(
WorkflowSerializationContext(
namespace=self._client.namespace,
workflow_id=input.id,
)
),
)
def fetch_workflow_history_events(
self, input: FetchWorkflowHistoryEventsInput
) -> WorkflowHistoryEventAsyncIterator:
return WorkflowHistoryEventAsyncIterator(self._client, input)
def list_workflows(
self, input: ListWorkflowsInput
) -> WorkflowExecutionAsyncIterator:
return WorkflowExecutionAsyncIterator(self._client, input)
async def count_workflows(
self, input: CountWorkflowsInput
) -> WorkflowExecutionCount:
return WorkflowExecutionCount._from_raw(
await self._client.workflow_service.count_workflow_executions(
temporalio.api.workflowservice.v1.CountWorkflowExecutionsRequest(
namespace=self._client.namespace,
query=input.query or "",
),
retry=True,
metadata=input.rpc_metadata,
timeout=input.rpc_timeout,
)
)
async def query_workflow(self, input: QueryWorkflowInput) -> Any:
data_converter = self._client.data_converter._with_contexts(
WorkflowSerializationContext(
namespace=self._client.namespace,
workflow_id=input.id,
),
StorageDriverStoreContext(
target=StorageDriverWorkflowInfo(
id=input.id,
run_id=input.run_id or None,
namespace=self._client.namespace,
),
),
)
req = temporalio.api.workflowservice.v1.QueryWorkflowRequest(
namespace=self._client.namespace,
execution=temporalio.api.common.v1.WorkflowExecution(
workflow_id=input.id,
run_id=input.run_id or "",
),
)
if input.reject_condition:
req.query_reject_condition = cast(
"temporalio.api.enums.v1.QueryRejectCondition.ValueType",
int(input.reject_condition),
)
req.query.query_type = input.query
if input.args:
req.query.query_args.payloads.extend(
await data_converter.encode(input.args)
)
if input.headers is not None: # type:ignore[reportUnnecessaryComparison]
await self._apply_headers(input.headers, req.query.header.fields)
try:
resp = await self._client.workflow_service.query_workflow(
req,
retry=True,
metadata=input.rpc_metadata,
timeout=input.rpc_timeout,
)
except RPCError as err:
# If the status is INVALID_ARGUMENT, we can assume it's a query
# failed error
if err.status == RPCStatusCode.INVALID_ARGUMENT:
raise WorkflowQueryFailedError(err.message)
else:
raise
if resp.HasField("query_rejected"):
raise WorkflowQueryRejectedError(
WorkflowExecutionStatus(resp.query_rejected.status)
if resp.query_rejected.status
else None
)
if not resp.query_result.payloads:
return None
type_hints = [input.ret_type] if input.ret_type else None
results = await data_converter.decode(resp.query_result.payloads, type_hints)
if not results:
return None
elif len(results) > 1:
warnings.warn(f"Expected single query result, got {len(results)}")
return results[0]
async def signal_workflow(self, input: SignalWorkflowInput) -> None:
data_converter = self._client.data_converter._with_contexts(
WorkflowSerializationContext(
namespace=self._client.namespace,
workflow_id=input.id,
),
StorageDriverStoreContext(
target=StorageDriverWorkflowInfo(
id=input.id,
run_id=input.run_id or None,
namespace=self._client.namespace,
),
),
)
req = temporalio.api.workflowservice.v1.SignalWorkflowExecutionRequest(
namespace=self._client.namespace,
workflow_execution=temporalio.api.common.v1.WorkflowExecution(
workflow_id=input.id,
run_id=input.run_id or "",
),
signal_name=input.signal,
identity=self._client.identity,
request_id=str(uuid.uuid4()),
)
if input.args:
req.input.payloads.extend(await data_converter.encode(input.args))
if input.headers is not None: # type:ignore[reportUnnecessaryComparison]
await self._apply_headers(input.headers, req.header.fields)
await self._client.workflow_service.signal_workflow_execution(
req, retry=True, metadata=input.rpc_metadata, timeout=input.rpc_timeout
)
async def terminate_workflow(self, input: TerminateWorkflowInput) -> None:
data_converter = self._client.data_converter._with_contexts(
WorkflowSerializationContext(
namespace=self._client.namespace,
workflow_id=input.id,
),
StorageDriverStoreContext(
target=StorageDriverWorkflowInfo(
id=input.id,
run_id=input.run_id or None,
namespace=self._client.namespace,
),
),
)
req = temporalio.api.workflowservice.v1.TerminateWorkflowExecutionRequest(
namespace=self._client.namespace,
workflow_execution=temporalio.api.common.v1.WorkflowExecution(
workflow_id=input.id,
run_id=input.run_id or "",
),
reason=input.reason or "",
identity=self._client.identity,
first_execution_run_id=input.first_execution_run_id or "",
)
if input.args:
req.details.payloads.extend(await data_converter.encode(input.args))
await self._client.workflow_service.terminate_workflow_execution(
req, retry=True, metadata=input.rpc_metadata, timeout=input.rpc_timeout
)
async def start_activity(self, input: StartActivityInput) -> ActivityHandle[Any]:
"""Start an activity and return a handle to it."""
if not (input.start_to_close_timeout or input.schedule_to_close_timeout):
raise ValueError(
"Activity must have start_to_close_timeout or schedule_to_close_timeout"
)
if input.start_delay is not None and input.start_delay < timedelta(0):
raise ValueError("start_delay must be non-negative")
req = await self._build_start_activity_execution_request(input)
resp: temporalio.api.workflowservice.v1.StartActivityExecutionResponse
try:
resp = await self._client.workflow_service.start_activity_execution(
req,
retry=True,
metadata=input.rpc_metadata,
timeout=input.rpc_timeout,
)
except RPCError as err:
# If the status is ALREADY_EXISTS and the details can be extracted
# as already started, use a different exception
if err.status == RPCStatusCode.ALREADY_EXISTS and err.grpc_status.details:
details = temporalio.api.errordetails.v1.ActivityExecutionAlreadyStartedFailure()
if err.grpc_status.details[0].Unpack(details):
raise temporalio.exceptions.ActivityAlreadyStartedError(
input.id, input.activity_type, run_id=details.run_id
)
raise
return ActivityHandle(
self._client,
input.id,
run_id=resp.run_id,
result_type=input.result_type,
)
async def _build_start_activity_execution_request(
self, input: StartActivityInput
) -> temporalio.api.workflowservice.v1.StartActivityExecutionRequest:
"""Build StartActivityExecutionRequest from input."""
data_converter = self._client.data_converter._with_contexts(
ActivitySerializationContext(
namespace=self._client.namespace,
activity_id=input.id,
activity_type=input.activity_type,
activity_task_queue=input.task_queue,
is_local=False,
workflow_id=None,
workflow_type=None,
),
StorageDriverStoreContext(
target=StorageDriverActivityInfo(
id=input.id,
type=input.activity_type,
namespace=self._client.namespace,
),
),
)
req = temporalio.api.workflowservice.v1.StartActivityExecutionRequest(
namespace=self._client.namespace,
identity=self._client.identity,
activity_id=input.id,
activity_type=temporalio.api.common.v1.ActivityType(
name=input.activity_type
),
task_queue=temporalio.api.taskqueue.v1.TaskQueue(name=input.task_queue),
id_reuse_policy=cast(
"temporalio.api.enums.v1.ActivityIdReusePolicy.ValueType",
int(input.id_reuse_policy),
),
id_conflict_policy=cast(
"temporalio.api.enums.v1.ActivityIdConflictPolicy.ValueType",
int(input.id_conflict_policy),
),
)
if input.schedule_to_close_timeout is not None:
req.schedule_to_close_timeout.FromTimedelta(input.schedule_to_close_timeout)
if input.start_to_close_timeout is not None:
req.start_to_close_timeout.FromTimedelta(input.start_to_close_timeout)
if input.schedule_to_start_timeout is not None:
req.schedule_to_start_timeout.FromTimedelta(input.schedule_to_start_timeout)
if input.heartbeat_timeout is not None:
req.heartbeat_timeout.FromTimedelta(input.heartbeat_timeout)
if input.start_delay is not None:
req.start_delay.FromTimedelta(input.start_delay)
if input.retry_policy is not None:
input.retry_policy.apply_to_proto(req.retry_policy)
# Set input payloads
if input.args:
req.input.payloads.extend(await data_converter.encode(input.args))
# Set search attributes
if input.search_attributes is not None:
temporalio.converter.encode_search_attributes(
input.search_attributes, req.search_attributes
)
# Set user metadata
metadata = await _encode_user_metadata(data_converter, input.summary, None)
if metadata is not None:
req.user_metadata.CopyFrom(metadata)
# Set headers
if input.headers:
await self._apply_headers(input.headers, req.header.fields)
# Set priority
req.priority.CopyFrom(input.priority._to_proto())
return req
async def cancel_activity(self, input: CancelActivityInput) -> None:
"""Cancel an activity."""
await self._client.workflow_service.request_cancel_activity_execution(
temporalio.api.workflowservice.v1.RequestCancelActivityExecutionRequest(
namespace=self._client.namespace,
activity_id=input.activity_id,
run_id=input.activity_run_id or "",
identity=self._client.identity,
request_id=str(uuid.uuid4()),
reason=input.reason or "",
),
retry=True,
metadata=input.rpc_metadata,
timeout=input.rpc_timeout,
)
async def terminate_activity(self, input: TerminateActivityInput) -> None:
"""Terminate an activity."""
await self._client.workflow_service.terminate_activity_execution(
temporalio.api.workflowservice.v1.TerminateActivityExecutionRequest(
namespace=self._client.namespace,
activity_id=input.activity_id,
run_id=input.activity_run_id or "",
reason=input.reason or "",
identity=self._client.identity,
),
retry=True,
metadata=input.rpc_metadata,
timeout=input.rpc_timeout,
)
async def describe_activity(
self, input: DescribeActivityInput
) -> ActivityExecutionDescription:
"""Describe an activity."""
resp = await self._client.workflow_service.describe_activity_execution(
temporalio.api.workflowservice.v1.DescribeActivityExecutionRequest(
namespace=self._client.namespace,
activity_id=input.activity_id,
run_id=input.activity_run_id or "",
long_poll_token=input.long_poll_token or b"",
),
retry=True,
metadata=input.rpc_metadata,
timeout=input.rpc_timeout,
)
return await ActivityExecutionDescription._from_execution_info(
info=resp.info,
long_poll_token=resp.long_poll_token or None,
namespace=self._client.namespace,
data_converter=self._client.data_converter.with_context(
ActivitySerializationContext(
namespace=self._client.namespace,
activity_id=resp.info.activity_id,
activity_task_queue=resp.info.task_queue,
activity_type=resp.info.activity_type.name,
workflow_id=None,
workflow_type=None,
is_local=False,
)
),
)
def list_activities(
self, input: ListActivitiesInput
) -> ActivityExecutionAsyncIterator:
return ActivityExecutionAsyncIterator(self._client, input)
async def count_activities(
self, input: CountActivitiesInput
) -> ActivityExecutionCount:
return ActivityExecutionCount._from_raw(
await self._client.workflow_service.count_activity_executions(
temporalio.api.workflowservice.v1.CountActivityExecutionsRequest(
namespace=self._client.namespace,
query=input.query or "",
),
retry=True,
metadata=input.rpc_metadata,
timeout=input.rpc_timeout,
)
)
async def start_workflow_update(
self, input: StartWorkflowUpdateInput
) -> WorkflowUpdateHandle[Any]:
workflow_id = input.id
req = await self._build_update_workflow_execution_request(input, workflow_id)
# Repeatedly try to invoke UpdateWorkflowExecution until the update is durable.
resp: temporalio.api.workflowservice.v1.UpdateWorkflowExecutionResponse
while True:
try:
resp = await self._client.workflow_service.update_workflow_execution(
req,
retry=True,
metadata=input.rpc_metadata,
timeout=input.rpc_timeout,
)
except RPCError as err:
if (
err.status == RPCStatusCode.DEADLINE_EXCEEDED
or err.status == RPCStatusCode.CANCELLED
):
raise WorkflowUpdateRPCTimeoutOrCancelledError() from err
else:
raise
except asyncio.CancelledError as err:
raise WorkflowUpdateRPCTimeoutOrCancelledError() from err
if (
resp.stage
>= temporalio.api.enums.v1.UpdateWorkflowExecutionLifecycleStage.UPDATE_WORKFLOW_EXECUTION_LIFECYCLE_STAGE_ACCEPTED
):
break
# Build the handle. If the user's wait stage is COMPLETED, make sure we
# poll for result.
handle: WorkflowUpdateHandle[Any] = WorkflowUpdateHandle(
client=self._client,
id=req.request.meta.update_id,
workflow_id=workflow_id,
workflow_run_id=resp.update_ref.workflow_execution.run_id,
result_type=input.ret_type,
)
if resp.HasField("outcome"):
handle._known_outcome = resp.outcome
if input.wait_for_stage == WorkflowUpdateStage.COMPLETED:
await handle._poll_until_outcome()
return handle
async def _build_update_workflow_execution_request(
self,
input: StartWorkflowUpdateInput | UpdateWithStartUpdateWorkflowInput,
workflow_id: str,
) -> temporalio.api.workflowservice.v1.UpdateWorkflowExecutionRequest:
data_converter = self._client.data_converter._with_contexts(
WorkflowSerializationContext(
namespace=self._client.namespace,
workflow_id=workflow_id,
),
StorageDriverStoreContext(
target=StorageDriverWorkflowInfo(
id=workflow_id,
run_id=(input.run_id or None)
if isinstance(input, StartWorkflowUpdateInput)
else None,
namespace=self._client.namespace,
),
),
)
run_id, first_execution_run_id = (
(
input.run_id,
input.first_execution_run_id,
)
if isinstance(input, StartWorkflowUpdateInput)
else (None, None)
)
req = temporalio.api.workflowservice.v1.UpdateWorkflowExecutionRequest(
namespace=self._client.namespace,
workflow_execution=temporalio.api.common.v1.WorkflowExecution(
workflow_id=workflow_id,
run_id=run_id or "",
),
first_execution_run_id=first_execution_run_id or "",
request=temporalio.api.update.v1.Request(
meta=temporalio.api.update.v1.Meta(
update_id=input.update_id or str(uuid.uuid4()),
identity=self._client.identity,
),
input=temporalio.api.update.v1.Input(
name=input.update,
),
),
wait_policy=temporalio.api.update.v1.WaitPolicy(
lifecycle_stage=temporalio.api.enums.v1.UpdateWorkflowExecutionLifecycleStage.ValueType(
input.wait_for_stage
)
),
)
if input.args:
req.request.input.args.payloads.extend(
await data_converter.encode(input.args)
)
if input.headers is not None: # type:ignore[reportUnnecessaryComparison]
await self._apply_headers(input.headers, req.request.input.header.fields)
return req
async def start_update_with_start_workflow(
self, input: StartWorkflowUpdateWithStartInput
) -> WorkflowUpdateHandle[Any]:
seen_start = False
def on_start(
start_response: temporalio.api.workflowservice.v1.StartWorkflowExecutionResponse,
):
nonlocal seen_start
if not seen_start:
input._on_start(start_response)
seen_start = True
err: BaseException | None = None
try:
return await self._start_workflow_update_with_start(
input.start_workflow_input, input.update_workflow_input, on_start
)
except asyncio.CancelledError as _err:
err = _err
raise WorkflowUpdateRPCTimeoutOrCancelledError() from err
except RPCError as _err:
err = _err
if err.status in [
RPCStatusCode.DEADLINE_EXCEEDED,
RPCStatusCode.CANCELLED,
]:
raise WorkflowUpdateRPCTimeoutOrCancelledError() from err
else:
multiop_failure = (
temporalio.api.errordetails.v1.MultiOperationExecutionFailure()
)
if err.grpc_status.details and err.grpc_status.details[0].Unpack(
multiop_failure
):
status = next(
(
st
for st in multiop_failure.statuses
if (
st.code != RPCStatusCode.OK
and not (
st.details
and st.details[0].Is(
temporalio.api.failure.v1.MultiOperationExecutionAborted.DESCRIPTOR
)
)
)
),
None,
)
if status and status.code in list(RPCStatusCode):
if (
status.code == RPCStatusCode.ALREADY_EXISTS
and status.details
):
details = temporalio.api.errordetails.v1.WorkflowExecutionAlreadyStartedFailure()
if status.details[0].Unpack(details):
err = temporalio.exceptions.WorkflowAlreadyStartedError(
input.start_workflow_input.id,
input.start_workflow_input.workflow,
run_id=details.run_id,
)
else:
err = RPCError(
status.message,
RPCStatusCode(status.code),
err.raw_grpc_status,
)
raise err
finally:
if err and not seen_start:
input._on_start_error(err)
async def _start_workflow_update_with_start(
self,
start_input: UpdateWithStartStartWorkflowInput,
update_input: UpdateWithStartUpdateWorkflowInput,
on_start: Callable[
[temporalio.api.workflowservice.v1.StartWorkflowExecutionResponse], None
],
) -> WorkflowUpdateHandle[Any]:
start_req = (
await self._build_update_with_start_start_workflow_execution_request(
start_input
)
)
update_req = await self._build_update_workflow_execution_request(
update_input, workflow_id=start_input.id
)
multiop_req = temporalio.api.workflowservice.v1.ExecuteMultiOperationRequest(
namespace=self._client.namespace,
operations=[
temporalio.api.workflowservice.v1.ExecuteMultiOperationRequest.Operation(
start_workflow=start_req
),
temporalio.api.workflowservice.v1.ExecuteMultiOperationRequest.Operation(
update_workflow=update_req
),
],
)
# Repeatedly try to invoke ExecuteMultiOperation until the update is durable
while True:
multiop_response = (
await self._client.workflow_service.execute_multi_operation(multiop_req)
)
start_response = multiop_response.responses[0].start_workflow
update_response = multiop_response.responses[1].update_workflow
on_start(start_response)
known_outcome = (
update_response.outcome if update_response.HasField("outcome") else None
)
if (
update_response.stage
>= temporalio.api.enums.v1.UpdateWorkflowExecutionLifecycleStage.UPDATE_WORKFLOW_EXECUTION_LIFECYCLE_STAGE_ACCEPTED
):
break
handle: WorkflowUpdateHandle[Any] = WorkflowUpdateHandle(
client=self._client,
id=update_req.request.meta.update_id,
workflow_id=start_input.id,
workflow_run_id=start_response.run_id,
known_outcome=known_outcome,
result_type=update_input.ret_type,
)
if update_input.wait_for_stage == WorkflowUpdateStage.COMPLETED:
await handle._poll_until_outcome()
return handle
### Async activity calls
def _get_async_activity_store_context(
self, id_or_token: AsyncActivityIDReference | bytes
) -> StorageDriverStoreContext:
if isinstance(id_or_token, AsyncActivityIDReference):
if id_or_token.workflow_id:
return StorageDriverStoreContext(
target=StorageDriverWorkflowInfo(
id=id_or_token.workflow_id or None,
run_id=id_or_token.run_id or None,
namespace=self._client.namespace,
),
)
return StorageDriverStoreContext(
target=StorageDriverActivityInfo(
id=id_or_token.activity_id,
run_id=id_or_token.run_id or None,
namespace=self._client.namespace,
),
)
else:
return StorageDriverStoreContext(target=None)
async def heartbeat_async_activity(
self, input: HeartbeatAsyncActivityInput
) -> None:
data_converter = (
input.data_converter_override or self._client.data_converter
)._with_store_context(self._get_async_activity_store_context(input.id_or_token))