agentmux_srv_core/backend/reactive/
controller_wait.rs1use std::sync::{Arc, OnceLock};
16
17pub const NO_CONTROLLER: &str = "no controller for block";
19
20type HasController = Arc<dyn Fn(&str) -> bool + Send + Sync>;
21
22static HAS_CONTROLLER: OnceLock<HasController> = OnceLock::new();
23
24pub fn set_has_controller(probe: HasController) {
27 let _ = HAS_CONTROLLER.set(probe);
28}
29
30pub fn awaits_controller(block_id: &str) -> bool {
33 HAS_CONTROLLER.get().is_some_and(|has| !has(block_id))
34}
35
36pub fn is_no_controller(error: &str) -> bool {
39 error.starts_with(NO_CONTROLLER)
40}
41
42pub fn controller_registered() {
45 super::held_jekt_wake().notify_one();
46 super::held_input_wake().notify_one();
47 crate::backend::jobs::pending_wake().notify_one();
48}
49
50#[cfg(any(test, feature = "test-support"))]
54pub mod testing {
55 use std::collections::HashSet;
56 use std::sync::{Arc, LazyLock, Mutex};
57
58 static WAITING: LazyLock<Mutex<HashSet<String>>> = LazyLock::new(Default::default);
59
60 fn waiting() -> std::sync::MutexGuard<'static, HashSet<String>> {
61 WAITING.lock().unwrap_or_else(|e| e.into_inner())
62 }
63
64 pub fn without_controller(block_id: &str) {
66 super::set_has_controller(Arc::new(|block_id: &str| !waiting().contains(block_id)));
67 waiting().insert(block_id.to_string());
68 }
69
70 pub fn controller_arrived(block_id: &str) {
72 waiting().remove(block_id);
73 super::controller_registered();
74 }
75}
76
77#[cfg(test)]
78mod tests {
79 use super::*;
80
81 #[test]
82 fn a_block_waits_only_while_the_probe_says_it_has_no_controller() {
83 let block = format!("cw-{}", uuid::Uuid::new_v4());
84 testing::without_controller(&block);
85 assert!(awaits_controller(&block));
86 assert!(!awaits_controller("some-other-block"), "every other block is untouched");
87 testing::controller_arrived(&block);
88 assert!(!awaits_controller(&block));
89 }
90
91 #[test]
92 fn the_no_controller_error_is_recognised_and_waits_like_a_starting_agent() {
93 let error = format!("{NO_CONTROLLER} blk-1");
94 assert!(is_no_controller(&error));
95 assert!(crate::backend::reactive::is_transient_delivery_error(&error), "retried, never counted as a refusal");
96 for other in ["agent not found: x", "persistent process not running", "NOT_RUNNING: no controller for block x", ""] {
97 assert!(!is_no_controller(other), "{other:?}");
98 }
99 }
100}