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};
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() }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ConcurrencyPolicy {
Skip,
Allow,
Queue,
}
fn default_concurrency_policy() -> ConcurrencyPolicy {
ConcurrencyPolicy::Skip
}
fn default_timezone() -> String {
"UTC".to_string()
}
fn default_missed() -> MissedFirePolicy {
MissedFirePolicy::Skip
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CronJobStatus {
Active,
Paused,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateCronJobRequest {
pub name: String,
#[serde(alias = "target")]
pub workflow_id: String,
pub cron_expression: String,
#[serde(default = "default_timezone")]
pub timezone: String,
#[serde(default)]
pub input: Option<WorkflowState>,
#[serde(default = "default_concurrency_policy")]
pub concurrency_policy: ConcurrencyPolicy,
#[serde(default = "default_missed")]
pub missed_fire_policy: MissedFirePolicy,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CronJobResponse {
pub job_id: String,
pub name: String,
pub workflow_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub cron_expression: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub timezone: Option<String>,
pub spec: ScheduleSpec,
pub status: CronJobStatus,
pub concurrency_policy: ConcurrencyPolicy,
pub missed_fire_policy: MissedFirePolicy,
#[serde(skip_serializing_if = "Option::is_none")]
pub next_fire_at: Option<String>,
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,
}
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PatchCronJobRequest {
pub status: CronJobStatus,
}
#[derive(Clone)]
#[non_exhaustive]
pub struct CronState {
pub schedules: Arc<dyn ScheduleStore>,
pub background_state: BackgroundState,
pub jitter: Option<Jitter>,
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 {
pub fn new(background_state: BackgroundState) -> Self {
Self {
schedules: Arc::new(InMemoryScheduleStore::new()),
background_state,
jitter: None,
audit: None,
}
}
#[must_use]
pub fn with_schedule_store(mut self, store: Arc<dyn ScheduleStore>) -> Self {
self.schedules = store;
self
}
#[must_use]
pub fn with_jitter(mut self, jitter: Jitter) -> Self {
self.jitter = Some(jitter);
self
}
#[must_use]
pub fn with_audit(mut self, trail: AuditTrail) -> Self {
self.audit = Some(trail);
self
}
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())
}
fn schedule_id(owner: Option<&str>, name: &str) -> String {
match owner {
Some(owner) => format!("{}:{owner}:{name}", owner.len()),
None => name.to_string(),
}
}
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), ""))
})
}
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
}
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)))
}
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())
});
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()),
}
}
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),
}
}
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),
}
}
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),
}
}
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),
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RunCronJobNowResponse {
pub job_id: String,
pub run_id: String,
pub status: super::RunStatus,
pub idempotency_key: String,
pub existing: bool,
}
pub const RUN_NOW_IDEMPOTENCY_HEADER: &str = "idempotency-key";
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()
}
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");
}
}
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");
}
}
})
}
pub fn cron_jobs_router(background_state: BackgroundState) -> Router {
cron_jobs_router_with_state(CronState::new(background_state))
}
pub fn cron_jobs_router_with_state(state: CronState) -> Router {
warn_open_mode("/cron");
cron_routes(state)
}
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)
}