forked from temporalio/sdk-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_workflow_instance.py
More file actions
3849 lines (3451 loc) · 156 KB
/
Copy path_workflow_instance.py
File metadata and controls
3849 lines (3451 loc) · 156 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
"""Workflow worker runner and instance."""
from __future__ import annotations
import asyncio
import collections
import contextvars
import inspect
import json
import logging
import random
import sys
import threading
import traceback
import warnings
from abc import ABC, abstractmethod
from collections import deque
from collections.abc import (
Awaitable,
Callable,
Coroutine,
Generator,
Iterable,
Iterator,
Mapping,
MutableMapping,
Sequence,
)
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import timedelta
from enum import IntEnum
from typing import (
Any,
Generic,
NoReturn,
TypeAlias,
TypeVar,
cast,
)
import nexusrpc
from nexusrpc import InputT, OutputT
from typing_extensions import Self, TypedDict, TypeVarTuple, Unpack
import temporalio.activity
import temporalio.api.common.v1
import temporalio.api.enums.v1
import temporalio.api.sdk.v1
import temporalio.bridge.proto.activity_result
import temporalio.bridge.proto.child_workflow
import temporalio.bridge.proto.common
import temporalio.bridge.proto.nexus
import temporalio.bridge.proto.workflow_activation
import temporalio.bridge.proto.workflow_commands
import temporalio.bridge.proto.workflow_completion
import temporalio.common
import temporalio.converter
import temporalio.exceptions
import temporalio.workflow
from temporalio.converter import StorageDriverStoreContext, StorageDriverWorkflowInfo
from temporalio.service import __version__
from ..api.failure.v1.message_pb2 import Failure
from . import _command_aware_visitor
from ._interceptor import (
ContinueAsNewInput,
ExecuteWorkflowInput,
HandleQueryInput,
HandleSignalInput,
HandleUpdateInput,
SignalChildWorkflowInput,
SignalExternalWorkflowInput,
StartActivityInput,
StartChildWorkflowInput,
StartLocalActivityInput,
StartNexusOperationInput,
WorkflowInboundInterceptor,
WorkflowOutboundInterceptor,
)
logger = logging.getLogger(__name__)
# Set to true to log all cases where we're ignoring things during delete
LOG_IGNORE_DURING_DELETE = False
class WorkflowRunner(ABC):
"""Abstract runner for workflows that creates workflow instances to run.
:py:class:`UnsandboxedWorkflowRunner` is an implementation that locally runs
the workflow.
"""
@abstractmethod
def prepare_workflow(self, defn: temporalio.workflow._Definition) -> None:
"""Prepare a workflow for future execution.
This is run once for each workflow definition when a worker starts. This
allows the runner to do anything necessarily to prepare for this
definition to be used multiple times in create_instance.
Args:
defn: The workflow definition.
"""
raise NotImplementedError
@abstractmethod
def create_instance(self, det: WorkflowInstanceDetails) -> WorkflowInstance:
"""Create a workflow instance that can handle activations.
Args:
det: Details that can be used to create the instance.
Returns:
Workflow instance that can handle activations.
"""
raise NotImplementedError
def set_worker_level_failure_exception_types(
self,
types: Sequence[type[BaseException]], # type:ignore[reportUnusedParameter]
) -> None:
"""Set worker-level failure exception types that will be used to
validate in the sandbox when calling ``prepare_workflow``.
Args:
types: Exception types.
"""
pass
@dataclass(frozen=True)
class WorkflowInstanceDetails:
"""Immutable details for creating a workflow instance."""
payload_converter_class: type[temporalio.converter.PayloadConverter]
failure_converter_class: type[temporalio.converter.FailureConverter]
interceptor_classes: Sequence[type[WorkflowInboundInterceptor]]
defn: temporalio.workflow._Definition
info: temporalio.workflow.Info
randomness_seed: int
extern_functions: Mapping[str, Callable]
disable_eager_activity_execution: bool
worker_level_failure_exception_types: Sequence[type[BaseException]]
last_completion_result: temporalio.api.common.v1.Payloads
last_failure: Failure | None
class WorkflowInstance(ABC):
"""Instance of a workflow that can handle activations."""
@abstractmethod
def activate(
self, act: temporalio.bridge.proto.workflow_activation.WorkflowActivation
) -> temporalio.bridge.proto.workflow_completion.WorkflowActivationCompletion:
"""Handle an activation and return completion.
This should never raise an exception, but instead catch all exceptions
and set as completion failure.
Args:
act: Protobuf activation.
Returns:
Completion object with successful commands set or failure info set.
"""
raise NotImplementedError
@abstractmethod
def get_serialization_context(
self,
command_info: _command_aware_visitor.CommandInfo | None,
) -> temporalio.converter.SerializationContext | None:
"""Return appropriate serialization context.
Args:
command_info: Optional information identifying the associated command. If set, the payload
codec will have serialization context set appropriately for that command.
Returns:
The serialization context, or None if no context should be set.
"""
raise NotImplementedError
@abstractmethod
def get_external_store_context(
self,
command_info: _command_aware_visitor.CommandInfo | None,
) -> StorageDriverStoreContext:
"""Return appropriate store context for external storage operations.
Args:
command_info: Optional information identifying the associated command.
Returns:
The store context associated with the command.
"""
raise NotImplementedError
@abstractmethod
def get_info(self) -> temporalio.workflow.Info:
"""Return the workflow info for this instance."""
raise NotImplementedError
def get_thread_id(self) -> int | None:
"""Return the thread identifier that this workflow is running on.
Not an abstractmethod because it is not mandatory to implement. Used primarily for getting the frames of a deadlocked thread.
Returns:
Thread ID if the workflow is running, None if not.
"""
return None
class UnsandboxedWorkflowRunner(WorkflowRunner):
"""Workflow runner that does not do any sandboxing."""
def prepare_workflow(self, defn: temporalio.workflow._Definition) -> None:
"""Implements :py:meth:`WorkflowRunner.prepare_workflow` as a no-op."""
pass
def create_instance(self, det: WorkflowInstanceDetails) -> WorkflowInstance:
"""Implements :py:meth:`WorkflowRunner.create_instance`."""
# We ignore MyPy failing to instantiate this because it's not _really_
# abstract at runtime. All of the asyncio.AbstractEventLoop calls that
# we are not implementing are not abstract, they just throw not-impl'd
# errors.
return _WorkflowInstanceImpl(det) # type: ignore[abstract]
_T = TypeVar("_T")
_Context: TypeAlias = dict[str, Any]
_ExceptionHandler: TypeAlias = Callable[[asyncio.AbstractEventLoop, _Context], Any]
class _WorkflowInstanceImpl( # type: ignore[reportImplicitAbstractClass]
WorkflowInstance, temporalio.workflow._Runtime, asyncio.AbstractEventLoop
):
def __init__(self, det: WorkflowInstanceDetails) -> None:
# No init for AbstractEventLoop
WorkflowInstance.__init__(self)
temporalio.workflow._Runtime.__init__(self)
self._defn = det.defn
self._workflow_input: ExecuteWorkflowInput | None = None
self._info = det.info
self._context_free_payload_converter = det.payload_converter_class()
self._context_free_failure_converter = det.failure_converter_class()
workflow_context = temporalio.converter.WorkflowSerializationContext(
namespace=det.info.namespace,
workflow_id=det.info.workflow_id,
)
self._workflow_context_payload_converter = self._payload_converter_with_context(
workflow_context
)
self._workflow_context_failure_converter = self._failure_converter_with_context(
workflow_context
)
self._extern_functions = det.extern_functions
self._disable_eager_activity_execution = det.disable_eager_activity_execution
self._worker_level_failure_exception_types = (
det.worker_level_failure_exception_types
)
self._primary_task: asyncio.Task[None] | None = None
self._time_ns = 0
self._cancel_requested = False
self._deployment_version_for_current_task: None | (
temporalio.bridge.proto.common.WorkerDeploymentVersion
) = None
self._current_history_length = 0
self._current_history_size = 0
self._continue_as_new_suggested = False
self._target_worker_deployment_version_changed = False
# Lazily loaded
self._untyped_converted_memo: MutableMapping[str, Any] | None = None
# Handles which are ready to run on the next event loop iteration
self._ready: deque[asyncio.Handle] = collections.deque()
self._conditions: list[tuple[Callable[[], bool], asyncio.Future]] = []
# Keyed by seq
self._pending_timers: dict[int, _TimerHandle] = {}
self._pending_activities: dict[int, _ActivityHandle] = {}
self._pending_child_workflows: dict[int, _ChildWorkflowHandle] = {}
self._pending_nexus_operations: dict[int, _NexusOperationHandle] = {}
self._pending_external_signals: dict[int, tuple[asyncio.Future, str]] = {}
self._pending_external_cancels: dict[int, tuple[asyncio.Future, str]] = {}
# Keyed by type
self._curr_seqs: dict[str, int] = {}
# TODO(cretz): Any concerns about not sharing this? Maybe the types I
# need to lookup should be done at definition time?
self._exception_handler: _ExceptionHandler | None = None
# The actual instance, instantiated on first _run_once
self._object: Any = None
self._is_replaying: bool = False
self._random = random.Random(det.randomness_seed)
self._current_seed = det.randomness_seed
self._seed_callbacks: list[Callable[[int], None]] = []
self._read_only = False
self._in_query_or_validator = False
# Patches we have been notified of and memoized patch responses
self._patches_notified: set[str] = set()
self._patches_memoized: dict[str, bool] = {}
# Tasks stored by asyncio are weak references and therefore can get GC'd
# which can cause warnings like "Task was destroyed but it is pending!".
# So we store the tasks ourselves.
# See https://bugs.python.org/issue21163 and others.
self._tasks: set[asyncio.Task] = set()
# We maintain signals, queries, and updates on this class since handlers can be
# added during workflow execution
self._signals = dict(self._defn.signals)
self._queries = dict(self._defn.queries)
self._updates = dict(self._defn.updates)
# We record in-progress signals and updates in order to support waiting for handlers to
# finish, and issuing warnings when the workflow exits with unfinished handlers. Since
# signals lack a unique per-invocation identifier, we introduce a sequence number for the
# purpose.
self._handled_signals_seq = 0
self._in_progress_signals: dict[int, HandlerExecution] = {}
self._in_progress_updates: dict[str, HandlerExecution] = {}
# Add stack trace handler
# TODO(cretz): Is it ok that this can be forcefully overridden by the
# workflow author? They could technically override in interceptor
# anyways. Putting here ensures it ends up in the query list on
# query-not-found error.
self._queries["__stack_trace"] = temporalio.workflow._QueryDefinition(
name="__stack_trace",
fn=self._stack_trace,
is_method=False,
arg_types=[],
ret_type=str,
)
self._queries["__enhanced_stack_trace"] = temporalio.workflow._QueryDefinition(
name="__enhanced_stack_trace",
fn=self._enhanced_stack_trace,
is_method=False,
arg_types=[],
ret_type=temporalio.api.sdk.v1.EnhancedStackTrace,
)
self._queries["__temporal_workflow_metadata"] = (
temporalio.workflow._QueryDefinition(
name="__temporal_workflow_metadata",
fn=self._temporal_workflow_metadata,
is_method=False,
arg_types=[],
ret_type=temporalio.api.sdk.v1.WorkflowMetadata,
)
)
# Maintain buffered signals for later-added dynamic handlers
self._buffered_signals: dict[
str, list[temporalio.bridge.proto.workflow_activation.SignalWorkflow]
] = {}
# When we evict, we have to mark the workflow as deleting so we don't
# add any commands and we swallow exceptions on tear down
self._deleting = False
# We only create the metric meter lazily
self._metric_meter: _ReplaySafeMetricMeter | None = None
# For tracking the thread this workflow is running on (primarily for deadlock situations)
self._current_thread_id: int | None = None
# The current details (as opposed to static details on workflow start), returned in the
# metadata query
self._current_details = ""
self._last_completion_result = det.last_completion_result
self._last_failure = det.last_failure
# The versioning behavior of this workflow, as established by annotation or by the dynamic
# config function. Is only set once upon initialization.
self._versioning_behavior: temporalio.common.VersioningBehavior | None = None
# Dynamic failure exception types as overridden by the dynamic config function
self._dynamic_failure_exception_types: (
None | (Sequence[type[BaseException]])
) = None
# Create interceptors. We do this with our runtime on the loop just in
# case they want to access info() during init(). This should remain at the end of the constructor so that variables are defined during interceptor creation
temporalio.workflow._Runtime.set_on_loop(asyncio.get_running_loop(), self)
try:
root_inbound = _WorkflowInboundImpl(self)
self._inbound: WorkflowInboundInterceptor = root_inbound
for interceptor_class in reversed(list(det.interceptor_classes)):
self._inbound = interceptor_class(self._inbound)
# During init we set ourselves on the current loop
self._inbound.init(_WorkflowOutboundImpl(self))
self._outbound = root_inbound._outbound
finally:
# Remove our runtime from the loop
temporalio.workflow._Runtime.set_on_loop(asyncio.get_running_loop(), None)
# Set ourselves on our own loop
temporalio.workflow._Runtime.set_on_loop(self, self)
def get_thread_id(self) -> int | None:
return self._current_thread_id
#### Activation functions ####
# These are in alphabetical order and besides "activate", and
# "_make_workflow_input", all other calls are "_apply_" + the job field
# name.
def activate(
self, act: temporalio.bridge.proto.workflow_activation.WorkflowActivation
) -> temporalio.bridge.proto.workflow_completion.WorkflowActivationCompletion:
# Reset current completion, time, and whether replaying
self._current_completion = (
temporalio.bridge.proto.workflow_completion.WorkflowActivationCompletion()
)
self._current_completion.successful.SetInParent()
self._current_activation_error: Exception | None = None
self._deployment_version_for_current_task = (
act.deployment_version_for_current_task
)
self._current_history_length = act.history_length
self._current_history_size = act.history_size_bytes
self._continue_as_new_suggested = act.continue_as_new_suggested
self._target_worker_deployment_version_changed = (
act.target_worker_deployment_version_changed
)
self._time_ns = act.timestamp.ToNanoseconds()
self._is_replaying = act.is_replaying
self._current_thread_id = threading.get_ident()
self._current_internal_flags = act.available_internal_flags
activation_err: Exception | None = None
try:
# Split into job sets with patches, then signals + updates, then
# non-queries, then queries
start_job = None
job_sets: list[
list[temporalio.bridge.proto.workflow_activation.WorkflowActivationJob]
] = [[], [], [], []]
for job in act.jobs:
if job.HasField("notify_has_patch"):
job_sets[0].append(job)
elif job.HasField("signal_workflow") or job.HasField("do_update"):
job_sets[1].append(job)
elif not job.HasField("query_workflow"):
if job.HasField("initialize_workflow"):
start_job = job.initialize_workflow
job_sets[2].append(job)
else:
job_sets[3].append(job)
if start_job:
self._workflow_input = self._make_workflow_input(start_job)
# Apply every job set, running after each set
for index, job_set in enumerate(job_sets):
if not job_set:
continue
# Separate local-activity resolutions from other jobs.
# Local activity results may arrive in non-deterministic
# order (completion order varies between first-execution
# and replay). Sort them by sequence number so coroutines
# always resume in scheduling order, ensuring deterministic
# interleaving regardless of execution mode.
local_activity_jobs = []
other_jobs = []
for job in job_set:
if (
job.HasField("resolve_activity")
and job.resolve_activity.is_local
):
local_activity_jobs.append(job)
else:
other_jobs.append(job)
# Apply non-local-activity jobs first
for job in other_jobs:
self._apply(job)
# Apply local activity resolutions sorted by seq number.
local_activity_jobs.sort(key=lambda j: j.resolve_activity.seq)
for job in local_activity_jobs:
self._apply(job)
# Run one iteration of the loop. We do not allow conditions to
# be checked in patch jobs (first index) or query jobs (last
# index).
self._run_once(check_conditions=index == 1 or index == 2)
except Exception as err:
# We want some errors during activation, like those that can happen
# during payload conversion, to be able to fail the workflow not the
# task
if self.workflow_is_failure_exception(err):
try:
self._set_workflow_failure(err)
except Exception as inner_err:
activation_err = inner_err
else:
# Otherwise all exceptions are activation errors
activation_err = err
# If we're deleting, swallow any activation error
if self._deleting:
if LOG_IGNORE_DURING_DELETE:
logger.debug(
"Ignoring exception while deleting workflow", exc_info=True
)
activation_err = None
# Apply versioning behavior if one was established
if self._versioning_behavior:
self._current_completion.successful.versioning_behavior = (
self._versioning_behavior.value
)
# If we're deleting, there better be no more tasks. It is important for
# the integrity of the system that we check this. If there are tasks
# remaining, they and any associated coroutines will get garbage
# collected which can trigger a GeneratorExit exception thrown in the
# coroutine which can cause it to wakeup on a different thread which may
# have a different workflow/event-loop going.
if self._deleting and self._tasks:
raise RuntimeError(
f"Eviction processed, but {len(self._tasks)} tasks remain. "
+ f"Stack traces below:\n\n{self._stack_trace()}"
)
if activation_err:
logger.warning(
f"Failed activation on workflow {self._info.workflow_type} with ID {self._info.workflow_id} and run ID {self._info.run_id}",
exc_info=activation_err,
extra={
"temporal_workflow": self._info._logger_details(),
"__temporal_error_identifier": "WorkflowTaskFailure",
},
)
# Set completion failure
self._current_completion.failed.failure.SetInParent()
try:
self._workflow_context_failure_converter.to_failure(
activation_err,
self._workflow_context_payload_converter,
self._current_completion.failed.failure,
)
except Exception as inner_err:
logger.exception(
f"Failed converting activation exception on workflow with run ID {act.run_id}"
)
self._current_completion.failed.failure.message = (
f"Failed converting activation exception: {inner_err}"
)
self._current_completion.failed.failure.application_failure_info.SetInParent()
def is_completion(
command: temporalio.bridge.proto.workflow_commands.workflow_commands_pb2.WorkflowCommand,
):
return (
command.HasField("complete_workflow_execution")
or command.HasField("continue_as_new_workflow_execution")
or command.HasField("fail_workflow_execution")
or command.HasField("cancel_workflow_execution")
)
if any(map(is_completion, self._current_completion.successful.commands)):
self._warn_if_unfinished_handlers()
return self._current_completion
def _apply(
self, job: temporalio.bridge.proto.workflow_activation.WorkflowActivationJob
) -> None:
if job.HasField("cancel_workflow"):
self._apply_cancel_workflow(job.cancel_workflow)
elif job.HasField("do_update"):
self._apply_do_update(job.do_update)
elif job.HasField("fire_timer"):
self._apply_fire_timer(job.fire_timer)
elif job.HasField("query_workflow"):
self._apply_query_workflow(job.query_workflow)
elif job.HasField("notify_has_patch"):
self._apply_notify_has_patch(job.notify_has_patch)
elif job.HasField("remove_from_cache"):
self._apply_remove_from_cache(job.remove_from_cache)
elif job.HasField("resolve_activity"):
self._apply_resolve_activity(job.resolve_activity)
elif job.HasField("resolve_child_workflow_execution"):
self._apply_resolve_child_workflow_execution(
job.resolve_child_workflow_execution
)
elif job.HasField("resolve_child_workflow_execution_start"):
self._apply_resolve_child_workflow_execution_start(
job.resolve_child_workflow_execution_start
)
elif job.HasField("resolve_nexus_operation_start"):
self._apply_resolve_nexus_operation_start(job.resolve_nexus_operation_start)
elif job.HasField("resolve_nexus_operation"):
self._apply_resolve_nexus_operation(job.resolve_nexus_operation)
elif job.HasField("resolve_request_cancel_external_workflow"):
self._apply_resolve_request_cancel_external_workflow(
job.resolve_request_cancel_external_workflow
)
elif job.HasField("resolve_signal_external_workflow"):
self._apply_resolve_signal_external_workflow(
job.resolve_signal_external_workflow
)
elif job.HasField("signal_workflow"):
self._apply_signal_workflow(job.signal_workflow)
elif job.HasField("initialize_workflow"):
self._apply_initialize_workflow(job.initialize_workflow)
elif job.HasField("update_random_seed"):
self._apply_update_random_seed(job.update_random_seed)
else:
raise RuntimeError(f"Unrecognized job: {job.WhichOneof('variant')}")
def _apply_cancel_workflow(
self, _job: temporalio.bridge.proto.workflow_activation.CancelWorkflow
) -> None:
self._cancel_requested = True
# TODO(cretz): Details or cancel message or whatever?
if self._primary_task:
# The primary task may not have started yet and we want to give the
# workflow the ability to receive the cancellation, so we must defer
# this cancellation to the next iteration of the event loop.
self.call_soon(self._primary_task.cancel)
def _apply_do_update(
self, job: temporalio.bridge.proto.workflow_activation.DoUpdate
):
# Run the validator & handler in a task. Everything, including looking up the update definition, needs to be
# inside the task, since the update may not be defined until after we have started the workflow - for example
# if an update is in the first WFT & is also registered dynamically at the top of workflow code.
async def run_update() -> None:
# Set the current update for the life of this task
temporalio.workflow._set_current_update_info(
temporalio.workflow.UpdateInfo(id=job.id, name=job.name)
)
command = self._add_command()
command.update_response.protocol_instance_id = job.protocol_instance_id
past_validation = False
try:
defn = self._updates.get(job.name) or self._updates.get(None)
if not defn:
known_updates = sorted([k for k in self._updates.keys() if k])
raise RuntimeError(
f"Update handler for '{job.name}' expected but not found, and there is no dynamic handler. "
f"known updates: [{' '.join(known_updates)}]"
)
self._in_progress_updates[job.id] = HandlerExecution(
job.name, defn.unfinished_policy, job.id
)
args = self._process_handler_args(
job.name,
job.input,
defn.name,
defn.arg_types,
defn.dynamic_vararg,
)
handler_input = HandleUpdateInput(
id=job.id,
update=job.name,
args=args,
headers=job.headers,
)
if job.run_validator and defn.validator is not None:
with self._as_read_only(in_query_or_validator=True):
self._inbound.handle_update_validator(handler_input)
# Re-process arguments to avoid any problems caused by user mutation of them during validation
args = self._process_handler_args(
job.name,
job.input,
defn.name,
defn.arg_types,
defn.dynamic_vararg,
)
handler_input.args = args
past_validation = True
# Accept the update
command.update_response.accepted.SetInParent()
command = None # type: ignore
# Run the handler
success = await self._inbound.handle_update_handler(handler_input)
result_payloads = self._workflow_context_payload_converter.to_payloads(
[success]
)
if len(result_payloads) != 1:
raise ValueError(
f"Expected 1 result payload, got {len(result_payloads)}"
)
command = self._add_command()
command.update_response.protocol_instance_id = job.protocol_instance_id
command.update_response.completed.CopyFrom(result_payloads[0])
except (Exception, asyncio.CancelledError) as err:
logger.debug(
f"Update raised failure with run ID {self._info.run_id}",
exc_info=True,
)
# All asyncio cancelled errors become Temporal cancelled errors
if isinstance(err, asyncio.CancelledError):
err = temporalio.exceptions.CancelledError(
f"Cancellation raised within update {err}"
)
# Read-only issues during validation should fail the task
if isinstance(err, temporalio.workflow.ReadOnlyContextError):
self._current_activation_error = err
return
# Validation failures are always update failures. We reuse
# workflow failure logic to decide task failure vs update
# failure after validation.
if not past_validation or self.workflow_is_failure_exception(err):
if command is None:
command = self._add_command()
command.update_response.protocol_instance_id = (
job.protocol_instance_id
)
command.update_response.rejected.SetInParent()
self._workflow_context_failure_converter.to_failure(
err,
self._workflow_context_payload_converter,
command.update_response.rejected,
)
else:
self._current_activation_error = err
return
except BaseException:
if self._deleting:
if LOG_IGNORE_DURING_DELETE:
logger.debug(
"Ignoring exception while deleting workflow", exc_info=True
)
return
raise
finally:
self._in_progress_updates.pop(job.id, None)
self.create_task(
run_update(),
name=f"update: {job.name}",
)
def _apply_fire_timer(
self, job: temporalio.bridge.proto.workflow_activation.FireTimer
) -> None:
# We ignore an absent handler because it may have been cancelled and
# removed earlier this activation by a signal
handle = self._pending_timers.pop(job.seq, None)
if handle:
self._ready.append(handle)
def _apply_query_workflow(
self, job: temporalio.bridge.proto.workflow_activation.QueryWorkflow
) -> None:
# Wrap entire bunch of work in a task
async def run_query() -> None:
try:
with self._as_read_only(in_query_or_validator=True):
# Named query or dynamic
defn = self._queries.get(job.query_type) or self._queries.get(None)
if not defn:
known_queries = sorted([k for k in self._queries.keys() if k])
raise RuntimeError(
f"Query handler for '{job.query_type}' expected but not found, "
f"known queries: [{' '.join(known_queries)}]"
)
# Create input
args = self._process_handler_args(
job.query_type,
job.arguments,
defn.name,
defn.arg_types,
defn.dynamic_vararg,
)
input = HandleQueryInput(
id=job.query_id,
query=job.query_type,
args=args,
headers=job.headers,
)
success = await self._inbound.handle_query(input)
result_payloads = (
self._workflow_context_payload_converter.to_payloads([success])
)
if len(result_payloads) != 1:
raise ValueError(
f"Expected 1 result payload, got {len(result_payloads)}"
)
command = self._add_command()
command.respond_to_query.query_id = job.query_id
command.respond_to_query.succeeded.response.CopyFrom(result_payloads[0])
except Exception as err:
try:
command = self._add_command()
command.respond_to_query.query_id = job.query_id
self._workflow_context_failure_converter.to_failure(
err,
self._workflow_context_payload_converter,
command.respond_to_query.failed,
)
except Exception as inner_err:
raise ValueError(
"Failed converting application error"
) from inner_err
# Schedule it
self.create_task(run_query(), name=f"query: {job.query_type}")
def _apply_notify_has_patch(
self, job: temporalio.bridge.proto.workflow_activation.NotifyHasPatch
) -> None:
self._patches_notified.add(job.patch_id)
def _apply_remove_from_cache(
self, _job: temporalio.bridge.proto.workflow_activation.RemoveFromCache
) -> None:
self._deleting = True
self._cancel_requested = True
# We consider eviction to be under replay so that certain code like
# logging that avoids replaying doesn't run during eviction either
self._is_replaying = True
# Cancel everything
for task in self._tasks:
task.cancel()
def _apply_resolve_activity(
self, job: temporalio.bridge.proto.workflow_activation.ResolveActivity
) -> None:
handle = self._pending_activities.pop(job.seq, None)
if not handle:
raise RuntimeError(f"Failed finding activity handle for sequence {job.seq}")
activity_context = temporalio.converter.ActivitySerializationContext(
namespace=self._info.namespace,
workflow_id=self._info.workflow_id,
workflow_type=self._info.workflow_type,
activity_type=handle._input.activity,
activity_id=handle._input.activity_id,
activity_task_queue=(
handle._input.task_queue or self._info.task_queue
if isinstance(handle._input, StartActivityInput)
else self._info.task_queue
),
is_local=isinstance(handle._input, StartLocalActivityInput),
)
payload_converter = self._payload_converter_with_context(activity_context)
failure_converter = self._failure_converter_with_context(activity_context)
if job.result.HasField("completed"):
ret: Any | None = None
if job.result.completed.HasField("result"):
ret_types = [handle._input.ret_type] if handle._input.ret_type else None
ret_vals = self._convert_payloads(
[job.result.completed.result],
ret_types,
payload_converter,
)
ret = ret_vals[0]
handle._resolve_success(ret)
elif job.result.HasField("failed"):
handle._resolve_failure(
failure_converter.from_failure(
job.result.failed.failure, payload_converter
)
)
elif job.result.HasField("cancelled"):
handle._resolve_failure(
failure_converter.from_failure(
job.result.cancelled.failure, payload_converter
)
)
elif job.result.HasField("backoff"):
handle._resolve_backoff(job.result.backoff)
else:
raise RuntimeError("Activity did not have result")
def _apply_resolve_child_workflow_execution(
self,
job: temporalio.bridge.proto.workflow_activation.ResolveChildWorkflowExecution,
) -> None:
handle = self._pending_child_workflows.pop(job.seq, None)
if not handle:
raise RuntimeError(
f"Failed finding child workflow handle for sequence {job.seq}"
)
if job.result.HasField("completed"):
ret: Any | None = None
if job.result.completed.HasField("result"):
ret_types = [handle._input.ret_type] if handle._input.ret_type else None
ret_vals = self._convert_payloads(
[job.result.completed.result],
ret_types,
handle._payload_converter,
)
ret = ret_vals[0]
handle._resolve_success(ret)
elif job.result.HasField("failed"):
handle._resolve_failure(
handle._failure_converter.from_failure(
job.result.failed.failure, handle._payload_converter
)
)
elif job.result.HasField("cancelled"):
handle._resolve_failure(
handle._failure_converter.from_failure(
job.result.cancelled.failure, handle._payload_converter
)
)
else:
raise RuntimeError("Child workflow did not have result")
def _apply_resolve_child_workflow_execution_start(
self,
job: temporalio.bridge.proto.workflow_activation.ResolveChildWorkflowExecutionStart,
) -> None:
handle = self._pending_child_workflows.get(job.seq)
if not handle:
raise RuntimeError(
f"Failed finding child workflow handle for sequence {job.seq}"
)
if job.HasField("succeeded"):
# We intentionally do not pop here because this same handle is used
# for waiting on the entire workflow to complete
handle._resolve_start_success(job.succeeded.run_id)
elif job.HasField("failed"):
self._pending_child_workflows.pop(job.seq)
if (
job.failed.cause
== temporalio.bridge.proto.child_workflow.StartChildWorkflowExecutionFailedCause.START_CHILD_WORKFLOW_EXECUTION_FAILED_CAUSE_WORKFLOW_ALREADY_EXISTS
):
handle._resolve_failure(
temporalio.exceptions.WorkflowAlreadyStartedError(
job.failed.workflow_id, job.failed.workflow_type
)
)
else:
handle._resolve_failure(
RuntimeError(f"Unknown child start fail cause: {job.failed.cause}")
)
elif job.HasField("cancelled"):
self._pending_child_workflows.pop(job.seq)
handle._resolve_failure(
handle._failure_converter.from_failure(
job.cancelled.failure, handle._payload_converter
)
)
else:
raise RuntimeError("Child workflow start did not have a known status")
def _apply_resolve_nexus_operation_start(
self,
job: temporalio.bridge.proto.workflow_activation.ResolveNexusOperationStart,
) -> None:
handle = self._pending_nexus_operations.get(job.seq)
if not handle:
raise RuntimeError(
f"Failed to find nexus operation handle for job sequence number {job.seq}"
)
if job.HasField("operation_token"):
# The nexus operation started asynchronously. A `ResolveNexusOperation` job
# will follow in a future activation.
handle._resolve_start_success(job.operation_token)
elif job.HasField("started_sync"):
# The nexus operation 'started' in the sense that it's already resolved. A
# `ResolveNexusOperation` job will be in the same activation.
handle._resolve_start_success(None)
elif job.HasField("failed"):
# The nexus operation start failed; no ResolveNexusOperation will follow.
self._pending_nexus_operations.pop(job.seq, None)
handle._resolve_failure(
handle._failure_converter.from_failure(
job.failed, handle._payload_converter
)
)
else:
raise ValueError(f"Unknown Nexus operation start status: {job}")
def _apply_resolve_nexus_operation(
self,
job: temporalio.bridge.proto.workflow_activation.ResolveNexusOperation,
) -> None:
handle = self._pending_nexus_operations.pop(job.seq, None)
if not handle:
# One way this can occur is:
# 1. Cancel request issued with cancellation_type=WaitRequested.
# 2. Server receives nexus cancel handler task completion and writes
# NexusOperationCancelRequestCompleted / NexusOperationCancelRequestFailed. On
# consuming this event, core sends an activation resolving the handle future as
# completed / failed.
# 4. Subsequently, the nexus operation completes as completed/failed, causing the server
# to write NexusOperationCompleted / NexusOperationFailed. On consuming this event,
# core sends an activation which would attempt to resolve the handle future as
# completed / failed, but it has already been resolved.
return