encore-dev 2.0.0-beta.15

Rust SDK for Encore applications
Documentation
//! Cron jobs: requests Encore makes of a service on a schedule.
//!
//! A job is declared as a `static`, with the path it requests and when:
//!
//! ```ignore
//! use encore::cron::{Job, Schedule};
//!
//! /// Removes the sessions nobody has used in a month.
//! static CLEANUP: Job =
//!     Job::new("cleanup", "/internal/cleanup", Schedule::Cron("0 4 * * *")).title("Nightly cleanup");
//!
//! static REFRESH: Job = Job::new("refresh-rates", "/internal/rates", Schedule::Every("30m"));
//! ```
//!
//! When the job is due, Encore sends a `POST` request for the path to the
//! service that declares the job. What runs is whatever the service serves
//! there, so the route and the job are best kept in step by declaring the one
//! from the other:
//!
//! ```ignore
//! let app = Router::new().route(CLEANUP.path(), post(cleanup));
//! ```
//!
//! # Each run
//!
//! The request carries an idempotency key in [`IDEMPOTENCY_KEY_HEADER`]: an
//! id for the run that is the same each time Encore sends it, as when it
//! sends it again after a failure. A job that must not do its work twice can
//! check whether it has seen the key before:
//!
//! ```ignore
//! async fn cleanup(headers: HeaderMap) -> StatusCode {
//!     let key = headers.get(encore::cron::IDEMPOTENCY_KEY_HEADER);
//!     // ...
//! }
//! ```
//!
//! [`TRIGGER_HEADER`] says why the job runs. Only Encore sends either: a
//! gateway removes them from the requests it takes from clients.
//!
//! # Running locally and under test
//!
//! A job is scheduled where the app is deployed, not on a developer's
//! machine, unless [`Job::run_in_local`] says otherwise:
//!
//! ```ignore
//! static REFRESH: Job = Job::new("refresh-rates", "/internal/rates", Schedule::Every("30m"))
//!     .run_in_local(true);
//! ```
//!
//! Locally, it runs on schedule while the app has a session open, as `encore
//! run` keeps one, and a developer can turn that on or off for their checkout
//! whatever the declaration says. Nothing is scheduled by `encore test`.
//! `encore cron trigger <name>` runs a job now, as Encore runs it when it is
//! due, with both headers. Or request its path, or call what serves it.

/// The header with a run's idempotency key: an id that is the same each
/// time Encore sends the run. See the [module documentation](self).
pub const IDEMPOTENCY_KEY_HEADER: &str = "x-encore-cron-execution";

/// The header that says why a job runs: `scheduled`, when it was due, or
/// `manual`, when someone asked for it to run now.
pub const TRIGGER_HEADER: &str = "x-encore-cron-trigger";

/// When a [`Job`] runs.
///
/// Written out where the job is declared, with a string literal: Encore reads
/// it from the source.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Schedule {
    /// At the times a [cron expression] names: five fields — minute, hour, day
    /// of month, month and day of week — in UTC. `"0 4 * * *"` is 04:00 every
    /// day, `"0 9 * * 1"` 09:00 on Mondays.
    ///
    /// [cron expression]: https://en.wikipedia.org/wiki/Cron#Cron_expression
    Cron(&'static str),
    /// Every so often: a duration of hours and minutes, as in `"30m"`, `"6h"`
    /// or `"1h30m"`.
    ///
    /// The runs are laid out over the day from midnight UTC, the same every
    /// day — `"6h"` is 00:00, 06:00, 12:00 and 18:00 — so the interval is a
    /// whole number of minutes that divides 24 hours evenly: `"45m"` and
    /// `"8h"` do, `"50m"` and `"7h"` do not.
    Every(&'static str),
}

/// A cron job. See the [module documentation](self).
///
/// Declared as a module-level `static`, with a name unique in the app:
/// lowercase letters, digits and dashes.
#[derive(Debug)]
pub struct Job {
    name: &'static str,
    path: &'static str,
    schedule: Schedule,
    title: Option<&'static str>,
    run_in_local: bool,
}

impl Job {
    /// Declares the job `name`, which requests `path` of the service that
    /// declares it whenever `schedule` says it is due. The path starts with a
    /// `/`.
    ///
    /// The name and the path must be string literals, and the schedule
    /// written out here: Encore reads them from the source.
    pub const fn new(name: &'static str, path: &'static str, schedule: Schedule) -> Self {
        Self {
            name,
            path,
            schedule,
            title: None,
            run_in_local: false,
        }
    }

    /// What the job is called where people read it, in place of its name.
    pub const fn title(mut self, title: &'static str) -> Self {
        self.title = Some(title);
        self
    }

    /// Whether the job is scheduled on a developer's machine too, while the
    /// app has a session open there. False unless set: a developer can
    /// override it for their checkout either way. Wherever the app is
    /// deployed, it is scheduled regardless.
    ///
    /// ```no_run
    /// use encore::cron::{Job, Schedule};
    ///
    /// static REFRESH: Job = Job::new("refresh-rates", "/internal/rates", Schedule::Every("30m"))
    ///     .run_in_local(true);
    /// ```
    pub const fn run_in_local(mut self, local: bool) -> Self {
        self.run_in_local = local;
        self
    }

    /// Tags the job with `key` and `value`: key/value classification, such
    /// as `.tag("data", "pci")`, for policies to read. One call per tag, each
    /// with its own key. Encore reads them from the source, so both are string
    /// literals. A key is lowercase letters, digits, `_` and `-`, starting with
    /// a letter and not with `encore`, which is kept for Encore's own tags; a
    /// value is the same characters, or empty. Each is at most 63 characters,
    /// and a job has at most 32 tags.
    ///
    /// Part of the declaration: it takes the job by value, so it cannot be
    /// called on the `static`.
    ///
    /// ```no_run
    /// use encore::cron::{Job, Schedule};
    ///
    /// static CLEANUP: Job =
    ///     Job::new("cleanup", "/internal/cleanup", Schedule::Cron("0 4 * * *")).tag("team", "ops");
    /// ```
    pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
        self
    }

    /// The job's name.
    pub const fn name(&self) -> &'static str {
        self.name
    }

    /// The path the job requests: where the service serves it.
    pub const fn path(&self) -> &'static str {
        self.path
    }

    /// When the job runs.
    pub const fn schedule(&self) -> Schedule {
        self.schedule
    }

    /// Whether the job is declared to be scheduled locally too (see
    /// [`run_in_local`](Self::run_in_local)). A developer can override it.
    pub const fn runs_in_local(&self) -> bool {
        self.run_in_local
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    static CLEANUP: Job = Job::new("cleanup", "/internal/cleanup", Schedule::Cron("0 4 * * *"))
        .title("Nightly cleanup");
    static REFRESH: Job =
        Job::new("refresh-rates", "/internal/rates", Schedule::Every("30m")).run_in_local(true);

    #[test]
    fn a_job_is_declared_in_a_static() {
        assert_eq!(CLEANUP.name(), "cleanup");
        assert_eq!(CLEANUP.path(), "/internal/cleanup");
        assert_eq!(CLEANUP.schedule(), Schedule::Cron("0 4 * * *"));
        assert_eq!(CLEANUP.title, Some("Nightly cleanup"));

        assert_eq!(REFRESH.schedule(), Schedule::Every("30m"));
        assert_eq!(REFRESH.title, None);
    }

    #[test]
    fn a_job_runs_locally_only_when_it_says_so() {
        assert!(!CLEANUP.runs_in_local());
        assert!(REFRESH.runs_in_local());
    }
}