-
Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathschedules.rs
More file actions
1679 lines (1509 loc) · 55 KB
/
schedules.rs
File metadata and controls
1679 lines (1509 loc) · 55 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
use crate::{Client, NamespacedClient, grpc::WorkflowService};
use futures_util::stream;
use std::{
collections::VecDeque,
pin::Pin,
task::{Context, Poll},
time::{Duration, SystemTime},
};
use temporalio_common::protos::{
proto_ts_to_system_time,
temporal::api::{
common::v1 as common_proto, schedule::v1 as schedule_proto,
taskqueue::v1 as taskqueue_proto, workflow::v1 as workflow_proto, workflowservice::v1::*,
},
};
use tonic::IntoRequest;
use uuid::Uuid;
/// Errors returned by schedule operations.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ScheduleError {
/// An rpc error from the server.
#[error("Server error: {0}")]
Rpc(#[from] tonic::Status),
}
/// Options for creating a schedule.
#[derive(Debug, Clone, bon::Builder)]
#[builder(on(String, into))]
#[non_exhaustive]
pub struct CreateScheduleOptions {
/// The action the schedule should perform on each trigger.
pub action: ScheduleAction,
/// Defines when the schedule should trigger.
pub spec: ScheduleSpec,
/// Whether to trigger the schedule immediately upon creation.
#[builder(default)]
pub trigger_immediately: bool,
/// Overlap policy for the schedule. Also used for the initial trigger when
/// `trigger_immediately` is true.
#[builder(default)]
pub overlap_policy: ScheduleOverlapPolicy,
/// Whether the schedule starts in a paused state.
#[builder(default)]
pub paused: bool,
/// A note to attach to the schedule state (e.g., reason for pausing).
#[builder(default)]
pub note: String,
}
/// The action a schedule should perform on each trigger.
// TODO: The proto supports other action types beyond StartWorkflow.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum ScheduleAction {
/// Start a workflow execution.
StartWorkflow {
/// The workflow type name.
workflow_type: String,
/// The task queue to run the workflow on.
task_queue: String,
/// The workflow ID prefix. The server may append a timestamp.
workflow_id: String,
},
}
impl ScheduleAction {
/// Create a start-workflow action.
pub fn start_workflow(
workflow_type: impl Into<String>,
task_queue: impl Into<String>,
workflow_id: impl Into<String>,
) -> Self {
Self::StartWorkflow {
workflow_type: workflow_type.into(),
task_queue: task_queue.into(),
workflow_id: workflow_id.into(),
}
}
pub(crate) fn into_proto(self) -> schedule_proto::ScheduleAction {
match self {
Self::StartWorkflow {
workflow_type,
task_queue,
workflow_id,
} => schedule_proto::ScheduleAction {
action: Some(schedule_proto::schedule_action::Action::StartWorkflow(
workflow_proto::NewWorkflowExecutionInfo {
workflow_id,
workflow_type: Some(common_proto::WorkflowType {
name: workflow_type,
}),
task_queue: Some(taskqueue_proto::TaskQueue {
name: task_queue,
..Default::default()
}),
..Default::default()
},
)),
},
}
}
}
/// Defines when a schedule should trigger.
///
/// Note: `set_spec` on [`ScheduleUpdate`] replaces the entire spec. Fields not
/// set here will use their proto defaults on the server.
#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
#[builder(on(String, into))]
pub struct ScheduleSpec {
/// Interval-based triggers (e.g., every 1 hour).
#[builder(default)]
pub intervals: Vec<ScheduleIntervalSpec>,
/// Calendar-based triggers using range strings.
#[builder(default)]
pub calendars: Vec<ScheduleCalendarSpec>,
/// Calendar-based exclusions. Matching times are skipped.
#[builder(default)]
pub exclude_calendars: Vec<ScheduleCalendarSpec>,
/// Cron expression triggers (e.g., `"0 12 * * MON-FRI"`).
#[builder(default)]
pub cron_strings: Vec<String>,
/// IANA timezone name (e.g., `"US/Eastern"`). Empty uses UTC.
#[builder(default)]
pub timezone_name: String,
/// Earliest time the schedule is active.
pub start_time: Option<SystemTime>,
/// Latest time the schedule is active.
pub end_time: Option<SystemTime>,
/// Random jitter applied to each action time.
pub jitter: Option<Duration>,
}
impl ScheduleSpec {
/// Create a spec that triggers on a single interval.
pub fn from_interval(every: Duration) -> Self {
Self {
intervals: vec![every.into()],
..Default::default()
}
}
/// Create a spec that triggers on a single calendar schedule.
pub fn from_calendar(calendar: ScheduleCalendarSpec) -> Self {
Self {
calendars: vec![calendar],
..Default::default()
}
}
pub(crate) fn into_proto(self) -> schedule_proto::ScheduleSpec {
#[allow(deprecated)]
schedule_proto::ScheduleSpec {
interval: self.intervals.into_iter().map(Into::into).collect(),
calendar: self.calendars.into_iter().map(Into::into).collect(),
exclude_calendar: self.exclude_calendars.into_iter().map(Into::into).collect(),
cron_string: self.cron_strings,
timezone_name: self.timezone_name,
start_time: self.start_time.map(Into::into),
end_time: self.end_time.map(Into::into),
jitter: self.jitter.and_then(|d| d.try_into().ok()),
..Default::default()
}
}
}
/// An interval-based schedule trigger.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct ScheduleIntervalSpec {
/// How often the action should repeat.
pub every: Duration,
/// Fixed offset added to each interval.
pub offset: Option<Duration>,
}
impl ScheduleIntervalSpec {
/// Create an interval with an optional offset.
pub fn new(every: Duration, offset: Option<Duration>) -> Self {
Self { every, offset }
}
}
impl From<Duration> for ScheduleIntervalSpec {
fn from(every: Duration) -> Self {
Self {
every,
offset: None,
}
}
}
impl From<ScheduleIntervalSpec> for schedule_proto::IntervalSpec {
fn from(s: ScheduleIntervalSpec) -> Self {
Self {
interval: Some(s.every.try_into().unwrap_or_default()),
phase: s.offset.and_then(|d| d.try_into().ok()),
}
}
}
/// A calendar-based schedule trigger using range strings (e.g., `"2-7"` for hours 2 through 7).
///
/// Empty strings use server defaults (typically `"*"` for most fields, `"0"` for seconds/minutes).
#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
#[builder(on(String, into))]
#[non_exhaustive]
pub struct ScheduleCalendarSpec {
/// Second within the minute. Default: `"0"`.
#[builder(default)]
pub second: String,
/// Minute within the hour. Default: `"0"`.
#[builder(default)]
pub minute: String,
/// Hour of the day. Default: `"0"`.
#[builder(default)]
pub hour: String,
/// Day of the month. Default: `"*"`.
#[builder(default)]
pub day_of_month: String,
/// Month of the year. Default: `"*"`.
#[builder(default)]
pub month: String,
/// Day of the week. Default: `"*"`.
#[builder(default)]
pub day_of_week: String,
/// Year. Default: `"*"`.
#[builder(default)]
pub year: String,
/// Free-form comment.
#[builder(default)]
pub comment: String,
}
impl From<ScheduleCalendarSpec> for schedule_proto::CalendarSpec {
fn from(s: ScheduleCalendarSpec) -> Self {
Self {
second: s.second,
minute: s.minute,
hour: s.hour,
day_of_month: s.day_of_month,
month: s.month,
day_of_week: s.day_of_week,
year: s.year,
comment: s.comment,
}
}
}
/// Options for listing schedules.
#[derive(Debug, Clone, Default, bon::Builder)]
#[non_exhaustive]
pub struct ListSchedulesOptions {
/// Maximum number of results per page (server-side hint).
#[builder(default)]
pub maximum_page_size: i32,
/// Query filter string.
#[builder(default)]
pub query: String,
}
/// A stream of schedule summaries from a list operation.
/// Internally paginates through results from the server.
pub struct ListSchedulesStream {
inner: Pin<Box<dyn futures_util::Stream<Item = Result<ScheduleSummary, ScheduleError>> + Send>>,
}
impl ListSchedulesStream {
pub(crate) fn new(
inner: Pin<
Box<dyn futures_util::Stream<Item = Result<ScheduleSummary, ScheduleError>> + Send>,
>,
) -> Self {
Self { inner }
}
}
impl futures_util::Stream for ListSchedulesStream {
type Item = Result<ScheduleSummary, ScheduleError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.inner.as_mut().poll_next(cx)
}
}
/// A recent action taken by a schedule.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct ScheduleRecentAction {
/// When this action was scheduled to occur (including jitter).
pub schedule_time: Option<SystemTime>,
/// When this action actually occurred.
pub actual_time: Option<SystemTime>,
/// Workflow ID of the started workflow.
pub workflow_id: String,
/// Run ID of the started workflow.
pub run_id: String,
}
/// A currently-running workflow started by a schedule.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct ScheduleRunningAction {
/// Workflow ID of the running workflow.
pub workflow_id: String,
/// Run ID of the running workflow.
pub run_id: String,
}
impl From<&schedule_proto::ScheduleActionResult> for ScheduleRecentAction {
fn from(a: &schedule_proto::ScheduleActionResult) -> Self {
let workflow_result = a
.start_workflow_result
.as_ref()
.expect("unsupported schedule action: start_workflow_result should be present");
ScheduleRecentAction {
schedule_time: a.schedule_time.as_ref().and_then(proto_ts_to_system_time),
actual_time: a.actual_time.as_ref().and_then(proto_ts_to_system_time),
workflow_id: workflow_result.workflow_id.clone(),
run_id: workflow_result.run_id.clone(),
}
}
}
/// Description of a schedule returned by describe().
///
/// Provides ergonomic accessors over the raw `DescribeScheduleResponse` proto.
/// Use [`raw()`](Self::raw) or [`into_raw()`](Self::into_raw) to access the
/// full proto when needed.
#[derive(Debug, Clone)]
pub struct ScheduleDescription {
raw: DescribeScheduleResponse,
}
impl ScheduleDescription {
/// Token used for optimistic concurrency on updates.
pub fn conflict_token(&self) -> &[u8] {
&self.raw.conflict_token
}
/// Whether the schedule is paused.
pub fn paused(&self) -> bool {
self.raw
.schedule
.as_ref()
.and_then(|s| s.state.as_ref())
.is_some_and(|st| st.paused)
}
/// Note on the schedule state (e.g., reason for pause).
/// Returns `None` if no note is set or the note is empty.
pub fn note(&self) -> Option<&str> {
self.raw
.schedule
.as_ref()
.and_then(|s| s.state.as_ref())
.map(|st| st.notes.as_str())
.filter(|s| !s.is_empty())
}
/// Total number of actions taken by this schedule.
pub fn action_count(&self) -> i64 {
self.info().map_or(0, |i| i.action_count)
}
/// Number of times a scheduled action was skipped due to missing the catchup window.
pub fn missed_catchup_window(&self) -> i64 {
self.info().map_or(0, |i| i.missed_catchup_window)
}
/// Number of skipped actions due to overlap.
pub fn overlap_skipped(&self) -> i64 {
self.info().map_or(0, |i| i.overlap_skipped)
}
/// Most recent action results (up to 10).
pub fn recent_actions(&self) -> Vec<ScheduleRecentAction> {
self.info()
.map(|i| {
i.recent_actions
.iter()
.map(ScheduleRecentAction::from)
.collect()
})
.unwrap_or_default()
}
/// Currently-running workflows started by this schedule.
pub fn running_actions(&self) -> Vec<ScheduleRunningAction> {
self.info()
.map(|i| {
i.running_workflows
.iter()
.map(|w| ScheduleRunningAction {
workflow_id: w.workflow_id.clone(),
run_id: w.run_id.clone(),
})
.collect()
})
.unwrap_or_default()
}
/// Next scheduled action times.
pub fn future_action_times(&self) -> Vec<SystemTime> {
self.info()
.map(|i| {
i.future_action_times
.iter()
.filter_map(proto_ts_to_system_time)
.collect()
})
.unwrap_or_default()
}
/// When the schedule was created.
pub fn create_time(&self) -> Option<SystemTime> {
self.info()
.and_then(|i| i.create_time.as_ref())
.and_then(proto_ts_to_system_time)
}
/// When the schedule was last updated.
pub fn update_time(&self) -> Option<SystemTime> {
self.info()
.and_then(|i| i.update_time.as_ref())
.and_then(proto_ts_to_system_time)
}
/// Memo attached to the schedule.
pub fn memo(&self) -> Option<&common_proto::Memo> {
self.raw.memo.as_ref()
}
/// Search attributes on the schedule.
pub fn search_attributes(&self) -> Option<&common_proto::SearchAttributes> {
self.raw.search_attributes.as_ref()
}
/// Access the raw proto for additional fields not exposed via accessors.
pub fn raw(&self) -> &DescribeScheduleResponse {
&self.raw
}
/// Consume the wrapper and return the raw proto.
pub fn into_raw(self) -> DescribeScheduleResponse {
self.raw
}
fn info(&self) -> Option<&schedule_proto::ScheduleInfo> {
self.raw.info.as_ref()
}
/// Convert this description into a [`ScheduleUpdate`] for use with
/// [`ScheduleHandle::send_update()`].
///
/// Extracts the schedule definition from the description.
pub fn into_update(self) -> ScheduleUpdate {
ScheduleUpdate {
schedule: self.raw.schedule.unwrap_or_default(),
}
}
}
impl From<DescribeScheduleResponse> for ScheduleDescription {
fn from(raw: DescribeScheduleResponse) -> Self {
Self { raw }
}
}
/// Controls what happens when a scheduled workflow would overlap with a running one.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ScheduleOverlapPolicy {
/// Use the server default (currently Skip).
#[default]
Unspecified,
/// Don't start a new workflow if one is already running.
Skip,
/// Buffer one workflow start, to run after the current one completes.
BufferOne,
/// Buffer all workflow starts, to run sequentially.
BufferAll,
/// Cancel the running workflow and start a new one.
CancelOther,
/// Terminate the running workflow and start a new one.
TerminateOther,
/// Start any number of concurrent workflows.
AllowAll,
}
impl ScheduleOverlapPolicy {
pub(crate) fn to_proto(self) -> i32 {
match self {
Self::Unspecified => 0,
Self::Skip => 1,
Self::BufferOne => 2,
Self::BufferAll => 3,
Self::CancelOther => 4,
Self::TerminateOther => 5,
Self::AllowAll => 6,
}
}
}
/// A backfill request for a schedule, specifying a time range of missed runs.
#[derive(Debug, Clone, PartialEq, bon::Builder)]
#[non_exhaustive]
#[builder(start_fn = new)]
pub struct ScheduleBackfill {
/// Start of the time range to backfill.
#[builder(start_fn)]
pub start_time: SystemTime,
/// End of the time range to backfill.
#[builder(start_fn)]
pub end_time: SystemTime,
/// How overlapping runs are handled during backfill.
#[builder(default)]
pub overlap_policy: ScheduleOverlapPolicy,
}
/// An update to apply to a schedule definition.
///
/// Obtain from [`ScheduleDescription::into_update()`], modify the schedule
/// using the setter methods, then pass to [`ScheduleHandle::update()`].
#[derive(Debug, Clone)]
pub struct ScheduleUpdate {
schedule: schedule_proto::Schedule,
}
impl ScheduleUpdate {
/// Replace the schedule spec (when to trigger).
pub fn set_spec(&mut self, spec: ScheduleSpec) -> &mut Self {
self.schedule.spec = Some(spec.into_proto());
self
}
/// Replace the schedule action (what to do on trigger).
pub fn set_action(&mut self, action: ScheduleAction) -> &mut Self {
self.schedule.action = Some(action.into_proto());
self
}
/// Set whether the schedule is paused.
pub fn set_paused(&mut self, paused: bool) -> &mut Self {
self.state_mut().paused = paused;
self
}
/// Set the note on the schedule state.
pub fn set_note(&mut self, note: impl Into<String>) -> &mut Self {
self.state_mut().notes = note.into();
self
}
/// Set the overlap policy.
pub fn set_overlap_policy(&mut self, policy: ScheduleOverlapPolicy) -> &mut Self {
self.policies_mut().overlap_policy = policy.to_proto();
self
}
/// Set the catchup window. Actions missed by more than this duration are
/// skipped.
pub fn set_catchup_window(&mut self, window: Duration) -> &mut Self {
self.policies_mut().catchup_window = window.try_into().ok();
self
}
/// Set whether to pause the schedule when a workflow run fails or times out.
pub fn set_pause_on_failure(&mut self, pause_on_failure: bool) -> &mut Self {
self.policies_mut().pause_on_failure = pause_on_failure;
self
}
/// Set whether to keep the original workflow ID without appending a
/// timestamp.
pub fn set_keep_original_workflow_id(&mut self, keep: bool) -> &mut Self {
self.policies_mut().keep_original_workflow_id = keep;
self
}
/// Limit the schedule to a fixed number of remaining actions, after which
/// it stops triggering. Passing `None` removes the limit.
pub fn set_remaining_actions(&mut self, count: Option<i64>) -> &mut Self {
let state = self.state_mut();
match count {
Some(n) => {
state.limited_actions = true;
state.remaining_actions = n;
}
None => {
state.limited_actions = false;
state.remaining_actions = 0;
}
}
self
}
/// Access the raw schedule proto.
pub fn raw(&self) -> &schedule_proto::Schedule {
&self.schedule
}
/// Consume and return the raw schedule proto.
pub fn into_raw(self) -> schedule_proto::Schedule {
self.schedule
}
fn state_mut(&mut self) -> &mut schedule_proto::ScheduleState {
self.schedule.state.get_or_insert_with(Default::default)
}
fn policies_mut(&mut self) -> &mut schedule_proto::SchedulePolicies {
self.schedule.policies.get_or_insert_with(Default::default)
}
}
/// Summary of a schedule returned in list operations.
///
/// Provides ergonomic accessors over the raw `ScheduleListEntry` proto.
/// Use [`raw()`](Self::raw) or [`into_raw()`](Self::into_raw) to access the
/// full proto when needed.
#[derive(Debug, Clone)]
pub struct ScheduleSummary {
raw: schedule_proto::ScheduleListEntry,
}
impl ScheduleSummary {
/// The schedule ID.
pub fn schedule_id(&self) -> &str {
&self.raw.schedule_id
}
/// The workflow type name for start-workflow actions.
pub fn workflow_type(&self) -> Option<&str> {
self.info()
.and_then(|i| i.workflow_type.as_ref())
.map(|wt| wt.name.as_str())
}
/// Note on the schedule state.
/// Returns `None` if no note is set or the note is empty.
pub fn note(&self) -> Option<&str> {
self.info()
.map(|i| i.notes.as_str())
.filter(|s| !s.is_empty())
}
/// Whether the schedule is paused.
pub fn paused(&self) -> bool {
self.info().is_some_and(|i| i.paused)
}
/// Most recent action results (up to 10).
pub fn recent_actions(&self) -> Vec<ScheduleRecentAction> {
self.info()
.map(|i| {
i.recent_actions
.iter()
.map(ScheduleRecentAction::from)
.collect()
})
.unwrap_or_default()
}
/// Next scheduled action times.
pub fn future_action_times(&self) -> Vec<SystemTime> {
self.info()
.map(|i| {
i.future_action_times
.iter()
.filter_map(proto_ts_to_system_time)
.collect()
})
.unwrap_or_default()
}
/// Memo attached to the schedule.
pub fn memo(&self) -> Option<&common_proto::Memo> {
self.raw.memo.as_ref()
}
/// Search attributes on the schedule.
pub fn search_attributes(&self) -> Option<&common_proto::SearchAttributes> {
self.raw.search_attributes.as_ref()
}
/// Access the raw proto for additional fields not exposed via accessors.
pub fn raw(&self) -> &schedule_proto::ScheduleListEntry {
&self.raw
}
/// Consume the wrapper and return the raw proto.
pub fn into_raw(self) -> schedule_proto::ScheduleListEntry {
self.raw
}
fn info(&self) -> Option<&schedule_proto::ScheduleListInfo> {
self.raw.info.as_ref()
}
}
impl From<schedule_proto::ScheduleListEntry> for ScheduleSummary {
fn from(raw: schedule_proto::ScheduleListEntry) -> Self {
Self { raw }
}
}
/// Handle to an existing schedule. Obtained from
/// [`Client::create_schedule`](crate::Client::create_schedule) or
/// [`Client::get_schedule_handle`](crate::Client::get_schedule_handle).
#[derive(Clone, derive_more::Debug)]
pub struct ScheduleHandle<CT> {
#[debug(skip)]
client: CT,
namespace: String,
schedule_id: String,
}
impl<CT> ScheduleHandle<CT>
where
CT: WorkflowService + NamespacedClient + Clone + Send + Sync,
{
pub(crate) fn new(client: CT, namespace: String, schedule_id: String) -> Self {
Self {
client,
namespace,
schedule_id,
}
}
/// The namespace the schedule belongs to.
pub fn namespace(&self) -> &str {
&self.namespace
}
/// The schedule ID.
pub fn schedule_id(&self) -> &str {
&self.schedule_id
}
/// Describe this schedule, returning its full definition, info, and conflict token.
pub async fn describe(&self) -> Result<ScheduleDescription, ScheduleError> {
let resp = WorkflowService::describe_schedule(
&mut self.client.clone(),
DescribeScheduleRequest {
namespace: self.namespace.clone(),
schedule_id: self.schedule_id.clone(),
}
.into_request(),
)
.await?
.into_inner();
Ok(ScheduleDescription::from(resp))
}
/// Update the schedule definition.
///
/// Describes the current schedule, applies the closure to modify it, and
/// sends the update. The conflict token is managed automatically.
///
/// ```no_run
/// # async fn hidden(
/// # handle: &temporalio_client::schedules::ScheduleHandle<temporalio_client::Client>,
/// # ) -> Result<(), temporalio_client::schedules::ScheduleError> {
/// handle
/// .update(|u| {
/// u.set_note("updated").set_paused(true);
/// })
/// .await?;
/// # Ok(())
/// # }
/// ```
// TODO: Add a retry loop for conflict token mismatch. The server
// returns FailedPrecondition with "mismatched conflict token".
pub async fn update(
&self,
updater: impl FnOnce(&mut ScheduleUpdate),
) -> Result<(), ScheduleError> {
let desc = self.describe().await?;
let mut update = desc.into_update();
updater(&mut update);
self.send_update(update).await
}
/// Send a pre-built [`ScheduleUpdate`] to the server.
///
/// Prefer [`update()`](Self::update) for most use cases. Use this when you
/// need to inspect the [`ScheduleDescription`] before deciding what to
/// change.
pub async fn send_update(&self, update: ScheduleUpdate) -> Result<(), ScheduleError> {
WorkflowService::update_schedule(
&mut self.client.clone(),
UpdateScheduleRequest {
namespace: self.namespace.clone(),
schedule_id: self.schedule_id.clone(),
schedule: Some(update.schedule),
identity: self.client.identity(),
request_id: Uuid::new_v4().to_string(),
..Default::default()
}
.into_request(),
)
.await?;
Ok(())
}
/// Delete this schedule.
pub async fn delete(&self) -> Result<(), ScheduleError> {
WorkflowService::delete_schedule(
&mut self.client.clone(),
DeleteScheduleRequest {
namespace: self.namespace.clone(),
schedule_id: self.schedule_id.clone(),
identity: self.client.identity(),
}
.into_request(),
)
.await?;
Ok(())
}
/// Pause the schedule with an optional note.
///
/// If `note` is `None`, a default note is used.
pub async fn pause(&self, note: Option<impl Into<String>>) -> Result<(), ScheduleError> {
let note = note.map_or_else(|| "Paused via Rust SDK".to_string(), |s| s.into());
WorkflowService::patch_schedule(
&mut self.client.clone(),
PatchScheduleRequest {
namespace: self.namespace.clone(),
schedule_id: self.schedule_id.clone(),
patch: Some(schedule_proto::SchedulePatch {
pause: note,
..Default::default()
}),
identity: self.client.identity(),
request_id: Uuid::new_v4().to_string(),
}
.into_request(),
)
.await?;
Ok(())
}
/// Unpause the schedule with an optional note.
///
/// If `note` is `None`, a default note is used.
pub async fn unpause(&self, note: Option<impl Into<String>>) -> Result<(), ScheduleError> {
let note = note.map_or_else(|| "Unpaused via Rust SDK".to_string(), |s| s.into());
WorkflowService::patch_schedule(
&mut self.client.clone(),
PatchScheduleRequest {
namespace: self.namespace.clone(),
schedule_id: self.schedule_id.clone(),
patch: Some(schedule_proto::SchedulePatch {
unpause: note,
..Default::default()
}),
identity: self.client.identity(),
request_id: Uuid::new_v4().to_string(),
}
.into_request(),
)
.await?;
Ok(())
}
/// Trigger the schedule to run immediately with the given overlap policy.
pub async fn trigger(
&self,
overlap_policy: ScheduleOverlapPolicy,
) -> Result<(), ScheduleError> {
WorkflowService::patch_schedule(
&mut self.client.clone(),
PatchScheduleRequest {
namespace: self.namespace.clone(),
schedule_id: self.schedule_id.clone(),
patch: Some(schedule_proto::SchedulePatch {
trigger_immediately: Some(schedule_proto::TriggerImmediatelyRequest {
overlap_policy: overlap_policy.to_proto(),
scheduled_time: None,
}),
..Default::default()
}),
identity: self.client.identity(),
request_id: Uuid::new_v4().to_string(),
}
.into_request(),
)
.await?;
Ok(())
}
/// Request backfill of missed runs.
pub async fn backfill(
&self,
backfills: impl IntoIterator<Item = ScheduleBackfill>,
) -> Result<(), ScheduleError> {
let backfill_requests: Vec<schedule_proto::BackfillRequest> = backfills
.into_iter()
.map(|b| schedule_proto::BackfillRequest {
start_time: Some(b.start_time.into()),
end_time: Some(b.end_time.into()),
overlap_policy: b.overlap_policy.to_proto(),
})
.collect();
WorkflowService::patch_schedule(
&mut self.client.clone(),
PatchScheduleRequest {
namespace: self.namespace.clone(),
schedule_id: self.schedule_id.clone(),
patch: Some(schedule_proto::SchedulePatch {
backfill_request: backfill_requests,
..Default::default()
}),
identity: self.client.identity(),
request_id: Uuid::new_v4().to_string(),
}
.into_request(),
)
.await?;
Ok(())
}
}
// Schedule operations on Client.
impl Client {
/// Create a schedule and return a handle to it.
pub async fn create_schedule(
&self,
schedule_id: impl Into<String>,
opts: CreateScheduleOptions,
) -> Result<ScheduleHandle<Self>, ScheduleError> {
let schedule_id = schedule_id.into();
let namespace = self.namespace();
let initial_patch = if opts.trigger_immediately {
Some(schedule_proto::SchedulePatch {
trigger_immediately: Some(schedule_proto::TriggerImmediatelyRequest {
// Always use AllowAll for the initial trigger so the
// schedule fires immediately regardless of overlap state.
overlap_policy: ScheduleOverlapPolicy::AllowAll.to_proto(),
scheduled_time: None,
}),
..Default::default()
})
} else {
None
};
// Only send explicit policies when the user set a non-default overlap
// policy, so the server uses its own defaults otherwise.
let policies = (opts.overlap_policy != ScheduleOverlapPolicy::Unspecified).then(|| {
schedule_proto::SchedulePolicies {
overlap_policy: opts.overlap_policy.to_proto(),
..Default::default()
}
});
let schedule = schedule_proto::Schedule {
spec: Some(opts.spec.into_proto()),
action: Some(opts.action.into_proto()),
policies,
state: Some(schedule_proto::ScheduleState {
paused: opts.paused,
notes: opts.note,
..Default::default()
}),
};
WorkflowService::create_schedule(
&mut self.clone(),
CreateScheduleRequest {
namespace: namespace.clone(),
schedule_id: schedule_id.clone(),
schedule: Some(schedule),
initial_patch,
identity: self.identity(),
request_id: Uuid::new_v4().to_string(),
..Default::default()
}
.into_request(),
)
.await?;
Ok(ScheduleHandle::new(self.clone(), namespace, schedule_id))
}
/// Get a handle to an existing schedule by ID.
pub fn get_schedule_handle(&self, schedule_id: impl Into<String>) -> ScheduleHandle<Self> {
ScheduleHandle::new(self.clone(), self.namespace(), schedule_id.into())
}
/// List schedules matching the query, returning a stream that lazily
/// paginates through results.
pub fn list_schedules(&self, opts: ListSchedulesOptions) -> ListSchedulesStream {
let client = self.clone();
let namespace = self.namespace();
let query = opts.query;
let page_size = opts.maximum_page_size;