ora 0.12.7

Part of the Ora scheduler framework.
Documentation
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
//! Schedule management.

use std::{cmp, marker::PhantomData, pin::pin};

use eyre::{Context, OptionExt};
use futures::{Stream, TryStreamExt};
use tonic::Request;
use uuid::Uuid;

use crate::{
    admin::{
        AdminClient,
        jobs::{Job, JobFilters, JobOrderBy},
    },
    common::{AddedOrExisting, LabelFilter, TimeRange},
    job_type::{AnyJobType, JobType, JobTypeId},
    proto::{
        self,
        admin::v1::{AddSchedulesRequest, ListSchedulesRequest, PaginationOptions},
    },
    schedule::{ScheduleDefinition, ScheduleId},
};

impl AdminClient {
    /// Add a new schedule.
    pub async fn add_schedule<J>(
        &self,
        schedule: ScheduleDefinition<J>,
    ) -> crate::Result<Schedule<J>>
    where
        J: JobType,
    {
        let id = self
            .inner
            .add_schedules(Request::new(AddSchedulesRequest {
                schedules: vec![schedule.try_into()?],
                if_not_exists: None,
                inherit_labels: Some(true),
            }))
            .await?
            .into_inner()
            .schedule_ids
            .pop()
            .ok_or_eyre("schedule ID not returned after creating the schedule")?
            .parse::<Uuid>()
            .wrap_err("invalid schedule ID")
            .map(ScheduleId)?;

        Ok(Schedule {
            id,
            client: self.clone(),
            raw: None,
            phantom: PhantomData,
        })
    }

    /// Add multiple schedules.
    pub async fn add_schedules<I>(&self, schedules: I) -> crate::Result<Vec<Schedule<AnyJobType>>>
    where
        I: IntoIterator<Item: TryInto<proto::schedules::v1::Schedule, Error: Into<crate::Error>>>,
    {
        let schedules = schedules
            .into_iter()
            .map(TryInto::try_into)
            .collect::<Result<Vec<_>, _>>()
            .map_err(Into::into)?;

        self.inner
            .add_schedules(Request::new(AddSchedulesRequest {
                schedules,
                if_not_exists: None,
                inherit_labels: Some(true),
            }))
            .await?
            .into_inner()
            .schedule_ids
            .into_iter()
            .map(|id| {
                Result::<_, crate::Error>::Ok(Schedule {
                    client: self.clone(),
                    id: ScheduleId(
                        id.parse::<Uuid>()
                            .wrap_err("server returned invalid schedule ID")?,
                    ),
                    raw: None,
                    phantom: PhantomData,
                })
            })
            .collect::<Result<Vec<_>, _>>()
    }

    /// Add a schedule if no schedules exist with the given filter.
    ///
    /// If multiple existing schedules are matched by the filter,
    /// one is arbitrarily chosen and returned.
    pub async fn add_schedule_if_not_exists<J>(
        &self,
        schedule: ScheduleDefinition<J>,
        filters: ScheduleFilters,
    ) -> crate::Result<AddedOrExisting<Schedule<AnyJobType>>>
    where
        J: JobType,
    {
        let res = self
            .inner
            .add_schedules(Request::new(AddSchedulesRequest {
                schedules: vec![schedule.try_into()?],
                if_not_exists: Some(filters.into()),
                inherit_labels: Some(true),
            }))
            .await?
            .into_inner();

        let added_schedule_id = res
            .schedule_ids
            .into_iter()
            .next()
            .map(|id| {
                id.parse::<Uuid>()
                    .map(ScheduleId)
                    .wrap_err("server returned invalid schedule ID")
            })
            .transpose()?;

        let existing_schedule_id = res
            .existing_schedule_ids
            .into_iter()
            .next()
            .map(|id| {
                id.parse::<Uuid>()
                    .map(ScheduleId)
                    .wrap_err("server returned invalid schedule ID")
            })
            .transpose()?;

        match (added_schedule_id, existing_schedule_id) {
            (Some(added_schedule_id), None) => Ok(AddedOrExisting::Added(Schedule {
                client: self.clone(),
                id: added_schedule_id,
                raw: None,
                phantom: PhantomData,
            })),
            (None, Some(existing_schedule_id)) => Ok(AddedOrExisting::Existing(Schedule {
                client: self.clone(),
                id: existing_schedule_id,
                raw: None,
                phantom: PhantomData,
            })),
            (None, None) => Err(eyre::eyre!(
                "no schedule was added but no existing schedule was returned by the server"
            )
            .into()),
            (Some(_), Some(_)) => Err(eyre::eyre!(
                "server returned both an added schedule ID and an existing schedule ID, which is unexpected"
            )
            .into()),
        }
    }

