1use std::collections::{HashMap, HashSet};
34use std::future::Future;
35use std::pin::Pin;
36use std::sync::Arc;
37use std::time::Duration;
38
39use futures_util::StreamExt;
40use serde_json::{json, Map, Value};
41use sha2::{Digest, Sha256};
42
43use super::definition::{event_source, trigger_kind};
44use crate::backend::cron::{CronScheduler, JobEvent};
45use crate::backend::storage::cron::CronJob;
46use crate::backend::storage::store::Store;
47
48pub const QUERIES: [&str; 5] = ["tasks", "jobs", "agents", "lan_peers", "api"];
50pub const MIN_EVERY_MINUTES: u64 = 1;
51pub const MAX_EVERY_MINUTES: u64 = 24 * 60;
52pub const MIN_API_EVERY_MINUTES: u64 = 5;
55pub const API_DEFAULT_ITEMS: usize = 100;
57pub const API_MAX_ITEMS: usize = 200;
58const MAX_TASKS: u64 = 200;
60const MAX_RUNS: u64 = 100;
61pub const MAX_NEW_PER_POLL: usize = 20;
63const TICK: Duration = Duration::from_secs(30);
65pub const API_ASKS_AT_ONCE: usize = 4;
68
69const COMMON_KEYS: [&str; 3] = ["query", "every_minutes", "include_existing"];
70
71pub type Check = Arc<dyn Fn(Map<String, Value>) -> Pin<Box<dyn Future<Output = Result<Value, String>> + Send>> + Send + Sync>;
74
75struct Shape {
77 items: &'static str,
78 id: &'static [&'static str],
79}
80
81fn shape_of(query: &str) -> Option<Shape> {
82 match query {
83 "tasks" => Some(Shape { items: "tasks", id: &["num"] }),
84 "jobs" => Some(Shape { items: "runs", id: &["id"] }),
85 "agents" => Some(Shape { items: "problems", id: &["agent", "state"] }),
86 "lan_peers" => Some(Shape { items: "peers", id: &["host"] }),
87 "api" => Some(Shape { items: "items", id: &["id"] }),
89 _ => None,
90 }
91}
92
93fn own_keys(query: &str) -> &'static [&'static str] {
95 match query {
96 "tasks" => &["holder", "state", "pr", "limit"],
97 "jobs" => &["job", "limit"],
98 "api" => &["url", "auth", "headers", "items", "id", "limit"],
99 _ => &[],
100 }
101}
102
103pub fn validate_filter(filter: &Map<String, Value>) -> Result<(), String> {
105 let query = filter.get("query").and_then(Value::as_str).unwrap_or("");
106 if !QUERIES.contains(&query) {
107 return Err(format!("trigger: a poll filter names its query, one of {}", QUERIES.join(", ")));
108 }
109 let own = own_keys(query);
110 if let Some(key) = filter.keys().find(|k| !COMMON_KEYS.contains(&k.as_str()) && !own.contains(&k.as_str())) {
111 let mut has: Vec<&str> = COMMON_KEYS.to_vec();
112 has.extend(own);
113 return Err(format!("trigger: a poll of {query} has no filter key {key:?}; it has {}", has.join(", ")));
114 }
115 match filter.get("every_minutes").and_then(Value::as_u64) {
116 Some(n) if (MIN_EVERY_MINUTES..=MAX_EVERY_MINUTES).contains(&n) => {}
117 _ => return Err(format!("trigger: a poll filter has every_minutes, a whole number of {MIN_EVERY_MINUTES} to {MAX_EVERY_MINUTES}")),
118 }
119 if filter.get("include_existing").is_some_and(|v| !v.is_boolean()) {
120 return Err("trigger: include_existing is true or false".to_string());
121 }
122 for key in ["holder", "state", "pr", "job"] {
123 if filter.get(key).is_some_and(|v| !v.is_string()) {
124 return Err(format!("trigger: poll filter {key:?} is text"));
125 }
126 }
127 if query == "jobs" && !filter.get("job").and_then(Value::as_str).is_some_and(|j| !j.trim().is_empty()) {
128 return Err("trigger: a poll of jobs has job, the name or id of the job whose runs it watches".to_string());
130 }
131 if filter.get("limit").is_some_and(|v| !v.as_u64().is_some_and(|n| (1..=200).contains(&n))) {
132 return Err("trigger: poll filter \"limit\" is a whole number of 1 to 200".to_string());
133 }
134 if query == "api" {
135 validate_api_filter(filter)?;
136 }
137 Ok(())
138}
139
140fn validate_api_filter(filter: &Map<String, Value>) -> Result<(), String> {
142 let url = filter.get("url").and_then(Value::as_str).unwrap_or("").trim();
143 if url.is_empty() {
144 return Err("trigger: a poll of api has url, the https address of the list".to_string());
145 }
146 if url.contains("{{") {
147 return Err("trigger: a poll of api writes its url out: no {{reference}} in it".to_string());
148 }
149 let parsed = reqwest::Url::parse(url).map_err(|e| format!("trigger: the poll's url is not an address: {e}"))?;
150 if parsed.scheme() != "https" || parsed.host_str().is_none() || !parsed.username().is_empty() || parsed.password().is_some() {
151 return Err("trigger: a poll of api calls an https address with no user name or password in it".to_string());
152 }
153 if filter.get("every_minutes").and_then(Value::as_u64).is_some_and(|n| n < MIN_API_EVERY_MINUTES) {
154 return Err(format!("trigger: a poll of api asks at most every {MIN_API_EVERY_MINUTES} minutes: every_minutes is {MIN_API_EVERY_MINUTES} or more"));
155 }
156 if let Some(auth) = filter.get("auth").filter(|a| !a.is_null()) {
157 let obj = auth.as_object().ok_or("trigger: poll filter \"auth\" is { \"vault\": \"<entry>\", \"as\": \"bearer\" }")?;
159 if let Some(key) = obj.keys().find(|k| !matches!(k.as_str(), "vault" | "as")) {
160 return Err(format!("trigger: poll auth has no {key:?}: it takes vault and as"));
161 }
162 if !obj.get("vault").and_then(Value::as_str).is_some_and(|v| !v.trim().is_empty() && !v.contains("{{")) {
163 return Err("trigger: poll auth names its Vault entry in vault, written out".to_string());
164 }
165 }
166 if let Some(headers) = filter.get("headers") {
167 let Some(obj) = headers.as_object() else { return Err("trigger: poll filter \"headers\" is an object of text".to_string()) };
168 for (name, value) in obj {
169 if !value.is_string() || value.as_str().is_some_and(|v| v.contains("{{")) {
170 return Err(format!("trigger: poll header {name:?} is plain text, with no {{{{reference}}}}"));
171 }
172 }
173 }
174 for key in ["items", "id"] {
175 if filter.get(key).is_some_and(|v| !v.is_string()) {
176 return Err(format!("trigger: poll filter {key:?} is a dotted path, like data.items"));
177 }
178 }
179 Ok(())
180}
181
182#[derive(Debug, PartialEq)]
184struct Plan {
185 query: String,
186 every_ms: i64,
187 include_existing: bool,
188 ask: Map<String, Value>,
190 signature: String,
192}
193
194fn plan_of(job: &CronJob) -> Option<Plan> {
195 if !job.enabled || job.trigger_kind != trigger_kind::EVENT {
196 return None;
197 }
198 let t = &job.trigger_event;
199 if t.get("source").and_then(Value::as_str) != Some(event_source::POLL) {
200 return None;
201 }
202 let filter = t.get("filter").and_then(Value::as_object)?;
203 validate_filter(filter).ok()?;
204 let mut ask = filter.clone();
205 ask.remove("every_minutes");
206 match filter.get("query").and_then(Value::as_str) {
208 Some("tasks") => {
209 ask.entry("limit").or_insert(json!(MAX_TASKS));
210 }
211 Some("jobs") => {
212 ask.entry("limit").or_insert(json!(MAX_RUNS));
213 }
214 Some("api") => {
215 ask.entry("limit").or_insert(json!(API_DEFAULT_ITEMS));
216 }
217 _ => {}
218 }
219 let include_existing = ask.remove("include_existing").and_then(|v| v.as_bool()).unwrap_or(false);
220 let signature = hex::encode(&Sha256::digest(Value::Object(ask.clone()).to_string().as_bytes())[..6]);
221 Some(Plan {
222 query: filter.get("query").and_then(Value::as_str)?.to_string(),
223 every_ms: filter.get("every_minutes").and_then(Value::as_u64)? as i64 * 60_000,
224 include_existing,
225 ask,
226 signature,
227 })
228}
229
230fn part(item: &Value, field: &str) -> Option<String> {
232 match item.get(field)? {
233 Value::String(s) if !s.is_empty() => Some(s.clone()),
234 Value::Number(n) => Some(n.to_string()),
235 _ => None,
236 }
237}
238
239fn items_of(query: &str, answer: &Value) -> Vec<(String, Value)> {
241 let Some(shape) = shape_of(query) else { return Vec::new() };
242 let Some(items) = answer.get(shape.items).and_then(Value::as_array) else { return Vec::new() };
243 let mut seen = HashSet::new();
244 items
245 .iter()
246 .filter_map(|item| {
247 let parts = shape.id.iter().map(|f| part(item, f)).collect::<Option<Vec<_>>>()?;
248 let id = parts.join(":");
249 let item = if query == "api" { item.get("item").cloned()? } else { item.clone() };
251 seen.insert(id.clone()).then(|| (id, item))
252 })
253 .collect()
254}
255
256#[cfg(test)]
257pub(crate) fn items_of_for_test(query: &str, answer: &Value) -> Vec<(String, Value)> {
258 items_of(query, answer)
259}
260
261fn baseline_marker(signature: &str) -> String {
263 format!("poll:baseline:{signature}")
264}
265
266#[cfg(test)]
267pub(crate) fn marker_of_for_test(job: &CronJob) -> Option<String> {
268 plan_of(job).map(|p| baseline_marker(&p.signature))
269}
270
271fn event_id(query: &str, id: &str) -> String {
272 format!("poll:{query}:{id}")
273}
274
275struct JobPoll {
277 signature: String,
278 next_due_ms: i64,
279 seen: HashSet<String>,
281 baselined: bool,
282}
283
284#[derive(Default)]
286pub struct PollState {
287 jobs: HashMap<String, JobPoll>,
288}
289
290#[derive(Debug, Clone, Copy, PartialEq, Eq)]
294pub enum PollKind {
295 All,
297 Local,
299 Api,
301}
302
303impl PollKind {
304 fn takes(self, query: &str) -> bool {
305 match self {
306 PollKind::All => true,
307 PollKind::Local => query != "api",
308 PollKind::Api => query == "api",
309 }
310 }
311}
312
313pub async fn poll_due(scheduler: &CronScheduler, all: &[CronJob], check: &Check, state: &mut PollState, now: i64) -> usize {
316 poll_due_of(PollKind::All, scheduler, all, check, state, now).await
317}
318
319pub async fn poll_due_of(kind: PollKind, scheduler: &CronScheduler, all: &[CronJob], check: &Check, state: &mut PollState, now: i64) -> usize {
322 let Some(ledger) = scheduler.runs().cloned() else { return 0 };
325 let store = ledger.store().clone();
326 let polling: Vec<(&CronJob, Plan)> = all.iter().filter_map(|j| plan_of(j).map(|p| (j, p))).filter(|(_, p)| kind.takes(&p.query)).collect();
327 state.jobs.retain(|id, _| polling.iter().any(|(j, _)| &j.id == id));
329 let mut offered = 0;
330 let mut due: Vec<(usize, Map<String, Value>)> = Vec::new();
332 for (idx, (job, plan)) in polling.iter().enumerate() {
333 let st = state.jobs.entry(job.id.clone()).or_insert_with(|| JobPoll { signature: plan.signature.clone(), next_due_ms: now, seen: HashSet::new(), baselined: false });
334 if st.signature != plan.signature {
335 *st = JobPoll { signature: plan.signature.clone(), next_due_ms: now, seen: HashSet::new(), baselined: false };
336 }
337 if now < st.next_due_ms {
338 continue;
339 }
340 st.next_due_ms = now + plan.every_ms;
341 let mut question = plan.ask.clone();
342 if plan.query == "api" {
343 let drone = (job.action_kind == super::definition::action_kind::DRONE).then(|| job.action.get("drone_id").and_then(Value::as_str)).flatten();
345 question.insert("drone_id".to_string(), json!(drone.unwrap_or("")));
346 }
347 due.push((idx, question));
348 }
349 let at_once = if kind == PollKind::Api { API_ASKS_AT_ONCE } else { 1 };
350 let answers: Vec<(usize, Result<Value, String>)> = futures_util::stream::iter(due)
351 .map(|(idx, question)| {
352 let asking = check(question);
353 async move { (idx, asking.await) }
354 })
355 .buffered(at_once)
356 .collect()
357 .await;
358 for (idx, answer) in answers {
359 let (job, plan) = &polling[idx];
360 let Some(st) = state.jobs.get_mut(&job.id) else { continue };
361 let answer = match answer {
362 Ok(answer) => answer,
363 Err(e) => {
364 tracing::warn!(job_id = %job.id, query = %plan.query, error = %e, "jobs: a poll's question failed; asking again next time");
365 continue;
366 }
367 };
368 let items = items_of(&plan.query, &answer);
369 let present: HashSet<String> = items.iter().map(|(id, _)| id.clone()).collect();
370 let marker = baseline_marker(&plan.signature);
371 if !plan.include_existing {
372 let _ = store.job_event_touch(&job.id, &marker, now);
375 }
376 if !st.baselined {
377 if !plan.include_existing {
378 let ids: Vec<String> = items.iter().map(|(id, _)| event_id(&plan.query, id)).collect();
381 match store.job_event_claim_baseline(&job.id, &marker, &ids, now) {
382 Ok(true) => {
383 st.baselined = true;
384 st.seen = present;
385 continue;
386 }
387 Ok(false) => {}
388 Err(e) => {
389 tracing::warn!(job_id = %job.id, error = %e, "jobs: a poll couldn't record its first look; trying again next time");
391 continue;
392 }
393 }
394 }
395 st.baselined = true;
396 }
397 let mut started = 0;
398 for (id, item) in items {
399 if st.seen.contains(&id) {
400 continue;
401 }
402 if started >= MAX_NEW_PER_POLL {
403 break;
404 }
405 started += 1;
406 st.seen.insert(id.clone());
407 let input = json!({ "query": plan.query, "key": id, "item": item });
408 let fired = scheduler.fire_event(job, JobEvent { id: event_id(&plan.query, &id), source: event_source::POLL.to_string(), input }).await;
409 offered += usize::from(fired.run_id.is_some());
411 }
412 st.seen.retain(|id| present.contains(id));
413 }
414 offered
415}
416
417pub fn spawn(jobs: Arc<Store>, scheduler: Arc<CronScheduler>, check: Check) {
420 if tokio::runtime::Handle::try_current().is_err() {
421 return;
422 }
423 {
424 let (jobs, scheduler, check) = (jobs.clone(), scheduler.clone(), check.clone());
425 tokio::spawn(async move {
426 let mut state = PollState::default();
427 let mut expects = super::expect::ExpectState::default();
428 loop {
429 tokio::time::sleep(TICK).await;
430 let all = enabled_jobs(&jobs).await;
431 let now = agentmux_common::time::now_ms();
432 poll_due_of(PollKind::Local, &scheduler, &all, &check, &mut state, now).await;
433 super::expect::expect_due(&scheduler, &all, &check, &mut expects, now).await;
434 }
435 });
436 }
437 tokio::spawn(async move {
438 let mut state = PollState::default();
439 loop {
440 tokio::time::sleep(TICK).await;
441 let all = enabled_jobs(&jobs).await;
442 poll_due_of(PollKind::Api, &scheduler, &all, &check, &mut state, agentmux_common::time::now_ms()).await;
443 }
444 });
445}
446
447async fn enabled_jobs(jobs: &Arc<Store>) -> Vec<CronJob> {
448 let listing = jobs.clone();
449 tokio::task::spawn_blocking(move || listing.cron_list_enabled()).await.ok().and_then(Result::ok).unwrap_or_default()
450}