ryuk 0.1.0

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
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
//! Task scheduler, shaped like Laravel's: declare tasks in code, tick once a minute.
//!
//! ```
//! use ryuk::schedule::Schedule;
//!
//! let mut schedule = Schedule::new();
//! schedule.call("prune", || async { /* delete old rows */ }).daily_at("03:00").unwrap().without_overlapping();
//! schedule.call("ping", || async {}).every_five_minutes();
//! // in main: schedule.spawn(async { let _ = tokio::signal::ctrl_c().await; });
//! ```
//!
//! shortcut: UTC only, no per-entry time zone; add a `chrono::TimeZone` when needed.
//! shortcut: `without_overlapping` is in-process only; use a DB or Redis lock for several instances.

use chrono::{DateTime, Datelike, Timelike, Utc};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

/// Boxed error a task may return.
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;

/// What a task future may resolve to: `()` or `Result<(), impl Into<BoxError>>`.
pub trait TaskResult {
    /// Converts into a plain result.
    fn into_result(self) -> Result<(), BoxError>;
}
impl TaskResult for () {
    fn into_result(self) -> Result<(), BoxError> {
        Ok(())
    }
}
impl<Er: Into<BoxError>> TaskResult for Result<(), Er> {
    fn into_result(self) -> Result<(), BoxError> {
        self.map_err(Into::into)
    }
}

/// Invalid cron expression or time.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
#[error("invalid schedule: {0}")]
pub struct CronError(pub String);

/// A parsed 5-field cron expression (`m h dom mon dow`; `*`, lists, ranges, steps).
/// When both day-of-month and day-of-week are restricted, either matching is enough (as in cron).
///
/// ```
/// use ryuk::schedule::Cron;
/// assert!(Cron::parse("*/15 9-17 * * 1-5").is_ok());
/// assert!(Cron::parse("61 * * * *").is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Cron {
    minute: u64,
    hour: u64,
    dom: u64,
    month: u64,
    dow: u64,
    dom_star: bool,
    dow_star: bool,
}

fn field(src: &str, min: u32, max: u32) -> Result<(u64, bool), CronError> {
    let err = |m: &str| CronError(format!("{m} in `{src}`"));
    let mut mask = 0u64;
    for part in src.split(',') {
        let (range, step) = match part.split_once('/') {
            Some((r, s)) => (r, s.parse::<u32>().map_err(|_| err("bad step"))?),
            None => (part, 1),
        };
        if step == 0 {
            return Err(err("zero step"));
        }
        let num = |s: &str| s.parse::<u32>().map_err(|_| err("bad number"));
        let (lo, hi) = if range == "*" {
            (min, max)
        } else if let Some((a, b)) = range.split_once('-') {
            (num(a)?, num(b)?)
        } else {
            let a = num(range)?;
            (a, if part.contains('/') { max } else { a })
        };
        if lo < min || hi > max || lo > hi {
            return Err(err("out of range"));
        }
        let mut v = lo;
        while v <= hi {
            mask |= 1 << v;
            v += step;
        }
    }
    Ok((mask, src.starts_with('*')))
}

impl Cron {
    /// Parses `"m h dom mon dow"`. Returns `Err` (never panics) on bad input.
    pub fn parse(expr: &str) -> Result<Self, CronError> {
        let f: Vec<&str> = expr.split_whitespace().collect();
        let [m, h, dom, mon, dow] = f[..] else {
            return Err(CronError(format!("expected 5 fields in `{expr}`")));
        };
        let (minute, _) = field(m, 0, 59)?;
        let (hour, _) = field(h, 0, 23)?;
        let (dom, dom_star) = field(dom, 1, 31)?;
        let (month, _) = field(mon, 1, 12)?;
        let (mut dow, dow_star) = field(dow, 0, 7)?;
        if dow & (1 << 7) != 0 {
            dow = (dow & !(1 << 7)) | 1; // 7 is Sunday too
        }
        Ok(Self {
            minute,
            hour,
            dom,
            month,
            dow,
            dom_star,
            dow_star,
        })
    }

    /// Whether `t` (to the minute) matches.
    pub fn matches(&self, t: DateTime<Utc>) -> bool {
        let bit = |mask: u64, v: u32| mask & (1 << v) != 0;
        let dom = bit(self.dom, t.day());
        let dow = bit(self.dow, t.weekday().num_days_from_sunday());
        let day = if !self.dom_star && !self.dow_star {
            dom || dow
        } else {
            dom && dow
        };
        bit(self.minute, t.minute())
            && bit(self.hour, t.hour())
            && bit(self.month, t.month())
            && day
    }
}

type Task =
    Arc<dyn Fn() -> Pin<Box<dyn Future<Output = Result<(), BoxError>> + Send>> + Send + Sync>;

/// One scheduled task; configure it with the chained methods.
pub struct Entry {
    name: String,
    cron: Cron,
    task: Task,
    no_overlap: bool,
    running: Arc<AtomicBool>,
    filters: Vec<Box<dyn Fn() -> bool + Send + Sync>>,
}

