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
use std::time::Duration;

use anyhow::bail;
use serde::{Deserialize, Serialize};
use time::OffsetDateTime;
use uuid::Uuid;

use crate::pretty_duration::PrettyDuration;

use super::{EntityDescriptorConst, JobDefinition};

pub type CronJobId = Uuid;

/// A cronjob.
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug, schemars::JsonSchema)]
pub struct CronJobSpecV1 {
    /// Define when to execute the job.
    /// May be either:
    /// - an interval, eg "2days", "1h[our]", "30s", ...
    /// - A cron expression, eg "0 0 * * *", "0 0 1 * *", ...
    ///   See https://en.wikipedia.org/wiki/Cron for the syntax
    pub schedule: String,

    /// Defines the time range in which the job may be executed.
    ///
    /// The system will try to backfill missed job executions to ensure each
    /// job is executed.
    /// This setting limits the time range in which backfilling is performed.
    pub max_schedule_drift: Option<PrettyDuration>,

    #[serde(flatten)]
    pub job: JobDefinition,
}

impl CronJobSpecV1 {
    pub fn parse_schedule(&self) -> Result<CronSchedule, CronTabParseError> {
        self.schedule.parse()
    }
}

impl EntityDescriptorConst for CronJobSpecV1 {
    const NAMESPACE: &'static str = "wasmer.io";
    const NAME: &'static str = "CronJob";
    const VERSION: &'static str = "v1-alpha1";
    const KIND: &'static str = "wasmer.io/CronJob.v1-alpha1";
    type Spec = Self;
    type State = ();
}

#[derive(PartialEq, Eq, Clone, Debug)]
pub enum CronSchedule {
    Interval(std::time::Duration),
    CronTab(CronTab),
}

impl CronSchedule {
    pub fn next(
        &self,
        last: Option<time::OffsetDateTime>,
        drift: Option<Duration>,
    ) -> Result<OffsetDateTime, anyhow::Error> {
        match self {
            CronSchedule::Interval(duration) => {
                if let Some(last) = last {
                    Ok(last + *duration)
                } else {
                    Ok(OffsetDateTime::now_utc())
                }
            }
            CronSchedule::CronTab(c) => c.next(last, drift),
        }
    }

    /// Get the maximum time allowed between job invocations.
    pub fn max_timewindow(&self) -> Duration {
        match self {
            CronSchedule::Interval(duration) => *duration,
            CronSchedule::CronTab(c) => c.max_timewindow(),
        }
    }
}

impl std::fmt::Display for CronSchedule {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CronSchedule::Interval(d) => write!(f, "{}", PrettyDuration::from(*d)),
            CronSchedule::CronTab(c) => c.fmt(f),
        }
    }
}

impl std::str::FromStr for CronSchedule {
    type Err = CronTabParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.parse::<crate::pretty_duration::PrettyDuration>() {
            Ok(d) => Ok(Self::Interval(d.0)),
            Err(_) => match s.parse::<CronTab>() {
                Ok(c) => Ok(Self::CronTab(c)),
                Err(_) => Err(CronTabParseError::new(
                    s,
                    "invalid cron schedule - expected either an interval like '1m10s' or a valid crontab".to_string(),
                )),
            },
        }
    }
}

#[derive(PartialEq, Eq, Clone, Debug)]
enum CronTabValue {
    All,
    Value(u8),
}

impl std::fmt::Display for CronTabValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CronTabValue::All => write!(f, "*"),
            CronTabValue::Value(x) => write!(f, "{x}"),
        }
    }
}

