adk-server 3.0.0

HTTP server for ADK-Rust agents: REST and SSE, A2A v1.0, background runs and cron, approvals, and the AWP agent edge
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
//! Cron jobs: REST endpoints over a [`ScheduleStore`] and the scheduling loop.
//!
//! A cron job is a [`Schedule`] with a [`ScheduleSpec::Cron`] spec whose run template
//! targets a workflow or agent. The scheduler started by [`start_cron_scheduler`] is a
//! [`DurableScheduler`]; run it on every replica.
//!
//! | Route | Does |
//! |-------|------|
//! | `POST /cron` | Creates a job |
//! | `GET /cron`, `GET /cron/{job_id}` | Lists the jobs, reads one |
//! | `PATCH /cron/{job_id}` | Pauses or resumes a job |
//! | `POST /cron/{job_id}/run` | Runs the job now, outside its schedule ([`run_cron_job_now`]) |
//! | `DELETE /cron/{job_id}` | Deletes a job |
//!
//! [`CronState::with_jitter`] spreads the jobs' fires (see the scheduler's
//! [Jitter](super::scheduler#jitter)); [`CronState::with_audit`] records each run now.
//!
//! With a `RequestContextExtractor` on the server, a job belongs to the authenticated caller
//! who created it (spec 3.1 §8.2): its runs act for that caller, and only that caller lists,
//! reads, pauses, resumes, or deletes it — another owner's job answers `404`, and two owners
//! may each have a job of the same name. Without an extractor the routes run in
//! [open mode](super#open-mode): every client sees every job, the job's name is its schedule
//! id, and its runs act for the user `cron`.

use std::sync::Arc;

use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind, AuditTrail};
use adk_core::principal::SubjectRef;
use adk_core::schedule::{Jitter, MissedFirePolicy, Schedule, ScheduleSpec};
use adk_core::{
    Enqueued, InMemoryScheduleStore, NewRun, OnConflict, RequestContext, ScheduleStore,
};
use axum::{
    Extension, Json, Router,
    extract::{Path, State},
    http::{HeaderMap, StatusCode},
    response::{IntoResponse, Response},
    routing::{get, post},
};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::{BackgroundState, DurableScheduler, WorkflowState, run_owner, warn_open_mode};

/// Checks that `expression` parses as a cron expression (five, six, or seven fields).
///
/// # Example
///
/// ```rust
/// use adk_server::background::validate_cron_expression;
///
/// assert!(validate_cron_expression("*/5 * * * *").is_ok());
/// assert!(validate_cron_expression("not cron").is_err());
/// ```
///
/// # Errors
///
/// Returns why the expression does not parse.
pub fn validate_cron_expression(expression: &str) -> Result<(), String> {
    cron_spec(expression, "UTC").next_after(Utc::now()).map(|_| ()).map_err(|e| e.to_string())
}

fn cron_spec(expression: &str, timezone: &str) -> ScheduleSpec {
    ScheduleSpec::Cron { expr: expression.to_string(), timezone: timezone.to_string() }
}

/// What a cron job does when a previous run is still active.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ConcurrencyPolicy {
    /// Skip the occurrence (`OnConflict::Reject` on the job's concurrency key).
    Skip,
    /// Run alongside the active run (no concurrency key).
    Allow,
    /// Queue behind the active run (`OnConflict::Enqueue`).
    Queue,
}

fn default_concurrency_policy() -> ConcurrencyPolicy {
    ConcurrencyPolicy::Skip
}

fn default_timezone() -> String {
    "UTC".to_string()
}

fn default_missed() -> MissedFirePolicy {
    MissedFirePolicy::Skip
}

/// Cron job lifecycle status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CronJobStatus {
    /// The job fires.
    Active,
    /// The job does not fire; occurrences inside the pause are skipped.
    Paused,
}