impl Entry {
    /// Custom 5-field cron expression.
    pub fn cron(&mut self, expr: &str) -> Result<&mut Self, CronError> {
        self.cron = Cron::parse(expr)?;
        Ok(self)
    }
    fn set(&mut self, expr: &str) -> &mut Self {
        self.cron = Cron::parse(expr).expect("built-in expression is valid");
        self
    }
    /// Every minute (the default).
    pub fn every_minute(&mut self) -> &mut Self {
        self.set("* * * * *")
    }
    /// Every five minutes.
    pub fn every_five_minutes(&mut self) -> &mut Self {
        self.set("*/5 * * * *")
    }
    /// Every `n` minutes (1..=59; other values are clamped).
    pub fn every_n_minutes(&mut self, n: u32) -> &mut Self {
        self.set(&format!("*/{} * * * *", n.clamp(1, 59)))
    }
    /// At minute 0 of every hour.
    pub fn hourly(&mut self) -> &mut Self {
        self.hourly_at(0)
    }
    /// At `minute` (0..=59, clamped) of every hour.
    pub fn hourly_at(&mut self, minute: u32) -> &mut Self {
        self.set(&format!("{} * * * *", minute.min(59)))
    }
    /// Daily at 00:00 UTC.
    pub fn daily(&mut self) -> &mut Self {
        self.set("0 0 * * *")
    }
    /// Daily at `"HH:MM"` UTC.
    pub fn daily_at(&mut self, hhmm: &str) -> Result<&mut Self, CronError> {
        let bad = || CronError(format!("expected HH:MM, got `{hhmm}`"));
        let (h, m) = hhmm.split_once(':').ok_or_else(bad)?;
        let (h, m): (u32, u32) = (h.parse().map_err(|_| bad())?, m.parse().map_err(|_| bad())?);
        self.cron(&format!("{m} {h} * * *"))
    }
    /// Sundays at 00:00 UTC.
    pub fn weekly(&mut self) -> &mut Self {
        self.set("0 0 * * 0")
    }
    /// The first of the month at 00:00 UTC.
    pub fn monthly(&mut self) -> &mut Self {
        self.set("0 0 1 * *")
    }
    /// Skip a run while the previous run of this entry is still going (this process only).
    pub fn without_overlapping(&mut self) -> &mut Self {
        self.no_overlap = true;
        self
    }
    /// Only run when `f` returns true at tick time.
    pub fn when(&mut self, f: impl Fn() -> bool + Send + Sync + 'static) -> &mut Self {
        self.filters.push(Box::new(f));
        self
    }
}

/// Releases the overlap flag even if the task panics.
struct Release(Arc<AtomicBool>);
impl Drop for Release {
    fn drop(&mut self) {
        self.0.store(false, Ordering::SeqCst);
    }
}

/// A set of scheduled tasks.
#[derive(Default)]
pub struct Schedule {
    entries: Vec<Entry>,
}

impl Schedule {
    /// An empty schedule.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a task (default: every minute) and returns its entry for configuration.
    /// A task returning `Err` is logged; a panic is caught per run. Neither stops the loop.
    pub fn call<F, Fut>(&mut self, name: impl Into<String>, f: F) -> &mut Entry
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future + Send + 'static,
        Fut::Output: TaskResult,
    {
        let task: Task = Arc::new(move || {
            let fut = f();
            Box::pin(async move { fut.await.into_result() })
        });
        self.entries.push(Entry {
            name: name.into(),
            cron: Cron::parse("* * * * *").expect("valid"),
            task,
            no_overlap: false,
            running: Arc::new(AtomicBool::new(false)),
            filters: Vec::new(),
        });
        self.entries.last_mut().expect("just pushed")
    }

    fn start_due(&self, now: DateTime<Utc>) -> Vec<tokio::task::JoinHandle<()>> {
        let mut handles = Vec::new();
        for e in &self.entries {
            if !e.cron.matches(now) || !e.filters.iter().all(|f| f()) {
                continue;
            }
            let guard = if e.no_overlap {
                if e.running
                    .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
                    .is_err()
                {
                    tracing::warn!(task = %e.name, "scheduled task skipped, previous run still going");
                    continue;
                }
                Some(Release(e.running.clone()))
            } else {
                None
            };
            let (name, task) = (e.name.clone(), e.task.clone());
            handles.push(tokio::spawn(async move {
                let _guard = guard;
                if let Err(err) = task().await {
                    tracing::error!(task = %name, %err, "scheduled task failed");
                }
            }));
        }
        handles
    }

    /// One tick: starts every entry due at `now` (to the minute), awaits them, and returns
    /// how many ran. Panics are caught and logged.
    ///
    /// ```
    /// # #[tokio::main] async fn main() {
    /// use chrono::{TimeZone, Utc};
    /// let mut s = ryuk::schedule::Schedule::new();
    /// s.call("t", || async {}).daily_at("03:00").unwrap();
    /// assert_eq!(s.run_due(Utc.with_ymd_and_hms(2026, 1, 1, 3, 0, 0).unwrap()).await, 1);
    /// assert_eq!(s.run_due(Utc.with_ymd_and_hms(2026, 1, 1, 3, 1, 0).unwrap()).await, 0);
    /// # }
    /// ```
    pub async fn run_due(&self, now: DateTime<Utc>) -> usize {
        let handles = self.start_due(now);
        let n = handles.len();
        for h in handles {
            if let Err(err) = h.await {
                tracing::error!(%err, "scheduled task panicked");
            }
        }
        n
    }

