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//! A job is scheduled where the app is deployed, not on a developer's
44//! machine, unless [`Job::run_in_local`] says otherwise:
45//!
46//! ```ignore
47//! static REFRESH: Job = Job::new("refresh-rates", "/internal/rates", Schedule::Every("30m"))
48//! .run_in_local(true);
49//! ```
50//!
51//! Locally, it runs on schedule while the app has a session open, as `encore
52//! run` keeps one, and a developer can turn that on or off for their checkout
53//! whatever the declaration says. Nothing is scheduled by `encore test`.
54//! `encore cron trigger <name>` runs a job now, as Encore runs it when it is
55//! due, with both headers. Or request its path, or call what serves it.
56
57/// The header with a run's idempotency key: an id that is the same each
58/// time Encore sends the run. See the [module documentation](self).
59pub const IDEMPOTENCY_KEY_HEADER: &str = "x-encore-cron-execution";
60
61/// The header that says why a job runs: `scheduled`, when it was due, or
62/// `manual`, when someone asked for it to run now.
63pub const TRIGGER_HEADER: &str = "x-encore-cron-trigger";
64
65/// When a [`Job`] runs.
66///
67/// Written out where the job is declared, with a string literal: Encore reads
68/// it from the source.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum Schedule {
71 /// At the times a [cron expression] names: five fields — minute, hour, day
72 /// of month, month and day of week — in UTC. `"0 4 * * *"` is 04:00 every
73 /// day, `"0 9 * * 1"` 09:00 on Mondays.
74 ///
75 /// [cron expression]: https://en.wikipedia.org/wiki/Cron#Cron_expression
76 Cron(&'static str),
77 /// Every so often: a duration of hours and minutes, as in `"30m"`, `"6h"`
78 /// or `"1h30m"`.
79 ///
80 /// The runs are laid out over the day from midnight UTC, the same every
81 /// day — `"6h"` is 00:00, 06:00, 12:00 and 18:00 — so the interval is a
82 /// whole number of minutes that divides 24 hours evenly: `"45m"` and
83 /// `"8h"` do, `"50m"` and `"7h"` do not.
84 Every(&'static str),
85}
86
87/// A cron job. See the [module documentation](self).
88///
89/// Declared as a module-level `static`, with a name unique in the app:
90/// lowercase letters, digits and dashes.
91#[derive(Debug)]
92pub struct Job {
93 name: &'static str,
94 path: &'static str,
95 schedule: Schedule,
96 title: Option<&'static str>,
97 run_in_local: bool,
98}
99
100impl Job {
101 /// Declares the job `name`, which requests `path` of the service that
102 /// declares it whenever `schedule` says it is due. The path starts with a
103 /// `/`.
104 ///
105 /// The name and the path must be string literals, and the schedule
106 /// written out here: Encore reads them from the source.
107 pub const fn new(name: &'static str, path: &'static str, schedule: Schedule) -> Self {
108 Self {
109 name,
110 path,
111 schedule,
112 title: None,
113 run_in_local: false,
114 }
115 }
116
117 /// What the job is called where people read it, in place of its name.
118 pub const fn title(mut self, title: &'static str) -> Self {
119 self.title = Some(title);
120 self
121 }
122
123 /// Whether the job is scheduled on a developer's machine too, while the
124 /// app has a session open there. False unless set: a developer can
125 /// override it for their checkout either way. Wherever the app is
126 /// deployed, it is scheduled regardless.
127 ///
128 /// ```no_run
129 /// use encore::cron::{Job, Schedule};
130 ///
131 /// static REFRESH: Job = Job::new("refresh-rates", "/internal/rates", Schedule::Every("30m"))
132 /// .run_in_local(true);
133 /// ```
134 pub const fn run_in_local(mut self, local: bool) -> Self {
135 self.run_in_local = local;
136 self
137 }
138
139 /// Tags the job with `key` and `value`: key/value classification, such
140 /// as `.tag("data", "pci")`, for policies to read. One call per tag, each
141 /// with its own key. Encore reads them from the source, so both are string
142 /// literals. A key is lowercase letters, digits, `_` and `-`, starting with
143 /// a letter and not with `encore`, which is kept for Encore's own tags; a
144 /// value is the same characters, or empty. Each is at most 63 characters,
145 /// and a job has at most 32 tags.
146 ///
147 /// Part of the declaration: it takes the job by value, so it cannot be
148 /// called on the `static`.
149 ///
150 /// ```no_run
151 /// use encore::cron::{Job, Schedule};
152 ///
153 /// static CLEANUP: Job =
154 /// Job::new("cleanup", "/internal/cleanup", Schedule::Cron("0 4 * * *")).tag("team", "ops");
155 /// ```
156 pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
157 self
158 }
159
160 /// The job's name.
161 pub const fn name(&self) -> &'static str {
162 self.name
163 }
164
165 /// The path the job requests: where the service serves it.
166 pub const fn path(&self) -> &'static str {
167 self.path
168 }
169
170 /// When the job runs.
171 pub const fn schedule(&self) -> Schedule {
172 self.schedule
173 }
174
175 /// Whether the job is declared to be scheduled locally too (see
176 /// [`run_in_local`](Self::run_in_local)). A developer can override it.
177 pub const fn runs_in_local(&self) -> bool {
178 self.run_in_local
179 }
180}
181
182#[cfg(test)]
183mod tests {
184 use super::*;
185
186 static CLEANUP: Job = Job::new("cleanup", "/internal/cleanup", Schedule::Cron("0 4 * * *"))
187 .title("Nightly cleanup");
188 static REFRESH: Job =
189 Job::new("refresh-rates", "/internal/rates", Schedule::Every("30m")).run_in_local(true);
190
191 #[test]
192 fn a_job_is_declared_in_a_static() {
193 assert_eq!(CLEANUP.name(), "cleanup");
194 assert_eq!(CLEANUP.path(), "/internal/cleanup");
195 assert_eq!(CLEANUP.schedule(), Schedule::Cron("0 4 * * *"));
196 assert_eq!(CLEANUP.title, Some("Nightly cleanup"));
197
198 assert_eq!(REFRESH.schedule(), Schedule::Every("30m"));
199 assert_eq!(REFRESH.title, None);
200 }
201
202 #[test]
203 fn a_job_runs_locally_only_when_it_says_so() {
204 assert!(!CLEANUP.runs_in_local());
205 assert!(REFRESH.runs_in_local());
206 }
207}