agentmux_srv_core/backend/jobs/admission/
events.rs1use agentmux_common::time::now_ms;
20use serde_json::Value;
21
22use super::Admission;
23use crate::backend::jobs::definition::{DEFAULT_EVENT_RATE_PER_HOUR, MAX_EVENT_DELAY_MINUTES, MAX_EVENT_RATE_PER_HOUR};
24use crate::backend::jobs::caps::Refusal;
25use crate::backend::jobs::policy::Decision;
26use crate::backend::jobs::{Begin, RunLedger, BY_EVENT, SOURCE_CRON, TRIGGER_EVENT};
27use crate::backend::storage::cron::CronJob;
28use crate::backend::storage::job_events::{INPUT_KEEP_MS, KEEP_MS};
29use crate::backend::storage::job_runs::{reason, state, JobRun};
30
31impl RunLedger {
32 pub fn event_input(&self, run_id: &str) -> Option<Value> {
35 self.store.job_event_input_get(run_id).unwrap_or_else(|e| {
36 tracing::warn!(run_id, error = %e, "jobs: couldn't read an event's input");
37 None
38 })
39 }
40
41 pub(in crate::backend::jobs) fn drop_event_input(&self, run_id: &str) {
43 if let Err(e) = self.store.job_event_input_drop(run_id) {
44 tracing::warn!(run_id, error = %e, "jobs: couldn't let go of an event's input");
45 }
46 }
47
48 pub(in crate::backend::jobs) fn carry_event_input(&self, from: &str, to: &str) {
50 if let Err(e) = self.store.job_event_input_carry(from, to) {
51 tracing::warn!(run_id = from, error = %e, "jobs: couldn't hand an event's input to its retry");
52 }
53 }
54
55 pub fn admit_event(&self, job: &CronJob, event_id: &str, source: &str, input: &Value) -> Admission {
59 let _one_at_a_time = self.admission.lock().unwrap_or_else(|e| e.into_inner());
60 let now = now_ms();
61 let id = uuid::Uuid::new_v4().to_string();
62 match self.store.job_event_claim(&job.id, event_id, &id, now) {
63 Ok(true) => {
64 if let Err(e) = self.store.job_events_forget_before(now - KEEP_MS).and(self.store.job_event_inputs_forget_before(now - INPUT_KEEP_MS)) {
65 tracing::warn!(error = %e, "jobs: couldn't forget old event ids");
66 }
67 }
68 Ok(false) => return Admission::Taken,
69 Err(e) => {
70 tracing::warn!(job_id = %job.id, error = %e, "jobs: couldn't record an event; firing it unrecorded");
71 return Admission::Unrecorded;
72 }
73 }
74 let admission = self.admit_claimed(job, id, source, input, now);
75 if matches!(admission, Admission::Skipped | Admission::Capped(_) | Admission::Refused) {
76 if let Err(e) = self.store.job_event_unadmit(&job.id, event_id) {
77 tracing::warn!(job_id = %job.id, error = %e, "jobs: couldn't mark an event as not started");
78 }
79 }
80 admission
81 }
82
83 fn admit_claimed(&self, job: &CronJob, id: String, source: &str, input: &Value, now: i64) -> Admission {
85 if self.paused_all().is_some() {
86 return self.skip_event(job, id, source, reason::PAUSED_ALL);
87 }
88 let heard = self.store.job_events_since(&job.id, now - HOUR_MS).unwrap_or(0);
90 if heard > event_rate_limit(job) {
91 let first = self.first_cap_skip_today(job);
92 let skipped = self.skip_event(job, id, source, reason::RATE);
93 if first {
94 self.alert_cap(job, Refusal::Rate);
95 }
96 return skipped;
97 }
98 let delay_ms = event_delay_ms(job);
99 if delay_ms > 0 {
100 return self.hold_for_delay(job, id, source, input, now, delay_ms);
101 }
102 let decision = self.decide(job, false);
103 if decision == Decision::SkipOverlap {
104 return self.skip_event(job, id, source, reason::OVERLAP);
105 }
106 let mut account = String::new();
107 if matches!(decision, Decision::Start | Decision::CancelThenStart) {
108 let gate = self.cap_gate(job);
109 if let Some(refusal) = gate.refusal {
110 if let Begin::Run(run_id) = self.begin_event(job, &id, source, now) {
111 self.skip_run_for_cap(&run_id, job, refusal);
112 }
113 return Admission::Skipped;
114 }
115 account = gate.account;
116 }
117 let run_id = match self.begin_event(job, &id, source, now) {
118 Begin::Run(run_id) => run_id,
119 Begin::SlotTaken => return Admission::Taken,
120 Begin::Unrecorded => return Admission::Unrecorded,
121 };
122 self.note_account(&run_id, &account);
123 self.keep_event_input(&run_id, &job.id, input, now);
124 match decision {
125 Decision::Wait(why) => {
126 if let Err(e) = self.store.job_run_set_wait(&run_id, why) {
127 tracing::warn!(run_id = %run_id, error = %e, "jobs: couldn't make an event's run wait");
128 }
129 self.changed(&job.id);
130 self.ask_remote_stops(job, decision);
131 Admission::Waiting(run_id, why)
132 }
133 Decision::CancelThenStart => {
134 self.cancel_started(job);
135 Admission::Run(run_id)
136 }
137 Decision::Start | Decision::SkipOverlap => Admission::Run(run_id),
138 }
139 }
140
141 fn event_row(&self, job: &CronJob, run_id: &str, source: &str, now: i64) -> JobRun {
143 let mut run = JobRun::new(run_id, &job.id, SOURCE_CRON, &job.name, TRIGGER_EVENT, state::SCHEDULED, now);
144 run.recorded_by = self.recorded_by.clone();
145 run.triggered_by = format!("{BY_EVENT}:{source}");
146 run.target_agent_uid = job.target_uid.clone();
147 run
148 }
149
150 fn begin_event(&self, job: &CronJob, run_id: &str, source: &str, now: i64) -> Begin {
152 let run = self.event_row(job, run_id, source, now);
153 match self.store.job_run_insert(&run) {
154 Ok(true) => Begin::Run(run.id),
155 Ok(false) => Begin::SlotTaken,
156 Err(e) => {
157 tracing::warn!(job_id = %job.id, error = %e, "jobs: couldn't record an event's run");
158 Begin::Unrecorded
159 }
160 }
161 }
162
163 fn hold_for_delay(&self, job: &CronJob, run_id: String, source: &str, input: &Value, now: i64, delay_ms: i64) -> Admission {
165 let mut run = self.event_row(job, &run_id, source, now);
166 run.reason = reason::DELAY_WAIT.to_string();
167 run.links = serde_json::json!({ "due_at_ms": now + delay_ms });
168 match self.store.job_run_insert(&run) {
169 Ok(true) => {}
170 Ok(false) => return Admission::Taken,
171 Err(e) => {
172 tracing::warn!(job_id = %job.id, error = %e, "jobs: couldn't record a delayed event's run");
173 return Admission::Unrecorded;
174 }
175 }
176 self.keep_event_input(&run_id, &job.id, input, now);
177 self.changed(&job.id);
178 Admission::Waiting(run_id, reason::DELAY_WAIT)
179 }
180
181 fn keep_event_input(&self, run_id: &str, job_id: &str, input: &Value, now: i64) {
183 if let Err(e) = self.store.job_event_input_put(run_id, job_id, input, now) {
184 tracing::warn!(run_id, error = %e, "jobs: couldn't keep an event's input");
185 }
186 }
187
188 fn skip_event(&self, job: &CronJob, run_id: String, source: &str, why: &str) -> Admission {
190 if let Begin::Run(id) = self.begin_event(job, &run_id, source, now_ms()) {
191 if let Err(e) = self.store.job_run_skip(&id, why, 1, now_ms()) {
192 tracing::warn!(run_id = %id, error = %e, "jobs: couldn't skip an event's run");
193 }
194 }
195 self.changed(&job.id);
196 Admission::Skipped
197 }
198}
199
200fn event_delay_ms(job: &CronJob) -> i64 {
202 let minutes = job.trigger_event.get("delay").and_then(Value::as_u64).unwrap_or(0);
203 i64::try_from(minutes.min(u64::from(MAX_EVENT_DELAY_MINUTES))).unwrap_or(0) * 60_000
204}
205
206const HOUR_MS: i64 = 3_600_000;
207
208fn event_rate_limit(job: &CronJob) -> i64 {
210 let n = job.trigger_event.get("max_per_hour").and_then(Value::as_u64).unwrap_or(u64::from(DEFAULT_EVENT_RATE_PER_HOUR));
211 i64::try_from(n.clamp(1, u64::from(MAX_EVENT_RATE_PER_HOUR))).unwrap_or(1)
212}