Skip to main content

adk_server/background/
cron.rs

1//! Cron jobs: REST endpoints over a [`ScheduleStore`] and the scheduling loop.
2//!
3//! A cron job is a [`Schedule`] with a [`ScheduleSpec::Cron`] spec whose run template
4//! targets a workflow or agent. The scheduler started by [`start_cron_scheduler`] is a
5//! [`DurableScheduler`]; run it on every replica.
6//!
7//! | Route | Does |
8//! |-------|------|
9//! | `POST /cron` | Creates a job |
10//! | `GET /cron`, `GET /cron/{job_id}` | Lists the jobs, reads one |
11//! | `PATCH /cron/{job_id}` | Pauses or resumes a job |
12//! | `POST /cron/{job_id}/run` | Runs the job now, outside its schedule ([`run_cron_job_now`]) |
13//! | `DELETE /cron/{job_id}` | Deletes a job |
14//!
15//! [`CronState::with_jitter`] spreads the jobs' fires (see the scheduler's
16//! [Jitter](super::scheduler#jitter)); [`CronState::with_audit`] records each run now.
17//!
18//! With a `RequestContextExtractor` on the server, a job belongs to the authenticated caller
19//! who created it (spec 3.1 §8.2): its runs act for that caller, and only that caller lists,
20//! reads, pauses, resumes, or deletes it — another owner's job answers `404`, and two owners
21//! may each have a job of the same name. Without an extractor the routes run in
22//! [open mode](super#open-mode): every client sees every job, the job's name is its schedule
23//! id, and its runs act for the user `cron`.
24
25use std::sync::Arc;
26
27use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind, AuditTrail};
28use adk_core::principal::SubjectRef;
29use adk_core::schedule::{Jitter, MissedFirePolicy, Schedule, ScheduleSpec};
30use adk_core::{
31    Enqueued, InMemoryScheduleStore, NewRun, OnConflict, RequestContext, ScheduleStore,
32};
33use axum::{
34    Extension, Json, Router,
35    extract::{Path, State},
36    http::{HeaderMap, StatusCode},
37    response::{IntoResponse, Response},
38    routing::{get, post},
39};
40use chrono::Utc;
41use serde::{Deserialize, Serialize};
42use serde_json::Value;
43
44use super::{BackgroundState, DurableScheduler, WorkflowState, run_owner, warn_open_mode};
45
46/// Checks that `expression` parses as a cron expression (five, six, or seven fields).
47///
48/// # Example
49///
50/// ```rust
51/// use adk_server::background::validate_cron_expression;
52///
53/// assert!(validate_cron_expression("*/5 * * * *").is_ok());
54/// assert!(validate_cron_expression("not cron").is_err());
55/// ```
56///
57/// # Errors
58///
59/// Returns why the expression does not parse.
60pub fn validate_cron_expression(expression: &str) -> Result<(), String> {
61    cron_spec(expression, "UTC").next_after(Utc::now()).map(|_| ()).map_err(|e| e.to_string())
62}
63
64fn cron_spec(expression: &str, timezone: &str) -> ScheduleSpec {
65    ScheduleSpec::Cron { expr: expression.to_string(), timezone: timezone.to_string() }
66}
67
68/// What a cron job does when a previous run is still active.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
70#[serde(rename_all = "lowercase")]
71pub enum ConcurrencyPolicy {
72    /// Skip the occurrence (`OnConflict::Reject` on the job's concurrency key).
73    Skip,
74    /// Run alongside the active run (no concurrency key).
75    Allow,
76    /// Queue behind the active run (`OnConflict::Enqueue`).
77    Queue,
78}
79
80fn default_concurrency_policy() -> ConcurrencyPolicy {
81    ConcurrencyPolicy::Skip
82}
83
84fn default_timezone() -> String {
85    "UTC".to_string()
86}
87
88fn default_missed() -> MissedFirePolicy {
89    MissedFirePolicy::Skip
90}
91
92/// Cron job lifecycle status.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
94#[serde(rename_all = "lowercase")]
95pub enum CronJobStatus {
96    /// The job fires.
97    Active,
98    /// The job does not fire; occurrences inside the pause are skipped.
99    Paused,
100}
101
102/// `POST /cron` request body.
103#[derive(Debug, Deserialize)]
104#[serde(rename_all = "camelCase")]
105pub struct CreateCronJobRequest {
106    /// The job's name, which is also its id.
107    pub name: String,
108    /// The workflow or agent each firing runs.
109    #[serde(alias = "target")]
110    pub workflow_id: String,
111    /// The cron expression (five, six, or seven fields).
112    pub cron_expression: String,
113    /// The IANA time zone the expression is evaluated in. Defaults to `UTC`.
114    #[serde(default = "default_timezone")]
115    pub timezone: String,
116    /// The input each run receives.
117    #[serde(default)]
118    pub input: Option<WorkflowState>,
119    /// What happens when a previous run is still active. Defaults to `skip`.
120    #[serde(default = "default_concurrency_policy")]
121    pub concurrency_policy: ConcurrencyPolicy,
122    /// Which occurrences fire after the scheduler fell behind. Defaults to `skip`.
123    #[serde(default = "default_missed")]
124    pub missed_fire_policy: MissedFirePolicy,
125}
126
127/// A cron job as the REST API reports it.
128#[derive(Debug, Serialize)]
129#[serde(rename_all = "camelCase")]
130pub struct CronJobResponse {
131    /// The job id, equal to its name.
132    pub job_id: String,
133    /// The job's name.
134    pub name: String,
135    /// The workflow or agent each firing runs.
136    pub workflow_id: String,
137    /// The cron expression; absent for a schedule with another spec.
138    #[serde(skip_serializing_if = "Option::is_none")]
139    pub cron_expression: Option<String>,
140    /// The time zone; absent for a schedule with another spec.
141    #[serde(skip_serializing_if = "Option::is_none")]
142    pub timezone: Option<String>,
143    /// The schedule's spec.
144    pub spec: ScheduleSpec,
145    /// Whether the job fires.
146    pub status: CronJobStatus,
147    /// What happens when a previous run is still active.
148    pub concurrency_policy: ConcurrencyPolicy,
149    /// Which occurrences fire after the scheduler fell behind.
150    pub missed_fire_policy: MissedFirePolicy,
151    /// The next occurrence to fire.
152    #[serde(skip_serializing_if = "Option::is_none")]
153    pub next_fire_at: Option<String>,
154    /// The schedule's revision.
155    pub revision: u64,
156}
157
158impl From<Schedule> for CronJobResponse {
159    fn from(schedule: Schedule) -> Self {
160        let (cron_expression, timezone) = match &schedule.spec {
161            ScheduleSpec::Cron { expr, timezone } => (Some(expr.clone()), Some(timezone.clone())),
162            _ => (None, None),
163        };
164        let concurrency_policy = match (&schedule.run.concurrency_key, schedule.run.on_conflict) {
165            (None, _) => ConcurrencyPolicy::Allow,
166            (Some(_), OnConflict::Reject) => ConcurrencyPolicy::Skip,
167            (Some(_), _) => ConcurrencyPolicy::Queue,
168        };
169        Self {
170            job_id: schedule.id.clone(),
171            name: schedule.id,
172            workflow_id: schedule.run.target,
173            cron_expression,
174            timezone,
175            spec: schedule.spec,
176            status: if schedule.paused { CronJobStatus::Paused } else { CronJobStatus::Active },
177            concurrency_policy,
178            missed_fire_policy: schedule.missed,
179            next_fire_at: schedule.next_fire_at.map(|at| at.to_rfc3339()),
180            revision: schedule.revision,
181        }
182    }
183}
184
185/// `PATCH /cron/{job_id}` request body.
186#[derive(Debug, Deserialize)]
187#[serde(rename_all = "camelCase")]
188pub struct PatchCronJobRequest {
189    /// The status to set.
190    pub status: CronJobStatus,
191}
192
193/// Shared state for the cron endpoints and the scheduler.
194#[derive(Clone)]
195#[non_exhaustive]
196pub struct CronState {
197    /// Where schedules are stored.
198    pub schedules: Arc<dyn ScheduleStore>,
199    /// The background runs state whose run store the schedules enqueue into.
200    pub background_state: BackgroundState,
201    /// The jitter each fire is delayed by; none by default.
202    pub jitter: Option<Jitter>,
203    /// Where each run now is recorded; none by default.
204    pub audit: Option<AuditTrail>,
205}
206
207impl std::fmt::Debug for CronState {
208    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
209        f.debug_struct("CronState")
210            .field("background_state", &self.background_state)
211            .field("jitter", &self.jitter)
212            .field("audit", &self.audit.is_some())
213            .finish()
214    }
215}
216
217impl CronState {
218    /// A cron state over a fresh [`InMemoryScheduleStore`].
219    pub fn new(background_state: BackgroundState) -> Self {
220        Self {
221            schedules: Arc::new(InMemoryScheduleStore::new()),
222            background_state,
223            jitter: None,
224            audit: None,
225        }
226    }
227
228    /// Uses `store` for schedules; share one store across replicas.
229    #[must_use]
230    pub fn with_schedule_store(mut self, store: Arc<dyn ScheduleStore>) -> Self {
231        self.schedules = store;
232        self
233    }
234
235    /// Delays each fire by its job's [`Jitter`] offset (see the scheduler's
236    /// [Jitter](super::scheduler#jitter)).
237    ///
238    /// # Example
239    ///
240    /// ```rust
241    /// use adk_core::schedule::Jitter;
242    /// use adk_server::background::{BackgroundState, CronState};
243    ///
244    /// let state = CronState::new(BackgroundState::new()).with_jitter(Jitter::default());
245    /// assert_eq!(state.scheduler().jitter(), Some(Jitter::default()));
246    /// ```
247    #[must_use]
248    pub fn with_jitter(mut self, jitter: Jitter) -> Self {
249        self.jitter = Some(jitter);
250        self
251    }
252
253    /// Records every run now in `trail` as a `schedule.run_now` record: the caller, the job
254    /// and the run it enqueued, or why it enqueued none.
255    #[must_use]
256    pub fn with_audit(mut self, trail: AuditTrail) -> Self {
257        self.audit = Some(trail);
258        self
259    }
260
261    /// A [`DurableScheduler`] over this state's stores, jitter and current governance
262    /// control.
263    pub fn scheduler(&self) -> DurableScheduler {
264        let mut scheduler = DurableScheduler::new(
265            Arc::clone(&self.schedules),
266            Arc::clone(self.background_state.run_store()),
267        );
268        if let Some(jitter) = self.jitter {
269            scheduler = scheduler.with_jitter(jitter);
270        }
271        match self.background_state.governance() {
272            Some(control) => scheduler.with_governance(control),
273            None => scheduler,
274        }
275    }
276}
277
278fn problem(status: StatusCode, message: impl Into<String>) -> Response {
279    (status, Json(serde_json::json!({ "error": message.into() }))).into_response()
280}
281
282fn store_error(error: &adk_core::AdkError) -> Response {
283    if error.is_not_found() {
284        return problem(StatusCode::NOT_FOUND, "cron job not found");
285    }
286    let status =
287        StatusCode::from_u16(error.http_status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
288    problem(status, error.to_string())
289}
290
291/// The schedule id of `owner`'s job `name`: the name itself without an authenticated caller,
292/// and the name behind the owner with one. The length prefix keeps ("a:b", "c") and ("a",
293/// "b:c") apart, as the run routes' scoped keys do.
294fn schedule_id(owner: Option<&str>, name: &str) -> String {
295    match owner {
296        Some(owner) => format!("{}:{owner}:{name}", owner.len()),
297        None => name.to_string(),
298    }
299}
300
301/// Whether `owner` may see `schedule`: any schedule without an authenticated caller, only the
302/// caller's own with one.
303fn visible_to(schedule: &Schedule, owner: Option<&str>) -> bool {
304    owner.is_none_or(|owner| {
305        schedule.run.user_id == owner && schedule.id.starts_with(&schedule_id(Some(owner), ""))
306    })
307}
308
309/// The job as `owner` sees it, named as its owner named it.
310fn job_for(schedule: Schedule, owner: Option<&str>) -> CronJobResponse {
311    let prefix = schedule_id(owner, "");
312    let name = owner.and_then(|_| schedule.id.strip_prefix(&prefix)).map(str::to_string);
313    let mut job = CronJobResponse::from(schedule);
314    if let Some(name) = name {
315        job.job_id.clone_from(&name);
316        job.name = name;
317    }
318    job
319}
320
321/// `owner`'s job `name`, or `None` when it does not exist or belongs to another owner.
322async fn visible_job(
323    state: &CronState,
324    owner: Option<&str>,
325    name: &str,
326) -> std::result::Result<Option<Schedule>, adk_core::AdkError> {
327    let schedule = state.schedules.get(&schedule_id(owner, name)).await?;
328    Ok(schedule.filter(|schedule| visible_to(schedule, owner)))
329}
330
331/// POST /cron — Create a cron job.
332async fn create_cron_job(
333    State(state): State<CronState>,
334    caller: Option<Extension<Option<RequestContext>>>,
335    Json(request): Json<CreateCronJobRequest>,
336) -> Response {
337    let owner = run_owner(caller);
338    let id = schedule_id(owner.as_deref(), &request.name);
339    let spec = cron_spec(&request.cron_expression, &request.timezone);
340    let first = match spec.next_after(Utc::now()) {
341        Ok(first) => first,
342        Err(error) => {
343            return (
344                StatusCode::BAD_REQUEST,
345                Json(serde_json::json!({
346                    "error": "invalid cron expression",
347                    "expression": request.cron_expression,
348                    "reason": error.to_string(),
349                })),
350            )
351                .into_response();
352        }
353    };
354    match state.schedules.get(&id).await {
355        Ok(Some(_)) => {
356            return problem(
357                StatusCode::CONFLICT,
358                format!("a cron job named '{}' already exists", request.name),
359            );
360        }
361        Ok(None) => {}
362        Err(error) => return store_error(&error),
363    }
364    let background = &state.background_state;
365    let input = request.input.map_or(Value::Object(Default::default()), |input| {
366        Value::Object(input.into_iter().collect())
367    });
368    // An authenticated owner's job runs for that owner, as the identity the server
369    // authenticated when the job was created.
370    let mut run = NewRun::new(
371        background.worker.queue.clone(),
372        background.app_name_for(&request.workflow_id),
373        owner.clone().unwrap_or_else(|| "cron".to_string()),
374        request.workflow_id,
375        input,
376    );
377    if owner.is_some() {
378        run = run.with_authenticated_user();
379    }
380    let concurrency_key = format!("cron:{id}");
381    run = match request.concurrency_policy {
382        ConcurrencyPolicy::Skip => run.with_concurrency_key(concurrency_key, OnConflict::Reject),
383        ConcurrencyPolicy::Queue => run.with_concurrency_key(concurrency_key, OnConflict::Enqueue),
384        ConcurrencyPolicy::Allow => run,
385    };
386    let mut schedule = Schedule::new(id, spec, run, request.missed_fire_policy);
387    if let Some(first) = first {
388        schedule = schedule.with_next_fire_at(first);
389    }
390    match state.schedules.upsert(schedule).await {
391        Ok(stored) => {
392            tracing::info!(schedule.id = %stored.id, "cron job created");
393            (StatusCode::CREATED, Json(job_for(stored, owner.as_deref()))).into_response()
394        }
395        Err(error) => problem(StatusCode::BAD_REQUEST, error.to_string()),
396    }
397}
398
399/// GET /cron — List cron jobs; with an authenticated caller, only the caller's.
400async fn list_cron_jobs(
401    State(state): State<CronState>,
402    caller: Option<Extension<Option<RequestContext>>>,
403) -> Response {
404    let owner = run_owner(caller);
405    match state.schedules.list().await {
406        Ok(schedules) => {
407            let jobs: Vec<CronJobResponse> = schedules
408                .into_iter()
409                .filter(|schedule| visible_to(schedule, owner.as_deref()))
410                .map(|schedule| job_for(schedule, owner.as_deref()))
411                .collect();
412            (StatusCode::OK, Json(jobs)).into_response()
413        }
414        Err(error) => store_error(&error),
415    }
416}
417
418/// GET /cron/{job_id} — Get a cron job; another owner's job is `404`.
419async fn get_cron_job(
420    State(state): State<CronState>,
421    caller: Option<Extension<Option<RequestContext>>>,
422    Path(job_id): Path<String>,
423) -> Response {
424    let owner = run_owner(caller);
425    match visible_job(&state, owner.as_deref(), &job_id).await {
426        Ok(Some(schedule)) => {
427            (StatusCode::OK, Json(job_for(schedule, owner.as_deref()))).into_response()
428        }
429        Ok(None) => problem(StatusCode::NOT_FOUND, format!("cron job '{job_id}' not found")),
430        Err(error) => store_error(&error),
431    }
432}
433
434/// PATCH /cron/{job_id} — Pause or resume a cron job; another owner's job is `404`.
435///
436/// Resuming moves the next fire time to the first occurrence after now, so occurrences
437/// that fell inside the pause are skipped rather than replayed.
438async fn patch_cron_job(
439    State(state): State<CronState>,
440    caller: Option<Extension<Option<RequestContext>>>,
441    Path(job_id): Path<String>,
442    Json(request): Json<PatchCronJobRequest>,
443) -> Response {
444    let owner = run_owner(caller);
445    let id = schedule_id(owner.as_deref(), &job_id);
446    match visible_job(&state, owner.as_deref(), &job_id).await {
447        Ok(Some(_)) => {}
448        Ok(None) => return problem(StatusCode::NOT_FOUND, "cron job not found"),
449        Err(error) => return store_error(&error),
450    }
451    let result = match request.status {
452        CronJobStatus::Paused => state.schedules.set_paused(&id, true).await,
453        CronJobStatus::Active => match state.schedules.get(&id).await {
454            Ok(Some(schedule)) if schedule.paused => {
455                let next = match schedule.spec.next_after(Utc::now()) {
456                    Ok(next) => next,
457                    Err(error) => return problem(StatusCode::BAD_REQUEST, error.to_string()),
458                };
459                let mut resumed = schedule.with_paused(false);
460                resumed.next_fire_at = next;
461                state.schedules.upsert(resumed).await
462            }
463            Ok(Some(schedule)) => Ok(schedule),
464            Ok(None) => return problem(StatusCode::NOT_FOUND, "cron job not found"),
465            Err(error) => Err(error),
466        },
467    };
468    match result {
469        Ok(schedule) => (StatusCode::OK, Json(job_for(schedule, owner.as_deref()))).into_response(),
470        Err(error) => store_error(&error),
471    }
472}
473
474/// DELETE /cron/{job_id} — Delete a cron job; another owner's job is `404`.
475async fn delete_cron_job(
476    State(state): State<CronState>,
477    caller: Option<Extension<Option<RequestContext>>>,
478    Path(job_id): Path<String>,
479) -> Response {
480    let owner = run_owner(caller);
481    match visible_job(&state, owner.as_deref(), &job_id).await {
482        Ok(Some(schedule)) => match state.schedules.delete(&schedule.id).await {
483            Ok(()) => (StatusCode::NO_CONTENT, ()).into_response(),
484            Err(error) => store_error(&error),
485        },
486        Ok(None) => problem(StatusCode::NOT_FOUND, "cron job not found"),
487        Err(error) => store_error(&error),
488    }
489}
490
491/// `POST /cron/{job_id}/run` response.
492#[derive(Debug, Serialize)]
493#[serde(rename_all = "camelCase")]
494pub struct RunCronJobNowResponse {
495    /// The job's id, as its owner named it.
496    pub job_id: String,
497    /// The run the request enqueued, or the one an earlier request with the same key did.
498    pub run_id: String,
499    /// The run's status.
500    pub status: super::RunStatus,
501    /// The run's idempotency key, `schedule:{id}:manual:{request id}`.
502    pub idempotency_key: String,
503    /// `true` when an earlier request with the same `Idempotency-Key` enqueued the run.
504    pub existing: bool,
505}
506
507/// The `Idempotency-Key` header of a run now; a retried request with the same key returns
508/// the run the first one enqueued.
509pub const RUN_NOW_IDEMPOTENCY_HEADER: &str = "idempotency-key";
510
511/// `POST /cron/{job_id}/run` — Runs a cron job now, outside its schedule; another owner's job
512/// is `404`.
513///
514/// The run is the job's template, acting for the job's owner as a fire does, with the job's
515/// concurrency key, so it is subject to the same overlap rule; its idempotency key is
516/// `schedule:{id}:manual:{request id}`, the request id taken from the `Idempotency-Key`
517/// header or generated. The job itself is not changed: its next fire time and revision stay
518/// where they are, and a paused job stays paused and still runs now.
519///
520/// | Outcome | Status |
521/// |---------|--------|
522/// | Run enqueued | `202 Accepted` |
523/// | The `Idempotency-Key` already enqueued a run | `200 OK`, `existing: true` |
524/// | The kill switch refuses work | `503 Service Unavailable`; nothing is enqueued |
525/// | The job's concurrency policy is `skip` and a run is active | `409 Conflict`, with `blockingRunId` |
526/// | No such job for this caller | `404 Not Found` |
527///
528/// With [`CronState::with_audit`], every outcome but `404` is recorded as `schedule.run_now`.
529pub async fn run_cron_job_now(
530    State(state): State<CronState>,
531    caller: Option<Extension<Option<RequestContext>>>,
532    Path(job_id): Path<String>,
533    headers: HeaderMap,
534) -> Response {
535    let owner = run_owner(caller);
536    let schedule = match visible_job(&state, owner.as_deref(), &job_id).await {
537        Ok(Some(schedule)) => schedule,
538        Ok(None) => return problem(StatusCode::NOT_FOUND, "cron job not found"),
539        Err(error) => return store_error(&error),
540    };
541    let request_id = headers
542        .get(RUN_NOW_IDEMPOTENCY_HEADER)
543        .and_then(|value| value.to_str().ok())
544        .map(str::trim)
545        .filter(|value| !value.is_empty())
546        .map_or_else(|| uuid::Uuid::new_v4().to_string(), str::to_string);
547    let run = schedule.run_now(&request_id);
548    let key = run.idempotency_key.clone().unwrap_or_default();
549    let requester = owner.as_deref().unwrap_or("anonymous");
550    if let Some(control) = state.background_state.governance()
551        && let Err(error) = control.check()
552    {
553        record_run_now(&state, requester, &schedule.id, &key, None, "refused_frozen").await;
554        return problem(StatusCode::SERVICE_UNAVAILABLE, error.to_string());
555    }
556    let enqueued = match state.background_state.run_store().enqueue(run).await {
557        Ok(enqueued) => enqueued,
558        Err(error) => return store_error(&error),
559    };
560    let (status, record, existing) = match enqueued {
561        Enqueued::Created(record) => (StatusCode::ACCEPTED, record, false),
562        Enqueued::Existing(record) => (StatusCode::OK, record, true),
563        Enqueued::Rejected { blocking_run_id } => {
564            record_run_now(&state, requester, &schedule.id, &key, None, "refused_concurrency")
565                .await;
566            return (
567                StatusCode::CONFLICT,
568                Json(serde_json::json!({
569                    "error": "a run of this cron job is still active and its concurrency policy is skip",
570                    "blockingRunId": blocking_run_id,
571                })),
572            )
573                .into_response();
574        }
575    };
576    state.background_state.ensure_worker_started();
577    state.background_state.wake_worker();
578    let outcome = if existing { "existing" } else { "enqueued" };
579    record_run_now(&state, requester, &schedule.id, &key, Some(&record.run_id), outcome).await;
580    tracing::info!(schedule.id = %schedule.id, run.id = %record.run_id, run.existing = existing, "cron job run now");
581    let response = RunCronJobNowResponse {
582        job_id: job_for(schedule, owner.as_deref()).job_id,
583        run_id: record.run_id,
584        status: record.state.into(),
585        idempotency_key: key,
586        existing,
587    };
588    (status, Json(response)).into_response()
589}
590
591/// Records a run now in the state's audit trail, when it has one. A failed write is logged:
592/// the run, once enqueued, is the durable fact.
593async fn record_run_now(
594    state: &CronState,
595    requester: &str,
596    schedule_id: &str,
597    key: &str,
598    run_id: Option<&str>,
599    outcome: &str,
600) {
601    let Some(trail) = &state.audit else { return };
602    let draft =
603        AuditRecordDraft::new(AuditRecordKind::Other("schedule".to_string()), "schedule.run_now")
604            .actor(AuditActor::subject(SubjectRef::human(requester)))
605            .ext("schedule", serde_json::json!(schedule_id))
606            .ext("idempotencyKey", serde_json::json!(key))
607            .ext("runId", serde_json::json!(run_id))
608            .ext("outcome", serde_json::json!(outcome));
609    if let Err(error) = trail.record(draft).await {
610        tracing::warn!(schedule.id = %schedule_id, error = %error, "could not record a cron job run now");
611    }
612}
613
614/// Starts the scheduling loop: a [`DurableScheduler`] tick every second over the state's
615/// schedule and run stores. Run it on every replica; each fire time is enqueued once.
616///
617/// The governance control is read on every tick, so one installed later by
618/// [`ServerBuilder`](crate::ServerBuilder) applies.
619pub fn start_cron_scheduler(state: CronState) -> tokio::task::JoinHandle<()> {
620    tokio::spawn(async move {
621        let mut interval = tokio::time::interval(std::time::Duration::from_secs(1));
622        interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
623        loop {
624            interval.tick().await;
625            if let Err(error) = state.scheduler().tick().await {
626                tracing::warn!(error = %error, "scheduler tick failed");
627            }
628        }
629    })
630}
631
632/// Create the cron jobs router over a fresh in-memory schedule store.
633///
634/// > **Important:** the router carries no authentication. Anyone who reaches it can
635/// > schedule recurring work. Mount it through
636/// > [`ServerBuilder::with_cron_jobs`](crate::ServerBuilder::with_cron_jobs), which
637/// > applies the server's auth middleware, or behind your own authentication layer.
638pub fn cron_jobs_router(background_state: BackgroundState) -> Router {
639    cron_jobs_router_with_state(CronState::new(background_state))
640}
641
642/// Create the cron jobs router with a pre-configured state.
643///
644/// The routes run in [open mode](super#open-mode), and building the router logs a warning
645/// that says so.
646///
647/// > **Important:** the router carries no authentication; see [`cron_jobs_router`].
648pub fn cron_jobs_router_with_state(state: CronState) -> Router {
649    warn_open_mode("/cron");
650    cron_routes(state)
651}
652
653/// The cron routes without the open-mode warning, for [`ServerBuilder`](crate::ServerBuilder),
654/// which knows whether it authenticates callers.
655pub(crate) fn cron_routes(state: CronState) -> Router {
656    Router::new()
657        .route("/cron", post(create_cron_job).get(list_cron_jobs))
658        .route("/cron/{job_id}", get(get_cron_job).patch(patch_cron_job).delete(delete_cron_job))
659        .route("/cron/{job_id}/run", post(run_cron_job_now))
660        .with_state(state)
661}