backbone-jobs 3.7.1

Job scheduling and cron management for the Backbone Framework
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
//! Cron expression parsing and scheduling utilities

use crate::error::{JobError, JobResult};
use chrono::{DateTime, Datelike, Duration, Timelike, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;

/// Cron expression parser and scheduler
#[derive(Debug, Clone)]
pub struct CronScheduler {
    expression: CronExpression,
    timezone: chrono_tz::Tz,
}

impl CronScheduler {
    /// Create a new cron scheduler with the given expression and timezone
    pub fn new(expression: &str, timezone: &str) -> JobResult<Self> {
        let cron_expr = CronExpression::parse(expression)?;
        let tz = timezone.parse::<chrono_tz::Tz>()
            .map_err(|_| JobError::time_zone(&format!("Invalid timezone: {}", timezone)))?;

        Ok(Self {
            expression: cron_expr,
            timezone: tz,
        })
    }

    /// Create a new cron scheduler with UTC timezone
    pub fn new_utc(expression: &str) -> JobResult<Self> {
        Self::new(expression, "UTC")
    }

    /// Get the next execution time after the given datetime
    pub fn next_after(&self, after: DateTime<Utc>) -> JobResult<DateTime<Utc>> {
        self.expression.next_after(after, &self.timezone)
    }

    /// Get the next n execution times after the given datetime
    pub fn next_n_after(&self, after: DateTime<Utc>, n: usize) -> JobResult<Vec<DateTime<Utc>>> {
        let mut times = Vec::with_capacity(n);
        let mut current = after;

        for _ in 0..n {
            let next = self.next_after(current)?;
            times.push(next);
            current = next + Duration::seconds(1);
        }

        Ok(times)
    }

    /// Check if the given datetime matches the cron expression
    pub fn matches(&self, datetime: DateTime<Utc>) -> bool {
        self.expression.matches(datetime, &self.timezone)
    }

    /// Get the cron expression
    pub fn expression(&self) -> &CronExpression {
        &self.expression
    }

    /// Get the timezone
    pub fn timezone(&self) -> &chrono_tz::Tz {
        &self.timezone
    }
}

/// Parsed cron expression with all fields
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CronExpression {
    /// Minute field (0-59)
    pub minute: CronField,
    /// Hour field (0-23)
    pub hour: CronField,
    /// Day of month field (1-31)
    pub day_of_month: CronField,
    /// Month field (1-12)
    pub month: CronField,
    /// Day of week field (0-6, 0=Sunday)
    pub day_of_week: CronField,
}

impl CronExpression {
    /// Parse a cron expression string
    /// Format: "minute hour day-of-month month day-of-week"
    /// Examples:
    /// - "0 12 * * *" - Every day at noon
    /// - "*/15 * * * *" - Every 15 minutes
    /// - "0 2 * * 0" - Every Sunday at 2 AM
    pub fn parse(expression: &str) -> JobResult<Self> {
        let parts: Vec<&str> = expression.split_whitespace().collect();

        if parts.len() != 5 {
            return Err(JobError::cron_parsing(
                &format!(
                    "Cron expression must have 5 fields, got {}: '{}'",
                    parts.len(),
                    expression
                )
            ));
        }

        Ok(Self {
            minute: CronField::parse(parts[0], 0, 59)?,
            hour: CronField::parse(parts[1], 0, 23)?,
            day_of_month: CronField::parse(parts[2], 1, 31)?,
            month: CronField::parse(parts[3], 1, 12)?,
            day_of_week: CronField::parse(parts[4], 0, 6)?,
        })
    }

    /// Get the next execution time after the given datetime
    pub fn next_after(&self, after: DateTime<Utc>, timezone: &chrono_tz::Tz) -> JobResult<DateTime<Utc>> {
        // Cron has minute resolution: always advance to the start of the next
        // minute so we never return the same minute we were called with.
        let mut current = (after + Duration::seconds(60 - after.second() as i64))
            .with_nanosecond(0)
            .unwrap();
        let mut attempts = 0;
        const MAX_ATTEMPTS: u32 = 100_000; // covers up to ~2 months at minute resolution

        while attempts < MAX_ATTEMPTS {
            if self.matches(current, timezone) {
                return Ok(current);
            }

            current = current + Duration::seconds(60);
            attempts += 1;
        }

        Err(JobError::cron_parsing("Could not find next execution time within reasonable bounds"))
    }

    /// Check if the given datetime matches the cron expression
    pub fn matches(&self, datetime: DateTime<Utc>, timezone: &chrono_tz::Tz) -> bool {
        let local = datetime.with_timezone(timezone);

        self.minute.matches(local.minute())
            && self.hour.matches(local.hour())
            && self.day_of_month.matches(local.day())
            && self.month.matches(local.month())
            && self.day_of_week.matches(local.weekday().num_days_from_sunday())
    }

}

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

/// Individual cron field (minute, hour, day, etc.)
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum CronField {
    /// All values (*)
    All,
    /// Single value
    Single(u32),
    /// Range of values (e.g., 1-5)
    Range(u32, u32),
    /// List of values (e.g., 1,3,5)
    List(HashSet<u32>),
    /// Step values (e.g., */15 or 1-30/5)
    Step(Box<CronField>, u32),
}

impl CronField {
    /// Parse a cron field value
    pub fn parse(value: &str, min: u32, max: u32) -> JobResult<Self> {
        if value == "*" {
            return Ok(CronField::All);
        }

        // Handle step values
        if let Some((base, step)) = value.split_once('/') {
            let step_val = step.parse::<u32>()
                .map_err(|_| JobError::cron_parsing(&format!("Invalid step value: {}", step)))?;

            if step_val == 0 {
                return Err(JobError::cron_parsing("Step value cannot be zero"));
            }

            let base_field = CronField::parse(base, min, max)?;
            return Ok(CronField::Step(Box::new(base_field), step_val));
        }

        // Handle ranges
        if let Some((start, end)) = value.split_once('-') {
            let start_val = start.parse::<u32>()
                .map_err(|_| JobError::cron_parsing(&format!("Invalid range start: {}", start)))?;
            let end_val = end.parse::<u32>()
                .map_err(|_| JobError::cron_parsing(&format!("Invalid range end: {}", end)))?;

            if start_val < min || end_val > max || start_val > end_val {
                return Err(JobError::cron_parsing(&format!(
                    "Invalid range values: {}-{} (expected {}-{})",
                    start_val, end_val, min, max
                )));
            }

            return Ok(CronField::Range(start_val, end_val));
        }

        // Handle lists
        if value.contains(',') {
            let values: Result<HashSet<u32>, _> = value
                .split(',')
                .map(|v| {
                    v.parse::<u32>().map_err(|_| {
                        JobError::cron_parsing(&format!("Invalid list value: {}", v))
                    })
                })
                .collect();

            let values = values?;
            for &val in &values {
                if val < min || val > max {
                    return Err(JobError::cron_parsing(&format!(
                        "Value {} out of range (expected {}-{})",
                        val, min, max
                    )));
                }
            }
            return Ok(CronField::List(values));
        }

        // Single value
        let single_val = value.parse::<u32>()
            .map_err(|_| JobError::cron_parsing(&format!("Invalid value: {}", value)))?;

        if single_val < min || single_val > max {
            return Err(JobError::cron_parsing(&format!(
                "Value {} out of range (expected {}-{})",
                single_val, min, max
            )));
        }

        Ok(CronField::Single(single_val))
    }

    /// Check if the field matches a given value
    pub fn matches(&self, value: u32) -> bool {
        match self {
            CronField::All => true,
            CronField::Single(v) => *v == value,
            CronField::Range(start, end) => value >= *start && value <= *end,
            CronField::List(values) => values.contains(&value),
            CronField::Step(base, step) => {
                if let CronField::All = **base {
                    value.is_multiple_of(*step)
                } else if base.matches(value) {
                    // For step on specific values, we need to find the offset
                    match **base {
                        CronField::Single(base_val) => (value - base_val).is_multiple_of(*step),
                        CronField::Range(start, _) => (value - start).is_multiple_of(*step),
                        _ => false, // Complex cases handled differently
                    }
                } else {
                    false
                }
            }
        }
    }

}

impl std::fmt::Display for CronField {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CronField::All => write!(f, "*"),
            CronField::Single(v) => write!(f, "{}", v),
            CronField::Range(start, end) => write!(f, "{}-{}", start, end),
            CronField::List(values) => {
                let mut sorted: Vec<_> = values.iter().collect();
                sorted.sort();
                write!(f, "{}", sorted.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(","))
            }
            CronField::Step(base, step) => write!(f, "{}/{}", base, step),
        }
    }
}

