agentmux_srv_core/backend/cron/
start.rs1use std::future::Future;
9use std::pin::Pin;
10use std::sync::Arc;
11
12use super::{CronScheduler, FireOutcome, Fired};
13use crate::backend::jobs;
14use crate::backend::storage::cron::CronJob;
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum ActionOutcome {
19 Filed { work_id: String, num: i64 },
21 Spawned { block_id: String, def_id: String, slug: String, brief: String, keep: bool },
24 Drone,
27 Failed(String),
28}
29
30pub type ActionRunner = Arc<dyn Fn(CronJob, String) -> Pin<Box<dyn Future<Output = ActionOutcome> + Send>> + Send + Sync>;
33
34impl CronScheduler {
35 pub fn install_actions(&self, runner: ActionRunner) {
37 let _ = self.actions.set(runner);
38 }
39
40 pub(crate) async fn start_run(&self, job: &CronJob, run_id: Option<String>, scheduled: bool, late_for: Option<i64>) -> Fired {
44 let delivery_started = agentmux_common::time::now_ms();
45 let mut to_deliver = job.clone();
46 let mut worker_started = false;
47 if matches!(job.action_kind.as_str(), "task" | "spawn" | "drone") {
48 let acted = match self.actions.get() {
49 Some(runner) => runner(job.clone(), run_id.clone().unwrap_or_default()).await,
50 None => ActionOutcome::Failed("this build can't run the job's action here".to_string()),
51 };
52 match acted {
53 ActionOutcome::Filed { work_id, num } => {
54 if let (Some(runs), Some(run_id)) = (self.runs(), &run_id) {
55 let (runs, run_id, name) = (runs.clone(), run_id.clone(), job.name.clone());
56 let _ = tokio::task::spawn_blocking(move || runs.task_filed(&run_id, &name, &work_id, num)).await;
57 }
58 let outcome = FireOutcome::Delivered { block_id: None };
59 if scheduled {
60 self.record_result(&job.id, &outcome);
61 }
62 self.publish_changed();
63 return Fired { run_id, outcome: Some(outcome), waiting: None };
64 }
65 ActionOutcome::Drone => {
66 let outcome = FireOutcome::Delivered { block_id: None };
67 if scheduled {
68 self.record_result(&job.id, &outcome);
69 }
70 self.publish_changed();
71 return Fired { run_id, outcome: Some(outcome), waiting: None };
72 }
73 ActionOutcome::Failed(error) => return self.finish_undelivered(job, run_id, FireOutcome::Failed { error }, scheduled, delivery_started),
74 ActionOutcome::Spawned { block_id, def_id, slug, brief, keep } => {
75 if let (Some(runs), Some(run_id)) = (self.runs(), &run_id) {
76 let links = serde_json::json!({ "worker": { "block_id": block_id, "def_id": def_id, "keep": keep } });
77 let _ = runs.store().job_run_add_links(run_id, &links);
78 }
79 (to_deliver.target, to_deliver.target_uid, to_deliver.prompt) = (slug, def_id, brief);
80 worker_started = true;
81 }
82 }
83 }
84 let Some(mut outcome) = self.deliver(&to_deliver, run_id.as_deref(), late_for).await else {
85 let failed = FireOutcome::Failed { error: "no way to deliver".to_string() };
86 if let (Some(runs), Some(run_id)) = (self.runs(), &run_id) {
87 runs.record_delivery(run_id, &to_deliver, &failed, false, delivery_started);
88 }
89 return Fired { run_id, outcome: None, waiting: None };
90 };
91 if worker_started && !outcome.delivered() {
92 outcome = FireOutcome::Failed { error: format!("the spawned worker didn't take its brief ({:?})", outcome.miss_reason()) };
95 }
96 if let (Some(runs), Some(run_id)) = (self.runs(), &run_id) {
97 let (runs, run_id, job, o) = (runs.clone(), run_id.clone(), to_deliver.clone(), outcome.clone());
98 let _ = tokio::task::spawn_blocking(move || runs.record_delivery(&run_id, &job, &o, scheduled, delivery_started)).await;
99 }
100 if scheduled {
103 self.record_result(&job.id, &outcome);
104 }
105 self.publish_changed();
106 Fired { run_id, outcome: Some(outcome), waiting: None }
107 }
108
109 fn finish_undelivered(&self, job: &CronJob, run_id: Option<String>, outcome: FireOutcome, scheduled: bool, started_ms: i64) -> Fired {
111 if let (Some(runs), Some(run_id)) = (self.runs(), &run_id) {
112 runs.record_delivery(run_id, job, &outcome, scheduled, started_ms);
113 }
114 if scheduled {
115 self.record_result(&job.id, &outcome);
116 }
117 self.publish_changed();
118 Fired { run_id, outcome: Some(outcome), waiting: None }
119 }
120
121 pub(crate) async fn run_policy_pass(&self) -> usize {
125 let Some(runs) = self.runs().cloned() else { return 0 };
126 let started = {
127 let runs = runs.clone();
128 tokio::task::spawn_blocking(move || {
129 runs.enforce_timeouts();
130 runs.start_waiting()
131 })
132 .await
133 .unwrap_or_default()
134 };
135 let n = started.len();
136 for (run, job) in started {
137 let scheduled = run.trigger != jobs::TRIGGER_MANUAL && run.trigger != jobs::TRIGGER_RETRY;
138 let fired = self.start_run(&job, Some(run.id.clone()), scheduled, run.scheduled_for_ms).await;
139 if matches!(fired.outcome, Some(FireOutcome::Delivered { .. })) {
140 self.stop_at_max_fires(&job.id);
141 }
142 }
143 n
144 }
145}