/// `POST /cron` request body.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateCronJobRequest {
    /// The job's name, which is also its id.
    pub name: String,
    /// The workflow or agent each firing runs.
    #[serde(alias = "target")]
    pub workflow_id: String,
    /// The cron expression (five, six, or seven fields).
    pub cron_expression: String,
    /// The IANA time zone the expression is evaluated in. Defaults to `UTC`.
    #[serde(default = "default_timezone")]
    pub timezone: String,
    /// The input each run receives.
    #[serde(default)]
    pub input: Option<WorkflowState>,
    /// What happens when a previous run is still active. Defaults to `skip`.
    #[serde(default = "default_concurrency_policy")]
    pub concurrency_policy: ConcurrencyPolicy,
    /// Which occurrences fire after the scheduler fell behind. Defaults to `skip`.
    #[serde(default = "default_missed")]
    pub missed_fire_policy: MissedFirePolicy,
}

/// A cron job as the REST API reports it.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CronJobResponse {
    /// The job id, equal to its name.
    pub job_id: String,
    /// The job's name.
    pub name: String,
    /// The workflow or agent each firing runs.
    pub workflow_id: String,
    /// The cron expression; absent for a schedule with another spec.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cron_expression: Option<String>,
    /// The time zone; absent for a schedule with another spec.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timezone: Option<String>,
    /// The schedule's spec.
    pub spec: ScheduleSpec,
    /// Whether the job fires.
    pub status: CronJobStatus,
    /// What happens when a previous run is still active.
    pub concurrency_policy: ConcurrencyPolicy,
    /// Which occurrences fire after the scheduler fell behind.
    pub missed_fire_policy: MissedFirePolicy,
    /// The next occurrence to fire.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_fire_at: Option<String>,
    /// The schedule's revision.
    pub revision: u64,
}

impl From<Schedule> for CronJobResponse {
    fn from(schedule: Schedule) -> Self {
        let (cron_expression, timezone) = match &schedule.spec {
            ScheduleSpec::Cron { expr, timezone } => (Some(expr.clone()), Some(timezone.clone())),
            _ => (None, None),
        };
        let concurrency_policy = match (&schedule.run.concurrency_key, schedule.run.on_conflict) {
            (None, _) => ConcurrencyPolicy::Allow,
            (Some(_), OnConflict::Reject) => ConcurrencyPolicy::Skip,
            (Some(_), _) => ConcurrencyPolicy::Queue,
        };
        Self {
            job_id: schedule.id.clone(),
            name: schedule.id,
            workflow_id: schedule.run.target,
            cron_expression,
            timezone,
            spec: schedule.spec,
            status: if schedule.paused { CronJobStatus::Paused } else { CronJobStatus::Active },
            concurrency_policy,
            missed_fire_policy: schedule.missed,
            next_fire_at: schedule.next_fire_at.map(|at| at.to_rfc3339()),
            revision: schedule.revision,
        }
    }
}

/// `PATCH /cron/{job_id}` request body.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PatchCronJobRequest {
    /// The status to set.
    pub status: CronJobStatus,
}

/// Shared state for the cron endpoints and the scheduler.
#[derive(Clone)]
#[non_exhaustive]
pub struct CronState {
    /// Where schedules are stored.
    pub schedules: Arc<dyn ScheduleStore>,
    /// The background runs state whose run store the schedules enqueue into.
    pub background_state: BackgroundState,
    /// The jitter each fire is delayed by; none by default.
    pub jitter: Option<Jitter>,
    /// Where each run now is recorded; none by default.
    pub audit: Option<AuditTrail>,
}

impl std::fmt::Debug for CronState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CronState")
            .field("background_state", &self.background_state)
            .field("jitter", &self.jitter)
            .field("audit", &self.audit.is_some())
            .finish()
    }
}

impl CronState {
    /// A cron state over a fresh [`InMemoryScheduleStore`].
    pub fn new(background_state: BackgroundState) -> Self {
        Self {
            schedules: Arc::new(InMemoryScheduleStore::new()),
            background_state,
            jitter: None,
            audit: None,
        }
    }

    /// Uses `store` for schedules; share one store across replicas.
    #[must_use]
    pub fn with_schedule_store(mut self, store: Arc<dyn ScheduleStore>) -> Self {
        self.schedules = store;
        self
    }