/// Common cron expression templates
pub mod templates {
    

    /// Every minute
    pub const EVERY_MINUTE: &str = "* * * * *";

    /// Every hour at minute 0
    pub const HOURLY: &str = "0 * * * *";

    /// Every day at midnight
    pub const DAILY_MIDNIGHT: &str = "0 0 * * *";

    /// Every day at noon
    pub const DAILY_NOON: &str = "0 12 * * *";

    /// Every Monday at 9 AM
    pub const WEEKLY_MONDAY_9AM: &str = "0 9 * * 1";

    /// Every Sunday at 2 AM
    pub const WEEKLY_SUNDAY_2AM: &str = "0 2 * * 0";

    /// First day of every month at midnight
    pub const MONTHLY_FIRST: &str = "0 0 1 * *";

    /// Last day of every month at midnight
    pub const MONTHLY_LAST: &str = "0 0 L * *";

    /// Every 5 minutes
    pub const EVERY_5_MINUTES: &str = "*/5 * * * *";

    /// Every 15 minutes
    pub const EVERY_15_MINUTES: &str = "*/15 * * * *";

    /// Every 30 minutes
    pub const EVERY_30_MINUTES: &str = "*/30 * * * *";

    /// Every 2 hours
    pub const EVERY_2_HOURS: &str = "0 */2 * * *";