/// Crontab schedule.
///
/// See https://en.wikipedia.org/wiki/Cron
///
/// # ┌───────────── minute (0 - 59)
/// # │ ┌───────────── hour (0 - 23)
/// # │ │ ┌───────────── day of the month (1 - 31)
/// # │ │ │ ┌───────────── month (1 - 12)
/// # │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday;
/// # │ │ │ │ │                                   7 is also Sunday on some systems)
/// # │ │ │ │ │
/// # │ │ │ │ │
/// # * * * * *
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct CronTab {
    // NOTE: fields are private to prevent invalid values.

    // * / 0-59
    minute: CronTabValue,
    // * / 0-23
    hour: CronTabValue,
    // * / 1-31
    day_of_month: CronTabValue,
    // * / 1-12
    month: CronTabValue,
    // 0-6
    day_of_week: CronTabValue,
}

impl CronTab {
    pub fn next(
        &self,
        _last: Option<time::OffsetDateTime>,
        _drift: Option<Duration>,
    ) -> Result<OffsetDateTime, anyhow::Error> {
        let now = OffsetDateTime::now_utc();

        // Round up to next full minute.
        let mut target =
            now.replace_nanosecond(0)? + std::time::Duration::from_secs(60 - now.second() as u64);

        match self.minute {
            CronTabValue::All => {}
            CronTabValue::Value(val) => {
                if target.minute() < val {
                    let diff = 60 - val - target.minute();
                    target += Duration::from_secs(diff as u64 * 60);
                } else {
                    target = target.replace_minute(val)?;
                }
            }
        }

        match self.hour {
            CronTabValue::All => {}
            CronTabValue::Value(hour) => {
                if target.hour() < hour {
                    let diff = 24 - hour - target.hour();
                    target += Duration::from_secs(diff as u64 * 60 * 60);
                } else {
                    target = target.replace_hour(hour)?;
                }
            }
        }

        match self.month {
            CronTabValue::All => {}
            CronTabValue::Value(month) => {
                let cur_month: u8 = target.month().into();
                if month < cur_month {
                    let diff = 12 - cur_month - month;
                    target += Duration::from_secs(diff as u64 * 60 * 60 * 24 * 30);
                } else {
                    target = target.replace_month(month.try_into()?)?;
                }
            }
        }

        match self.day_of_week {
            CronTabValue::All => {}
            CronTabValue::Value(_dm) => {
                // FIXME: implement day of week in crons
                bail!("day of week schedule not supported yet");
            }
        }

        Ok(target)
    }

    pub fn max_timewindow(&self) -> Duration {
        Duration::from_secs(60 * 5)
    }
}

impl std::str::FromStr for CronTab {
    type Err = CronTabParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut parts = s.split_whitespace();

        let part = parts
            .next()
            .ok_or_else(|| CronTabParseError::new(s, "missing minute specifier"))?;

        let minute = match part {
            "*" => CronTabValue::All,
            x => {
                let x = x.parse::<u8>().map_err(|err| {
                    CronTabParseError::new(
                        s,
                        format!("invalid minute specifier '{x}' - expected * or [0-59]: '{err}'"),
                    )
                })?;

                if x > 59 {
                    return Err(CronTabParseError::new(s, format!("invalid minute specifier '{x}': expected * or a number between 0 and 59")));
                }

                CronTabValue::Value(x)
            }
        };

        let part = parts
            .next()
            .ok_or_else(|| CronTabParseError::new(s, "missing hour specifier"))?;
        let hour = match part {
            "*" => CronTabValue::All,
            x => {
                let x = x.parse::<u8>().map_err(|err| {
                    CronTabParseError::new(
                        s,
                        format!("invalid hour specifier '{x}' - expected * or [0-23]: '{err}'"),
                    )
                })?;

                if x > 23 {
                    return Err(CronTabParseError::new(
                        s,
                        format!(
                            "invalid hour specifier '{x}': expected * or a number between 0 and 23"
                        ),
                    ));
                }

                CronTabValue::Value(x)
            }
        };

