encore-dev 2.0.0-beta.18

Rust SDK for Encore applications
Documentation
//! Scheduled cron jobs that invoke an HTTP endpoint on your service.
//!
//! Declare a job as a module-level `static` with its target path and schedule:
//!
//! ```ignore
//! use encore::cron::{Job, Schedule};
//!
//! /// Removes sessions that have been inactive for 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 to the configured path on
//! the declaring service. Register your route using [`Job::path`] so the route
//! and cron declaration stay in sync:
//!
//! ```ignore
//! let app = Router::new().route(CLEANUP.path(), post(cleanup));
//! ```
//!
//! # Execution headers
//!
//! Each cron request includes an idempotency key in [`IDEMPOTENCY_KEY_HEADER`].
//! This ID remains the same across retries of the same scheduled run, so
//! handlers that must avoid duplicate work can deduplicate on it:
//!
//! ```ignore
//! async fn cleanup(headers: HeaderMap) -> StatusCode {
//!     let key = headers.get(encore::cron::IDEMPOTENCY_KEY_HEADER);
//!     // ...
//! }
//! ```
//!
//! [`TRIGGER_HEADER`] indicates whether the job was triggered on schedule or
//! manually. Gateways strip both headers from external client requests so only
//! Encore can set them.
//!
//! # Running locally and in tests
//!
//! By default, cron jobs only run on schedule in deployed environments. To run
//! a job on schedule during local development as well, enable
//! [`Job::run_in_local`]:
//!
//! ```ignore
//! static REFRESH: Job = Job::new("refresh-rates", "/internal/rates", Schedule::Every("30m"))
//!     .run_in_local(true);
//! ```
//!
//! Locally, scheduled jobs run while an `encore run` session is active, and
//! developers can toggle local scheduling per checkout regardless of the
//! declaration. Cron jobs are not scheduled under `encore test`. Run a job
//! immediately with `encore cron trigger <name>` (which includes both headers),
//! or send a `POST` request directly to its handler path.

/// Header containing the idempotency key for a cron execution.
///
/// The value stays the same if Encore retries the same run. See the
/// [module documentation](self).
pub const IDEMPOTENCY_KEY_HEADER: &str = "x-encore-cron-execution";

/// Header indicating why a cron job ran: `"scheduled"` for a scheduled run, or
/// `"manual"` when triggered on demand.
pub const TRIGGER_HEADER: &str = "x-encore-cron-trigger";

/// Schedule defining when a [`Job`] runs.
///
/// Must be written inline with a string literal where the job is declared so
/// Encore can parse it statically.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Schedule {
    /// Runs according to a five-field [cron expression] (minute, hour, day of
    /// month, month, day of week) in UTC. For example, `"0 4 * * *"` runs daily
    /// at 04:00 UTC, and `"0 9 * * 1"` runs Mondays at 09:00 UTC.
    ///
    /// [cron expression]: https://en.wikipedia.org/wiki/Cron#Cron_expression
    Cron(&'static str),
    /// Runs at a fixed interval specified in hours and minutes, such as `"30m"`,
    /// `"6h"`, or `"1h30m"`.
    ///
    /// Runs are aligned to midnight UTC each day (for example, `"6h"` runs at
    /// 00:00, 06:00, 12:00, and 18:00 UTC). The interval must be a whole number
    /// of minutes that divides 24 hours evenly (for example, `"45m"` and `"8h"`
    /// are valid, whereas `"50m"` and `"7h"` are not).
    Every(&'static str),
}

/// A declared cron job. See the [module documentation](self).
///
/// Declare as a module-level `static` with an app-wide unique name using
/// 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 a cron job named `name` that sends a `POST` request to `path` on
    /// the declaring service according to `schedule`.
    ///
    /// `path` must start with `/`. Both `name` and `path` must be string
    /// literals, and `schedule` must be written inline so Encore can parse them
    /// statically.
    pub const fn new(name: &'static str, path: &'static str, schedule: Schedule) -> Self {
        Self {
            name,
            path,
            schedule,
            title: None,
            run_in_local: false,
        }
    }

    /// Sets a human-readable display title shown in the dashboard instead of
    /// the job's identifier.
    pub const fn title(mut self, title: &'static str) -> Self {
        self.title = Some(title);
        self
    }

    /// Controls whether the job runs on schedule during local development while
    /// an `encore run` session is active.
    ///
    /// Defaults to `false`. Developers can still override this setting per
    /// checkout. Deployed environments always schedule the job regardless of
    /// this setting.
    ///
    /// ```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
    }

    /// Attaches a key/value tag to the job (for example, `.tag("data", "pci")`)
    /// for policy and governance tooling.
    ///
    /// Call once per tag with unique keys. Both `key` and `value` must be string
    /// literals so Encore can parse them statically. Keys must start with a
    /// letter, contain only lowercase letters, digits, `_`, and `-`, and must
    /// not start with `encore` (reserved for Encore's own tags). Values use the
    /// same character set or may be empty. Each key and value is at most 63
    /// characters, and a job may have at most 32 tags.
    ///
    /// ```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
    }

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

    /// Returns the HTTP path that Encore invokes when the job runs.
    pub const fn path(&self) -> &'static str {
        self.path
    }

    /// Returns the job's schedule.
    pub const fn schedule(&self) -> Schedule {
        self.schedule
    }

    /// Returns whether the job is configured to run on schedule locally (see
    /// [`run_in_local`](Self::run_in_local)).
    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());
    }
}