    /// Ticks at every minute boundary until `shutdown` resolves. Runs are detached, so a slow
    /// task never delays the next tick (use `without_overlapping` to prevent piling up).
    pub async fn run(&self, shutdown: impl Future<Output = ()>) {
        tokio::pin!(shutdown);
        loop {
            let now = Utc::now();
            let next = now
                .with_second(0)
                .and_then(|t| t.with_nanosecond(0))
                .unwrap_or(now)
                + chrono::Duration::minutes(1);
            let wait = (next - now).to_std().unwrap_or_default();
            tokio::select! {
                _ = &mut shutdown => return,
                _ = tokio::time::sleep(wait) => { self.start_due(next); }
            }
        }
    }

    /// Runs [`run`](Self::run) in a background task.
    pub fn spawn(
        self,
        shutdown: impl Future<Output = ()> + Send + 'static,
    ) -> tokio::task::JoinHandle<()> {
        tokio::spawn(async move { self.run(shutdown).await })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::TimeZone;
    use std::sync::atomic::AtomicUsize;

    fn t(y: i32, mo: u32, d: u32, h: u32, mi: u32) -> DateTime<Utc> {
        Utc.with_ymd_and_hms(y, mo, d, h, mi, 0).unwrap()
    }

    fn boom(msg: &str) -> Result<(), BoxError> {
        panic!("{msg}")
    }

    #[test]
    fn cron_table() {
        // 2026-01-05 is a Monday
        let cases = [
            ("* * * * *", t(2026, 1, 5, 4, 7), true),
            ("*/15 * * * *", t(2026, 1, 5, 4, 30), true),
            ("*/15 * * * *", t(2026, 1, 5, 4, 31), false),
            ("0,30 9-17 * * *", t(2026, 1, 5, 17, 30), true),
            ("0,30 9-17 * * *", t(2026, 1, 5, 18, 0), false),
            ("0 0 * * 7", t(2026, 1, 4, 0, 0), true),
            ("0 0 * * 1-5", t(2026, 1, 4, 0, 0), false),
            ("5/20 * * * *", t(2026, 1, 5, 0, 45), true),
            ("0 0 1 * 1", t(2026, 1, 5, 0, 0), true), // dom or dow
            ("0 0 1 * 1", t(2026, 1, 6, 0, 0), false),
        ];
        for (e, when, want) in cases {
            assert_eq!(Cron::parse(e).unwrap().matches(when), want, "{e} at {when}");
        }
    }

    #[test]
    fn cron_invalid() {
        for e in [
            "",
            "* * * *",
            "* * * * * *",
            "60 * * * *",
            "* 24 * * *",
            "* * 0 * *",
            "* * * 13 *",
            "*/0 * * * *",
            "5-1 * * * *",
            "a * * * *",
            "*/x * * * *",
            "1- * * * *",
        ] {
            assert!(Cron::parse(e).is_err(), "{e}");
        }
        let mut s = Schedule::new();
        assert!(s.call("x", || async {}).daily_at("25:00").is_err());
        assert!(s.call("y", || async {}).daily_at("nope").is_err());
    }

    #[tokio::test]
    async fn run_due_fixed_times_when_and_failures() {
        let hits = Arc::new(AtomicUsize::new(0));
        let mut s = Schedule::new();
        let h = hits.clone();
        s.call("hourly", move || {
            let h = h.clone();
            async move {
                h.fetch_add(1, Ordering::SeqCst);
            }
        })
        .hourly_at(15);
        s.call("fails", || async { Err::<(), _>("x") });
        s.call("panics", || async { boom("boom") });
        s.call("off", || async { boom("must not run") })
            .when(|| false);
        assert_eq!(s.run_due(t(2026, 1, 1, 5, 15)).await, 3);
        assert_eq!(s.run_due(t(2026, 1, 1, 5, 16)).await, 2);
        assert_eq!(hits.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn overlap_guard() {
        let runs = Arc::new(AtomicUsize::new(0));
        let mut s = Schedule::new();
        let r = runs.clone();
        s.call("slow", move || {
            let r = r.clone();
            async move {
                r.fetch_add(1, Ordering::SeqCst);
                tokio::time::sleep(std::time::Duration::from_millis(80)).await;
            }
        })
        .without_overlapping();
        let now = t(2026, 1, 1, 0, 0);
        let (a, b) = tokio::join!(s.run_due(now), s.run_due(now));
        assert_eq!(a + b, 1);
        assert_eq!(s.run_due(now).await, 1); // released after finishing
        assert_eq!(runs.load(Ordering::SeqCst), 2);
    }
}