agentmux_srv/drone/executor/scheduler/
wait.rs1use serde_json::{json, Value};
16
17use super::Scheduler;
18use crate::drone::executor::schedule;
19use crate::backend::drone_wait;
20use crate::drone::executor::blocks::approval::{self, Card};
21use crate::drone::executor::blocks::wait::{self as config, Wait};
22use crate::drone::executor::engine::RunEvent;
23use crate::drone::types::FlowNode;
24use agentmux_common::time::now_ms;
25
26struct OpenKey(String, Option<(String, String)>);
29
30impl Drop for OpenKey {
31 fn drop(&mut self) {
32 drone_wait::close(&self.0);
33 if let Some((run, block)) = &self.1 {
34 crate::backend::drone_approval::forget(run, block);
35 }
36 }
37}
38
39impl<'a> Scheduler<'a> {
40 pub(super) async fn run_wait(&mut self, node: &'a FlowNode) -> Result<Value, String> {
43 let wait = config::parse(node, &|t| self.scope.resolve(t), now_ms())?;
44 self.wait_for(node, wait, None).await
45 }
46
47 pub(super) async fn run_approval(&mut self, node: &'a FlowNode) -> Result<Value, String> {
50 let card = approval::card(node, &self.scope)?;
51 let limit = schedule::timeout_seconds(node)?.unwrap_or(approval::DEFAULT_TIMEOUT_S);
52 match self.wait_for(node, Wait::On("approval".to_string()), Some((card, limit))).await {
53 Ok(done) => approval::decide(done.get("payload").unwrap_or(&Value::Null)),
54 Err(e) if e.starts_with("timed out") => Err(format!("approval_timeout: nobody answered ({e})")),
55 Err(e) => Err(e),
56 }
57 }
58
59 async fn wait_for(&mut self, node: &'a FlowNode, wait: Wait, approval: Option<(Card, u64)>) -> Result<Value, String> {
60 let id = node.id.as_str();
61 let now = now_ms();
62 let restored_at = self.deadlines.get(id).copied();
63 let restored_key = self.resume_on.get(id).cloned();
64 let restored = restored_at.is_some() || restored_key.is_some();
65 let limit_s = match &approval {
67 Some((_, limit)) => Some(*limit),
68 None => schedule::timeout_seconds(node)?,
69 };
70 let timeout_at = self.wait_timeouts.get(id).copied().or_else(|| limit_s.map(|s| now.saturating_add(i64::try_from(s).unwrap_or(i64::MAX) * 1000)));
71 let timed_out = || Err(format!("timed out after {}", super::plain_duration(std::time::Duration::from_secs(limit_s.unwrap_or(0)))));
72
73 let (at, event) = match &wait {
75 Wait::For(ms) => (Some(restored_at.unwrap_or(now.saturating_add(*ms))), None),
76 Wait::Until(at) => (Some(*at), None),
77 Wait::On(_) if timeout_at.is_some_and(|t| t <= now) => return timed_out(),
80 Wait::On(label) => {
81 let key = restored_key.unwrap_or_else(drone_wait::new_key);
82 let rx = drone_wait::open(&key);
83 (None, Some((label.clone(), key, rx)))
84 }
85 };
86 if let (Some(at), Some(t)) = (at, timeout_at) {
88 if t < at && t <= now {
89 return timed_out();
90 }
91 }
92 let _open = event.as_ref().map(|(_, key, _)| OpenKey(key.clone(), approval.as_ref().map(|_| (self.run_id.to_string(), id.to_string()))));
93 if let (Some((card, _)), Some((_, key, _)), Some(deadline)) = (&approval, &event, timeout_at) {
94 crate::backend::drone_approval::register(
95 crate::backend::drone_approval::DroneApproval {
96 run_id: self.run_id.to_string(),
97 block_id: id.to_string(),
98 drone_id: self.scope.drone_id.clone(),
99 title: card.title.clone(),
100 items: card.items.clone(),
101 deadline_ms: deadline,
102 },
103 key,
104 );
105 }
106 if let Some(at) = at {
107 self.deadlines.insert(id.to_string(), at);
108 }
109 if let Some((_, key, _)) = &event {
110 self.resume_on.insert(id.to_string(), key.clone());
111 }
112 if let Some(t) = timeout_at {
113 self.wait_timeouts.insert(id.to_string(), t);
114 }
115 if !restored {
116 self.checkpoint_required(id)?;
118 }
119 let _ = self.tx.send(RunEvent::Waiting {
120 run_id: self.run_id.to_string(),
121 block_id: id.to_string(),
122 resume_at: at,
123 on: event.as_ref().map(|(label, _, _)| label.clone()),
124 key: event.as_ref().filter(|_| approval.is_none()).map(|(_, key, _)| key.clone()),
126 });
127
128 let until_timeout = || timeout_at.map(|t| u64::try_from(t - now_ms()).unwrap_or(0));
130 if let Some(at) = at {
131 if let Some(t) = timeout_at.filter(|t| *t < at) {
133 tokio::time::sleep(std::time::Duration::from_millis(u64::try_from(t - now_ms()).unwrap_or(0))).await;
134 return timed_out();
135 }
136 let left = at - now_ms();
137 if left > 0 {
138 tokio::time::sleep(std::time::Duration::from_millis(u64::try_from(left).unwrap_or(0))).await;
139 }
140 let late_ms = if restored_at.is_some() { (now - at).max(0) } else { 0 };
142 return Ok(json!({ "resume_at": at, "late": late_ms > 0, "late_ms": late_ms }));
143 }
144 let Some((label, _, rx)) = event else { return Err("the wait has nothing to wait for".to_string()) };
145 let payload = match until_timeout() {
146 Some(t) => tokio::select! {
147 biased;
148 () = tokio::time::sleep(std::time::Duration::from_millis(t)) => return timed_out(),
149 payload = rx => payload,
150 },
151 None => rx.await,
152 }
153 .map_err(|_| "the run stopped waiting for its event".to_string())?;
154 Ok(json!({ "on": label, "payload": payload, "late": false, "late_ms": 0 }))
155 }
156
157 pub(super) fn end_wait(&mut self, id: &str, late: bool) {
159 self.waiting = None;
160 self.deadlines.remove(id);
161 self.resume_on.remove(id);
162 self.wait_timeouts.remove(id);
163 let _ = self.tx.send(RunEvent::WaitEnded { run_id: self.run_id.to_string(), block_id: id.to_string(), late });
164 }
165}