1use std::collections::HashMap;
17use std::sync::Arc;
18
19use serde_json::Value;
20
21use crate::backend::eventbus::EventBus;
22use crate::backend::mps::{Broker, MuxEvent, EVENT_AGENT_TURN};
23use crate::backend::obj::Block;
24use crate::backend::storage::store::Store;
25
26use super::app_api::agent_attach::{desired_of, set_running_unless_stopped_since, DESIRED_STOPPED};
27
28type Turn = (String, u64, u64);
30
31fn running_turn(event: &str, data: Option<&Value>) -> Option<Turn> {
33 if event != EVENT_AGENT_TURN {
34 return None;
35 }
36 let d = data?;
37 if d.get("end").is_some() || d.get("active").and_then(Value::as_bool) != Some(true) {
38 return None;
39 }
40 Some((d.get("block_id")?.as_str()?.to_string(), d.get("turn_id")?.as_u64()?, d.get("started_at_ms")?.as_u64()?))
41}
42
43fn is_new_turn(last: &mut HashMap<String, u64>, block_id: &str, turn_id: u64) -> bool {
46 if last.get(block_id).is_some_and(|seen| *seen >= turn_id) {
47 return false;
48 }
49 last.insert(block_id.to_string(), turn_id);
50 true
51}
52
53fn wake(mstore: &Store, block_id: &str, started_at_ms: u64) -> bool {
57 let Some(block) = mstore.get::<Block>(block_id).ok().flatten() else { return false };
58 if desired_of(&block).as_deref() != Some(DESIRED_STOPPED) {
59 return false;
60 }
61 let woke = set_running_unless_stopped_since(mstore, block_id, started_at_ms);
64 if woke {
65 tracing::info!(block_id, "a turn started on an agent recorded as stopped: it is wanted running again");
66 }
67 woke
68}
69
70pub(crate) fn install(broker: Arc<Broker>, mstore: Arc<Store>, event_bus: Arc<EventBus>) {
73 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Turn>();
74 broker.add_observer(Arc::new(move |ev: &MuxEvent| {
76 if let Some(turn) = running_turn(&ev.event, ev.data.as_ref()) {
77 let _ = tx.send(turn);
78 }
79 }));
80 tokio::spawn(async move {
81 let mut last = HashMap::new();
82 while let Some((block_id, turn_id, started_at_ms)) = rx.recv().await {
83 if !is_new_turn(&mut last, &block_id, turn_id) {
84 continue;
85 }
86 let (mstore, bus) = (Arc::clone(&mstore), Arc::clone(&event_bus));
87 let _ = tokio::task::spawn_blocking(move || {
88 if wake(&mstore, &block_id, started_at_ms) {
89 crate::backend::blockcontroller::core::broadcast_block_update(&mstore, &bus, &block_id);
90 }
91 })
92 .await;
93 }
94 });
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100 use super::super::app_api::agent_attach::{set_desired, stopped_at_ms};
101 use serde_json::json;
102
103 fn block_with(store: &Store, desired: Option<&str>) -> String {
104 let mut block = Block::default();
105 block.oid = uuid::Uuid::new_v4().to_string();
106 if let Some(d) = desired {
107 block.meta.insert("agent:desired".into(), json!(d));
108 }
109 store.insert(&mut block).unwrap();
110 block.oid
111 }
112
113 fn desired(store: &Store, id: &str) -> Option<String> {
114 desired_of(&store.get::<Block>(id).unwrap().unwrap())
115 }
116
117 #[test]
118 fn only_a_running_turn_of_the_turn_event_counts() {
119 let turn = |end: Option<&str>, active: bool| {
120 let mut d = json!({ "block_id": "b1", "turn_id": 7, "started_at_ms": 100, "active": active });
121 if let Some(e) = end {
122 d["end"] = json!(e);
123 }
124 d
125 };
126 assert_eq!(running_turn("agentturn", Some(&turn(None, true))), Some(("b1".into(), 7, 100)));
127 assert_eq!(running_turn("agentturn", Some(&turn(None, false))), None, "between passes");
128 assert_eq!(running_turn("agentturn", Some(&turn(Some("completed"), false))), None, "ended");
129 assert_eq!(running_turn("agentstatus", Some(&turn(None, true))), None, "another event");
130 }
131
132 #[test]
133 fn a_turn_is_new_once_and_an_older_one_arriving_late_is_not() {
134 let mut last = HashMap::new();
135 assert!(is_new_turn(&mut last, "b", 5));
136 assert!(!is_new_turn(&mut last, "b", 5), "the same turn's next publish");
137 assert!(!is_new_turn(&mut last, "b", 4), "an older turn");
138 assert!(is_new_turn(&mut last, "b", 6), "the next turn");
139 assert!(is_new_turn(&mut last, "other", 1), "each block has its own");
140 }
141
142 #[test]
146 fn a_turn_that_began_after_the_stop_records_the_agent_as_running() {
147 let store = Store::open_in_memory().unwrap();
148
149 let stopped = block_with(&store, Some("running"));
150 set_desired(&store, &stopped, DESIRED_STOPPED);
151 let at = stopped_at_ms(&stopped).unwrap();
152 assert!(wake(&store, &stopped, at + 1), "a turn began after the stop");
153 assert_eq!(desired(&store, &stopped).as_deref(), Some("running"));
154 assert!(stopped_at_ms(&stopped).is_none(), "the stop is no longer in force");
155
156 let quit_mid_turn = block_with(&store, Some("running"));
157 set_desired(&store, &quit_mid_turn, DESIRED_STOPPED);
158 let at = stopped_at_ms(&quit_mid_turn).unwrap();
159 assert!(!wake(&store, &quit_mid_turn, at.saturating_sub(5_000)), "the turn began before the stop was decided");
160 assert!(!wake(&store, &quit_mid_turn, at), "or as it was");
161 assert_eq!(desired(&store, &quit_mid_turn).as_deref(), Some("stopped"));
162
163 let stale = block_with(&store, Some("stopped"));
164 assert!(wake(&store, &stale, 1), "a stopped read from the database is older than any turn of this run");
165 assert_eq!(desired(&store, &stale).as_deref(), Some("running"));
166
167 let running = block_with(&store, Some("running"));
168 assert!(!wake(&store, &running, u64::MAX), "already wanted running");
169 assert!(!wake(&store, &block_with(&store, None), u64::MAX), "nothing recorded");
170 }
171}