    /// Add multiple schedules if no schedules exist with the given filter.
    pub async fn add_schedules_if_not_exists<I>(
        &self,
        schedules: I,
        filters: ScheduleFilters,
    ) -> crate::Result<AddedOrExisting<Vec<Schedule<AnyJobType>>>>
    where
        I: IntoIterator<Item: TryInto<proto::schedules::v1::Schedule, Error = crate::Error>>,
    {
        let schedules = schedules
            .into_iter()
            .map(TryInto::try_into)
            .collect::<Result<Vec<_>, _>>()?;

        let res = self
            .inner
            .add_schedules(Request::new(AddSchedulesRequest {
                schedules,
                if_not_exists: Some(filters.into()),
                inherit_labels: Some(true),
            }))
            .await?
            .into_inner();

        if res.schedule_ids.is_empty() {
            Ok(AddedOrExisting::Existing(
                res.existing_schedule_ids
                    .into_iter()
                    .map(|id| {
                        Result::<_, crate::Error>::Ok(Schedule {
                            client: self.clone(),
                            id: ScheduleId(
                                id.parse::<Uuid>()
                                    .wrap_err("server returned invalid job ID")?,
                            ),
                            raw: None,
                            phantom: PhantomData,
                        })
                    })
                    .collect::<Result<Vec<_>, _>>()?,
            ))
        } else {
            Ok(AddedOrExisting::Added(
                res.schedule_ids
                    .into_iter()
                    .map(|id| {
                        Result::<_, crate::Error>::Ok(Schedule {
                            client: self.clone(),
                            id: ScheduleId(
                                id.parse::<Uuid>()
                                    .wrap_err("server returned invalid job ID")?,
                            ),
                            raw: None,
                            phantom: PhantomData,
                        })
                    })
                    .collect::<Result<Vec<_>, _>>()?,
            ))
        }
    }

    /// List schedules based on the given filters.
    pub fn list_schedules(
        &self,
        filters: ScheduleFilters,
        order: ScheduleOrderBy,
        limit: Option<u32>,
    ) -> impl Stream<Item = crate::Result<Schedule<AnyJobType>>> {
        async_stream::try_stream!({
            let mut total_count = 0;
            let mut next_page_token = None;

            let filters: proto::admin::v1::ScheduleFilters = filters.into();

            loop {
                if let Some(limit) = limit
                    && total_count >= limit
                {
                    break;
                }

                let response = self
                    .inner
                    .list_schedules(Request::new(ListSchedulesRequest {
                        filters: Some(filters.clone()),
                        order_by: match order {
                            ScheduleOrderBy::CreatedAtAsc => {
                                proto::admin::v1::ScheduleOrderBy::CreatedAtAsc as i32
                            }
                            ScheduleOrderBy::CreatedAtDesc => {
                                proto::admin::v1::ScheduleOrderBy::CreatedAtDesc as i32
                            }
                        },
                        pagination: Some(PaginationOptions {
                            page_size: if let Some(limit) = limit {
                                cmp::min(25, limit)
                            } else {
                                25
                            },
                            next_page_token: next_page_token.clone(),
                        }),
                    }))
                    .await?
                    .into_inner();

                for schedule_proto in response.schedules {
                    let schedule_id = ScheduleId(
                        schedule_proto
                            .id
                            .parse::<Uuid>()
                            .wrap_err("server returned invalid schedule ID")?,
                    );

                    yield Schedule {
                        client: self.clone(),
                        id: schedule_id,
                        raw: Some(schedule_proto),
                        phantom: PhantomData,
                    };
                    total_count += 1;
                }

                next_page_token = response.next_page_token;

                if next_page_token.is_none() {
                    break;
                }
            }
        })
    }

    /// Return the first schedule matching the given filters, if any.
    ///
    /// This is just a convenience method that calls `list_schedules` with a limit of 1.
    pub async fn first_schedule(
        &self,
        filters: ScheduleFilters,
        order: ScheduleOrderBy,
    ) -> crate::Result<Option<Schedule<AnyJobType>>> {
        pin!(self.list_schedules(filters, order, Some(1)))
            .try_next()
            .await
    }

