1use std::collections::HashMap;
18use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
19use std::sync::Arc;
20
21use axum::body::Bytes;
22use base64::Engine as _;
23use serde::Serialize;
24use tokio::sync::mpsc;
25
26use crate::backend::agent_state::AgentStatus;
27use crate::backend::mps::{self, MuxEvent, StreamPos};
28
29pub const MAX_BEHIND_BYTES: usize = 1024 * 1024;
31pub const TERM_FILE: &str = "term";
33pub const MAX_FRAME_BYTES: usize = 64 * 1024;
35pub const TRUNCATED_HEAD_CHARS: usize = 2048;
37
38pub fn wire_size(records: &[u8]) -> usize {
45 records
46 .split(|b| *b == b'\n')
47 .map(|line| {
48 let kept = &line[..line.len().min(MAX_FRAME_BYTES)];
49 let escapes: usize = kept
50 .iter()
51 .map(|b| match b {
52 b'"' | b'\\' | b'\t' | b'\r' | 0x08 | 0x0c => 1,
53 0..=0x1f => 5,
54 _ => 0,
55 })
56 .sum();
57 kept.len() + escapes + 1
58 })
59 .sum()
60}
61
62fn queued_size(filename: &str, records: &[u8]) -> usize {
65 if filename == TERM_FILE {
66 records.len()
67 } else {
68 wire_size(records)
69 }
70}
71
72#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum HubEvent {
75 Append { pos: Vec<StreamPos>, offset: Option<u64>, records: Vec<u8> },
79 Rewritten { fileop: String },
82 Behind,
84}
85
86struct Subscriber {
87 id: u64,
88 tx: mpsc::UnboundedSender<HubEvent>,
89 pending: Arc<AtomicUsize>,
91 behind: Arc<AtomicBool>,
92}
93
94pub struct FeedHub {
96 subs: parking_lot::RwLock<HashMap<(String, String), Vec<Subscriber>>>,
97 next_id: AtomicU64,
98 max_behind: usize,
99}
100
101impl Default for FeedHub {
102 fn default() -> Self {
103 Self::with_max_behind(MAX_BEHIND_BYTES)
104 }
105}
106
107impl FeedHub {
108 pub fn with_max_behind(max_behind: usize) -> Self {
109 Self {
110 subs: parking_lot::RwLock::new(HashMap::new()),
111 next_id: AtomicU64::new(1),
112 max_behind,
113 }
114 }
115
116 pub fn install(self: &Arc<Self>, broker: &mps::Broker) {
118 let hub = Arc::clone(self);
119 broker.add_observer(Arc::new(move |event: &MuxEvent| hub.observe(event)));
120 }
121
122 pub fn subscribe(self: &Arc<Self>, block_id: &str) -> FeedSubscription {
126 self.subscribe_file(block_id, crate::backend::agent_session::OUTPUT_FILE)
127 }
128
129 pub fn subscribe_file(self: &Arc<Self>, block_id: &str, filename: &str) -> FeedSubscription {
132 let (tx, rx) = mpsc::unbounded_channel();
133 let id = self.next_id.fetch_add(1, Ordering::Relaxed);
134 let pending = Arc::new(AtomicUsize::new(0));
135 let behind = Arc::new(AtomicBool::new(false));
136 let key = (block_id.to_string(), filename.to_string());
137 self.subs.write().entry(key.clone()).or_default().push(Subscriber {
138 id,
139 tx,
140 pending: Arc::clone(&pending),
141 behind,
142 });
143 FeedSubscription { hub: Arc::clone(self), key, id, rx, pending }
144 }
145
146 #[cfg(test)]
147 pub fn subscribers(&self, block_id: &str) -> usize {
148 let key = (block_id.to_string(), crate::backend::agent_session::OUTPUT_FILE.to_string());
149 self.subs.read().get(&key).map_or(0, Vec::len)
150 }
151
152 fn unsubscribe(&self, key: &(String, String), id: u64) {
153 let mut subs = self.subs.write();
154 if let Some(list) = subs.get_mut(key) {
155 list.retain(|s| s.id != id);
156 if list.is_empty() {
157 subs.remove(key);
158 }
159 }
160 }
161
162 pub fn observe(&self, event: &MuxEvent) {
166 if event.event != mps::EVENT_BLOCK_FILE {
167 return;
168 }
169 let Some(data) = event.data.as_ref() else { return };
170 let Some(filename) = data.get("filename").and_then(|v| v.as_str()) else { return };
171 if filename != crate::backend::agent_session::OUTPUT_FILE && filename != TERM_FILE {
172 return;
173 }
174 let Some(block_id) = data.get("zoneid").and_then(|v| v.as_str()) else { return };
175 let subs = self.subs.read();
176 let Some(list) = subs.get(&(block_id.to_string(), filename.to_string())) else { return };
177 let Ok(file) = serde_json::from_value::<mps::WSFileEventData>(data.clone()) else { return };
178 let event = if file.fileop == mps::FILE_OP_APPEND {
179 let Ok(records) = base64::engine::general_purpose::STANDARD.decode(file.data64.as_bytes()) else {
180 return;
181 };
182 HubEvent::Append { pos: file.pos, offset: file.offset, records }
183 } else {
184 HubEvent::Rewritten { fileop: file.fileop }
185 };
186 let size = match &event {
187 HubEvent::Append { records, .. } => queued_size(filename, records),
188 _ => 0,
189 };
190 for sub in list {
191 if sub.behind.load(Ordering::Relaxed) {
192 continue;
193 }
194 if sub.pending.load(Ordering::Relaxed) + size > self.max_behind {
195 sub.behind.store(true, Ordering::Relaxed);
196 let _ = sub.tx.send(HubEvent::Behind);
197 continue;
198 }
199 sub.pending.fetch_add(size, Ordering::Relaxed);
200 let _ = sub.tx.send(event.clone());
201 }
202 }
203}
204
205pub struct FeedSubscription {
207 hub: Arc<FeedHub>,
208 key: (String, String),
210 id: u64,
211 rx: mpsc::UnboundedReceiver<HubEvent>,
212 pending: Arc<AtomicUsize>,
213}
214
215impl FeedSubscription {
216 pub async fn recv(&mut self) -> Option<HubEvent> {
217 let event = self.rx.recv().await?;
218 if let HubEvent::Append { records, .. } = &event {
219 self.pending.fetch_sub(queued_size(&self.key.1, records), Ordering::Relaxed);
220 }
221 Some(event)
222 }
223}
224
225impl Drop for FeedSubscription {
226 fn drop(&mut self) {
227 self.hub.unsubscribe(&self.key, self.id);
228 }
229}
230
231#[derive(Debug, Clone, PartialEq, Eq)]
234pub struct Cursor {
235 pub stream: String,
238 pub gen: String,
240 pub next_line: u64,
241}
242
243impl Cursor {
244 pub fn event_id(&self) -> String {
246 format!("{}:{}", self.gen, self.next_line)
247 }
248}
249
250pub fn parse_event_id(id: &str) -> Option<(String, u64)> {
252 let (gen, line) = id.trim().rsplit_once(':')?;
253 if gen.is_empty() {
254 return None;
255 }
256 Some((gen.to_string(), line.parse().ok()?))
257}
258
259#[derive(Debug, Clone, PartialEq, Eq)]
261pub enum AppendStep {
262 Send { line: u64, lines: Vec<String> },
264 Skip,
266 Resync(&'static str),
269}
270
271pub fn split_records(records: &[u8]) -> Vec<String> {
274 String::from_utf8_lossy(records)
275 .lines()
276 .filter(|l| !l.trim().is_empty())
277 .map(str::to_string)
278 .collect()
279}
280
281pub fn apply_append(cursor: &mut Cursor, pos: &[StreamPos], records: &[u8]) -> AppendStep {
283 let Some(pos) = pos.iter().find(|p| p.stream == cursor.stream) else {
284 return AppendStep::Skip;
285 };
286 if pos.gen != cursor.gen {
287 if cursor.gen.is_empty() && cursor.next_line == 0 {
290 cursor.gen = pos.gen.clone();
291 } else {
292 return AppendStep::Resync("gen");
293 }
294 }
295 if pos.lines <= cursor.next_line {
296 return AppendStep::Skip;
297 }
298 if pos.line > cursor.next_line {
299 return AppendStep::Resync("gap");
300 }
301 let mut lines = split_records(records);
302 if lines.len() as u64 != pos.lines - pos.line {
303 return AppendStep::Resync("count");
304 }
305 let skip = (cursor.next_line - pos.line) as usize;
306 lines.drain(..skip);
307 let line = cursor.next_line;
308 cursor.next_line = pos.lines;
309 AppendStep::Send { line, lines }
310}
311
312pub fn status_step(
319 shown: &mut Option<AgentStatus>,
320 now: Option<AgentStatus>,
321 after_snapshot: bool,
322) -> Option<Option<AgentStatus>> {
323 let send = match (&*shown, &now) {
324 (_, Some(now)) => after_snapshot || shown.as_ref() != Some(now),
325 (Some(_), None) => true,
326 (None, None) => false,
327 };
328 *shown = now;
329 send.then_some(now)
330}
331
332pub fn device_frame(line: String) -> String {
335 if line.len() <= MAX_FRAME_BYTES {
336 return line;
337 }
338 let head: String = line.chars().take(TRUNCATED_HEAD_CHARS).collect();
339 serde_json::json!({ "type": "amx_truncated", "bytes": line.len(), "head": head }).to_string()
340}
341
342pub fn device_frames(lines: Vec<String>) -> Vec<String> {
344 lines.into_iter().map(device_frame).collect()
345}
346
347pub fn sse_event(name: &str, id: Option<&str>, data: &impl Serialize) -> Bytes {
350 let json = serde_json::to_string(data).unwrap_or_else(|_| "{}".to_string());
351 match id {
352 Some(id) => Bytes::from(format!("event: {name}\nid: {id}\ndata: {json}\n\n")),
353 None => Bytes::from(format!("event: {name}\ndata: {json}\n\n")),
354 }
355}
356
357#[cfg(test)]
358mod tests {
359 use super::*;
360
361 fn pos(stream: &str, gen: &str, line: u64, lines: u64) -> Vec<StreamPos> {
362 vec![StreamPos { stream: stream.into(), gen: gen.into(), line, lines }]
363 }
364
365 fn cursor(gen: &str, next: u64) -> Cursor {
366 Cursor { stream: "b:blk".into(), gen: gen.into(), next_line: next }
367 }
368
369 #[test]
370 fn appends_continue_the_cursor_and_drop_what_was_sent() {
371 let mut c = cursor("g1", 3);
372 let step = apply_append(&mut c, &pos("b:blk", "g1", 3, 5), b"{\"a\":1}\n{\"a\":2}\n");
373 assert_eq!(step, AppendStep::Send { line: 3, lines: vec!["{\"a\":1}".into(), "{\"a\":2}".into()] });
374 assert_eq!(c.next_line, 5);
375
376 assert_eq!(apply_append(&mut c, &pos("b:blk", "g1", 4, 5), b"x\n"), AppendStep::Skip);
378 let step = apply_append(&mut c, &pos("b:blk", "g1", 4, 7), b"x\ny\nz\n");
380 assert_eq!(step, AppendStep::Send { line: 5, lines: vec!["y".into(), "z".into()] });
381 assert_eq!(c.event_id(), "g1:7");
382 }
383
384 #[test]
385 fn another_generation_a_gap_or_a_bad_count_resyncs() {
386 let mut c = cursor("g1", 3);
387 assert_eq!(apply_append(&mut c, &pos("b:blk", "g2", 0, 1), b"x\n"), AppendStep::Resync("gen"));
388 assert_eq!(apply_append(&mut c, &pos("b:blk", "g1", 4, 5), b"x\n"), AppendStep::Resync("gap"));
389 assert_eq!(apply_append(&mut c, &pos("b:blk", "g1", 3, 5), b"x\n"), AppendStep::Resync("count"));
390 assert_eq!(c.next_line, 3, "nothing moved");
391 }
392
393 #[test]
394 fn other_streams_are_ignored_and_a_new_transcript_is_adopted() {
395 let mut c = cursor("g1", 3);
396 assert_eq!(apply_append(&mut c, &pos("g:agent:x:current", "zz", 0, 9), b"x\n"), AppendStep::Skip);
397 let mut fresh = cursor("", 0);
398 let step = apply_append(&mut fresh, &pos("b:blk", "g9", 0, 1), b"first\n");
399 assert_eq!(step, AppendStep::Send { line: 0, lines: vec!["first".into()] });
400 assert_eq!(fresh.gen, "g9");
401 }
402
403 #[test]
404 fn event_ids_round_trip() {
405 assert_eq!(parse_event_id("ab12:40"), Some(("ab12".into(), 40)));
406 assert_eq!(parse_event_id(" ab12:0 "), Some(("ab12".into(), 0)));
407 for bad in ["", ":4", "ab12", "ab12:x", "ab12:-1"] {
408 assert_eq!(parse_event_id(bad), None, "{bad}");
409 }
410 }
411
412 #[test]
413 fn a_frame_over_64_kb_is_replaced_by_its_head() {
414 let small = "x".repeat(MAX_FRAME_BYTES);
415 assert_eq!(device_frame(small.clone()), small);
416 let big = format!("{{\"type\":\"user\",\"text\":\"{}\"}}", "é".repeat(5 * 1024 * 1024 / 2));
417 let frame = device_frame(big.clone());
418 assert!(frame.len() < MAX_FRAME_BYTES);
419 let v: serde_json::Value = serde_json::from_str(&frame).unwrap();
420 assert_eq!(v["type"], "amx_truncated");
421 assert_eq!(v["bytes"], big.len());
422 let head = v["head"].as_str().unwrap();
423 assert_eq!(head.chars().count(), TRUNCATED_HEAD_CHARS);
424 assert!(big.starts_with(head));
425 }
426
427 #[test]
428 fn a_huge_line_counts_as_the_frame_the_device_gets() {
429 let huge = format!("{}\n", "x".repeat(5 * 1024 * 1024));
430 assert!(wire_size(huge.as_bytes()) <= MAX_FRAME_BYTES + 2);
431 assert_eq!(wire_size(b"ab\ncd\n"), 3 + 3 + 1);
432 }
433
434 #[test]
435 fn a_line_counts_with_the_escapes_it_gets_as_a_json_string() {
436 let line = r#"{"a":"b\"c"}"#;
439 let on_wire = serde_json::to_string(line).unwrap();
440 assert_eq!(wire_size(line.as_bytes()), on_wire.len() - 2 + 1, "the escaped string without its quotes, plus the newline");
441 assert_eq!(wire_size(b"\x01"), 6 + 1);
442 assert_eq!(wire_size(b"\t"), 2 + 1);
443 }
444
445 #[test]
446 fn status_is_sent_after_a_snapshot_on_change_and_once_when_it_goes() {
447 use crate::backend::agent_state::AgentState;
448 let working = AgentStatus { state: AgentState::Working, since_ms: 100 };
449 let idle = AgentStatus { state: AgentState::Idle, since_ms: 200 };
450 let mut shown = None;
451 assert_eq!(status_step(&mut shown, None, true), None, "no state yet: no event, even after a snapshot");
452 assert_eq!(status_step(&mut shown, None, false), None);
453 assert_eq!(status_step(&mut shown, Some(working), true), Some(Some(working)));
454 assert_eq!(status_step(&mut shown, Some(working), false), None, "unchanged");
455 assert_eq!(status_step(&mut shown, Some(working), true), Some(Some(working)), "every snapshot gets one");
456 assert_eq!(status_step(&mut shown, Some(idle), false), Some(Some(idle)));
457 let restarted = AgentStatus { state: AgentState::Idle, since_ms: 900 };
458 assert_eq!(status_step(&mut shown, Some(restarted), false), Some(Some(restarted)), "since_ms alone counts");
459 assert_eq!(status_step(&mut shown, None, false), Some(None), "gone: null, once");
460 assert_eq!(status_step(&mut shown, None, false), None);
461 assert_eq!(status_step(&mut shown, None, true), None);
462 }
463
464 #[test]
465 fn sse_events_are_one_data_line() {
466 let ev = sse_event("append", Some("g:3"), &serde_json::json!({"lines": ["a\nb"]}));
467 let text = String::from_utf8(ev.to_vec()).unwrap();
468 assert_eq!(text, "event: append\nid: g:3\ndata: {\"lines\":[\"a\\nb\"]}\n\n");
469 let reset = sse_event("reset", None, &serde_json::json!({"reason": "gen"}));
470 assert_eq!(String::from_utf8(reset.to_vec()).unwrap(), "event: reset\ndata: {\"reason\":\"gen\"}\n\n");
471 }
472
473 fn blockfile(block: &str, fileop: &str, records: &[u8], pos: Vec<StreamPos>) -> MuxEvent {
474 let data = mps::WSFileEventData {
475 zoneid: block.into(),
476 filename: "output".into(),
477 fileop: fileop.into(),
478 data64: base64::engine::general_purpose::STANDARD.encode(records),
479 offset: None,
480 pos,
481 echo: None,
482 };
483 MuxEvent {
484 event: mps::EVENT_BLOCK_FILE.into(),
485 scopes: vec![format!("block:{block}")],
486 sender: String::new(),
487 persist: 0,
488 data: serde_json::to_value(&data).ok(),
489 }
490 }
491
492 #[tokio::test]
493 async fn the_hub_delivers_only_the_followed_blocks_transcript() {
494 let broker = mps::Broker::new();
495 let hub = Arc::new(FeedHub::default());
496 hub.install(&broker);
497 let mut sub = hub.subscribe("b1");
498 broker.publish(blockfile("b2", "append", b"other\n", pos("b:b2", "g", 0, 1)));
499 let mut term = blockfile("b1", "append", b"tty", vec![]);
500 if let Some(d) = term.data.as_mut() {
501 d["filename"] = "term".into();
502 }
503 broker.publish(term);
504 broker.publish(blockfile("b1", "append", b"mine\n", pos("b:b1", "g", 0, 1)));
505 broker.publish(blockfile("b1", "replace", b"", vec![]));
506 assert_eq!(
507 sub.recv().await,
508 Some(HubEvent::Append { pos: pos("b:b1", "g", 0, 1), offset: None, records: b"mine\n".to_vec() })
509 );
510 assert_eq!(sub.recv().await, Some(HubEvent::Rewritten { fileop: "replace".into() }));
511 assert_eq!(hub.subscribers("b1"), 1);
512 drop(sub);
513 assert_eq!(hub.subscribers("b1"), 0, "dropping the subscription unsubscribes");
514 }
515
516 #[tokio::test]
517 async fn a_subscription_that_falls_behind_gets_behind_once_and_nothing_more() {
518 let broker = mps::Broker::new();
519 let hub = Arc::new(FeedHub::with_max_behind(10));
520 hub.install(&broker);
521 let mut sub = hub.subscribe("b1");
522 for i in 0..5u64 {
523 broker.publish(blockfile("b1", "append", b"12345\n", pos("b:b1", "g", i, i + 1)));
524 }
525 assert!(matches!(sub.recv().await, Some(HubEvent::Append { .. })));
526 assert_eq!(sub.recv().await, Some(HubEvent::Behind), "the second append would pass 10 bytes");
527 broker.publish(blockfile("b1", "append", b"x\n", pos("b:b1", "g", 5, 6)));
528 assert!(
529 tokio::time::timeout(std::time::Duration::from_millis(100), sub.recv()).await.is_err(),
530 "nothing is queued after Behind"
531 );
532 }
533}