    /// Delays each fire by its job's [`Jitter`] offset (see the scheduler's
    /// [Jitter](super::scheduler#jitter)).
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::schedule::Jitter;
    /// use adk_server::background::{BackgroundState, CronState};
    ///
    /// let state = CronState::new(BackgroundState::new()).with_jitter(Jitter::default());
    /// assert_eq!(state.scheduler().jitter(), Some(Jitter::default()));
    /// ```
    #[must_use]
    pub fn with_jitter(mut self, jitter: Jitter) -> Self {
        self.jitter = Some(jitter);
        self
    }

    /// Records every run now in `trail` as a `schedule.run_now` record: the caller, the job
    /// and the run it enqueued, or why it enqueued none.
    #[must_use]
    pub fn with_audit(mut self, trail: AuditTrail) -> Self {
        self.audit = Some(trail);
        self
    }

    /// A [`DurableScheduler`] over this state's stores, jitter and current governance
    /// control.
    pub fn scheduler(&self) -> DurableScheduler {
        let mut scheduler = DurableScheduler::new(
            Arc::clone(&self.schedules),
            Arc::clone(self.background_state.run_store()),
        );
        if let Some(jitter) = self.jitter {
            scheduler = scheduler.with_jitter(jitter);
        }
        match self.background_state.governance() {
            Some(control) => scheduler.with_governance(control),
            None => scheduler,
        }
    }
}

fn problem(status: StatusCode, message: impl Into<String>) -> Response {
    (status, Json(serde_json::json!({ "error": message.into() }))).into_response()
}

fn store_error(error: &adk_core::AdkError) -> Response {
    if error.is_not_found() {
        return problem(StatusCode::NOT_FOUND, "cron job not found");
    }
    let status =
        StatusCode::from_u16(error.http_status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
    problem(status, error.to_string())
}

/// The schedule id of `owner`'s job `name`: the name itself without an authenticated caller,
/// and the name behind the owner with one. The length prefix keeps ("a:b", "c") and ("a",
/// "b:c") apart, as the run routes' scoped keys do.
fn schedule_id(owner: Option<&str>, name: &str) -> String {
    match owner {
        Some(owner) => format!("{}:{owner}:{name}", owner.len()),
        None => name.to_string(),
    }
}

/// Whether `owner` may see `schedule`: any schedule without an authenticated caller, only the
/// caller's own with one.
fn visible_to(schedule: &Schedule, owner: Option<&str>) -> bool {
    owner.is_none_or(|owner| {
        schedule.run.user_id == owner && schedule.id.starts_with(&schedule_id(Some(owner), ""))
    })
}

/// The job as `owner` sees it, named as its owner named it.
fn job_for(schedule: Schedule, owner: Option<&str>) -> CronJobResponse {
    let prefix = schedule_id(owner, "");
    let name = owner.and_then(|_| schedule.id.strip_prefix(&prefix)).map(str::to_string);
    let mut job = CronJobResponse::from(schedule);
    if let Some(name) = name {
        job.job_id.clone_from(&name);
        job.name = name;
    }
    job
}

/// `owner`'s job `name`, or `None` when it does not exist or belongs to another owner.
async fn visible_job(
    state: &CronState,
    owner: Option<&str>,
    name: &str,
) -> std::result::Result<Option<Schedule>, adk_core::AdkError> {
    let schedule = state.schedules.get(&schedule_id(owner, name)).await?;
    Ok(schedule.filter(|schedule| visible_to(schedule, owner)))
}

/// POST /cron — Create a cron job.
async fn create_cron_job(
    State(state): State<CronState>,
    caller: Option<Extension<Option<RequestContext>>>,
    Json(request): Json<CreateCronJobRequest>,
) -> Response {
    let owner = run_owner(caller);
    let id = schedule_id(owner.as_deref(), &request.name);
    let spec = cron_spec(&request.cron_expression, &request.timezone);
    let first = match spec.next_after(Utc::now()) {
        Ok(first) => first,
        Err(error) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({
                    "error": "invalid cron expression",
                    "expression": request.cron_expression,
                    "reason": error.to_string(),
                })),
            )
                .into_response();
        }
    };
    match state.schedules.get(&id).await {
        Ok(Some(_)) => {
            return problem(
                StatusCode::CONFLICT,
                format!("a cron job named '{}' already exists", request.name),
            );
        }
        Ok(None) => {}
        Err(error) => return store_error(&error),
    }
    let background = &state.background_state;
    let input = request.input.map_or(Value::Object(Default::default()), |input| {
        Value::Object(input.into_iter().collect())
    });
    // An authenticated owner's job runs for that owner, as the identity the server
    // authenticated when the job was created.
    let mut run = NewRun::new(
        background.worker.queue.clone(),
        background.app_name_for(&request.workflow_id),
        owner.clone().unwrap_or_else(|| "cron".to_string()),
        request.workflow_id,
        input,
    );
    if owner.is_some() {
        run = run.with_authenticated_user();
    }
    let concurrency_key = format!("cron:{id}");
    run = match request.concurrency_policy {
        ConcurrencyPolicy::Skip => run.with_concurrency_key(concurrency_key, OnConflict::Reject),
        ConcurrencyPolicy::Queue => run.with_concurrency_key(concurrency_key, OnConflict::Enqueue),
        ConcurrencyPolicy::Allow => run,
    };
    let mut schedule = Schedule::new(id, spec, run, request.missed_fire_policy);
    if let Some(first) = first {
        schedule = schedule.with_next_fire_at(first);
    }
    match state.schedules.upsert(schedule).await {
        Ok(stored) => {
            tracing::info!(schedule.id = %stored.id, "cron job created");
            (StatusCode::CREATED, Json(job_for(stored, owner.as_deref()))).into_response()
        }
        Err(error) => problem(StatusCode::BAD_REQUEST, error.to_string()),
    }
}