    /// Count the amount of schedules matching the given filters.
    pub async fn count_schedules(&self, filters: ScheduleFilters) -> crate::Result<u64> {
        let response = self
            .inner
            .count_schedules(Request::new(proto::admin::v1::CountSchedulesRequest {
                filters: Some(filters.into()),
            }))
            .await?
            .into_inner();

        Ok(response.count)
    }

    /// Stop the schedules matching the given filters.
    pub async fn stop_schedules(
        &self,
        filters: ScheduleFilters,
        job_action: StoppedScheduleJobAction,
    ) -> crate::Result<Vec<Schedule<AnyJobType>>> {
        Ok(self
            .inner
            .stop_schedules(Request::new(proto::admin::v1::StopSchedulesRequest {
                filters: Some(filters.into()),
                cancel_active_jobs: matches!(job_action, StoppedScheduleJobAction::Cancel),
            }))
            .await?
            .into_inner()
            .cancelled_schedule_ids
            .into_iter()
            .map(|id| {
                Ok(Schedule {
                    client: self.clone(),
                    id: ScheduleId(id.parse()?),
                    raw: None,
                    phantom: PhantomData,
                })
            })
            .collect::<Result<Vec<_>, eyre::Report>>()?)
    }

    /// Return whether any schedules exist matching the given filters.
    pub async fn schedule_exists(&self, filters: ScheduleFilters) -> crate::Result<bool> {
        // As of writing this the API doesn't have a separate endpoint
        // for this, so we just count the schedules.
        let count = self.count_schedules(filters).await?;
        Ok(count > 0)
    }
}

/// A schedule in the ora scheduler.
pub struct Schedule<J> {
    pub(super) client: AdminClient,
    /// The unique ID of the schedule.
    pub(super) id: ScheduleId,
    /// The raw schedule details.
    pub(super) raw: Option<proto::admin::v1::Schedule>,
    pub(super) phantom: PhantomData<J>,
}

impl<J> Schedule<J> {
    /// Return the ID of this schedule.
    #[must_use]
    pub fn id(&self) -> ScheduleId {
        self.id
    }

    /// Stop this schedule.
    pub async fn stop(&self, job_action: StoppedScheduleJobAction) -> crate::Result<()> {
        self.client
            .stop_schedules(
                ScheduleFilters {
                    schedule_ids: Some(vec![self.id]),
                    ..Default::default()
                },
                job_action,
            )
            .await?;

        Ok(())
    }

    /// Fetch jobs of this schedule with the given additional filters.
    pub fn list_jobs(
        &self,
        mut filters: JobFilters,
        order: JobOrderBy,
        limit: Option<u32>,
    ) -> impl Stream<Item = crate::Result<Job<J>>> {
        filters.schedule_ids = Some(vec![self.id]);

        self.client
            .list_jobs(filters, order, limit)
            .map_ok(Job::cast_any)
    }

    /// Return the status of the schedule.
    pub async fn status(&mut self) -> crate::Result<ScheduleStatus> {
        let raw = self.fetch_raw().await?;

        let raw = raw
            .as_ref()
            .or(self.raw.as_ref())
            .ok_or_eyre("failed to retrieve schedule")?;

        match raw.status() {
            proto::admin::v1::ScheduleStatus::Active
            | proto::admin::v1::ScheduleStatus::Unspecified => Ok(ScheduleStatus::Active),
            proto::admin::v1::ScheduleStatus::Stopped => Ok(ScheduleStatus::Stopped),
        }
    }

    /// Fetch and return the raw data without any processing.
    pub async fn raw(&mut self) -> crate::Result<proto::admin::v1::Schedule> {
        let job = self.fetch_raw().await?;

        Ok(job
            .or_else(|| self.raw.clone())
            .ok_or_eyre("failed to retrieve schedule")?)
    }

    /// Return the cached raw schedule, if any.
    ///
    /// This will not fetch any data from the server.
    #[must_use]
    pub fn raw_cached(&self) -> Option<&proto::admin::v1::Schedule> {
        self.raw.as_ref()
    }

    /// Always fetch the raw raw data from the server.
    ///
    /// Returns `None` if the data was cached, this is
    /// to avoid cloning.
    async fn fetch_raw(&mut self) -> crate::Result<Option<proto::admin::v1::Schedule>> {
        let schedule = self
            .client
            .inner
            .list_schedules(Request::new(ListSchedulesRequest {
                filters: Some(proto::admin::v1::ScheduleFilters {
                    schedule_ids: vec![self.id.to_string()],
                    ..Default::default()
                }),
                order_by: proto::admin::v1::JobOrderBy::Unspecified as _,
                pagination: Some(PaginationOptions {
                    page_size: 1,
                    next_page_token: None,
                }),
            }))
            .await?
            .into_inner()
            .schedules
            .pop()
            .ok_or_eyre("schedule not found")?;

        match self.client.caching_strategy {
            crate::admin::CachingStrategy::Cache => {
                self.raw = Some(schedule);
                Ok(None)
            }
            crate::admin::CachingStrategy::NoCache => Ok(Some(schedule)),
        }
    }
}