    /// Every 6 hours
    pub const EVERY_6_HOURS: &str = "0 */6 * * *";

    /// Weekdays (Monday-Friday) at 9 AM
    pub const WEEKDAYS_9AM: &str = "0 9 * * 1-5";

    /// Weekends (Saturday-Sunday) at 10 AM
    pub const WEEKENDS_10AM: &str = "0 10 * * 6,0";

    /// Business hours (9 AM - 5 PM) every hour on weekdays
    pub const BUSINESS_HOURS: &str = "0 9-17 * * 1-5";
}

/// Helper functions for working with cron expressions
pub mod helpers {
    use super::*;
    use chrono::{DateTime, Utc};

    /// Calculate time until next execution
    pub fn time_until_next(
        expression: &str,
        timezone: &str,
        from: DateTime<Utc>,
    ) -> JobResult<Duration> {
        let scheduler = CronScheduler::new(expression, timezone)?;
        let next = scheduler.next_after(from)?;
        Ok(next - from)
    }

    /// Check if a cron expression is valid
    pub fn is_valid_expression(expression: &str) -> bool {
        CronExpression::parse(expression).is_ok()
    }

    /// Get a human-readable description of a cron expression
    pub fn describe_expression(expression: &str) -> JobResult<String> {
        let cron = CronExpression::parse(expression)?;

        let _minute_desc = describe_field(&cron.minute, "minute");
        let hour_desc = describe_field(&cron.hour, "hour");
        let day_desc = describe_field(&cron.day_of_month, "day");
        let month_desc = describe_field(&cron.month, "month");
        let weekday_desc = describe_field(&cron.day_of_week, "weekday");

        Ok(format!("Runs {} at {} on the {} of {}",
            weekday_desc, hour_desc, day_desc, month_desc))
    }