/// GET /cron — List cron jobs; with an authenticated caller, only the caller's.
async fn list_cron_jobs(
    State(state): State<CronState>,
    caller: Option<Extension<Option<RequestContext>>>,
) -> Response {
    let owner = run_owner(caller);
    match state.schedules.list().await {
        Ok(schedules) => {
            let jobs: Vec<CronJobResponse> = schedules
                .into_iter()
                .filter(|schedule| visible_to(schedule, owner.as_deref()))
                .map(|schedule| job_for(schedule, owner.as_deref()))
                .collect();
            (StatusCode::OK, Json(jobs)).into_response()
        }
        Err(error) => store_error(&error),
    }
}

/// GET /cron/{job_id} — Get a cron job; another owner's job is `404`.
async fn get_cron_job(
    State(state): State<CronState>,
    caller: Option<Extension<Option<RequestContext>>>,
    Path(job_id): Path<String>,
) -> Response {
    let owner = run_owner(caller);
    match visible_job(&state, owner.as_deref(), &job_id).await {
        Ok(Some(schedule)) => {
            (StatusCode::OK, Json(job_for(schedule, owner.as_deref()))).into_response()
        }
        Ok(None) => problem(StatusCode::NOT_FOUND, format!("cron job '{job_id}' not found")),
        Err(error) => store_error(&error),
    }
}

/// PATCH /cron/{job_id} — Pause or resume a cron job; another owner's job is `404`.
///
/// Resuming moves the next fire time to the first occurrence after now, so occurrences
/// that fell inside the pause are skipped rather than replayed.
async fn patch_cron_job(
    State(state): State<CronState>,
    caller: Option<Extension<Option<RequestContext>>>,
    Path(job_id): Path<String>,
    Json(request): Json<PatchCronJobRequest>,
) -> Response {
    let owner = run_owner(caller);
    let id = schedule_id(owner.as_deref(), &job_id);
    match visible_job(&state, owner.as_deref(), &job_id).await {
        Ok(Some(_)) => {}
        Ok(None) => return problem(StatusCode::NOT_FOUND, "cron job not found"),
        Err(error) => return store_error(&error),
    }
    let result = match request.status {
        CronJobStatus::Paused => state.schedules.set_paused(&id, true).await,
        CronJobStatus::Active => match state.schedules.get(&id).await {
            Ok(Some(schedule)) if schedule.paused => {
                let next = match schedule.spec.next_after(Utc::now()) {
                    Ok(next) => next,
                    Err(error) => return problem(StatusCode::BAD_REQUEST, error.to_string()),
                };
                let mut resumed = schedule.with_paused(false);
                resumed.next_fire_at = next;
                state.schedules.upsert(resumed).await
            }
            Ok(Some(schedule)) => Ok(schedule),
            Ok(None) => return problem(StatusCode::NOT_FOUND, "cron job not found"),
            Err(error) => Err(error),
        },
    };
    match result {
        Ok(schedule) => (StatusCode::OK, Json(job_for(schedule, owner.as_deref()))).into_response(),
        Err(error) => store_error(&error),
    }
}