        let part = parts
            .next()
            .ok_or_else(|| CronTabParseError::new(s, "missing day of month specifier"))?;
        let day_of_month = match part {
            "*" => CronTabValue::All,
            x => {
                let x = x.parse::<u8>().map_err(|err| {
                    CronTabParseError::new(
                        s,
                        format!(
                            "invalid day of month specifier '{x}' - expected * or [1-31]: '{err}'",
                        ),
                    )
                })?;

                if x < 1 || x > 31 {
                    return Err(CronTabParseError::new(
                        s,
                        format!(
                            "invalid day of month specifier '{x}': expected * or a number between 1 and 31",
                        ),
                    ));
                }

                CronTabValue::Value(x)
            }
        };

        let part = parts
            .next()
            .ok_or_else(|| CronTabParseError::new(s, "missing month specifier"))?;
        let month = match part {
            "*" => CronTabValue::All,
            x => {
                let x = x.parse::<u8>().map_err(|err| {
                    CronTabParseError::new(
                        s,
                        format!("invalid month specifier '{x}' - expected * or [1-12]: '{err}'"),
                    )
                })?;

                if x < 1 || x > 12 {
                    return Err(CronTabParseError::new(
                        s,
                        format!(
                            "invalid month specifier '{x}': expected * or a number between 1 and 12",
                        ),
                    ));
                }

                CronTabValue::Value(x)
            }
        };

        let part = parts
            .next()
            .ok_or_else(|| CronTabParseError::new(s, "missing day of week specifier"))?;
        let day_of_week = match part {
            "*" => CronTabValue::All,
            x => {
                let x = x.parse::<u8>().map_err(|err| {
                    CronTabParseError::new(
                        s,
                        format!(
                            "invalid day of week specifier '{x}' - expected * or [0-6]: '{err}'",
                        ),
                    )
                })?;

                if x > 6 {
                    return Err(CronTabParseError::new(
                        s,
                        format!(
                            "invalid day of week specifier '{x}': expected * or a number between 0 and 6",
                        ),
                    ));
                }

                CronTabValue::Value(x)
            }
        };

        Ok(Self {
            minute,
            hour,
            day_of_month,
            month,
            day_of_week,
        })
    }
}

impl std::fmt::Display for CronTab {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{minute} {hour} {day_of_month} {month} {day_of_week}",
            minute = self.minute,
            hour = self.hour,
            day_of_month = self.day_of_month,
            month = self.month,
            day_of_week = self.day_of_week,
        )
    }
}

#[derive(Debug)]
pub struct CronTabParseError {
    error: String,
    value: String,
}

impl CronTabParseError {
    pub fn new(tab: impl Into<String>, error: impl Into<String>) -> Self {
        Self {
            value: tab.into(),
            error: error.into(),
        }
    }
}

impl std::fmt::Display for CronTabParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Invalid cron tab '{}': {}", self.value, self.error,)
    }
}

impl std::error::Error for CronTabParseError {}

#[cfg(test)]
mod tests {
    use std::{str::FromStr, time::Duration};

    use super::*;

    #[test]
    fn test_parse_schedule() {
        assert_eq!(
            CronSchedule::from_str("1m").unwrap(),
            CronSchedule::Interval(Duration::from_secs(60)),
        );

        assert_eq!(
            CronSchedule::from_str("* * * * *").unwrap(),
            CronSchedule::CronTab(CronTab {
                minute: CronTabValue::All,
                hour: CronTabValue::All,
                day_of_month: CronTabValue::All,
                month: CronTabValue::All,
                day_of_week: CronTabValue::All,
            })
        );
    }

    #[test]
    fn test_parse_crontab() {
        assert_eq!(
            CronTab::from_str("* * * * *").unwrap(),
            CronTab {
                minute: CronTabValue::All,
                hour: CronTabValue::All,
                day_of_month: CronTabValue::All,
                month: CronTabValue::All,
                day_of_week: CronTabValue::All,
            },
        );

        assert_eq!(
            CronTab::from_str("1 1 1 1 1").unwrap(),
            CronTab {
                minute: CronTabValue::Value(1),
                hour: CronTabValue::Value(1),
                day_of_month: CronTabValue::Value(1),
                month: CronTabValue::Value(1),
                day_of_week: CronTabValue::Value(1),
            },
        );
    }
}