Skip to main content

graphile_worker/builder/
cron_input.rs

1use crate::cron::CronBuilder;
2use graphile_worker_crontab_parser::{parse_crontab, CrontabParseError};
3use graphile_worker_crontab_types::Crontab;
4use graphile_worker_task_handler::TaskHandler;
5
6use super::WorkerOptions;
7
8/// Input accepted by [`WorkerOptions::with_cron`].
9///
10/// Typed cron builders and raw [`Crontab`] values are infallible and return
11/// `WorkerOptions` directly. Crontab text is parsed and returns
12/// `Result<WorkerOptions, CrontabParseError>`.
13pub trait CronInput {
14    type Output;
15
16    fn append_to(self, options: WorkerOptions) -> Self::Output;
17}
18
19impl CronInput for Crontab {
20    type Output = WorkerOptions;
21
22    fn append_to(self, mut options: WorkerOptions) -> Self::Output {
23        options.append_crontabs(vec![self]);
24        options
25    }
26}
27
28impl<T: TaskHandler> CronInput for CronBuilder<T> {
29    type Output = WorkerOptions;
30
31    fn append_to(self, options: WorkerOptions) -> Self::Output {
32        self.build().append_to(options)
33    }
34}
35
36impl CronInput for &str {
37    type Output = Result<WorkerOptions, CrontabParseError>;
38
39    fn append_to(self, mut options: WorkerOptions) -> Self::Output {
40        let crontabs = parse_crontab(self)?;
41        options.append_crontabs(crontabs);
42        Ok(options)
43    }
44}
45
46impl CronInput for String {
47    type Output = Result<WorkerOptions, CrontabParseError>;
48
49    fn append_to(self, options: WorkerOptions) -> Self::Output {
50        self.as_str().append_to(options)
51    }
52}
53
54impl CronInput for &String {
55    type Output = Result<WorkerOptions, CrontabParseError>;
56
57    fn append_to(self, options: WorkerOptions) -> Self::Output {
58        self.as_str().append_to(options)
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    #[test]
67    fn string_reference_input_appends_parsed_crontabs() {
68        let input = String::from("0 8 * * * send_digest");
69        let options = (&input)
70            .append_to(WorkerOptions::default())
71            .expect("valid crontab");
72
73        let crontabs = options.crontabs.expect("crontabs should be set");
74
75        assert_eq!(crontabs.len(), 1);
76        assert_eq!(crontabs[0].task_identifier, "send_digest");
77    }
78}