/// DELETE /cron/{job_id} — Delete a cron job; another owner's job is `404`.
async fn delete_cron_job(
    State(state): State<CronState>,
    caller: Option<Extension<Option<RequestContext>>>,
    Path(job_id): Path<String>,
) -> Response {
    let owner = run_owner(caller);
    match visible_job(&state, owner.as_deref(), &job_id).await {
        Ok(Some(schedule)) => match state.schedules.delete(&schedule.id).await {
            Ok(()) => (StatusCode::NO_CONTENT, ()).into_response(),
            Err(error) => store_error(&error),
        },
        Ok(None) => problem(StatusCode::NOT_FOUND, "cron job not found"),
        Err(error) => store_error(&error),
    }
}

/// `POST /cron/{job_id}/run` response.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RunCronJobNowResponse {
    /// The job's id, as its owner named it.
    pub job_id: String,
    /// The run the request enqueued, or the one an earlier request with the same key did.
    pub run_id: String,
    /// The run's status.
    pub status: super::RunStatus,
    /// The run's idempotency key, `schedule:{id}:manual:{request id}`.
    pub idempotency_key: String,
    /// `true` when an earlier request with the same `Idempotency-Key` enqueued the run.
    pub existing: bool,
}

/// The `Idempotency-Key` header of a run now; a retried request with the same key returns
/// the run the first one enqueued.
pub const RUN_NOW_IDEMPOTENCY_HEADER: &str = "idempotency-key";

/// `POST /cron/{job_id}/run` — Runs a cron job now, outside its schedule; another owner's job
/// is `404`.
///
/// The run is the job's template, acting for the job's owner as a fire does, with the job's
/// concurrency key, so it is subject to the same overlap rule; its idempotency key is
/// `schedule:{id}:manual:{request id}`, the request id taken from the `Idempotency-Key`
/// header or generated. The job itself is not changed: its next fire time and revision stay
/// where they are, and a paused job stays paused and still runs now.
///
/// | Outcome | Status |
/// |---------|--------|
/// | Run enqueued | `202 Accepted` |
/// | The `Idempotency-Key` already enqueued a run | `200 OK`, `existing: true` |
/// | The kill switch refuses work | `503 Service Unavailable`; nothing is enqueued |
/// | The job's concurrency policy is `skip` and a run is active | `409 Conflict`, with `blockingRunId` |
/// | No such job for this caller | `404 Not Found` |
///
/// With [`CronState::with_audit`], every outcome but `404` is recorded as `schedule.run_now`.
pub async fn run_cron_job_now(
    State(state): State<CronState>,
    caller: Option<Extension<Option<RequestContext>>>,
    Path(job_id): Path<String>,
    headers: HeaderMap,
) -> Response {
    let owner = run_owner(caller);
    let schedule = match visible_job(&state, owner.as_deref(), &job_id).await {
        Ok(Some(schedule)) => schedule,
        Ok(None) => return problem(StatusCode::NOT_FOUND, "cron job not found"),
        Err(error) => return store_error(&error),
    };
    let request_id = headers
        .get(RUN_NOW_IDEMPOTENCY_HEADER)
        .and_then(|value| value.to_str().ok())
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map_or_else(|| uuid::Uuid::new_v4().to_string(), str::to_string);
    let run = schedule.run_now(&request_id);
    let key = run.idempotency_key.clone().unwrap_or_default();
    let requester = owner.as_deref().unwrap_or("anonymous");
    if let Some(control) = state.background_state.governance()
        && let Err(error) = control.check()
    {
        record_run_now(&state, requester, &schedule.id, &key, None, "refused_frozen").await;
        return problem(StatusCode::SERVICE_UNAVAILABLE, error.to_string());
    }
    let enqueued = match state.background_state.run_store().enqueue(run).await {
        Ok(enqueued) => enqueued,
        Err(error) => return store_error(&error),
    };
    let (status, record, existing) = match enqueued {
        Enqueued::Created(record) => (StatusCode::ACCEPTED, record, false),
        Enqueued::Existing(record) => (StatusCode::OK, record, true),
        Enqueued::Rejected { blocking_run_id } => {
            record_run_now(&state, requester, &schedule.id, &key, None, "refused_concurrency")
                .await;
            return (
                StatusCode::CONFLICT,
                Json(serde_json::json!({
                    "error": "a run of this cron job is still active and its concurrency policy is skip",
                    "blockingRunId": blocking_run_id,
                })),
            )
                .into_response();
        }
    };
    state.background_state.ensure_worker_started();
    state.background_state.wake_worker();
    let outcome = if existing { "existing" } else { "enqueued" };
    record_run_now(&state, requester, &schedule.id, &key, Some(&record.run_id), outcome).await;
    tracing::info!(schedule.id = %schedule.id, run.id = %record.run_id, run.existing = existing, "cron job run now");
    let response = RunCronJobNowResponse {
        job_id: job_for(schedule, owner.as_deref()).job_id,
        run_id: record.run_id,
        status: record.state.into(),
        idempotency_key: key,
        existing,
    };
    (status, Json(response)).into_response()
}

