Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathtask.py
More file actions
Latest commit
993 lines (814 loc) · 37.3 KB
/
Copy pathtask.py
File metadata and controls
993 lines (814 loc) · 37.3 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
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# See https://peps.python.org/pep-0563/
from __future__ importannotations
importlogging
importmath
fromabcimportABC, abstractmethod
fromcollections.abcimportCallable, Generator, Sequence
fromdataclassesimportdataclass
fromdatetimeimportdatetime, timedelta, timezone
fromtypingimportTYPE_CHECKING, Any, Generic, TypeAlias, TypeVar, cast, overload
fromdurabletask.entitiesimportDurableEntity, EntityInstanceId, EntityLock, EntityContext
importdurabletask.internal.helpersaspbh
importdurabletask.internal.orchestrator_service_pb2aspb
T=TypeVar('T')
TInput=TypeVar('TInput')
TOutput=TypeVar('TOutput')
classOrchestrationContext(ABC):
@property
@abstractmethod
definstance_id(self) ->str:
"""Get the ID of the current orchestration instance.
The instance ID is generated and fixed when the orchestrator function
is scheduled. It can be either auto-generated, in which case it is
formatted as a UUID, or it can be user-specified with any format.
Returns
-------
str
The ID of the current orchestration instance.
"""
pass
@property
@abstractmethod
defparent_instance_id(self) ->str|None:
"""Get the ID of the parent orchestration instance.
For a sub-orchestration, this is the instance ID of the orchestration
that scheduled it. For a top-level orchestration, this is ``None``.
Returns
-------
str | None
The parent orchestration instance ID, or ``None`` if this
orchestration was not scheduled by a parent orchestration.
"""
pass
@property
@abstractmethod
defversion(self) ->str|None:
"""Get the version of the orchestration instance.
This version is set when the orchestration is scheduled and can be used
to determine which version of the orchestrator function is being executed.
Returns
-------
str | None
The version of the orchestration instance, or None if not set.
"""
pass
@property
@abstractmethod
defcurrent_utc_datetime(self) ->datetime:
"""Get the current date/time as UTC.
This date/time value is derived from the orchestration history. It
always returns the same value at specific points in the orchestrator
function code, making it deterministic and safe for replay.
Returns
-------
datetime
The current timestamp in a way that is safe for use by orchestrator functions
"""
pass
@property
@abstractmethod
defis_replaying(self) ->bool:
"""Get the value indicating whether the orchestrator is replaying from history.
This property is useful when there is logic that needs to run only when
the orchestrator function is _not_ replaying. For example, certain
types of application logging may become too noisy when duplicated as
part of orchestrator function replay. The orchestrator code could check
to see whether the function is being replayed and then issue the log
statements when this value is `false`.
Returns
-------
bool
Value indicating whether the orchestrator function is currently replaying.
"""
pass
@abstractmethod
defset_custom_status(self, custom_status: Any) ->None:
"""Set the orchestration instance's custom status.
Parameters
----------
custom_status: Any
A JSON-serializable custom status value to set.
"""
pass
@abstractmethod
defcreate_timer(self, fire_at: datetime|timedelta) ->TimerTask:
"""Create a Timer Task to fire after at the specified deadline.
Parameters
----------
fire_at: datetime.datetime | datetime.timedelta
The time for the timer to trigger or a time delta from now.
Returns
-------
TimerTask
A Durable Timer Task that schedules the timer to wake up the orchestrator
"""
pass
@overload
defcall_activity(self, activity: Activity[TInput, TOutput] |str, *,
input: TInput|None= ...,
retry_policy: RetryPolicy|None= ...,
tags: dict[str, str] |None= ...,
return_type: type[T]) ->CompletableTask[T]:
...
@overload
defcall_activity(self, activity: Activity[TInput, TOutput] |str, *,
input: TInput|None= ...,
retry_policy: RetryPolicy|None= ...,
tags: dict[str, str] |None= ...,
return_type: None= ...) ->CompletableTask[TOutput]:
...
@abstractmethod
defcall_activity(self, activity: Activity[TInput, TOutput] |str, *,
input: TInput|None=None,
retry_policy: RetryPolicy|None=None,
tags: dict[str, str] |None=None,
return_type: type|None=None) ->CompletableTask[Any]:
"""Schedule an activity for execution.
Parameters
----------
activity: Activity[TInput, TOutput] | str
A reference to the activity function to call.
input: TInput | None
The JSON-serializable input (or None) to pass to the activity.
retry_policy: RetryPolicy | None
The retry policy to use for this activity call.
tags: dict[str, str] | None
Optional tags to associate with the activity invocation.
return_type: type | None
Optional type used to deserialize the activity's result. When
provided, the result is coerced to this type (dataclasses are
constructed from their dict payloads, types exposing a
``from_json()`` classmethod are reconstructed via that hook), and
the returned task is typed as ``CompletableTask[return_type]``.
When omitted, the return type is discovered from the activity
function's return annotation (if a function reference is passed and
it is annotated with a reconstructable type); otherwise the raw
deserialized JSON is returned.
Returns
-------
Task
A Durable Task that completes when the called activity function completes or fails.
"""
pass
@overload
defcall_entity(self,
entity: EntityInstanceId,
operation: str,
input: Any= ...,
*,
return_type: type[T]) ->CompletableTask[T]:
...
@overload
defcall_entity(self,
entity: EntityInstanceId,
operation: str,
input: Any= ...,
*,
return_type: None= ...) ->CompletableTask[Any]:
...
@abstractmethod
defcall_entity(self,
entity: EntityInstanceId,
operation: str,
input: Any=None,
*,
return_type: type|None=None) ->CompletableTask[Any]:
"""Schedule entity function for execution.
Parameters
----------
entity: EntityInstanceId
The ID of the entity instance to call.
operation: str
The name of the operation to invoke on the entity.
input: TInput | None
The optional JSON-serializable input to pass to the entity function.
return_type: type | None
Optional type used to deserialize the operation's result. When
provided, the result is coerced to this type and the returned task
is typed as ``CompletableTask[return_type]``; when omitted, the raw
deserialized JSON is returned.
Returns
-------
Task
A Durable Task that completes when the called entity function completes or fails.
"""
pass
@abstractmethod
defsignal_entity(
self,
entity_id: EntityInstanceId,
operation_name: str,
input: Any=None,
signal_time: datetime|None=None
) ->None:
"""Signal an entity function for execution.
Parameters
----------
entity_id: EntityInstanceId
The ID of the entity instance to signal.
operation_name: str
The name of the operation to invoke on the entity.
input: TInput | None
The optional JSON-serializable input to pass to the entity function.
signal_time: datetime | None
The optional time at which the signal should be delivered. If None, the
signal is delivered as soon as possible. Use this to schedule a future
operation on the entity.
"""
pass
@abstractmethod
deflock_entities(self, entities: list[EntityInstanceId]) ->CompletableTask[EntityLock]:
"""Creates a Task object that locks the specified entity instances.
The locks will be acquired the next time the orchestrator yields.
Best practice is to immediately yield this Task and enter the returned EntityLock.
The lock is released when the EntityLock is exited.
Parameters
----------
entities: list[EntityInstanceId]
The list of entity instance IDs to lock.
Returns
-------
EntityLock
A context manager object that releases the locks when exited.
"""
pass
@overload
defcall_sub_orchestrator(self, orchestrator: Orchestrator[TInput, TOutput] |str, *,
input: TInput|None= ...,
instance_id: str|None= ...,
retry_policy: RetryPolicy|None= ...,
version: str|None= ...,
return_type: type[T]) ->CompletableTask[T]:
...
@overload
defcall_sub_orchestrator(self, orchestrator: Orchestrator[TInput, TOutput] |str, *,
input: TInput|None= ...,
instance_id: str|None= ...,
retry_policy: RetryPolicy|None= ...,
version: str|None= ...,
return_type: None= ...) ->CompletableTask[TOutput]:
...
@abstractmethod
defcall_sub_orchestrator(self, orchestrator: Orchestrator[TInput, TOutput] |str, *,
input: TInput|None=None,
instance_id: str|None=None,
retry_policy: RetryPolicy|None=None,
version: str|None=None,
return_type: type|None=None) ->CompletableTask[Any]:
"""Schedule sub-orchestrator function for execution.
Parameters
----------
orchestrator: Orchestrator[TInput, TOutput]
A reference to the orchestrator function to call.
input: TInput | None
The optional JSON-serializable input to pass to the orchestrator function.
instance_id: str | None
A unique ID to use for the sub-orchestration instance. If not specified, a
random UUID will be used.
retry_policy: RetryPolicy | None
The retry policy to use for this sub-orchestrator call.
return_type: type | None
Optional type used to deserialize the sub-orchestrator's result. When
provided, the result is coerced to this type and the returned task is
typed as ``CompletableTask[return_type]``; when omitted, the raw
deserialized JSON is returned.
Returns
-------
Task
A Durable Task that completes when the called sub-orchestrator completes or fails.
"""
pass
# TOOD: Add a timeout parameter, which allows the task to be cancelled if the event is
# not received within the specified timeout. This requires support for task cancellation.
@overload
defwait_for_external_event(self, name: str, *,
data_type: type[T]) ->CancellableTask[T]:
...
@overload
defwait_for_external_event(self, name: str, *,
data_type: None= ...) ->CancellableTask[Any]:
...
@abstractmethod
defwait_for_external_event(self, name: str, *,
data_type: type|None=None) ->CancellableTask[Any]:
"""Wait asynchronously for an event to be raised with the name `name`.
Parameters
----------
name : str
The event name of the event that the task is waiting for.
data_type : type | None
Optional type used to deserialize the event payload. When provided,
the payload is coerced to this type and the returned task is typed
as ``CancellableTask[data_type]``; when omitted, the raw
deserialized JSON is returned.
Returns
-------
CancellableTask[Any]
A Durable Task that completes when the event is received.
"""
pass
defsend_event(self, instance_id: str, event_name: str, *,
data: Any|None=None) ->None:
"""Send an event to another orchestration instance.
The target orchestration can receive the event using
:meth:`wait_for_external_event`. This is a one-way operation and does
not wait for the target orchestration to process the event. If the
target orchestration does not exist, the event is silently dropped.
During replay, the Python SDK validates both the event name and target
instance ID. This is intentionally stricter than DurableTask.Core,
which does not validate the target instance ID.
Parameters
----------
instance_id : str
The ID of the orchestration instance to send the event to.
event_name : str
The name of the event to send. Event names are case-insensitive.
data : Any | None
The optional serializable event payload.
"""
raiseNotImplementedError(
"This OrchestrationContext implementation does not support "
"send_event()."
)
@abstractmethod
defcontinue_as_new(self, new_input: Any, *, save_events: bool=False,
new_version: str|None=None) ->None:
"""Continue the orchestration execution as a new instance.
Parameters
----------
new_input : Any
The new input to use for the new orchestration instance.
save_events : bool
A flag indicating whether to add any unprocessed external events in the new orchestration history.
new_version : str | None
An optional version to assign to the new orchestration instance.
"""
pass
@abstractmethod
defnew_uuid(self) ->str:
"""Create a new UUID that is safe for replay within an orchestration or operation.
The default implementation of this method creates a name-based UUID
using the algorithm from RFC 4122 §4.3. The name input used to generate
this value is a combination of the orchestration instance ID, the current UTC datetime,
and an internally managed counter.
Returns
-------
str
New UUID that is safe for replay within an orchestration or operation.
"""
pass
@abstractmethod
def_exit_critical_section(self) ->None:
pass
defcreate_replay_safe_logger(self, logger: logging.Logger) ->ReplaySafeLogger:
"""Create a replay-safe logger that suppresses log messages during orchestration replay.
The returned logger wraps the provided logger and only emits log messages when
the orchestrator is not replaying. This prevents duplicate log messages from
appearing as a side effect of orchestration replay.
Parameters
----------
logger : logging.Logger
The underlying logger to wrap.
Returns
-------
ReplaySafeLogger
A logger that only emits log messages when the orchestrator is not replaying.
"""
returnReplaySafeLogger(logger, lambda: self.is_replaying)
ifTYPE_CHECKING:
# logging.LoggerAdapter is generic in stubs but is not subscriptable
# at runtime before Python 3.11. Use a TYPE_CHECKING alias so the
# base class evaluates correctly at runtime.
_LoggerAdapterBase=logging.LoggerAdapter[logging.Logger]
else:
_LoggerAdapterBase=logging.LoggerAdapter
classReplaySafeLogger(_LoggerAdapterBase):
"""A logger adapter that suppresses log messages during orchestration replay.
This class extends :class:`logging.LoggerAdapter` and only emits log
messages when the orchestrator is *not* replaying. Use this to avoid
duplicate log entries that would otherwise appear every time the
orchestrator replays its history.
Obtain an instance by calling :meth:`OrchestrationContext.create_replay_safe_logger`.
"""
def__init__(self, logger: logging.Logger, is_replaying: Callable[[], bool]) ->None:
super().__init__(logger, {})
self._is_replaying=is_replaying
defisEnabledFor(self, level: int) ->bool:
"""Return whether logging is enabled for the given level.
Returns ``False`` while the orchestrator is replaying so that callers
can skip expensive message formatting during replay.
"""
ifself._is_replaying():
returnFalse
returnself.logger.isEnabledFor(level)
@dataclass(frozen=True)
classFailureDetails:
message: str
error_type: str
stack_trace: str|None
defis_caused_by(self, error_type: str|type[BaseException]) ->bool:
"""Return ``True`` if this failure was caused by ``error_type``.
This mirrors the .NET ``TaskFailureDetails.IsCausedBy<T>()`` and Java
``FailureDetails.isCausedBy(Class)`` helpers, letting a caller introspect
a failure instead of comparing :attr:`error_type` strings by hand::
try:
yield ctx.call_activity(my_activity)
except TaskFailedError as e:
if e.details.is_caused_by(ValueError):
...
``error_type`` may be either an exception type or a name string:
* When an exception **type** is given, the check is base-type aware: it
returns ``True`` if the failure's type is ``error_type`` or any of its
subclasses. To stay safe, this only inspects exception subclasses that
are already imported in the current process (it never imports a type by
name), so a subclass whose module has not been imported yet will not be
matched. Passing a non-exception type raises :class:`TypeError`.
* When a **string** is given, it is compared by name only (no base-type
awareness). The name may be fully qualified (``"module.ClassName"``) or
unqualified (``"ClassName"``); an unqualified name matches on the class
name alone and therefore cannot distinguish same-named types from
different modules.
Only this failure's own :attr:`error_type` is considered; chained/inner
causes are not traversed.
"""
ifisinstance(error_type, str):
returnself._name_matches(error_type)
# The annotation restricts callers to exception types, but this is a
# public API, so validate at runtime against arbitrary objects.
ifnot (isinstance(error_type, type) andissubclass(error_type, BaseException)): # pyright: ignore[reportUnnecessaryIsInstance]
raiseTypeError(
"is_caused_by() expects an exception type or a type-name string, "
f"but got {error_type!r}.")
# Base-type-aware match without importing the failure's type: walk the
# target type and its already-loaded subclasses (visited-marked to guard
# against diamond inheritance) and compare each candidate's qualified
# name against this failure's error_type.
visited: set[int] =set()
stack: list[type] = [error_type]
whilestack:
candidate=stack.pop()
ifid(candidate) invisited:
continue
visited.add(id(candidate))
ifself._type_matches(candidate):
returnTrue
stack.extend(candidate.__subclasses__())
returnFalse
def_type_matches(self, candidate: type) ->bool:
ifnotself.error_type:
returnFalse
candidate_name=pbh.get_qualified_name(candidate)
ifself.error_type==candidate_name:
returnTrue
# Back-compat: a bare (non-qualified) stored name -- e.g. produced by an
# older SDK version or a non-Python SDK -- can only be compared by the
# unqualified class name.
if"."notinself.error_type:
returnself.error_type==candidate_name.rsplit(".", 1)[-1]
returnFalse
def_name_matches(self, name: str) ->bool:
stored=self.error_type
ifnotstoredornotname:
returnFalse
ifstored==name:
returnTrue
# When both names are fully qualified, require an exact match so that
# same-named types from different modules are not confused. Otherwise,
# honor the "qualified or unqualified" contract by comparing the
# unqualified (trailing) segment.
if"."instoredand"."inname:
returnFalse
returnstored.rsplit(".", 1)[-1] ==name.rsplit(".", 1)[-1]
classTaskFailedError(Exception):
"""Exception type for all orchestration task failures."""
def__init__(self, message: str, details: pb.TaskFailureDetails|Exception):
super().__init__(message)
ifisinstance(details, Exception):
details=pbh.new_failure_details(details)
self._details=FailureDetails(
details.errorMessage,
details.errorType,
details.stackTrace.valueifnotpbh.is_empty(details.stackTrace) elseNone)
@property
defdetails(self) ->FailureDetails:
returnself._details
classNonDeterminismError(Exception):
pass
classOrchestrationStateError(Exception):
pass
classTaskCancelledError(Exception):
"""Exception type for cancelled orchestration tasks."""
classTask(ABC, Generic[T]):
"""Abstract base class for asynchronous tasks in a durable orchestration."""
_result: T
_exception: TaskFailedError|None
_parent: CompositeTask[Any] |None
def__init__(self) ->None:
super().__init__()
self._is_complete=False
self._exception=None
self._parent=None
@property
defis_complete(self) ->bool:
"""Returns True if the task has completed, False otherwise."""
returnself._is_complete
@property
defis_failed(self) ->bool:
"""Returns True if the task has failed, False otherwise."""
returnself._exceptionisnotNone
@property
defresult(self) ->T:
"""Returns the result of the task (alias for :meth:`get_result`)."""
returnself.get_result()
defget_result(self) ->T:
"""Returns the result of the task."""
ifnotself._is_complete:
raiseValueError('The task has not completed.')
elifself._exceptionisnotNone:
raiseself._exception
returnself._result
defget_exception(self) ->TaskFailedError:
"""Returns the exception that caused the task to fail."""
ifself._exceptionisNone:
raiseValueError('The task has not failed.')
returnself._exception
classCompositeTask(Task[T]):
"""A task that is composed of other tasks."""
_tasks: list[Task[Any]]
_completed_tasks: int
_failed_tasks: int
def__init__(self, tasks: list[Task[Any]]):
super().__init__()
self._tasks=tasks
self._completed_tasks=0
self._failed_tasks=0
fortaskintasks:
task._parent=self
iftask.is_complete:
self.on_child_completed(task)
defget_tasks(self) ->list[Task[Any]]:
returnself._tasks
@abstractmethod
defon_child_completed(self, task: Task[Any]) ->None:
pass
classWhenAllTask(CompositeTask[list[T]]):
"""A task that completes when all of its child tasks complete."""
def__init__(self, tasks: list[Task[T]]):
# Initialize state that on_child_completed() reads BEFORE invoking the
# base constructor: CompositeTask.__init__ calls on_child_completed()
# for any children that are already complete, so `_pending_exception`
# must exist first. The base constructor also initializes
# `_completed_tasks`/`_failed_tasks` to 0 and then accounts for
# pre-completed children, so they must not be reset afterwards.
self._pending_exception: TaskFailedError|None=None
super().__init__(cast(list[Task[Any]], tasks))
@property
defpending_tasks(self) ->int:
"""Returns the number of tasks that have not yet completed."""
returnlen(self._tasks) -self._completed_tasks
defon_child_completed(self, task: Task[Any]) ->None:
ifself.is_complete:
raiseValueError('The task has already completed.')
self._completed_tasks+=1
iftask.is_failed:
self._failed_tasks+=1
ifself._pending_exceptionisNone:
# Stage the first failure but do NOT expose it via `_exception`
# yet. Exposing it now would make `is_failed` return True while
# `is_complete` is still False, diverging from .NET's
# Task.WhenAll (which does not fault until all children finish).
self._pending_exception=task.get_exception()
ifself._completed_tasks==len(self._tasks):
# Only complete once every child task has completed. This matches the
# semantics of .NET's Task.WhenAll: the composite task waits for all
# children to finish and, if any failed, surfaces the first failure
# rather than failing fast on the first error.
self._is_complete=True
ifself._pending_exceptionisnotNone:
self._exception=self._pending_exception
else:
# The order of the result MUST match the order of the tasks
# provided to the constructor.
self._result= [child.get_result() forchildinself._tasks]
defget_completed_tasks(self) ->int:
returnself._completed_tasks
classCompletableTask(Task[T]):
def__init__(self, expected_type: type|None=None) ->None:
super().__init__()
self._retryable_parent: RetryableTask[Any] |None=None
self._expected_type=expected_type
defcomplete(self, result: T):
ifself._is_complete:
raiseValueError('The task has already completed.')
self._result=result
self._is_complete=True
ifself._parentisnotNone:
self._parent.on_child_completed(self)
deffail(self, message: str, details: Exception|pb.TaskFailureDetails):
ifself._is_complete:
raiseValueError('The task has already completed.')
self._exception=TaskFailedError(message, details)
self._is_complete=True
ifself._parentisnotNone:
self._parent.on_child_completed(self)
classCancellableTask(CompletableTask[T]):
"""A completable task that can be cancelled before it finishes."""
def__init__(self, expected_type: type|None=None) ->None:
super().__init__(expected_type)
self._is_cancelled=False
self._cancel_handler: Callable[[], None] |None=None
@property
defis_cancelled(self) ->bool:
"""Returns True if the task was cancelled, False otherwise."""
returnself._is_cancelled
defget_result(self) ->T:
ifself._is_cancelled:
raiseTaskCancelledError('The task was cancelled.')
returnsuper().get_result()
defset_cancel_handler(self, cancel_handler: Callable[[], None]) ->None:
self._cancel_handler=cancel_handler
defcancel(self) ->bool:
"""Attempts to cancel this task.
Returns
-------
bool
True if cancellation was applied, False if the task had already completed.
"""
ifself._is_complete:
returnFalse
ifself._cancel_handlerisnotNone:
self._cancel_handler()
self._is_cancelled=True
self._is_complete=True
ifself._parentisnotNone:
self._parent.on_child_completed(self)
returnTrue
classRetryableTask(CompletableTask[T]):
"""A task that can be retried according to a retry policy."""
def__init__(self, retry_policy: RetryPolicy, action: pb.OrchestratorAction,
start_time: datetime, is_sub_orch: bool,
expected_type: type|None=None) ->None:
super().__init__(expected_type)
self._action=action
self._retry_policy=retry_policy
self._attempt_count=1
self._start_time=start_time
self._is_sub_orch=is_sub_orch
defincrement_attempt_count(self) ->None:
self._attempt_count+=1
defcompute_next_delay(self) ->timedelta|None:
ifself._attempt_count>=self._retry_policy.max_number_of_attempts:
returnNone
retry_expiration: datetime=datetime.max
ifself._retry_policy.retry_timeoutisnotNoneandself._retry_policy.retry_timeout!=datetime.max:
retry_expiration=self._start_time+self._retry_policy.retry_timeout
ifself._retry_policy.backoff_coefficientisNone:
backoff_coefficient=1.0
else:
backoff_coefficient=self._retry_policy.backoff_coefficient
ifdatetime.now(tz=timezone.utc).replace(tzinfo=None) <retry_expiration:
next_delay_f=math.pow(backoff_coefficient, self._attempt_count-1) *self._retry_policy.first_retry_interval.total_seconds()
ifself._retry_policy.max_retry_intervalisnotNone:
next_delay_f=min(next_delay_f, self._retry_policy.max_retry_interval.total_seconds())
returntimedelta(seconds=next_delay_f)
returnNone
classTimerTask(CancellableTask[None]):
def__init__(self, final_fire_at: datetime|None=None,
maximum_timer_interval: timedelta|None=None):
super().__init__()
self._final_fire_at=final_fire_at
self._maximum_timer_interval=maximum_timer_interval
defset_retryable_parent(self, retryable_task: RetryableTask[Any]) ->None:
self._retryable_parent=retryable_task
def_handle_timer_fired(self, current_utc_datetime: datetime) ->datetime|None:
if (self._final_fire_atisnotNone
andself._maximum_timer_intervalisnotNone
andcurrent_utc_datetime<self._final_fire_at):
returnself._get_next_fire_at(current_utc_datetime)
super().complete(None)
returnNone
def_get_next_fire_at(self, current_utc_datetime: datetime) ->datetime:
# _handle_timer_fired guards both attributes before calling this method.
assertself._final_fire_atisnotNone
assertself._maximum_timer_intervalisnotNone
ifcurrent_utc_datetime+self._maximum_timer_interval<self._final_fire_at:
returncurrent_utc_datetime+self._maximum_timer_interval
returnself._final_fire_at
classWhenAnyTask(CompositeTask[Task[T]], Generic[T]):
"""A task that completes when any of its child tasks complete."""
def__init__(self, tasks: list[Task[T]]):
super().__init__(cast(list[Task[Any]], tasks))
defon_child_completed(self, task: Task[Any]) ->None:
# The first task to complete is the result of the WhenAnyTask.
ifnotself.is_complete:
self._is_complete=True
self._result=cast(Task[T], task)
defwhen_all(tasks: list[Task[T]]) ->WhenAllTask[T]:
"""Returns a task that completes when all of the provided tasks complete or when one of the tasks fail."""
returnWhenAllTask(tasks)
defwhen_any(tasks: Sequence[Task[T]]) ->WhenAnyTask[T]:
"""Returns a task that completes when any of the provided tasks complete or fail."""
returnWhenAnyTask(list(tasks))
classActivityContext:
def__init__(self, orchestration_id: str, task_id: int):
self._orchestration_id=orchestration_id
self._task_id=task_id
@property
deforchestration_id(self) ->str:
"""Get the ID of the orchestration instance that scheduled this activity.
Returns
-------
str
The ID of the current orchestration instance.
"""
returnself._orchestration_id
@property
deftask_id(self) ->int:
"""Get the task ID associated with this activity invocation.
The task ID is an auto-incrementing integer that is unique within
the scope of the orchestration instance. It can be used to distinguish
between multiple activity invocations that are part of the same
orchestration instance.
Returns
-------
str
The ID of the current orchestration instance.
"""
returnself._task_id
# Orchestrators are generators that yield tasks, receive any type, and return TOutput
Orchestrator: TypeAlias=Callable[[OrchestrationContext, TInput], Generator[Task[Any], Any, TOutput] |TOutput]
# Activities are simple functions that can be scheduled by orchestrators
Activity: TypeAlias=Callable[[ActivityContext, TInput], TOutput]
Entity: TypeAlias=Callable[[EntityContext, TInput], TOutput] |type[DurableEntity]
classRetryPolicy:
"""Represents the retry policy for an orchestration or activity function."""
def__init__(self, *,
first_retry_interval: timedelta,
max_number_of_attempts: int,
backoff_coefficient: float|None=1.0,
max_retry_interval: timedelta|None=None,
retry_timeout: timedelta|None=None):
"""Creates a new RetryPolicy instance.
Parameters
----------
first_retry_interval : timedelta
The retry interval to use for the first retry attempt.
max_number_of_attempts : int
The maximum number of retry attempts.
backoff_coefficient : float | None
The backoff coefficient to use for calculating the next retry interval.
max_retry_interval : timedelta | None
The maximum retry interval to use for any retry attempt.
retry_timeout : timedelta | None
The maximum amount of time to spend retrying the operation.
"""
# validate inputs
iffirst_retry_interval<timedelta(seconds=0):
raiseValueError('first_retry_interval must be >= 0')
ifmax_number_of_attempts<1:
raiseValueError('max_number_of_attempts must be >= 1')
ifbackoff_coefficientisnotNoneandbackoff_coefficient<1:
raiseValueError('backoff_coefficient must be >= 1')
ifmax_retry_intervalisnotNoneandmax_retry_interval<timedelta(seconds=0):
raiseValueError('max_retry_interval must be >= 0')
ifretry_timeoutisnotNoneandretry_timeout<timedelta(seconds=0):
raiseValueError('retry_timeout must be >= 0')
self._first_retry_interval=first_retry_interval
self._max_number_of_attempts=max_number_of_attempts
self._backoff_coefficient=backoff_coefficient
self._max_retry_interval=max_retry_interval
self._retry_timeout=retry_timeout
@property
deffirst_retry_interval(self) ->timedelta:
"""The retry interval to use for the first retry attempt."""
returnself._first_retry_interval
@property
defmax_number_of_attempts(self) ->int:
"""The maximum number of retry attempts."""
returnself._max_number_of_attempts
@property
defbackoff_coefficient(self) ->float|None:
"""The backoff coefficient to use for calculating the next retry interval."""
returnself._backoff_coefficient
@property
defmax_retry_interval(self) ->timedelta|None:
"""The maximum retry interval to use for any retry attempt."""
returnself._max_retry_interval
@property
defretry_timeout(self) ->timedelta|None:
"""The maximum amount of time to spend retrying the operation."""
returnself._retry_timeout
defget_entity_name(fn: Entity[Any, Any]) ->str:
ifhasattr(fn, "__durable_entity_name__"):
returngetattr(fn, "__durable_entity_name__")
ifisinstance(fn, type) andissubclass(fn, DurableEntity):
returnfn.__name__
returnget_name(cast(Callable[..., Any], fn))
defget_name(fn: Callable[..., Any]) ->str:
"""Returns the name of the provided function"""
name=fn.__name__
ifname=='<lambda>':
raiseValueError('Cannot infer a name from a lambda function. Please provide a name explicitly.')
returnname