1use std::collections::HashMap;
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::sync::{Arc, Mutex};
12
13use serde::{Deserialize, Serialize};
14
15use super::mps::{MuxEvent, WpsClient, EVENT_SYS_INFO, EVENT_BLOCK_STATS};
16
17pub const WS_EVENT_RPC: &str = "rpc";
20
21pub const WS_EVENT_MUX_OBJ_BATCHED_UPDATES: &str = "waveobj:batchedupdates";
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub enum Lane {
36 Priority,
37 Background,
38}
39
40const PRIORITY_LANE_CAPACITY: usize = 8192;
50const BACKGROUND_LANE_CAPACITY: usize = 256;
54
55pub struct WsReceivers {
59 pub priority: tokio::sync::mpsc::Receiver<serde_json::Value>,
60 pub background: tokio::sync::mpsc::Receiver<serde_json::Value>,
61 pub drops: Arc<LaneDrops>,
63}
64
65#[derive(Default)]
68struct LaneCount {
69 since_warn: AtomicU64,
70 last_warn_ms: AtomicU64,
71}
72
73const DROP_WARN_EVERY_MS: u64 = 5_000;
75
76#[derive(Default)]
83pub struct LaneDrops {
84 priority: LaneCount,
85 background: LaneCount,
86 unreported: AtomicU64,
88}
89
90impl LaneDrops {
91 fn record(&self, lane: Lane, now_ms: u64) -> Option<u64> {
93 let count = match lane {
94 Lane::Priority => {
95 self.unreported.fetch_add(1, Ordering::Relaxed);
96 &self.priority
97 }
98 Lane::Background => &self.background,
99 };
100 count.since_warn.fetch_add(1, Ordering::Relaxed);
101 let last = count.last_warn_ms.load(Ordering::Relaxed);
102 if now_ms.saturating_sub(last) < DROP_WARN_EVERY_MS
103 || count.last_warn_ms.compare_exchange(last, now_ms, Ordering::Relaxed, Ordering::Relaxed).is_err()
104 {
105 return None;
106 }
107 Some(count.since_warn.swap(0, Ordering::Relaxed))
108 }
109
110 pub fn has_unreported(&self) -> bool {
112 self.unreported.load(Ordering::Relaxed) > 0
113 }
114
115 pub fn take_unreported(&self) -> u64 {
117 self.unreported.swap(0, Ordering::Relaxed)
118 }
119}
120
121#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
124#[ts(export, export_to = "../../../frontend/types/rpc/")]
125pub struct EventsDroppedEvent {
126 pub dropped: u32,
127}
128
129#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct WSEventType {
133 pub eventtype: String,
134 #[serde(skip_serializing_if = "String::is_empty", default)]
135 pub oref: String,
136 #[serde(skip_serializing_if = "Option::is_none")]
137 pub data: Option<serde_json::Value>,
138}
139
140struct WindowWatchData {
141 priority: tokio::sync::mpsc::Sender<serde_json::Value>,
143 background: tokio::sync::mpsc::Sender<serde_json::Value>,
145 #[allow(dead_code)]
146 tab_id: String,
147 drops: Arc<LaneDrops>,
148}
149
150impl WindowWatchData {
151 fn sender(&self, lane: Lane) -> &tokio::sync::mpsc::Sender<serde_json::Value> {
152 match lane {
153 Lane::Priority => &self.priority,
154 Lane::Background => &self.background,
155 }
156 }
157}
158
159pub struct EventBus {
161 watches: Mutex<HashMap<String, WindowWatchData>>,
162}
163
164impl EventBus {
165 pub fn new() -> Self {
166 Self {
167 watches: Mutex::new(HashMap::new()),
168 }
169 }
170
171 pub fn register_ws(&self, conn_id: &str, tab_id: &str) -> WsReceivers {
174 let (priority_tx, priority_rx) = tokio::sync::mpsc::channel(PRIORITY_LANE_CAPACITY);
175 let (background_tx, background_rx) = tokio::sync::mpsc::channel(BACKGROUND_LANE_CAPACITY);
176 let drops = Arc::new(LaneDrops::default());
177 let mut watches = self.watches.lock().unwrap();
178 watches.insert(
179 conn_id.to_string(),
180 WindowWatchData {
181 priority: priority_tx,
182 background: background_tx,
183 tab_id: tab_id.to_string(),
184 drops: drops.clone(),
185 },
186 );
187 WsReceivers {
188 priority: priority_rx,
189 background: background_rx,
190 drops,
191 }
192 }
193
194 pub fn unregister_ws(&self, conn_id: &str) {
196 let mut watches = self.watches.lock().unwrap();
197 watches.remove(conn_id);
198 }
199
200 #[allow(dead_code)]
202 pub fn has_connections_for(&self, tab_id: &str) -> bool {
203 let watches = self.watches.lock().unwrap();
204 watches.values().any(|w| w.tab_id == tab_id)
205 }
206
207 #[allow(dead_code)]
209 pub async fn wait_for_connection(
210 &self,
211 tab_id: &str,
212 timeout: std::time::Duration,
213 ) -> bool {
214 let deadline = tokio::time::Instant::now() + timeout;
215 loop {
216 if self.has_connections_for(tab_id) {
217 return true;
218 }
219 if tokio::time::Instant::now() >= deadline {
220 return false;
221 }
222 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
223 }
224 }
225
226 #[cfg(test)]
229 pub fn send_to_conn_lane(&self, conn_id: &str, event: &WSEventType, lane: Lane) {
230 let data = match serde_json::to_value(event) {
231 Ok(v) => v,
232 Err(e) => {
233 tracing::error!("cannot marshal event: {}", e);
234 return;
235 }
236 };
237 self.send_value_to_conn_lane(conn_id, data, lane);
238 }
239
240 pub fn send_value_to_conn_lane(&self, conn_id: &str, data: serde_json::Value, lane: Lane) {
244 let watches = self.watches.lock().unwrap();
245 if let Some(watch) = watches.get(conn_id) {
246 Self::try_send_lane(conn_id, watch, lane, data);
247 }
248 }
249
250 pub fn broadcast_event(&self, event: &WSEventType) {
252 self.broadcast_event_lane(event, Lane::Priority);
253 }
254
255 pub fn typed_ws_event<E: super::mps_events::Event>(payload: &E::Payload, oref: impl Into<String>) -> WSEventType {
259 WSEventType {
261 eventtype: E::NAME.to_string(),
262 oref: oref.into(),
263 data: super::mps_events::payload_data(payload),
264 }
265 }
266
267 pub fn typed_frame<E: super::mps_events::Event>(payload: &E::Payload) -> serde_json::Value {
270 serde_json::json!({
271 "eventtype": WS_EVENT_RPC,
272 "data": { "command": "eventrecv", "data": { "event": E::NAME, "data": super::mps_events::payload_data(payload) } },
274 })
275 }
276
277 pub fn broadcast_typed<E: super::mps_events::Event>(&self, payload: &E::Payload) {
281 let event = MuxEvent {
283 event: E::NAME.to_string(),
284 scopes: vec![],
285 sender: String::new(),
286 persist: 0,
287 data: super::mps_events::payload_data(payload),
288 };
289 self.broadcast_event(&WSEventType {
290 eventtype: WS_EVENT_RPC.to_string(),
291 oref: String::new(),
292 data: Some(serde_json::json!({ "command": "eventrecv", "data": event })),
294 });
295 }
296
297 pub fn broadcast_mux_obj_updates(&self, updates: &[super::obj::MuxObjUpdate]) {
313 if updates.is_empty() {
314 return;
315 }
316 let batch = super::obj::MuxObjBatch(updates.to_vec());
317 self.broadcast_event(&Self::typed_ws_event::<super::mps_events::MuxObjBatchedUpdates>(&batch, String::new()));
318 }
319
320 pub fn broadcast_event_lane(&self, event: &WSEventType, lane: Lane) {
322 let data = match serde_json::to_value(event) {
323 Ok(v) => v,
324 Err(e) => {
325 tracing::error!("cannot marshal event: {}", e);
326 return;
327 }
328 };
329 self.broadcast_value_lane(data, lane);
330 }
331
332 pub fn broadcast_value_lane(&self, data: serde_json::Value, lane: Lane) {
334 let watches = self.watches.lock().unwrap();
335 for (conn_id, watch) in watches.iter() {
336 Self::try_send_lane(conn_id, watch, lane, data.clone());
337 }
338 }
339
340 fn try_send_lane(conn_id: &str, watch: &WindowWatchData, lane: Lane, data: serde_json::Value) {
345 match watch.sender(lane).try_send(data) {
346 Ok(()) => {}
347 Err(tokio::sync::mpsc::error::TrySendError::Full(dropped)) => {
348 if let Some(n) = watch.drops.record(lane, agentmux_common::time::now_ms() as u64) {
349 tracing::warn!(
350 "ws egress {:?} lane full for conn {} — consumer stalled, dropped {} events (latest: {})",
351 lane,
352 conn_id,
353 n,
354 dropped_event_name(&dropped)
355 );
356 }
357 }
358 Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => {
359 tracing::warn!("failed to send event to conn {}", conn_id);
360 }
361 }
362 }
363
364 #[allow(dead_code)]
366 pub fn send_to_tab(&self, tab_id: &str, event: &WSEventType) {
367 let data = match serde_json::to_value(event) {
368 Ok(v) => v,
369 Err(e) => {
370 tracing::error!("cannot marshal event: {}", e);
371 return;
372 }
373 };
374 let watches = self.watches.lock().unwrap();
375 for (conn_id, watch) in watches.iter() {
376 if watch.tab_id == tab_id {
377 Self::try_send_lane(conn_id, watch, Lane::Priority, data.clone());
378 }
379 }
380 }
381
382 pub fn connection_count(&self) -> usize {
384 self.watches.lock().unwrap().len()
385 }
386}
387
388impl Default for EventBus {
389 fn default() -> Self {
390 Self::new()
391 }
392}
393
394fn dropped_event_name(frame: &serde_json::Value) -> &str {
397 frame["data"]["data"]["event"].as_str().or_else(|| frame["eventtype"].as_str()).unwrap_or("?")
398}
399
400pub struct EventBusBridge {
403 event_bus: Arc<EventBus>,
404}
405
406impl EventBusBridge {
407 pub fn new(event_bus: Arc<EventBus>) -> Self {
408 Self { event_bus }
409 }
410}
411
412impl WpsClient for EventBusBridge {
413 fn send_event(&self, route_id: &str, event: MuxEvent) {
414 let lane = match event.event.as_str() {
420 EVENT_SYS_INFO | EVENT_BLOCK_STATS => Lane::Background,
421 _ => Lane::Priority,
422 };
423 let Some(data) = rpc_eventrecv_value(&event) else {
432 return;
433 };
434 if route_id == "ws-main" {
438 self.event_bus.broadcast_value_lane(data, lane);
439 } else {
440 self.event_bus.send_value_to_conn_lane(route_id, data, lane);
441 }
442 }
443}
444
445fn rpc_eventrecv_value(event: &MuxEvent) -> Option<serde_json::Value> {
448 let payload = match serde_json::to_value(event) {
449 Ok(v) => v,
450 Err(e) => {
451 tracing::error!("cannot marshal event: {}", e);
452 return None;
453 }
454 };
455 let mut inner = serde_json::Map::new();
456 inner.insert("command".to_string(), serde_json::Value::String("eventrecv".to_string()));
457 inner.insert("data".to_string(), payload);
458 let mut outer = serde_json::Map::new();
459 outer.insert("eventtype".to_string(), serde_json::Value::String(WS_EVENT_RPC.to_string()));
460 outer.insert("data".to_string(), serde_json::Value::Object(inner));
461 Some(serde_json::Value::Object(outer))
462}
463
464#[cfg(test)]
469mod tests {
470 use super::*;
471 use crate::backend::mps::EVENT_BLOCK_FILE;
472
473 #[test]
474 fn test_register_unregister() {
475 let bus = EventBus::new();
476 let _rx = bus.register_ws("conn-1", "tab-1");
477 assert_eq!(bus.connection_count(), 1);
478 assert!(bus.has_connections_for("tab-1"));
479 assert!(!bus.has_connections_for("tab-2"));
480
481 bus.unregister_ws("conn-1");
482 assert_eq!(bus.connection_count(), 0);
483 assert!(!bus.has_connections_for("tab-1"));
484 }
485
486 #[test]
487 fn test_broadcast_event() {
488 let bus = EventBus::new();
489 let mut rx1 = bus.register_ws("conn-1", "tab-1");
490 let mut rx2 = bus.register_ws("conn-2", "tab-2");
491
492 let event = WSEventType {
493 eventtype: WS_EVENT_RPC.to_string(),
494 oref: String::new(),
495 data: Some(serde_json::json!({"test": true})),
496 };
497 bus.broadcast_event(&event);
498
499 assert!(rx1.priority.try_recv().is_ok());
501 assert!(rx2.priority.try_recv().is_ok());
502 assert!(rx1.background.try_recv().is_err());
503 }
504
505 #[test]
506 fn test_send_to_tab() {
507 let bus = EventBus::new();
508 let mut rx1 = bus.register_ws("conn-1", "tab-1");
509 let mut rx2 = bus.register_ws("conn-2", "tab-2");
510
511 let event = WSEventType {
512 eventtype: WS_EVENT_RPC.to_string(),
513 oref: String::new(),
514 data: None,
515 };
516 bus.send_to_tab("tab-1", &event);
517
518 assert!(rx1.priority.try_recv().is_ok());
519 assert!(rx2.priority.try_recv().is_err()); }
521
522 #[test]
527 fn test_broadcast_mux_obj_updates_single_batched_frame() {
528 use crate::backend::obj::MuxObjUpdate;
529
530 let bus = EventBus::new();
531 let mut rx = bus.register_ws("conn-1", "tab-1");
532
533 let updates = vec![
534 MuxObjUpdate {
535 updatetype: "update".into(),
536 otype: "workspace".into(),
537 oid: "ws-1".into(),
538 obj: Some(serde_json::json!({"oid": "ws-1"})),
539 },
540 MuxObjUpdate {
541 updatetype: "delete".into(),
542 otype: "tab".into(),
543 oid: "tab-9".into(),
544 obj: None,
545 },
546 ];
547 bus.broadcast_mux_obj_updates(&updates);
548
549 let msg = rx.priority.try_recv().expect("one frame expected");
550 assert_eq!(
551 msg.get("eventtype").and_then(|v| v.as_str()),
552 Some(WS_EVENT_MUX_OBJ_BATCHED_UPDATES),
553 );
554 let arr = msg.get("data").and_then(|d| d.as_array()).expect("array payload");
555 assert_eq!(arr.len(), 2);
556 assert_eq!(arr[0].get("otype").and_then(|v| v.as_str()), Some("workspace"));
557 assert_eq!(arr[1].get("updatetype").and_then(|v| v.as_str()), Some("delete"));
558 assert!(rx.priority.try_recv().is_err());
560
561 bus.broadcast_mux_obj_updates(&[]);
563 assert!(rx.priority.try_recv().is_err());
564 }
565
566 #[test]
567 fn test_lane_separation() {
568 let bus = EventBus::new();
572 let mut rx = bus.register_ws("conn-1", "tab-1");
573
574 let event = WSEventType {
575 eventtype: WS_EVENT_RPC.to_string(),
576 oref: String::new(),
577 data: None,
578 };
579 bus.send_to_conn_lane("conn-1", &event, Lane::Background);
580 assert!(rx.priority.try_recv().is_err()); assert!(rx.background.try_recv().is_ok()); bus.send_to_conn_lane("conn-1", &event, Lane::Priority);
584 assert!(rx.background.try_recv().is_err()); assert!(rx.priority.try_recv().is_ok()); }
587
588 #[test]
589 fn test_stalled_consumer_drops_instead_of_growing_unbounded() {
590 let bus = EventBus::new();
597 let mut rx = bus.register_ws("conn-1", "tab-1"); let event = WSEventType {
599 eventtype: WS_EVENT_RPC.to_string(),
600 oref: String::new(),
601 data: None,
602 };
603 let sent = BACKGROUND_LANE_CAPACITY * 4;
604 for _ in 0..sent {
605 bus.send_to_conn_lane("conn-1", &event, Lane::Background);
606 }
607 let mut received = 0;
608 while rx.background.try_recv().is_ok() {
609 received += 1;
610 }
611 assert!(
612 received <= BACKGROUND_LANE_CAPACITY,
613 "received {received} events from a lane capped at {BACKGROUND_LANE_CAPACITY} — sends were not bounded"
614 );
615 assert!(received < sent, "no events were dropped despite flooding well past capacity");
616 }
617
618 #[test]
619 fn test_bridge_routes_telemetry_to_background() {
620 let bus = Arc::new(EventBus::new());
623 let mut rx = bus.register_ws("conn-1", "tab-1");
624 let bridge = EventBusBridge::new(bus.clone());
625
626 let telemetry = |event: &str| MuxEvent {
627 event: event.to_string(),
628 scopes: vec![],
629 sender: String::new(),
630 persist: 0,
631 data: None,
632 };
633
634 bridge.send_event("conn-1", telemetry(EVENT_SYS_INFO));
635 bridge.send_event("conn-1", telemetry(EVENT_BLOCK_STATS));
636 assert!(rx.priority.try_recv().is_err()); assert!(rx.background.try_recv().is_ok()); assert!(rx.background.try_recv().is_ok()); bridge.send_event("conn-1", telemetry(EVENT_BLOCK_FILE));
642 assert!(rx.priority.try_recv().is_ok());
643 assert!(rx.background.try_recv().is_err());
644 }
645
646 #[test]
647 fn test_ws_event_serialization() {
648 let event = WSEventType {
649 eventtype: "test".to_string(),
650 oref: String::new(),
651 data: Some(serde_json::json!(42)),
652 };
653 let json = serde_json::to_string(&event).unwrap();
654 assert!(json.contains("\"eventtype\":\"test\""));
655 assert!(!json.contains("\"oref\""));
657 }
658
659 #[test]
662 fn rpc_eventrecv_value_matches_wsevent_shape() {
663 let event = MuxEvent {
664 event: "blockfile".to_string(),
665 scopes: vec!["block:abc".to_string()],
666 sender: String::new(),
667 persist: 0,
668 data: Some(serde_json::json!({ "data64": "aGVsbG8=", "n": 3 })),
669 };
670 let old = serde_json::to_value(WSEventType {
671 eventtype: WS_EVENT_RPC.to_string(),
672 oref: String::new(),
673 data: Some(serde_json::json!({ "command": "eventrecv", "data": event })),
674 })
675 .unwrap();
676 assert_eq!(rpc_eventrecv_value(&event).unwrap(), old);
677 }
678
679 #[test]
680 fn send_event_delivers_the_eventrecv_envelope_to_the_subscribed_conn() {
681 let bus = Arc::new(EventBus::new());
682 let mut rx = bus.register_ws("conn-1", "tab-1");
683 let bridge = EventBusBridge::new(Arc::clone(&bus));
684 let event = MuxEvent {
685 event: "blockfile".to_string(),
686 scopes: vec![],
687 sender: String::new(),
688 persist: 0,
689 data: Some(serde_json::json!({ "k": "v" })),
690 };
691 bridge.send_event("conn-1", event.clone());
692 let got = rx.priority.try_recv().expect("delivered on the priority lane");
693 assert_eq!(got, rpc_eventrecv_value(&event).unwrap());
694 assert_eq!(got["eventtype"], "rpc");
695 assert_eq!(got["data"]["command"], "eventrecv");
696 assert_eq!(got["data"]["data"]["data"]["k"], "v");
697 }
698
699 fn update_frame(n: usize) -> WSEventType {
700 WSEventType { eventtype: "waveobj:update".into(), oref: format!("block:{n}"), data: None }
701 }
702
703 #[test]
707 fn a_full_priority_lane_is_counted_so_the_window_can_be_told() {
708 let bus = EventBus::new();
709 let rx = bus.register_ws("conn-1", "tab-1"); assert!(!rx.drops.has_unreported());
711 let sent = PRIORITY_LANE_CAPACITY + 1_808;
712 for n in 0..sent {
713 bus.send_to_conn_lane("conn-1", &update_frame(n), Lane::Priority);
714 }
715 assert!(rx.drops.has_unreported());
716 assert_eq!(rx.drops.take_unreported(), 1_808);
717 assert!(!rx.drops.has_unreported(), "taking the count tells the window once");
718 }
719
720 #[test]
723 fn a_full_background_lane_is_not_a_missed_event() {
724 let bus = EventBus::new();
725 let rx = bus.register_ws("conn-1", "tab-1");
726 for n in 0..BACKGROUND_LANE_CAPACITY + 50 {
727 bus.send_to_conn_lane("conn-1", &update_frame(n), Lane::Background);
728 }
729 assert!(!rx.drops.has_unreported());
730 }
731
732 #[test]
733 fn drops_warn_once_per_window_and_say_how_many() {
734 let d = LaneDrops::default();
735 let t0 = 1_000_000;
736 assert_eq!(d.record(Lane::Priority, t0), Some(1), "the first drop warns at once");
737 let quiet = (1..1_808).filter_map(|i| d.record(Lane::Priority, t0 + i % 4_000)).count();
738 assert_eq!(quiet, 0, "no more warns inside {DROP_WARN_EVERY_MS} ms");
739 assert_eq!(d.record(Lane::Priority, t0 + DROP_WARN_EVERY_MS), Some(1_808), "then one, with the count");
740 assert_eq!(d.record(Lane::Background, t0 + 10), Some(1));
742 }
743
744 #[test]
745 fn a_dropped_event_is_named_in_the_log() {
746 let rpc = rpc_eventrecv_value(&MuxEvent {
747 event: "agent:status".into(),
748 scopes: vec![],
749 sender: String::new(),
750 persist: 0,
751 data: None,
752 })
753 .unwrap();
754 assert_eq!(dropped_event_name(&rpc), "agent:status");
755 let raw = serde_json::to_value(update_frame(1)).unwrap();
756 assert_eq!(dropped_event_name(&raw), "waveobj:update");
757 assert_eq!(dropped_event_name(&serde_json::json!({})), "?");
758 }
759}