-
Notifications
You must be signed in to change notification settings - Fork 208
Expand file tree
/
Copy path_schedule.py
More file actions
1604 lines (1355 loc) · 54.4 KB
/
Copy path_schedule.py
File metadata and controls
1604 lines (1355 loc) · 54.4 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 dataclasses
from abc import ABC, abstractmethod
from collections.abc import (
Awaitable,
Callable,
Mapping,
Sequence,
)
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from enum import IntEnum
from typing import (
TYPE_CHECKING,
Any,
Concatenate,
overload,
)
import google.protobuf.duration_pb2
import google.protobuf.timestamp_pb2
import temporalio.api.common.v1
import temporalio.api.enums.v1
import temporalio.api.schedule.v1
import temporalio.api.taskqueue.v1
import temporalio.api.workflow.v1
import temporalio.api.workflowservice.v1
import temporalio.common
import temporalio.converter
import temporalio.workflow
from temporalio.converter import (
StorageDriverStoreContext,
StorageDriverWorkflowInfo,
WorkflowSerializationContext,
)
from ..common import HeaderCodecBehavior
from ..types import (
AnyType,
MethodAsyncNoParam,
MethodAsyncSingleParam,
MultiParamSpec,
ParamType,
ReturnType,
SelfType,
)
from ._helpers import _apply_headers, _encode_user_metadata
from ._interceptor import (
BackfillScheduleInput,
DeleteScheduleInput,
DescribeScheduleInput,
PauseScheduleInput,
TriggerScheduleInput,
UnpauseScheduleInput,
UpdateScheduleInput,
)
if TYPE_CHECKING:
from ._client import Client
from ._interceptor import ListSchedulesInput
class ScheduleHandle:
"""Handle for interacting with a schedule.
This is usually created via :py:meth:`Client.get_schedule_handle` or
returned from :py:meth:`Client.create_schedule`.
Attributes:
id: ID of the schedule.
"""
def __init__(self, client: Client, id: str) -> None:
"""Create schedule handle."""
self._client = client
self.id = id
async def backfill(
self,
*backfill: ScheduleBackfill,
rpc_metadata: Mapping[str, str | bytes] = {},
rpc_timeout: timedelta | None = None,
) -> None:
"""Backfill the schedule by going through the specified time periods as
if they passed right now.
Args:
backfill: Backfill periods.
rpc_metadata: Headers used on the RPC call. Keys here override
client-level RPC metadata keys.
rpc_timeout: Optional RPC deadline to set for the RPC call.
"""
if not backfill:
raise ValueError("At least one backfill required")
await self._client._impl.backfill_schedule(
BackfillScheduleInput(
id=self.id,
backfills=backfill,
rpc_metadata=rpc_metadata,
rpc_timeout=rpc_timeout,
),
)
async def delete(
self,
*,
rpc_metadata: Mapping[str, str | bytes] = {},
rpc_timeout: timedelta | None = None,
) -> None:
"""Delete this schedule.
Args:
rpc_metadata: Headers used on the RPC call. Keys here override
client-level RPC metadata keys.
rpc_timeout: Optional RPC deadline to set for the RPC call.
"""
await self._client._impl.delete_schedule(
DeleteScheduleInput(
id=self.id,
rpc_metadata=rpc_metadata,
rpc_timeout=rpc_timeout,
),
)
async def describe(
self,
*,
rpc_metadata: Mapping[str, str | bytes] = {},
rpc_timeout: timedelta | None = None,
) -> ScheduleDescription:
"""Fetch this schedule's description.
Args:
rpc_metadata: Headers used on the RPC call. Keys here override
client-level RPC metadata keys.
rpc_timeout: Optional RPC deadline to set for the RPC call.
"""
return await self._client._impl.describe_schedule(
DescribeScheduleInput(
id=self.id,
rpc_metadata=rpc_metadata,
rpc_timeout=rpc_timeout,
),
)
async def pause(
self,
*,
note: str | None = None,
rpc_metadata: Mapping[str, str | bytes] = {},
rpc_timeout: timedelta | None = None,
) -> None:
"""Pause the schedule and set a note.
Args:
note: Note to set on the schedule.
rpc_metadata: Headers used on the RPC call. Keys here override
client-level RPC metadata keys.
rpc_timeout: Optional RPC deadline to set for the RPC call.
"""
await self._client._impl.pause_schedule(
PauseScheduleInput(
id=self.id,
note=note,
rpc_metadata=rpc_metadata,
rpc_timeout=rpc_timeout,
),
)
async def trigger(
self,
*,
overlap: ScheduleOverlapPolicy | None = None,
rpc_metadata: Mapping[str, str | bytes] = {},
rpc_timeout: timedelta | None = None,
) -> None:
"""Trigger an action on this schedule to happen immediately.
Args:
overlap: If set, overrides the schedule's overlap policy.
rpc_metadata: Headers used on the RPC call. Keys here override
client-level RPC metadata keys.
rpc_timeout: Optional RPC deadline to set for the RPC call.
"""
await self._client._impl.trigger_schedule(
TriggerScheduleInput(
id=self.id,
overlap=overlap,
rpc_metadata=rpc_metadata,
rpc_timeout=rpc_timeout,
),
)
async def unpause(
self,
*,
note: str | None = None,
rpc_metadata: Mapping[str, str | bytes] = {},
rpc_timeout: timedelta | None = None,
) -> None:
"""Unpause the schedule and set a note.
Args:
note: Note to set on the schedule.
rpc_metadata: Headers used on the RPC call. Keys here override
client-level RPC metadata keys.
rpc_timeout: Optional RPC deadline to set for the RPC call.
"""
await self._client._impl.unpause_schedule(
UnpauseScheduleInput(
id=self.id,
note=note,
rpc_metadata=rpc_metadata,
rpc_timeout=rpc_timeout,
),
)
@overload
async def update(
self,
updater: Callable[[ScheduleUpdateInput], ScheduleUpdate | None],
*,
rpc_metadata: Mapping[str, str | bytes] = {},
rpc_timeout: timedelta | None = None,
) -> None: ...
@overload
async def update(
self,
updater: Callable[[ScheduleUpdateInput], Awaitable[ScheduleUpdate | None]],
*,
rpc_metadata: Mapping[str, str | bytes] = {},
rpc_timeout: timedelta | None = None,
) -> None: ...
async def update(
self,
updater: Callable[
[ScheduleUpdateInput],
ScheduleUpdate | None | Awaitable[ScheduleUpdate | None],
],
*,
rpc_metadata: Mapping[str, str | bytes] = {},
rpc_timeout: timedelta | None = None,
) -> None:
"""Update a schedule using a callback to build the update from the
description.
The callback may be invoked multiple times in a conflict-resolution
loop.
Args:
updater: Callback that returns the update. It accepts a
:py:class:`ScheduleUpdateInput` and returns a
:py:class:`ScheduleUpdate`. If None is returned or an error
occurs, the update is not attempted. This may be called multiple
times.
rpc_metadata: Headers used on the RPC call. Keys here override
client-level RPC metadata keys. This is for every call made
within.
rpc_timeout: Optional RPC deadline to set for the RPC call. This is
for each call made within, not overall.
"""
await self._client._impl.update_schedule(
UpdateScheduleInput(
id=self.id,
updater=updater,
rpc_metadata=rpc_metadata,
rpc_timeout=rpc_timeout,
),
)
@dataclass
class ScheduleSpec:
"""Specification of the times scheduled actions may occur.
The times are the union of :py:attr:`calendars`, :py:attr:`intervals`, and
:py:attr:`cron_expressions` excluding anything in :py:attr:`skip`.
"""
calendars: Sequence[ScheduleCalendarSpec] = dataclasses.field(default_factory=list)
"""Calendar-based specification of times."""
intervals: Sequence[ScheduleIntervalSpec] = dataclasses.field(default_factory=list)
"""Interval-based specification of times."""
cron_expressions: Sequence[str] = dataclasses.field(default_factory=list)
"""Cron-based specification of times.
This is provided for easy migration from legacy string-based cron
scheduling. New uses should use :py:attr:`calendars` instead. These
expressions will be translated to calendar-based specifications on the
server.
"""
skip: Sequence[ScheduleCalendarSpec] = dataclasses.field(default_factory=list)
"""Set of matching calendar times that will be skipped."""
start_at: datetime | None = None
"""Time before which any matching times will be skipped."""
end_at: datetime | None = None
"""Time after which any matching times will be skipped."""
jitter: timedelta | None = None
"""Jitter to apply each action.
An action's scheduled time will be incremented by a random value between 0
and this value if present (but not past the next schedule).
"""
time_zone_name: str | None = None
"""IANA time zone name, for example ``US/Central``."""
@staticmethod
def _from_proto(spec: temporalio.api.schedule.v1.ScheduleSpec) -> ScheduleSpec:
return ScheduleSpec(
calendars=[
ScheduleCalendarSpec._from_proto(c) for c in spec.structured_calendar
],
intervals=[ScheduleIntervalSpec._from_proto(i) for i in spec.interval],
cron_expressions=spec.cron_string,
skip=[
ScheduleCalendarSpec._from_proto(c)
for c in spec.exclude_structured_calendar
],
start_at=spec.start_time.ToDatetime().replace(tzinfo=timezone.utc)
if spec.HasField("start_time")
else None,
end_at=spec.end_time.ToDatetime().replace(tzinfo=timezone.utc)
if spec.HasField("end_time")
else None,
jitter=spec.jitter.ToTimedelta() if spec.HasField("jitter") else None,
time_zone_name=spec.timezone_name or None,
)
def _to_proto(self) -> temporalio.api.schedule.v1.ScheduleSpec:
start_time: google.protobuf.timestamp_pb2.Timestamp | None = None
if self.start_at:
start_time = google.protobuf.timestamp_pb2.Timestamp()
start_time.FromDatetime(self.start_at)
end_time: google.protobuf.timestamp_pb2.Timestamp | None = None
if self.end_at:
end_time = google.protobuf.timestamp_pb2.Timestamp()
end_time.FromDatetime(self.end_at)
jitter: google.protobuf.duration_pb2.Duration | None = None
if self.jitter:
jitter = google.protobuf.duration_pb2.Duration()
jitter.FromTimedelta(self.jitter)
return temporalio.api.schedule.v1.ScheduleSpec(
structured_calendar=[cal._to_proto() for cal in self.calendars],
cron_string=self.cron_expressions,
interval=[i._to_proto() for i in self.intervals],
exclude_structured_calendar=[cal._to_proto() for cal in self.skip],
start_time=start_time,
end_time=end_time,
jitter=jitter,
timezone_name=self.time_zone_name or "",
)
@dataclass(frozen=True)
class ScheduleRange:
"""Inclusive range for a schedule match value."""
start: int
"""Inclusive start of the range."""
end: int = 0
"""Inclusive end of the range.
If unset or less than start, defaults to start.
"""
step: int = 0
"""
Step to take between each value.
Unset or 0 defaults as 1.
"""
def __post_init__(self):
"""Set field defaults."""
# Class is frozen, so we must setattr bypassing dataclass setattr
if self.end < self.start:
object.__setattr__(self, "end", self.start)
if self.step == 0:
object.__setattr__(self, "step", 1)
@staticmethod
def _from_protos(
ranges: Sequence[temporalio.api.schedule.v1.Range],
) -> Sequence[ScheduleRange]:
return tuple(ScheduleRange._from_proto(r) for r in ranges)
@staticmethod
def _from_proto(range: temporalio.api.schedule.v1.Range) -> ScheduleRange:
return ScheduleRange(start=range.start, end=range.end, step=range.step)
@staticmethod
def _to_protos(
ranges: Sequence[ScheduleRange],
) -> Sequence[temporalio.api.schedule.v1.Range]:
return tuple(r._to_proto() for r in ranges)
def _to_proto(self) -> temporalio.api.schedule.v1.Range:
return temporalio.api.schedule.v1.Range(
start=self.start, end=self.end, step=self.step
)
@dataclass
class ScheduleCalendarSpec:
"""Specification relative to calendar time when to run an action.
A timestamp matches if at least one range of each field matches except for
year. If year is missing, that means all years match. For all fields besides
year, at least one range must be present to match anything.
"""
second: Sequence[ScheduleRange] = (ScheduleRange(0),)
"""Second range to match, 0-59. Default matches 0."""
minute: Sequence[ScheduleRange] = (ScheduleRange(0),)
"""Minute range to match, 0-59. Default matches 0."""
hour: Sequence[ScheduleRange] = (ScheduleRange(0),)
"""Hour range to match, 0-23. Default matches 0."""
day_of_month: Sequence[ScheduleRange] = (ScheduleRange(1, 31),)
"""Day of month range to match, 1-31. Default matches all days."""
month: Sequence[ScheduleRange] = (ScheduleRange(1, 12),)
"""Month range to match, 1-12. Default matches all months."""
year: Sequence[ScheduleRange] = ()
"""Optional year range to match. Default of empty matches all years."""
day_of_week: Sequence[ScheduleRange] = (ScheduleRange(0, 6),)
"""Day of week range to match, 0-6, 0 is Sunday. Default matches all
days."""
comment: str | None = None
"""Description of this schedule."""
@staticmethod
def _from_proto(
spec: temporalio.api.schedule.v1.StructuredCalendarSpec,
) -> ScheduleCalendarSpec:
return ScheduleCalendarSpec(
second=ScheduleRange._from_protos(spec.second),
minute=ScheduleRange._from_protos(spec.minute),
hour=ScheduleRange._from_protos(spec.hour),
day_of_month=ScheduleRange._from_protos(spec.day_of_month),
month=ScheduleRange._from_protos(spec.month),
year=ScheduleRange._from_protos(spec.year),
day_of_week=ScheduleRange._from_protos(spec.day_of_week),
comment=spec.comment or None,
)
def _to_proto(self) -> temporalio.api.schedule.v1.StructuredCalendarSpec:
return temporalio.api.schedule.v1.StructuredCalendarSpec(
second=ScheduleRange._to_protos(self.second),
minute=ScheduleRange._to_protos(self.minute),
hour=ScheduleRange._to_protos(self.hour),
day_of_month=ScheduleRange._to_protos(self.day_of_month),
month=ScheduleRange._to_protos(self.month),
year=ScheduleRange._to_protos(self.year),
day_of_week=ScheduleRange._to_protos(self.day_of_week),
comment=self.comment or "",
)
@dataclass
class ScheduleIntervalSpec:
"""Specification for scheduling on an interval.
Matches times expressed as epoch + (n * every) + offset.
"""
every: timedelta
"""Period to repeat the interval."""
offset: timedelta | None = None
"""Fixed offset added to each interval period."""
@staticmethod
def _from_proto(
spec: temporalio.api.schedule.v1.IntervalSpec,
) -> ScheduleIntervalSpec:
return ScheduleIntervalSpec(
every=spec.interval.ToTimedelta(),
offset=spec.phase.ToTimedelta() if spec.HasField("phase") else None,
)
def _to_proto(self) -> temporalio.api.schedule.v1.IntervalSpec:
interval = google.protobuf.duration_pb2.Duration()
interval.FromTimedelta(self.every)
phase: google.protobuf.duration_pb2.Duration | None = None
if self.offset:
phase = google.protobuf.duration_pb2.Duration()
phase.FromTimedelta(self.offset)
return temporalio.api.schedule.v1.IntervalSpec(interval=interval, phase=phase)
class ScheduleAction(ABC):
"""Base class for an action a schedule can take.
See :py:class:`ScheduleActionStartWorkflow` for the most commonly used
implementation.
"""
@staticmethod
def _from_proto(
action: temporalio.api.schedule.v1.ScheduleAction,
) -> ScheduleAction:
if action.HasField("start_workflow"):
return ScheduleActionStartWorkflow._from_proto(action.start_workflow)
else:
raise ValueError(f"Unsupported action: {action.WhichOneof('action')}")
@abstractmethod
async def _to_proto(
self, client: Client
) -> temporalio.api.schedule.v1.ScheduleAction: ...
@dataclass
class ScheduleActionStartWorkflow(ScheduleAction):
"""Schedule action to start a workflow."""
workflow: str
args: Sequence[Any] | Sequence[temporalio.api.common.v1.Payload]
id: str
task_queue: str
execution_timeout: timedelta | None
run_timeout: timedelta | None
task_timeout: timedelta | None
retry_policy: temporalio.common.RetryPolicy | None
memo: None | (Mapping[str, Any] | Mapping[str, temporalio.api.common.v1.Payload])
typed_search_attributes: temporalio.common.TypedSearchAttributes
untyped_search_attributes: temporalio.common.SearchAttributes
"""This is deprecated and is only present in case existing untyped
attributes already exist for update. This should never be used when
creating."""
static_summary: str | temporalio.api.common.v1.Payload | None
static_details: str | temporalio.api.common.v1.Payload | None
priority: temporalio.common.Priority
headers: Mapping[str, temporalio.api.common.v1.Payload] | None
"""
Headers may still be encoded by the payload codec if present.
"""
_from_raw: bool = dataclasses.field(compare=False, init=False)
@staticmethod
def _from_proto( # pyright: ignore
info: temporalio.api.workflow.v1.NewWorkflowExecutionInfo, # type: ignore[override]
) -> ScheduleActionStartWorkflow:
return ScheduleActionStartWorkflow("<unset>", raw_info=info)
# Overload for no-param workflow
@overload
def __init__(
self,
workflow: MethodAsyncNoParam[SelfType, ReturnType],
*,
id: str,
task_queue: str,
execution_timeout: timedelta | None = None,
run_timeout: timedelta | None = None,
task_timeout: timedelta | None = None,
retry_policy: temporalio.common.RetryPolicy | None = None,
memo: Mapping[str, Any] | None = None,
typed_search_attributes: temporalio.common.TypedSearchAttributes = temporalio.common.TypedSearchAttributes.empty,
static_summary: str | None = None,
static_details: str | None = None,
priority: temporalio.common.Priority = temporalio.common.Priority.default,
) -> None: ...
# Overload for single-param workflow
@overload
def __init__(
self,
workflow: MethodAsyncSingleParam[SelfType, ParamType, ReturnType],
arg: ParamType,
*,
id: str,
task_queue: str,
execution_timeout: timedelta | None = None,
run_timeout: timedelta | None = None,
task_timeout: timedelta | None = None,
retry_policy: temporalio.common.RetryPolicy | None = None,
memo: Mapping[str, Any] | None = None,
typed_search_attributes: temporalio.common.TypedSearchAttributes = temporalio.common.TypedSearchAttributes.empty,
static_summary: str | None = None,
static_details: str | None = None,
priority: temporalio.common.Priority = temporalio.common.Priority.default,
) -> None: ...
# Overload for multi-param workflow
@overload
def __init__(
self,
workflow: Callable[
Concatenate[SelfType, MultiParamSpec], Awaitable[ReturnType]
],
*,
args: Sequence[Any],
id: str,
task_queue: str,
execution_timeout: timedelta | None = None,
run_timeout: timedelta | None = None,
task_timeout: timedelta | None = None,
retry_policy: temporalio.common.RetryPolicy | None = None,
memo: Mapping[str, Any] | None = None,
typed_search_attributes: temporalio.common.TypedSearchAttributes = temporalio.common.TypedSearchAttributes.empty,
static_summary: str | None = None,
static_details: str | None = None,
priority: temporalio.common.Priority = temporalio.common.Priority.default,
) -> None: ...
# Overload for string-name workflow
@overload
def __init__(
self,
workflow: str,
arg: Any = temporalio.common._arg_unset,
*,
args: Sequence[Any] = [],
id: str,
task_queue: str,
execution_timeout: timedelta | None = None,
run_timeout: timedelta | None = None,
task_timeout: timedelta | None = None,
retry_policy: temporalio.common.RetryPolicy | None = None,
memo: Mapping[str, Any] | None = None,
typed_search_attributes: temporalio.common.TypedSearchAttributes = temporalio.common.TypedSearchAttributes.empty,
static_summary: str | None = None,
static_details: str | None = None,
priority: temporalio.common.Priority = temporalio.common.Priority.default,
) -> None: ...
# Overload for raw info
@overload
def __init__(
self,
workflow: str,
*,
raw_info: temporalio.api.workflow.v1.NewWorkflowExecutionInfo,
) -> None: ...
def __init__(
self,
workflow: str | Callable[..., Awaitable[Any]],
arg: Any = temporalio.common._arg_unset,
*,
args: Sequence[Any] = [],
id: str | None = None,
task_queue: str | None = None,
execution_timeout: timedelta | None = None,
run_timeout: timedelta | None = None,
task_timeout: timedelta | None = None,
retry_policy: temporalio.common.RetryPolicy | None = None,
memo: Mapping[str, Any] | None = None,
typed_search_attributes: temporalio.common.TypedSearchAttributes = temporalio.common.TypedSearchAttributes.empty,
untyped_search_attributes: temporalio.common.SearchAttributes = {},
static_summary: str | None = None,
static_details: str | None = None,
headers: Mapping[str, temporalio.api.common.v1.Payload] | None = None,
raw_info: temporalio.api.workflow.v1.NewWorkflowExecutionInfo | None = None,
priority: temporalio.common.Priority = temporalio.common.Priority.default,
) -> None:
"""Create a start-workflow action.
See :py:meth:`Client.start_workflow` for details on these parameter
values.
"""
super().__init__()
if raw_info:
self._from_raw = True
# Ignore other fields
self.workflow = raw_info.workflow_type.name
self.args = raw_info.input.payloads if raw_info.input else []
self.id = raw_info.workflow_id
self.task_queue = raw_info.task_queue.name
self.execution_timeout = (
raw_info.workflow_execution_timeout.ToTimedelta()
if raw_info.HasField("workflow_execution_timeout")
else None
)
self.run_timeout = (
raw_info.workflow_run_timeout.ToTimedelta()
if raw_info.HasField("workflow_run_timeout")
else None
)
self.task_timeout = (
raw_info.workflow_task_timeout.ToTimedelta()
if raw_info.HasField("workflow_task_timeout")
else None
)
self.retry_policy = (
temporalio.common.RetryPolicy.from_proto(raw_info.retry_policy)
if raw_info.HasField("retry_policy")
else None
)
self.memo = raw_info.memo.fields if raw_info.memo.fields else None
self.typed_search_attributes = (
temporalio.converter.decode_typed_search_attributes(
raw_info.search_attributes
)
)
self.headers = raw_info.header.fields if raw_info.header.fields else None
# Also set the untyped attributes as the set of attributes from
# decode with the typed ones removed
self.untyped_search_attributes = (
temporalio.converter.decode_search_attributes(
raw_info.search_attributes
)
)
for pair in self.typed_search_attributes:
if pair.key.name in self.untyped_search_attributes:
# We know this is mutable here
del self.untyped_search_attributes[pair.key.name] # type: ignore
self.static_summary = (
raw_info.user_metadata.summary
if raw_info.HasField("user_metadata") and raw_info.user_metadata.summary
else None
)
self.static_details = (
raw_info.user_metadata.details
if raw_info.HasField("user_metadata") and raw_info.user_metadata.details
else None
)
self.priority = (
temporalio.common.Priority._from_proto(raw_info.priority)
if raw_info.HasField("priority") and raw_info.priority
else temporalio.common.Priority.default
)
else:
self._from_raw = False
if not id:
raise ValueError("ID required")
if not task_queue:
raise ValueError("Task queue required")
# Use definition if callable
if callable(workflow):
defn = temporalio.workflow._Definition.must_from_run_fn(workflow)
if not defn.name:
raise ValueError("Cannot schedule dynamic workflow explicitly")
workflow = defn.name
elif not isinstance(workflow, str):
raise TypeError("Workflow must be a string or callable") # type:ignore[reportUnreachable]
self.workflow = workflow
self.args = temporalio.common._arg_or_args(arg, args)
self.id = id
self.task_queue = task_queue
self.execution_timeout = execution_timeout
self.run_timeout = run_timeout
self.task_timeout = task_timeout
self.retry_policy = retry_policy
self.memo = memo
self.typed_search_attributes = typed_search_attributes
self.untyped_search_attributes = untyped_search_attributes
self.headers = headers # encode here
self.static_summary = static_summary
self.static_details = static_details
self.priority = priority
async def _to_proto(
self, client: Client
) -> temporalio.api.schedule.v1.ScheduleAction:
execution_timeout: google.protobuf.duration_pb2.Duration | None = None
if self.execution_timeout:
execution_timeout = google.protobuf.duration_pb2.Duration()
execution_timeout.FromTimedelta(self.execution_timeout)
run_timeout: google.protobuf.duration_pb2.Duration | None = None
if self.run_timeout:
run_timeout = google.protobuf.duration_pb2.Duration()
run_timeout.FromTimedelta(self.run_timeout)
task_timeout: google.protobuf.duration_pb2.Duration | None = None
if self.task_timeout:
task_timeout = google.protobuf.duration_pb2.Duration()
task_timeout.FromTimedelta(self.task_timeout)
retry_policy: temporalio.api.common.v1.RetryPolicy | None = None
if self.retry_policy:
retry_policy = temporalio.api.common.v1.RetryPolicy()
self.retry_policy.apply_to_proto(retry_policy)
priority: temporalio.api.common.v1.Priority | None = None
if self.priority:
priority = self.priority._to_proto()
data_converter = client.data_converter._with_contexts(
WorkflowSerializationContext(
namespace=client.namespace,
workflow_id=self.id,
),
StorageDriverStoreContext(
target=StorageDriverWorkflowInfo(
id=self.id, type=self.workflow, namespace=client.namespace
),
),
)
action = temporalio.api.schedule.v1.ScheduleAction(
start_workflow=temporalio.api.workflow.v1.NewWorkflowExecutionInfo(
workflow_id=self.id,
workflow_type=temporalio.api.common.v1.WorkflowType(name=self.workflow),
task_queue=temporalio.api.taskqueue.v1.TaskQueue(name=self.task_queue),
input=(
temporalio.api.common.v1.Payloads(
payloads=[
a
if isinstance(a, temporalio.api.common.v1.Payload)
else (await data_converter.encode([a]))[0]
for a in self.args
]
)
if self.args
else None
),
workflow_execution_timeout=execution_timeout,
workflow_run_timeout=run_timeout,
workflow_task_timeout=task_timeout,
retry_policy=retry_policy,
memo=await data_converter._encode_memo(self.memo)
if self.memo
else None,
user_metadata=await _encode_user_metadata(
data_converter, self.static_summary, self.static_details
),
priority=priority,
),
)
# Add any untyped attributes that are not also in the typed set
untyped_not_in_typed = {
k: v
for k, v in self.untyped_search_attributes.items()
if k not in self.typed_search_attributes
}
if untyped_not_in_typed:
temporalio.converter.encode_search_attributes(
untyped_not_in_typed, action.start_workflow.search_attributes
)
# TODO (dan): confirm whether this be `is not None`
if self.typed_search_attributes:
temporalio.converter.encode_search_attributes(
self.typed_search_attributes,
action.start_workflow.search_attributes,
)
if self.headers:
await _apply_headers(
self.headers,
action.start_workflow.header.fields,
client.config(active_config=True)["header_codec_behavior"]
== HeaderCodecBehavior.CODEC
and not self._from_raw,
client.data_converter,
)
return action
class ScheduleOverlapPolicy(IntEnum):
"""Controls what happens when a workflow would be started by a schedule but
one is already running.
"""
SKIP = int(
temporalio.api.enums.v1.ScheduleOverlapPolicy.SCHEDULE_OVERLAP_POLICY_SKIP
)
"""Don't start anything.
When the workflow completes, the next scheduled event after that time will
be considered.
"""
BUFFER_ONE = int(
temporalio.api.enums.v1.ScheduleOverlapPolicy.SCHEDULE_OVERLAP_POLICY_BUFFER_ONE
)
"""Start the workflow again soon as the current one completes, but only
buffer one start in this way.
If another start is supposed to happen when the workflow is running, and one
is already buffered, then only the first one will be started after the
running workflow finishes.
"""
BUFFER_ALL = int(
temporalio.api.enums.v1.ScheduleOverlapPolicy.SCHEDULE_OVERLAP_POLICY_BUFFER_ALL
)
"""Buffer up any number of starts to all happen sequentially, immediately
after the running workflow completes."""
CANCEL_OTHER = int(
temporalio.api.enums.v1.ScheduleOverlapPolicy.SCHEDULE_OVERLAP_POLICY_CANCEL_OTHER
)
"""If there is another workflow running, cancel it, and start the new one
after the old one completes cancellation."""
TERMINATE_OTHER = int(
temporalio.api.enums.v1.ScheduleOverlapPolicy.SCHEDULE_OVERLAP_POLICY_TERMINATE_OTHER
)
"""If there is another workflow running, terminate it and start the new one
immediately."""
ALLOW_ALL = int(
temporalio.api.enums.v1.ScheduleOverlapPolicy.SCHEDULE_OVERLAP_POLICY_ALLOW_ALL
)
"""Start any number of concurrent workflows.
Note that with this policy, last completion result and last failure will not
be available since workflows are not sequential."""
@dataclass
class ScheduleBackfill:
"""Time period and policy for actions taken as if the time passed right
now.
"""
start_at: datetime
"""Start of the range to evaluate the schedule in.
This is exclusive
"""
end_at: datetime
overlap: ScheduleOverlapPolicy | None = None
def _to_proto(self) -> temporalio.api.schedule.v1.BackfillRequest:
start_time = google.protobuf.timestamp_pb2.Timestamp()
start_time.FromDatetime(self.start_at)
end_time = google.protobuf.timestamp_pb2.Timestamp()
end_time.FromDatetime(self.end_at)
overlap_policy = temporalio.api.enums.v1.ScheduleOverlapPolicy.SCHEDULE_OVERLAP_POLICY_UNSPECIFIED
if self.overlap:
overlap_policy = temporalio.api.enums.v1.ScheduleOverlapPolicy.ValueType(
self.overlap
)
return temporalio.api.schedule.v1.BackfillRequest(
start_time=start_time,
end_time=end_time,
overlap_policy=overlap_policy,
)
@dataclass
class SchedulePolicy:
"""Policies of a schedule."""
overlap: ScheduleOverlapPolicy = dataclasses.field(
default_factory=lambda: ScheduleOverlapPolicy.SKIP
)
"""Controls what happens when an action is started while another is still
running."""
catchup_window: timedelta = timedelta(days=365)
"""After a Temporal server is unavailable, amount of time in the past to
execute missed actions."""
pause_on_failure: bool = False
"""Whether to pause the schedule if an action fails or times out.
Note: For workflows, this only applies after all retries have been
exhausted.
"""
@staticmethod
def _from_proto(pol: temporalio.api.schedule.v1.SchedulePolicies) -> SchedulePolicy:
return SchedulePolicy(
overlap=ScheduleOverlapPolicy(int(pol.overlap_policy)),
catchup_window=pol.catchup_window.ToTimedelta(),
pause_on_failure=pol.pause_on_failure,
)
def _to_proto(self) -> temporalio.api.schedule.v1.SchedulePolicies:
catchup_window = google.protobuf.duration_pb2.Duration()
catchup_window.FromTimedelta(self.catchup_window)
return temporalio.api.schedule.v1.SchedulePolicies(
overlap_policy=temporalio.api.enums.v1.ScheduleOverlapPolicy.ValueType(
self.overlap
),
catchup_window=catchup_window,
pause_on_failure=self.pause_on_failure,
)
@dataclass
class ScheduleState:
"""State of a schedule."""
note: str | None = None
"""Human readable message for the schedule.
The system may overwrite this value on certain conditions like
pause-on-failure.
"""