    fn describe_field(field: &CronField, field_name: &str) -> String {
        match field {
            CronField::All => match field_name {
                "minute" => "every minute".to_string(),
                "hour" => "every hour".to_string(),
                "day" => "every day".to_string(),
                "month" => "every month".to_string(),
                "weekday" => "every day".to_string(),
                _ => format!("every {}", field_name),
            },
            CronField::Single(v) => format!("at {}", v),
            CronField::Range(start, end) => format!("from {} to {}", start, end),
            CronField::List(values) => {
                let mut sorted: Vec<_> = values.iter().collect();
                sorted.sort();
                format!("at {}", sorted.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "))
            }
            CronField::Step(base, step) => match **base {
                CronField::All => format!("every {} {}", step, field_name),
                _ => format!("every {} {}", step, field_name),
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::TimeZone;
    use chrono_tz::UTC;

    #[test]
    fn test_cron_parsing() {
        let cron = CronExpression::parse("0 12 * * *").unwrap();
        assert!(matches!(cron.minute, CronField::Single(0)));
        assert!(matches!(cron.hour, CronField::Single(12)));
        assert!(matches!(cron.day_of_month, CronField::All));
        assert!(matches!(cron.month, CronField::All));
        assert!(matches!(cron.day_of_week, CronField::All));
    }

    #[test]
    fn test_cron_ranges() {
        let cron = CronExpression::parse("0 9-17 * * 1-5").unwrap();
        assert!(matches!(cron.hour, CronField::Range(9, 17)));
        assert!(matches!(cron.day_of_week, CronField::Range(1, 5)));
    }

    #[test]
    fn test_cron_lists() {
        let cron = CronExpression::parse("0,30 8,12,18 * * 1,3,5").unwrap();
        assert!(matches!(cron.minute, CronField::List(_)));
        assert!(matches!(cron.hour, CronField::List(_)));
        assert!(matches!(cron.day_of_week, CronField::List(_)));
    }

    #[test]
    fn test_cron_steps() {
        let cron = CronExpression::parse("*/15 * * * *").unwrap();
        assert!(matches!(cron.minute, CronField::Step(_, 15)));
    }

    #[test]
    fn test_next_execution() {
        let scheduler = CronScheduler::new_utc("0 12 * * *").unwrap();
        let now = Utc.with_ymd_and_hms(2024, 1, 1, 10, 0, 0).unwrap();
        let next = scheduler.next_after(now).unwrap();
        assert_eq!(next.hour(), 12);
        assert_eq!(next.minute(), 0);
    }

    #[test]
    fn test_multiple_next_executions() {
        let scheduler = CronScheduler::new_utc("*/30 * * * *").unwrap();
        let now = Utc.with_ymd_and_hms(2024, 1, 1, 10, 15, 0).unwrap();
        let next_times = scheduler.next_n_after(now, 3).unwrap();

        assert_eq!(next_times[0].minute(), 30);
        assert_eq!(next_times[1].minute(), 0);
        assert_eq!(next_times[2].minute(), 30);
    }

    #[test]
    fn test_invalid_expressions() {
        assert!(CronExpression::parse("").is_err());
        assert!(CronExpression::parse("0 12 * *").is_err()); // Only 4 fields
        assert!(CronExpression::parse("60 * * * *").is_err()); // Invalid minute
        assert!(CronExpression::parse("0 25 * * *").is_err()); // Invalid hour
    }

    #[test]
    fn test_helpers() {
        assert!(helpers::is_valid_expression("0 12 * * *"));
        assert!(!helpers::is_valid_expression("invalid"));

        let desc = helpers::describe_expression("0 12 * * *").unwrap();
        assert!(desc.contains("12"));
    }

    #[test]
    fn test_templates() {
        assert!(helpers::is_valid_expression(templates::HOURLY));
        assert!(helpers::is_valid_expression(templates::DAILY_MIDNIGHT));
        assert!(helpers::is_valid_expression(templates::WEEKLY_MONDAY_9AM));
        assert!(helpers::is_valid_expression(templates::MONTHLY_FIRST));
        assert!(helpers::is_valid_expression(templates::BUSINESS_HOURS));
    }
}