1use 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
46pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
70#[serde(rename_all = "lowercase")]
71pub enum ConcurrencyPolicy {
72 Skip,
74 Allow,
76 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
94#[serde(rename_all = "lowercase")]
95pub enum CronJobStatus {
96 Active,
98 Paused,
100}
101
102#[derive(Debug, Deserialize)]
104#[serde(rename_all = "camelCase")]
105pub struct CreateCronJobRequest {
106 pub name: String,
108 #[serde(alias = "target")]
110 pub workflow_id: String,
111 pub cron_expression: String,
113 #[serde(default = "default_timezone")]
115 pub timezone: String,
116 #[serde(default)]
118 pub input: Option<WorkflowState>,
119 #[serde(default = "default_concurrency_policy")]
121 pub concurrency_policy: ConcurrencyPolicy,
122 #[serde(default = "default_missed")]
124 pub missed_fire_policy: MissedFirePolicy,
125}
126
127#[derive(Debug, Serialize)]
129#[serde(rename_all = "camelCase")]
130pub struct CronJobResponse {
131 pub job_id: String,
133 pub name: String,
135 pub workflow_id: String,
137 #[serde(skip_serializing_if = "Option::is_none")]
139 pub cron_expression: Option<String>,
140 #[serde(skip_serializing_if = "Option::is_none")]
142 pub timezone: Option<String>,
143 pub spec: ScheduleSpec,
145 pub status: CronJobStatus,
147 pub concurrency_policy: ConcurrencyPolicy,
149 pub missed_fire_policy: MissedFirePolicy,
151 #[serde(skip_serializing_if = "Option::is_none")]
153 pub next_fire_at: Option<String>,
154 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#[derive(Debug, Deserialize)]
187#[serde(rename_all = "camelCase")]
188pub struct PatchCronJobRequest {
189 pub status: CronJobStatus,
191}
192
193#[derive(Clone)]
195#[non_exhaustive]
196pub struct CronState {
197 pub schedules: Arc<dyn ScheduleStore>,
199 pub background_state: BackgroundState,
201 pub jitter: Option<Jitter>,
203 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 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 #[must_use]
230 pub fn with_schedule_store(mut self, store: Arc<dyn ScheduleStore>) -> Self {
231 self.schedules = store;
232 self
233 }
234
235 #[must_use]
248 pub fn with_jitter(mut self, jitter: Jitter) -> Self {
249 self.jitter = Some(jitter);
250 self
251 }
252
253 #[must_use]
256 pub fn with_audit(mut self, trail: AuditTrail) -> Self {
257 self.audit = Some(trail);
258 self
259 }
260
261 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
291fn 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
301fn 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
309fn 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
321async 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
331async 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 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
399async 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
418async 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
434async 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
474async 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#[derive(Debug, Serialize)]
493#[serde(rename_all = "camelCase")]
494pub struct RunCronJobNowResponse {
495 pub job_id: String,
497 pub run_id: String,
499 pub status: super::RunStatus,
501 pub idempotency_key: String,
503 pub existing: bool,
505}
506
507pub const RUN_NOW_IDEMPOTENCY_HEADER: &str = "idempotency-key";
510
511pub 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
591async 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
614pub 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
632pub fn cron_jobs_router(background_state: BackgroundState) -> Router {
639 cron_jobs_router_with_state(CronState::new(background_state))
640}
641
642pub fn cron_jobs_router_with_state(state: CronState) -> Router {
649 warn_open_mode("/cron");
650 cron_routes(state)
651}
652
653pub(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}