impl Schedule<AnyJobType> {
    /// Try to cast the schedule to the given job type,
    /// validating that the schedule is of the expected type.
    ///
    /// This function will fetch the required data
    /// from the server if necessary.
    pub async fn cast<J>(mut self) -> crate::Result<Option<Schedule<J>>>
    where
        J: JobType,
    {
        let schedule = self.fetch_raw().await?;

        let schedule = schedule
            .as_ref()
            .or(self.raw.as_ref())
            .ok_or_eyre("failed to fetch job")?;

        let job = schedule
            .schedule
            .as_ref()
            .ok_or_eyre("job definition is missing")?
            .job_template
            .as_ref()
            .ok_or_eyre("job template is missing")?;

        let job_type_id = &job.job_type_id;

        if job_type_id != J::job_type_id().as_str() {
            return Ok(None);
        }

        Ok(Some(Schedule {
            client: self.client,
            id: self.id,
            raw: self.raw,
            phantom: PhantomData,
        }))
    }

    /// Cast this schedule to the given job type.
    ///
    /// Note that no validation is performed to ensure
    /// that the schedule is actually of the given type.
    #[must_use]
    pub fn cast_unchecked<J>(self) -> Schedule<J>
    where
        J: JobType,
    {
        Schedule {
            client: self.client,
            id: self.id,
            raw: self.raw,
            phantom: PhantomData,
        }
    }
}

/// The status of a schedule.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScheduleStatus {
    /// The schedule is active.
    Active,
    /// The schedule was stopped.
    Stopped,
}

impl ScheduleStatus {
    /// Return whether the schedule is active.
    #[must_use]
    pub fn is_active(&self) -> bool {
        matches!(self, ScheduleStatus::Active)
    }
}

/// Filters for listing schedules.
#[derive(Debug, Default)]
#[must_use]
pub struct ScheduleFilters {
    /// Filter by schedule IDs.
    pub schedule_ids: Option<Vec<ScheduleId>>,
    /// Filter by job type IDs.
    pub job_type_ids: Option<Vec<JobTypeId>>,
    /// Filter by status.
    pub statuses: Option<Vec<ScheduleStatus>>,
    /// Filter by creation time.
    /// The range can be open-ended in either direction.
    pub created_at: Option<TimeRange>,
    /// Filter by labels.
    pub labels: Option<Vec<LabelFilter>>,
}

impl ScheduleFilters {
    /// Include all jobs.
    pub fn all() -> Self {
        Self::default()
    }

    /// Filter for a job type.
    pub fn job_type<J: JobType>(mut self) -> Self {
        self.job_type_ids = Some(vec![J::job_type_id()]);
        self
    }

    /// Filter for active schedules only.
    pub fn active_only(mut self) -> Self {
        self.statuses = Some(vec![ScheduleStatus::Active]);
        self
    }

    /// Filter for stopped schedules only.
    pub fn stopped_only(mut self) -> Self {
        self.statuses = Some(vec![ScheduleStatus::Stopped]);
        self
    }

    /// Filter by existence of a label.
    pub fn has_label<K: Into<String>>(mut self, key: K) -> Self {
        self.labels.get_or_insert_with(Vec::new).push(LabelFilter {
            key: key.into(),
            value: None,
        });

        self
    }

    /// Filter by a label key and value.
    pub fn has_label_value<K: Into<String>, V: Into<String>>(mut self, key: K, value: V) -> Self {
        self.labels.get_or_insert_with(Vec::new).push(LabelFilter {
            key: key.into(),
            value: Some(value.into()),
        });

        self
    }
}

/// The ordering options for listing schedules.
#[derive(Debug, Default, Clone, Copy)]
pub enum ScheduleOrderBy {
    /// Order by creation time ascending.
    #[default]
    CreatedAtAsc,
    /// Order by creation time descending.
    CreatedAtDesc,
}

/// What to do with jobs of stopped schedules.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum StoppedScheduleJobAction {
    /// Cancel all jobs of the stopped schedules.
    #[default]
    Cancel,
    /// Ignore the jobs of the stopped schedules.
    Ignore,
}