1use std::sync::Arc;
20
21use axum::extract::{Path, State};
22use axum::{Extension, Json};
23use serde::{Deserialize, Serialize};
24use serde_json::Value;
25
26use agentmux_common::time::now_ms;
27
28use crate::backend::cron::schedule::JobSchedule;
29use crate::backend::job_templates::cloud::CloudExpect;
30use crate::backend::job_templates::{self as job_templates, ApprovedTemplate};
31use crate::backend::jobs::caps;
32use crate::backend::jobs::from_template::{self, TemplatePinView};
33use crate::backend::jobs::verdict::{cron_job_state, job_failing, run_failed};
34use crate::backend::jobs::{self, RunLedger};
35use crate::backend::rpc::engine::WshRpcEngine;
36use crate::backend::rpc_types::*;
37use crate::backend::storage::cron::CronJob;
38use crate::backend::storage::job_incidents::JobIncident;
39use crate::backend::storage::job_runs::{JobFlag, JobRun};
40use crate::drone::storage::DroneStore;
41use crate::server::caller::Caller;
42use crate::server::cron::{handle_cron_delete, handle_cron_patch, handle_cron_run_now};
43use crate::server::job_caps;
44
45use super::AppState;
46
47const RECENT: i64 = 14;
49const RUNS_MAX: i64 = 200;
51const RUNS_DEFAULT: i64 = 50;
52const DAY_MS: i64 = 24 * 60 * 60 * 1000;
53
54#[derive(Debug, Clone, Serialize, ts_rs::TS)]
56#[ts(export, export_to = "../../../frontend/types/rpc/")]
57pub struct JobRunRow {
58 #[serde(flatten)]
59 #[ts(flatten)]
60 pub run: JobRun,
61 pub failed: bool,
62}
63
64impl From<JobRun> for JobRunRow {
65 fn from(run: JobRun) -> Self {
66 JobRunRow { failed: run_failed(&run), run }
67 }
68}
69
70#[derive(Debug, Clone, Serialize, ts_rs::TS)]
72#[ts(export, export_to = "../../../frontend/types/rpc/")]
73pub struct JobView {
74 pub id: String,
75 #[ts(type = r#""cron" | "drone" | "cloud""#)]
77 pub source: String,
78 pub name: String,
79 pub owner: String,
81 pub owner_uid: String,
82 pub owner_block_id: Option<String>,
84 pub target: String,
86 pub expression: String,
89 #[ts(type = r#""cron" | "every" | "once" | "manual""#)]
91 pub trigger_kind: String,
92 pub tz: String,
94 #[ts(type = "number | null")]
96 pub every_secs: Option<i64>,
97 #[ts(type = "number | null")]
99 pub once_at_ms: Option<i64>,
100 #[ts(type = "number | null")]
102 pub next_run_ms: Option<i64>,
103 #[ts(type = r#""active" | "paused" | "paused_all" | "ended""#)]
105 pub state: String,
106 pub catch_up: String,
108 #[ts(type = "number")]
109 pub fire_count: i64,
110 #[ts(type = "number | null")]
111 pub max_fires: Option<i64>,
112 #[ts(type = "number")]
113 pub missed_count: i64,
114 pub recent: Vec<JobRunRow>,
116 pub failing: bool,
118 pub incident: Option<JobIncident>,
120 pub cost_today_usd: f64,
122 pub cost_week_usd: f64,
123 pub cost_known: bool,
125 pub actions: bool,
128 pub over_cap: Option<String>,
131 #[ts(type = "number | null")]
133 pub run_cap_usd: Option<f64>,
134 #[ts(type = "number | null")]
135 pub day_cap_usd: Option<f64>,
136 pub cost_not_reported: bool,
139 pub template: Option<TemplatePinView>,
142 pub cloud: Option<CloudJobView>,
144}
145
146#[derive(Debug, Clone, Serialize, ts_rs::TS)]
149#[ts(export, export_to = "../../../frontend/types/rpc/")]
150pub struct CloudJobView {
151 pub reporter: String,
153 pub reporter_pinned: bool,
154 pub grace_minutes: Option<u32>,
156 pub max_run_minutes: Option<u32>,
158 pub run_now_link: Option<String>,
160 pub run_now_ask_owner: Option<String>,
161 #[ts(type = "number")]
163 pub approved_at_ms: i64,
164}
165
166#[derive(Debug, Clone, Serialize, ts_rs::TS)]
168#[ts(export, export_to = "../../../frontend/types/rpc/")]
169pub struct DroppedEvents {
170 pub reason: String,
171 #[ts(type = "number")]
172 pub count: u64,
173}
174
175#[derive(Debug, Clone, Serialize, ts_rs::TS)]
178#[ts(export, export_to = "../../../frontend/types/rpc/")]
179pub struct CapDefaults {
180 pub run_usd: f64,
181 pub job_day_usd: f64,
182 pub account_day_usd: f64,
183 pub messages_per_day: u32,
184}
185
186#[derive(Debug, Clone, Serialize, ts_rs::TS)]
187#[ts(export, export_to = "../../../frontend/types/rpc/")]
188pub struct JobsListResult {
189 pub jobs: Vec<JobView>,
190 pub paused_all: Option<JobFlag>,
192 #[ts(type = "number")]
193 pub now_ms: i64,
194 pub defaults: CapDefaults,
195 pub dropped: Vec<DroppedEvents>,
197}
198
199#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
200#[ts(export, export_to = "../../../frontend/types/rpc/")]
201pub struct JobsRunsRequest {
202 pub job_id: String,
203 #[serde(default)]
204 #[ts(optional, type = "number")]
205 pub limit: Option<i64>,
206 #[serde(default)]
208 #[ts(optional, type = "number")]
209 pub before: Option<i64>,
210}
211
212#[derive(Debug, Clone, Serialize, ts_rs::TS)]
213#[ts(export, export_to = "../../../frontend/types/rpc/")]
214pub struct JobsRunsResult {
215 pub runs: Vec<JobRunRow>,
216}
217
218#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
219#[ts(export, export_to = "../../../frontend/types/rpc/")]
220pub struct JobsActRequest {
221 #[ts(type = r#""run_now" | "pause" | "resume" | "delete" | "pause_all" | "resume_all""#)]
222 pub action: String,
223 #[serde(default)]
225 #[ts(optional)]
226 pub job_id: Option<String>,
227}
228
229#[derive(Debug, Clone, Default, Serialize, ts_rs::TS)]
230#[ts(export, export_to = "../../../frontend/types/rpc/")]
231pub struct JobsActResult {
232 pub ok: bool,
233 pub run_id: Option<String>,
235 pub outcome: Option<String>,
237 pub error: Option<String>,
239}
240
241pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
242 let s = state.clone();
243 engine.register_typed(COMMAND_JOBS_LIST, move |_data: Value, _ctx| {
244 let s = s.clone();
245 async move { list(&s).await }
246 });
247 let s = state.clone();
248 engine.register_typed(COMMAND_JOBS_RUNS, move |req: JobsRunsRequest, _ctx| {
249 let s = s.clone();
250 async move { runs(&s, req).await }
251 });
252 let s = state.clone();
253 engine.register_typed(COMMAND_JOBS_ACT, move |req: JobsActRequest, ctx| {
254 let s = s.clone();
255 async move { act(&s, req, &ctx).await }
256 });
257}
258
259fn ledger(state: &AppState) -> Result<Arc<RunLedger>, String> {
260 state.cron_scheduler.runs().cloned().ok_or_else(|| "the run ledger isn't ready".to_string())
261}
262
263fn local_midnight_ms() -> i64 {
266 caps::local_day_start_ms(now_ms())
267}
268
269fn block_of(regs: &[crate::backend::reactive::types::AgentRegistration], uid: &str, name: &str) -> Option<String> {
271 let by_uid = (!uid.is_empty()).then(|| regs.iter().find(|r| r.uid.as_deref() == Some(uid))).flatten();
272 let by_name = || (!name.is_empty()).then(|| regs.iter().find(|r| r.agent_id.eq_ignore_ascii_case(name))).flatten();
273 by_uid.or_else(by_name).map(|r| r.block_id.clone())
274}
275
276struct Ledgered {
278 recent: Vec<JobRunRow>,
279 failing: bool,
280 incident: Option<JobIncident>,
281 cost_today_usd: f64,
282 cost_week_usd: f64,
283 cost_known: bool,
284}
285
286fn ledgered(ledger: &RunLedger, job_id: &str, midnight: i64, week: i64) -> Ledgered {
287 let store = ledger.store();
288 let runs = store.job_runs_for_job(job_id, RECENT, None).unwrap_or_default();
289 let failing = job_failing(store.job_run_last_decisive(job_id).ok().flatten().as_ref());
292 let (today, known_today) = store.job_runs_cost_since(job_id, midnight).unwrap_or((0.0, false));
293 let (week_usd, known_week) = store.job_runs_cost_since(job_id, week).unwrap_or((0.0, false));
294 Ledgered {
295 recent: runs.into_iter().map(JobRunRow::from).collect(),
296 failing,
297 incident: store.job_incident_open_for(job_id).ok().flatten(),
298 cost_today_usd: today,
299 cost_week_usd: week_usd,
300 cost_known: known_today || known_week,
301 }
302}
303
304fn cron_view(job: &CronJob, l: Ledgered, paused_all: bool, owner_block_id: Option<String>, now: i64) -> JobView {
305 let next_run_ms = if job.enabled { jobs::next_slot_after(job, now) } else { None };
306 JobView {
307 id: job.id.clone(),
308 source: jobs::SOURCE_CRON.to_string(),
309 name: job.name.clone(),
310 owner: job.created_by.clone(),
311 owner_uid: job.owner_uid().to_string(),
312 owner_block_id,
313 target: job.target.clone(),
314 expression: job.expression.clone(),
315 trigger_kind: if job.trigger_kind.is_empty() { "cron".to_string() } else { job.trigger_kind.clone() },
316 tz: if job.tz.is_empty() { "UTC".to_string() } else { job.tz.clone() },
317 every_secs: job.every_secs,
318 once_at_ms: job.once_at_ms,
319 next_run_ms,
320 state: cron_job_state(job, paused_all, now / 1000).to_string(),
321 catch_up: job.catch_up.clone(),
322 fire_count: job.fire_count,
323 max_fires: job.max_fires,
324 missed_count: job.missed_count,
325 recent: l.recent,
326 failing: l.failing,
327 incident: l.incident,
328 cost_today_usd: l.cost_today_usd,
329 cost_week_usd: l.cost_week_usd,
330 cost_known: l.cost_known,
331 actions: true,
332 over_cap: None,
333 run_cap_usd: None,
334 day_cap_usd: None,
335 cost_not_reported: false,
336 template: None,
337 cloud: None,
338 }
339}
340
341fn drone_view(id: &str, name: &str, l: Ledgered) -> JobView {
342 JobView {
343 id: id.to_string(),
344 source: jobs::SOURCE_DRONE.to_string(),
345 name: name.to_string(),
346 owner: String::new(),
347 owner_uid: String::new(),
348 owner_block_id: None,
349 target: String::new(),
350 expression: String::new(),
351 trigger_kind: "manual".to_string(),
352 tz: "UTC".to_string(),
353 every_secs: None,
354 once_at_ms: None,
355 next_run_ms: None,
356 state: crate::backend::jobs::verdict::job_state::ACTIVE.to_string(),
357 catch_up: String::new(),
358 fire_count: 0,
359 max_fires: None,
360 missed_count: 0,
361 recent: l.recent,
362 failing: l.failing,
363 incident: l.incident,
364 cost_today_usd: l.cost_today_usd,
365 cost_week_usd: l.cost_week_usd,
366 cost_known: l.cost_known,
367 actions: false,
368 over_cap: None,
369 run_cap_usd: None,
370 day_cap_usd: None,
371 cost_not_reported: false,
372 template: None,
373 cloud: None,
374 }
375}
376
377fn cloud_view(t: &ApprovedTemplate, l: Ledgered, regs: &[crate::backend::reactive::types::AgentRegistration], pinned: bool, now: i64) -> JobView {
380 let m = &t.manifest;
381 let named = m.owner.clone().unwrap_or_default();
382 let reg = regs
383 .iter()
384 .find(|r| r.uid.as_deref() == Some(named.as_str()))
385 .or_else(|| regs.iter().find(|r| r.agent_id.eq_ignore_ascii_case(&named)));
386 let owner = reg.map(|r| r.agent_id.clone()).unwrap_or_else(|| named.clone());
387 let owner_uid = reg.and_then(|r| r.uid.clone()).unwrap_or_else(|| named.clone());
388 let (schedule, grace_minutes) = match &m.expect {
389 Some(CloudExpect::Schedule(s)) => (Some(s), Some(s.grace_minutes)),
390 _ => (None, None),
391 };
392 let next_run_ms = schedule.and_then(|s| JobSchedule::cron(&s.cron, &s.tz).ok()).and_then(|sch| sch.next_after(now));
393 JobView {
394 id: t.id.clone(),
395 source: jobs::SOURCE_CLOUD.to_string(),
396 name: m.name.clone(),
397 owner,
398 owner_block_id: reg.map(|r| r.block_id.clone()),
399 owner_uid,
400 target: String::new(),
401 expression: schedule.map(|s| s.cron.clone()).unwrap_or_default(),
402 trigger_kind: if schedule.is_some() { "cron" } else { "manual" }.to_string(),
403 tz: schedule.map(|s| s.tz.clone()).unwrap_or_else(|| "UTC".to_string()),
404 every_secs: None,
405 once_at_ms: None,
406 next_run_ms,
407 state: crate::backend::jobs::verdict::job_state::ACTIVE.to_string(),
408 catch_up: String::new(),
409 fire_count: 0,
410 max_fires: None,
411 missed_count: 0,
412 recent: l.recent,
413 failing: l.failing,
414 incident: l.incident,
415 cost_today_usd: l.cost_today_usd,
416 cost_week_usd: l.cost_week_usd,
417 cost_known: l.cost_known,
418 actions: false,
419 over_cap: None,
420 run_cap_usd: None,
421 day_cap_usd: None,
422 cost_not_reported: false,
423 template: None,
424 cloud: Some(CloudJobView {
425 reporter: m.reporter.as_ref().map(|r| r.name.clone()).unwrap_or_default(),
426 reporter_pinned: pinned,
427 grace_minutes,
428 max_run_minutes: m.max_duration_minutes,
429 run_now_link: m.run_now.as_ref().and_then(|r| r.link.clone()),
430 run_now_ask_owner: m.run_now.as_ref().and_then(|r| r.ask_owner.clone()),
431 approved_at_ms: t.approved_at_ms,
432 }),
433 }
434}
435
436fn sort_jobs(jobs: &mut [JobView]) {
438 jobs.sort_by(|a, b| {
439 let key = |j: &JobView| j.next_run_ms.unwrap_or(i64::MAX);
440 key(a).cmp(&key(b)).then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
441 });
442}
443
444pub(super) async fn list(state: &AppState) -> Result<JobsListResult, String> {
445 let ledger = ledger(state)?;
446 let jobs_store = crate::server::cron::jobs_store(state);
447 let regs = state.reactive_handler.list_agents();
448 let st = state.clone();
449 tokio::task::spawn_blocking(move || {
450 let now = now_ms();
451 let (midnight, week) = (local_midnight_ms(), now - 7 * DAY_MS);
452 let paused_all = ledger.paused_all();
453 let cron_jobs = match &jobs_store {
454 Some(s) => s.cron_list().map_err(|e| e.to_string())?,
455 None => Vec::new(),
456 };
457 let mut templates = from_template::Latest::new();
458 let mut views: Vec<JobView> = cron_jobs
459 .iter()
460 .map(|job| {
461 let owner_block = block_of(®s, job.owner_uid(), &job.created_by);
462 let mut view = cron_view(job, ledgered(&ledger, &job.id, midnight, week), paused_all.is_some(), owner_block, now);
463 let eff = caps::effective(job.policy.caps.as_ref(), &ledger.limits());
464 view.over_cap = ledger.over_cap_today(job).map(str::to_string);
465 (view.run_cap_usd, view.day_cap_usd) = (Some(eff.run_usd), Some(eff.day_usd));
466 view.cost_not_reported = job_caps::no_cost_provider(&st, job).is_some();
467 view.template = job.template.as_ref().map(|pin| from_template::pin_view(pin, &mut templates));
468 view
469 })
470 .collect();
471 for drone in crate::server::drone_handlers::list_drones(&st).unwrap_or_default() {
474 let l = ledgered(&ledger, &drone.id, midnight, week);
475 if !l.recent.is_empty() {
476 views.push(drone_view(&drone.id, &drone.name, l));
477 }
478 }
479 if let Some(service) = job_templates::service() {
481 for t in service.approved_clouds() {
482 let pinned = t.manifest.reporter.as_ref().is_some_and(|r| service.reporters().fingerprint_of_pinned(&r.key).is_some());
483 views.push(cloud_view(&t, ledgered(&ledger, &t.id, midnight, week), ®s, pinned, now));
484 }
485 }
486 sort_jobs(&mut views);
487 let limits = job_caps::limits(&st);
488 let defaults = CapDefaults {
489 run_usd: limits.run_usd,
490 job_day_usd: limits.job_day_usd,
491 account_day_usd: limits.account_day_usd,
492 messages_per_day: limits.messages_per_day,
493 };
494 let dropped = crate::backend::jobs::cloud_events::drops()
495 .into_iter()
496 .map(|(reason, count)| DroppedEvents { reason: reason.to_string(), count })
497 .collect();
498 Ok(JobsListResult { jobs: views, paused_all, now_ms: now, defaults, dropped })
499 })
500 .await
501 .map_err(|e| e.to_string())?
502}
503
504async fn runs(state: &AppState, req: JobsRunsRequest) -> Result<JobsRunsResult, String> {
505 let ledger = ledger(state)?;
506 let limit = req.limit.unwrap_or(RUNS_DEFAULT).clamp(1, RUNS_MAX);
507 tokio::task::spawn_blocking(move || {
508 let runs = ledger.store().job_runs_for_job(&req.job_id, limit, req.before).map_err(|e| e.to_string())?;
509 Ok(JobsRunsResult { runs: runs.into_iter().map(JobRunRow::from).collect() })
510 })
511 .await
512 .map_err(|e| e.to_string())?
513}
514
515fn caller_of(state: &AppState, ctx: &RpcContext) -> Result<Option<Caller>, String> {
520 if ctx.agent_id.is_empty() {
521 ctx.operator_only("a job is acted on by the operator or by an agent")?;
522 return Ok(None);
523 }
524 state
525 .reactive_handler
526 .list_agents()
527 .into_iter()
528 .find(|r| r.agent_id.eq_ignore_ascii_case(&ctx.agent_id))
529 .and_then(|r| r.uid)
530 .filter(|u| !u.is_empty())
531 .map(|uid| Some(Caller::Agent { uid }))
532 .ok_or_else(|| "FORBIDDEN: this agent connection has no identity to act with".to_string())
533}
534
535fn answered(status: axum::http::StatusCode, body: &Value) -> Result<JobsActResult, String> {
538 let error = body.get("error").and_then(Value::as_str).map(str::to_string);
539 if !status.is_success() {
540 return Err(error.unwrap_or_else(|| format!("refused ({status})")));
541 }
542 let outcome = body.get("outcome").and_then(Value::as_str).map(str::to_string);
543 let ok = outcome.as_deref().is_none_or(|o| o == "delivered");
544 let run_id = body.get("run_id").and_then(Value::as_str).map(str::to_string);
545 Ok(JobsActResult { ok, run_id, outcome, error })
546}
547
548async fn act(state: &AppState, req: JobsActRequest, ctx: &RpcContext) -> Result<JobsActResult, String> {
549 match req.action.as_str() {
550 "pause_all" | "resume_all" => {
551 ctx.operator_only("only the operator can pause or resume every job")?;
552 let on = req.action == "pause_all";
553 let ledger = ledger(state)?;
554 tokio::task::spawn_blocking(move || ledger.set_paused_all(on, jobs::BY_OPERATOR))
555 .await
556 .map_err(|e| e.to_string())?
557 .map_err(|e| e.to_string())?;
558 state.broker.publish_event::<crate::backend::mps_events::CronChanged>(&(), vec![], 0);
559 Ok(JobsActResult { ok: true, ..Default::default() })
560 }
561 "run_now" | "pause" | "resume" | "delete" => {
562 let id = req.job_id.clone().filter(|id| !id.is_empty()).ok_or("which job? (job_id)")?;
563 let caller = caller_of(state, ctx)?.map(Extension);
564 let st = State(state.clone());
565 let (status, Json(body)) = match req.action.as_str() {
566 "run_now" => handle_cron_run_now(st, caller, Path(id)).await,
567 "delete" => handle_cron_delete(st, caller, Path(id)).await,
568 action => handle_cron_patch(st, caller, Path(id), Json(serde_json::json!({ "action": action }))).await,
569 };
570 let out = answered(status, &body);
571 if let Some(ledger) = state.cron_scheduler.runs() {
572 ledger.changed(req.job_id.as_deref().unwrap_or(""));
573 }
574 out
575 }
576 other => Err(format!("jobs.act: unknown action {other:?}")),
577 }
578}
579
580#[cfg(test)]
581#[path = "jobs_tests.rs"]
582mod tests;