agentmux_srv_core/backend/
drone_decision.rs1use std::collections::HashMap;
14use std::sync::{LazyLock, Mutex};
15
16use serde_json::Value;
17use tokio::sync::oneshot;
18
19#[derive(Debug, Clone, PartialEq)]
22pub enum Decision {
23 RunAgain,
25 Skip { output: Value },
29}
30
31static WAITING: LazyLock<Mutex<HashMap<String, oneshot::Sender<Decision>>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
33
34pub fn wait_for_decision(run_id: &str) -> oneshot::Receiver<Decision> {
37 let (tx, rx) = oneshot::channel();
38 WAITING.lock().unwrap_or_else(|e| e.into_inner()).insert(run_id.to_string(), tx);
39 rx
40}
41
42pub fn stop_waiting(run_id: &str) {
44 WAITING.lock().unwrap_or_else(|e| e.into_inner()).remove(run_id);
45}
46
47pub fn is_waiting(run_id: &str) -> bool {
49 WAITING.lock().unwrap_or_else(|e| e.into_inner()).contains_key(run_id)
50}
51
52pub fn decide(run_id: &str, decision: Decision) -> Result<(), String> {
55 let waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner()).remove(run_id);
56 let Some(tx) = waiting else { return Err(format!("run {run_id} is not waiting for an answer")) };
57 tx.send(decision).map_err(|_| format!("run {run_id} stopped waiting"))
58}
59
60#[cfg(test)]
61mod tests {
62 use super::*;
63 use serde_json::json;
64
65 #[tokio::test]
66 async fn a_waiting_run_gets_its_answer_once() {
67 let rx = wait_for_decision("decision-test-1");
68 assert!(is_waiting("decision-test-1"));
69 decide("decision-test-1", Decision::Skip { output: json!({ "value": 1 }) }).unwrap();
70 assert_eq!(rx.await.unwrap(), Decision::Skip { output: json!({ "value": 1 }) });
71 assert!(!is_waiting("decision-test-1"));
72 assert!(decide("decision-test-1", Decision::RunAgain).is_err(), "a second answer finds nothing waiting");
73 }
74
75 #[test]
76 fn a_run_that_is_not_waiting_cannot_be_answered() {
77 assert!(decide("decision-test-none", Decision::RunAgain).is_err());
78 }
79
80 #[tokio::test]
81 async fn a_run_that_stopped_waiting_is_not_answered() {
82 let rx = wait_for_decision("decision-test-2");
83 drop(rx);
84 assert!(decide("decision-test-2", Decision::RunAgain).is_err());
86 let _rx = wait_for_decision("decision-test-3");
87 stop_waiting("decision-test-3");
88 assert!(!is_waiting("decision-test-3"));
89 }
90}