agentmux_srv_core/muxbus/
relay_watch.rs1use std::collections::VecDeque;
15use std::sync::Mutex;
16use std::time::Duration;
17
18use serde_json::{json, Value};
19
20use crate::backend::reactive::handler::ReactiveHandler;
21use crate::backend::reactive::types::InjectionResponse;
22use crate::muxbus::delivery_status::notes::NOTE_MARKER;
23
24pub const RELAY_HOLD_MS: u64 = 30 * 60 * 1000;
26
27const SLACK_MS: u64 = 60 * 1000;
30
31const MAX_WATCHED: usize = 256;
33
34#[derive(Debug, Clone, PartialEq, Eq)]
35struct Watched {
36 id: String,
37 from: String,
39 to: String,
41 queued_ms: u64,
42}
43
44#[derive(Debug, Default)]
45struct Book {
46 entries: VecDeque<Watched>,
47}
48
49impl Book {
50 fn add(&mut self, w: Watched) {
51 if self.entries.len() >= MAX_WATCHED {
52 self.entries.pop_front();
53 }
54 self.entries.push_back(w);
55 }
56
57 fn heard_from(&mut self, sender: &str, receiver: &str) -> usize {
59 let before = self.entries.len();
60 self.entries.retain(|w| !(w.to.eq_ignore_ascii_case(sender) && w.from.eq_ignore_ascii_case(receiver)));
61 before - self.entries.len()
62 }
63
64 fn take(&mut self, id: &str) -> Option<Watched> {
65 let i = self.entries.iter().position(|w| w.id == id)?;
66 self.entries.remove(i)
67 }
68}
69
70static BOOK: Mutex<Book> = Mutex::new(Book { entries: VecDeque::new() });
71
72fn book() -> std::sync::MutexGuard<'static, Book> {
73 BOOK.lock().unwrap_or_else(|e| e.into_inner())
74}
75
76fn unconfirmed_note(w: &Watched) -> String {
78 format!(
79 "{NOTE_MARKER} Your message {id} to {to} went to the cloud relay {mins} minutes ago and was never confirmed \
80 delivered. The relay drops a message nobody has picked up after {mins} minutes, and {to} has not written to \
81 you since, so treat it as not received: send it again once {to} is running, or reach {to} another way \
82 (Agents list shows who is running).",
83 id = w.id,
84 to = w.to,
85 mins = RELAY_HOLD_MS / 60_000,
86 )
87}
88
89pub fn watch(handler: &'static ReactiveHandler, from: &str, to: &str, id: &str) {
92 if from.is_empty() || to.is_empty() || id.is_empty() {
93 return;
94 }
95 let w = Watched { id: id.to_string(), from: from.to_string(), to: to.to_string(), queued_ms: agentmux_common::time::now_ms_u64() };
96 book().add(w.clone());
97 tokio::spawn(async move {
98 tokio::time::sleep(Duration::from_millis(RELAY_HOLD_MS + SLACK_MS)).await;
99 let Some(due) = book().take(&w.id) else { return };
100 if let Err(e) = handler.hold_system_note(&due.from, &format!("relay-unconfirmed:{}", due.id), &unconfirmed_note(&due)) {
101 tracing::debug!(error = %e, id = %due.id, queued_ms = due.queued_ms, "relay unconfirmed note not held");
102 }
103 });
104}
105
106pub fn heard_from(sender: Option<&str>, receiver: &str) {
109 if let Some(sender) = sender.filter(|s| !s.is_empty()) {
110 book().heard_from(sender, receiver);
111 }
112}
113
114pub fn queued_answer(request_id: String, target_in_account: Option<bool>, lan_peers: Vec<String>, timestamp: u64) -> Value {
120 let body = InjectionResponse {
121 deferred: None,
122 success: true,
123 request_id,
124 block_id: None,
125 error: None,
126 timestamp,
127 effective_tier: None,
131 requires_stop: None,
132 channel_verified: None,
133 };
134 let mut body = serde_json::to_value(&body).unwrap_or_default();
135 if let Some(obj) = body.as_object_mut() {
136 if let Some(in_account) = target_in_account {
139 obj.insert("target_in_account".to_string(), Value::Bool(in_account));
140 }
141 obj.insert("lan_peers".to_string(), json!(lan_peers));
142 }
143 body
144}
145
146#[cfg(test)]
147mod tests {
148 use super::*;
149
150 fn w(id: &str, from: &str, to: &str) -> Watched {
151 Watched { id: id.into(), from: from.into(), to: to.into(), queued_ms: 1 }
152 }
153
154 #[test]
155 fn a_reply_from_the_target_stops_the_note_and_nothing_else_does() {
156 let mut b = Book::default();
157 b.add(w("inj-1", "agent2-5", "lazo"));
158 b.add(w("inj-2", "agent2-5", "posa"));
159 assert_eq!(b.heard_from("manoz", "agent2-5"), 0);
161 assert_eq!(b.heard_from("agent2-5", "lazo"), 0);
162 assert_eq!(b.heard_from("Lazo", "AGENT2-5"), 1);
164 assert!(b.take("inj-1").is_none());
165 assert_eq!(b.take("inj-2").map(|x| x.to), Some("posa".to_string()));
166 assert!(b.take("inj-2").is_none(), "a message is reported once");
167 }
168
169 #[test]
170 fn the_book_is_bounded_and_forgets_the_oldest() {
171 let mut b = Book::default();
172 for i in 0..(MAX_WATCHED + 5) {
173 b.add(w(&format!("inj-{i}"), "a", "b"));
174 }
175 assert_eq!(b.entries.len(), MAX_WATCHED);
176 assert!(b.take("inj-0").is_none());
177 assert!(b.take(&format!("inj-{}", MAX_WATCHED + 4)).is_some());
178 }
179
180 #[test]
181 fn the_note_names_the_target_and_the_message_and_never_says_lost() {
182 let note = unconfirmed_note(&w("inj-w-ab84", "agent2-5", "lazo"));
183 assert!(note.starts_with(NOTE_MARKER), "{note}");
184 assert!(note.contains("inj-w-ab84") && note.contains("lazo") && note.contains("30 minutes"), "{note}");
185 assert!(note.contains("never confirmed delivered"), "{note}");
186 }
187
188 #[test]
189 fn the_window_is_what_the_send_answer_promises() {
190 assert_eq!(RELAY_HOLD_MS, 30 * 60 * 1000);
191 }
192
193 #[test]
194 fn the_queued_answer_carries_the_hint_fields() {
195 let v = queued_answer("inj-w-1".into(), Some(false), vec!["Area54/stable (Microsoft Store, no agents)".into()], 7);
196 assert_eq!(v["success"], true);
197 assert_eq!(v["request_id"], "inj-w-1");
198 assert_eq!(v["target_in_account"], false);
199 assert_eq!(v["lan_peers"][0], "Area54/stable (Microsoft Store, no agents)");
200 let v = queued_answer("inj-w-2".into(), None, vec![], 7);
202 assert!(v.get("target_in_account").is_none());
203 assert_eq!(v["lan_peers"], json!([]));
204 }
205}