/// Records a run now in the state's audit trail, when it has one. A failed write is logged:
/// the run, once enqueued, is the durable fact.
async fn record_run_now(
    state: &CronState,
    requester: &str,
    schedule_id: &str,
    key: &str,
    run_id: Option<&str>,
    outcome: &str,
) {
    let Some(trail) = &state.audit else { return };
    let draft =
        AuditRecordDraft::new(AuditRecordKind::Other("schedule".to_string()), "schedule.run_now")
            .actor(AuditActor::subject(SubjectRef::human(requester)))
            .ext("schedule", serde_json::json!(schedule_id))
            .ext("idempotencyKey", serde_json::json!(key))
            .ext("runId", serde_json::json!(run_id))
            .ext("outcome", serde_json::json!(outcome));
    if let Err(error) = trail.record(draft).await {
        tracing::warn!(schedule.id = %schedule_id, error = %error, "could not record a cron job run now");
    }
}

/// Starts the scheduling loop: a [`DurableScheduler`] tick every second over the state's
/// schedule and run stores. Run it on every replica; each fire time is enqueued once.
///
/// The governance control is read on every tick, so one installed later by
/// [`ServerBuilder`](crate::ServerBuilder) applies.
pub fn start_cron_scheduler(state: CronState) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        let mut interval = tokio::time::interval(std::time::Duration::from_secs(1));
        interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
        loop {
            interval.tick().await;
            if let Err(error) = state.scheduler().tick().await {
                tracing::warn!(error = %error, "scheduler tick failed");
            }
        }
    })
}

/// Create the cron jobs router over a fresh in-memory schedule store.
///
/// > **Important:** the router carries no authentication. Anyone who reaches it can
/// > schedule recurring work. Mount it through
/// > [`ServerBuilder::with_cron_jobs`](crate::ServerBuilder::with_cron_jobs), which
/// > applies the server's auth middleware, or behind your own authentication layer.
pub fn cron_jobs_router(background_state: BackgroundState) -> Router {
    cron_jobs_router_with_state(CronState::new(background_state))
}

/// Create the cron jobs router with a pre-configured state.
///
/// The routes run in [open mode](super#open-mode), and building the router logs a warning
/// that says so.
///
/// > **Important:** the router carries no authentication; see [`cron_jobs_router`].
pub fn cron_jobs_router_with_state(state: CronState) -> Router {
    warn_open_mode("/cron");
    cron_routes(state)
}

/// The cron routes without the open-mode warning, for [`ServerBuilder`](crate::ServerBuilder),
/// which knows whether it authenticates callers.
pub(crate) fn cron_routes(state: CronState) -> Router {
    Router::new()
        .route("/cron", post(create_cron_job).get(list_cron_jobs))
        .route("/cron/{job_id}", get(get_cron_job).patch(patch_cron_job).delete(delete_cron_job))
        .route("/cron/{job_id}/run", post(run_cron_job_now))
        .with_state(state)
}