Skip to main content

encore/
cron.rs

1//! Cron jobs: requests Encore makes of a service on a schedule.
2//!
3//! A job is declared as a `static`, with the path it requests and when:
4//!
5//! ```ignore
6//! use encore::cron::{Job, Schedule};
7//!
8//! /// Removes the sessions nobody has used in a month.
9//! static CLEANUP: Job =
10//!     Job::new("cleanup", "/internal/cleanup", Schedule::Cron("0 4 * * *")).title("Nightly cleanup");
11//!
12//! static REFRESH: Job = Job::new("refresh-rates", "/internal/rates", Schedule::Every("30m"));
13//! ```
14//!
15//! When the job is due, Encore sends a `POST` request for the path to the
16//! service that declares the job. What runs is whatever the service serves
17//! there, so the route and the job are best kept in step by declaring the one
18//! from the other:
19//!
20//! ```ignore
21//! let app = Router::new().route(CLEANUP.path(), post(cleanup));
22//! ```
23//!
24//! # Each run
25//!
26//! The request carries an idempotency key in [`IDEMPOTENCY_KEY_HEADER`]: an
27//! id for the run that is the same each time Encore sends it, as when it
28//! sends it again after a failure. A job that must not do its work twice can
29//! check whether it has seen the key before:
30//!
31//! ```ignore
32//! async fn cleanup(headers: HeaderMap) -> StatusCode {
33//!     let key = headers.get(encore::cron::IDEMPOTENCY_KEY_HEADER);
34//!     // ...
35//! }
36//! ```
37//!
38//! [`TRIGGER_HEADER`] says why the job runs. Only Encore sends either: a
39//! gateway removes them from the requests it takes from clients.
40//!
41//! # Running locally and under test
42//!
43//! Nothing is scheduled by `encore run` or `encore test`: a job runs where the
44//! app is deployed. `encore cron trigger <name>` runs one now, as Encore runs it
45//! when it is due, with both headers. Or request its path, or call what
46//! serves it.
47
48/// The header with a run's idempotency key: an id that is the same each
49/// time Encore sends the run. See the [module documentation](self).
50pub const IDEMPOTENCY_KEY_HEADER: &str = "x-encore-cron-execution";
51
52/// The header that says why a job runs: `scheduled`, when it was due, or
53/// `manual`, when someone asked for it to run now.
54pub const TRIGGER_HEADER: &str = "x-encore-cron-trigger";
55
56/// When a [`Job`] runs.
57///
58/// Written out where the job is declared, with a string literal: Encore reads
59/// it from the source.
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum Schedule {
62    /// At the times a [cron expression] names: five fields — minute, hour, day
63    /// of month, month and day of week — in UTC. `"0 4 * * *"` is 04:00 every
64    /// day, `"0 9 * * 1"` 09:00 on Mondays.
65    ///
66    /// [cron expression]: https://en.wikipedia.org/wiki/Cron#Cron_expression
67    Cron(&'static str),
68    /// Every so often: a duration of hours and minutes, as in `"30m"`, `"6h"`
69    /// or `"1h30m"`.
70    ///
71    /// The runs are laid out over the day from midnight UTC, the same every
72    /// day — `"6h"` is 00:00, 06:00, 12:00 and 18:00 — so the interval is a
73    /// whole number of minutes that divides 24 hours evenly: `"45m"` and
74    /// `"8h"` do, `"50m"` and `"7h"` do not.
75    Every(&'static str),
76}
77
78/// A cron job. See the [module documentation](self).
79///
80/// Declared as a module-level `static`, with a name unique in the app:
81/// lowercase letters, digits and dashes.
82#[derive(Debug)]
83pub struct Job {
84    name: &'static str,
85    path: &'static str,
86    schedule: Schedule,
87    title: Option<&'static str>,
88}
89
90impl Job {
91    /// Declares the job `name`, which requests `path` of the service that
92    /// declares it whenever `schedule` says it is due. The path starts with a
93    /// `/`.
94    ///
95    /// The name and the path must be string literals, and the schedule
96    /// written out here: Encore reads them from the source.
97    pub const fn new(name: &'static str, path: &'static str, schedule: Schedule) -> Self {
98        Self {
99            name,
100            path,
101            schedule,
102            title: None,
103        }
104    }
105
106    /// What the job is called where people read it, in place of its name.
107    pub const fn title(mut self, title: &'static str) -> Self {
108        self.title = Some(title);
109        self
110    }
111
112    /// Tags the job with `key` and `value`: key/value classification, such
113    /// as `.tag("data", "pci")`, for policies to read. One call per tag, each
114    /// with its own key. Encore reads them from the source, so both are string
115    /// literals. A key is lowercase letters, digits, `_` and `-`, starting with
116    /// a letter and not with `encore`, which is kept for Encore's own tags; a
117    /// value is the same characters, or empty. Each is at most 63 characters,
118    /// and a job has at most 32 tags.
119    ///
120    /// Part of the declaration: it takes the job by value, so it cannot be
121    /// called on the `static`.
122    ///
123    /// ```no_run
124    /// use encore::cron::{Job, Schedule};
125    ///
126    /// static CLEANUP: Job =
127    ///     Job::new("cleanup", "/internal/cleanup", Schedule::Cron("0 4 * * *")).tag("team", "ops");
128    /// ```
129    pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
130        self
131    }
132
133    /// The job's name.
134    pub const fn name(&self) -> &'static str {
135        self.name
136    }
137
138    /// The path the job requests: where the service serves it.
139    pub const fn path(&self) -> &'static str {
140        self.path
141    }
142
143    /// When the job runs.
144    pub const fn schedule(&self) -> Schedule {
145        self.schedule
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    static CLEANUP: Job = Job::new("cleanup", "/internal/cleanup", Schedule::Cron("0 4 * * *"))
154        .title("Nightly cleanup");
155    static REFRESH: Job = Job::new("refresh-rates", "/internal/rates", Schedule::Every("30m"));
156
157    #[test]
158    fn a_job_is_declared_in_a_static() {
159        assert_eq!(CLEANUP.name(), "cleanup");
160        assert_eq!(CLEANUP.path(), "/internal/cleanup");
161        assert_eq!(CLEANUP.schedule(), Schedule::Cron("0 4 * * *"));
162        assert_eq!(CLEANUP.title, Some("Nightly cleanup"));
163
164        assert_eq!(REFRESH.schedule(), Schedule::Every("30m"));
165        assert_eq!(REFRESH.title, None);
166    }
167}