1use std::collections::{HashMap, HashSet};
16use std::sync::Mutex;
17
18use serde::{Deserialize, Serialize};
19
20#[allow(dead_code)]
23pub const EVENT_BLOCK_CLOSE: &str = "blockclose";
24#[allow(dead_code)]
25pub const EVENT_CONN_CHANGE: &str = "connchange";
26pub const EVENT_REMOTES_CHANGE: &str = "remoteschange";
29pub const EVENT_WIDGET_PACKAGES: &str = "widgetpackages";
32pub const EVENT_WIDGET_STORAGE: &str = "widgetstorage";
34pub const EVENT_WIDGET_REQUESTS: &str = "widgetrequests";
36pub const EVENT_FOLDER_OVERLAP_ASKS: &str = "folderoverlapasks";
39pub const EVENT_PIN_ASKS: &str = "pinasks";
41pub const EVENT_VAULT: &str = "vault";
44pub const EVENT_USER_ATTENTION: &str = "userattention";
47pub const EVENT_BROWSER_PAUSE_ALL: &str = "browserpauseall";
49pub const EVENT_SYS_INFO: &str = "sysinfo";
50pub const EVENT_CONTROLLER_STATUS: &str = "controllerstatus";
51pub const EVENT_AGENT_RUNTIME: &str = "agentruntime";
53pub const EVENT_AGENT_CONTEXT_USAGE: &str = "agentcontextusage";
56pub const EVENT_AGENT_TURN: &str = "agentturn";
59pub const EVENT_MUX_OBJ_UPDATE: &str = "waveobj:update";
60pub const EVENT_BLOCK_FILE: &str = "blockfile";
61pub const EVENT_INSTALL_PROGRESS: &str = "install_progress";
62#[allow(dead_code)]
63pub const EVENT_CONFIG: &str = "config";
64#[allow(dead_code)]
65pub const EVENT_USER_INPUT: &str = "userinput";
66pub const EVENT_AGENT_MESSAGE_ACCEPTED: &str = "agent-message-accepted";
71pub const EVENT_AGENT_MESSAGE_QUEUED: &str = "agent-message-queued";
75pub const EVENT_MESSAGE_FLOW: &str = "message-flow";
78pub const EVENT_CONTAINER_STATUS: &str = "container-status";
80pub const EVENT_CONTAINER_RUNTIME: &str = "container-runtime";
82pub const EVENT_TASK_FLOW: &str = "task-flow";
85pub const EVENT_REVIEW_FLOW: &str = "review-flow";
88pub const EVENT_CHECKS_FLOW: &str = "checks-flow";
91pub const EVENT_MERGE_FLOW: &str = "merge-flow";
93pub const EVENT_ATTACHMENT_PROGRESS: &str = "attachment:progress";
98pub const EVENT_ATTACHMENT_READY: &str = "attachment:ready";
99pub const EVENT_ATTACHMENT_FAILED: &str = "attachment:failed";
100pub const EVENT_ATTACHMENT_BATCH_DONE: &str = "attachment:batch-done";
101#[allow(dead_code)]
102pub const EVENT_ROUTE_GONE: &str = "route:gone";
103pub const EVENT_BLOCK_STATS: &str = "blockstats";
104pub const EVENT_AGENT_FAILURE: &str = "agentfailure";
108pub const EVENT_AGENT_RESUME_RETRY: &str = "agent-resume-retry";
123pub const EVENT_SRV_PANICS: &str = "srv-panics";
125pub const EVENT_RECORD_FLAGS: &str = "record-flags";
128pub const EVENT_AGENT_API_RETRY: &str = "agent-api-retry";
132pub const EVENT_SUBAGENT_BACKFILL_STATUS: &str = "subagent:backfill_status";
145pub const EVENT_SHELL_NODE_CREATE: &str = "shell_node_create";
149pub const EVENT_SHELL_CHUNK: &str = "shell_chunk";
153pub const EVENT_BLOCK_ACTIVITY: &str = "block:activity";
158pub const EVENT_CRON_CHANGED: &str = "cron_changed";
164pub const EVENT_DOCK_CLEAR: &str = "dock:clear";
173pub const EVENT_BTW_ANSWER_CHUNK: &str = "btw_answer_chunk";
192
193#[allow(dead_code)]
195pub const FILE_OP_CREATE: &str = "create";
196#[allow(dead_code)]
197pub const FILE_OP_DELETE: &str = "delete";
198pub const FILE_OP_APPEND: &str = "append";
199pub const FILE_OP_TRUNCATE: &str = "truncate";
200pub const FILE_OP_REPLACE: &str = "replace";
203#[allow(dead_code)]
204pub const FILE_OP_INVALIDATE: &str = "invalidate";
205
206const MAX_PERSIST: usize = 4096;
207const REMAKE_ARR_THRESHOLD: usize = 10 * 1024;
208const MAX_KEPT_BYTES_PER_SCOPE: usize = 2 * 1024 * 1024;
211
212#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
218#[ts(export, export_to = "../../../frontend/types/rpc/")]
219pub struct MuxEvent {
220 pub event: String,
221 #[serde(skip_serializing_if = "Vec::is_empty", default)]
223 #[ts(as = "Option<Vec<String>>", optional)]
224 pub scopes: Vec<String>,
225 #[serde(skip_serializing_if = "String::is_empty", default)]
226 #[ts(as = "Option<String>", optional)]
227 pub sender: String,
228 #[serde(skip_serializing_if = "is_zero", default)]
229 #[ts(as = "Option<u32>", optional)]
230 pub persist: usize,
231 #[serde(skip_serializing_if = "Option::is_none")]
232 #[ts(optional, type = "any")]
233 pub data: Option<serde_json::Value>,
234}
235
236fn is_zero(v: &usize) -> bool {
237 *v == 0
238}
239
240impl MuxEvent {
241 #[allow(dead_code)]
242 pub fn has_scope(&self, scope: &str) -> bool {
243 self.scopes.iter().any(|s| s == scope)
244 }
245}
246
247#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
248#[ts(export, export_to = "../../../frontend/types/rpc/")]
249pub struct SubscriptionRequest {
250 pub event: String,
251 #[serde(skip_serializing_if = "Vec::is_empty", default)]
252 pub scopes: Vec<String>,
253 #[serde(default)]
254 pub allscopes: bool,
255}
256
257#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
258#[ts(export, export_to = "../../../frontend/types/rpc/")]
259pub struct WSFileEventData {
260 pub zoneid: String,
261 pub filename: String,
262 pub fileop: String,
263 #[serde(skip_serializing_if = "String::is_empty", default)]
264 #[ts(as = "Option<String>", optional)]
265 pub data64: String,
266 #[serde(skip_serializing_if = "Option::is_none", default)]
272 #[ts(optional, type = "number")]
273 pub offset: Option<u64>,
274 #[serde(skip_serializing_if = "Vec::is_empty", default)]
280 #[ts(as = "Option<Vec<StreamPos>>", optional)]
281 pub pos: Vec<StreamPos>,
282 #[serde(skip_serializing_if = "Option::is_none", default)]
288 #[ts(optional)]
289 pub echo: Option<String>,
290}
291
292#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
295#[ts(export, export_to = "../../../frontend/types/rpc/")]
296pub struct StreamPos {
297 pub stream: String,
300 pub gen: String,
301 #[ts(type = "number")]
303 pub line: u64,
304 #[ts(type = "number")]
306 pub lines: u64,
307}
308
309pub trait WpsClient: Send + Sync {
313 fn send_event(&self, route_id: &str, event: MuxEvent);
314}
315
316#[derive(Default)]
319struct BrokerSubscription {
320 all_subs: Vec<String>,
322 scope_subs: HashMap<String, Vec<String>>,
324 star_subs: HashMap<String, Vec<String>>,
326}
327
328impl BrokerSubscription {
329 fn is_empty(&self) -> bool {
330 self.all_subs.is_empty() && self.scope_subs.is_empty() && self.star_subs.is_empty()
331 }
332}
333
334#[derive(Hash, Eq, PartialEq, Clone)]
335struct PersistKey {
336 event: String,
337 scope: String,
338}
339
340#[derive(Clone)]
343struct Kept {
344 event: std::sync::Arc<MuxEvent>,
345 bytes: usize,
346}
347
348struct PersistEventWrap {
349 arr_total_adds: usize,
350 events: Vec<Kept>,
351 bytes: usize,
353}
354
355fn kept_event_bytes(e: &MuxEvent) -> usize {
357 std::mem::size_of::<MuxEvent>()
358 + e.event.capacity()
359 + e.sender.capacity()
360 + e.scopes.iter().map(|s| s.capacity() + std::mem::size_of::<String>()).sum::<usize>()
361 + e.data.as_ref().map_or(0, crate::backend::mem_census::json_bytes)
362}
363
364pub struct Broker {
368 inner: Mutex<BrokerInner>,
369 observers: std::sync::RwLock<Vec<BrokerObserver>>,
373}
374
375pub type BrokerObserver = std::sync::Arc<dyn Fn(&MuxEvent) + Send + Sync>;
377
378type ReplayKey = (String, String, String);
385
386struct BrokerInner {
387 client: Option<Box<dyn WpsClient>>,
388 sub_map: HashMap<String, BrokerSubscription>,
389 persist_map: HashMap<PersistKey, PersistEventWrap>,
390 replayed: HashSet<ReplayKey>,
391}
392
393impl Broker {
394 pub fn new() -> Self {
395 Self {
396 inner: Mutex::new(BrokerInner {
397 client: None,
398 sub_map: HashMap::new(),
399 persist_map: HashMap::new(),
400 replayed: HashSet::new(),
401 }),
402 observers: std::sync::RwLock::new(Vec::new()),
403 }
404 }
405
406 pub fn add_observer(&self, f: BrokerObserver) {
410 self.observers.write().unwrap_or_else(|e| e.into_inner()).push(f);
411 }
412
413 pub fn set_client(&self, client: Box<dyn WpsClient>) {
414 let mut inner = self.inner.lock().unwrap();
415 inner.client = Some(client);
416 }
417
418 pub fn subscribe(&self, route_id: &str, sub: SubscriptionRequest) {
427 if sub.event.is_empty() {
428 return;
429 }
430 let mut inner = self.inner.lock().unwrap();
431 Self::unsubscribe_nolock(&mut inner, route_id, &sub.event);
433
434 let bs = inner
435 .sub_map
436 .entry(sub.event.clone())
437 .or_default();
438
439 if sub.allscopes {
440 add_unique(&mut bs.all_subs, route_id);
441 } else {
442 for scope in &sub.scopes {
443 if scope_has_star(scope) {
444 add_to_scope_map(&mut bs.star_subs, scope, route_id);
445 } else {
446 add_to_scope_map(&mut bs.scope_subs, scope, route_id);
447 }
448 }
449 }
450
451 Self::replay_to_route(&mut inner, route_id, &sub);
452 }
453
454 fn replay_to_route(
473 inner: &mut BrokerInner,
474 route_id: &str,
475 sub: &SubscriptionRequest,
476 ) {
477 let client = match &inner.client {
478 Some(c) => c,
479 None => return,
480 };
481
482 let mut scopes_to_deliver: Vec<String> = Vec::new();
483 if sub.allscopes {
484 scopes_to_deliver.push(String::new());
486 } else {
487 for scope in &sub.scopes {
488 if !scope_has_star(scope) {
489 scopes_to_deliver.push(scope.clone());
490 }
491 }
492 }
493
494 let mut to_send: Vec<MuxEvent> = Vec::new();
495 for scope in scopes_to_deliver {
496 let key = (route_id.to_string(), sub.event.clone(), scope.clone());
497 if inner.replayed.contains(&key) {
498 continue;
499 }
500 let pkey = PersistKey {
501 event: sub.event.clone(),
502 scope: scope.clone(),
503 };
504 if let Some(pe) = inner.persist_map.get(&pkey) {
505 for kept in &pe.events {
506 to_send.push(MuxEvent::clone(&kept.event));
507 }
508 }
509 inner.replayed.insert(key);
510 }
511 for event in to_send {
512 client.send_event(route_id, event);
513 }
514 }
515
516 pub fn has_subscribers(&self, event_name: &str) -> bool {
519 let inner = self.inner.lock().unwrap();
520 inner.sub_map.get(event_name).is_some_and(|bs| !bs.is_empty())
521 }
522
523 pub fn unsubscribe(&self, route_id: &str, event_name: &str) {
525 let mut inner = self.inner.lock().unwrap();
526 Self::unsubscribe_nolock(&mut inner, route_id, event_name);
527 }
528
529 pub fn unsubscribe_all(&self, route_id: &str) {
536 let mut inner = self.inner.lock().unwrap();
537 let events: Vec<String> = inner.sub_map.keys().cloned().collect();
538 for event in events {
539 Self::unsubscribe_nolock(&mut inner, route_id, &event);
540 }
541 inner.replayed.retain(|(r, _, _)| r != route_id);
542 }
543
544 pub fn purge_scope(&self, scope: &str) {
552 let mut inner = self.inner.lock().unwrap();
553 inner.persist_map.retain(|k, _| k.scope != scope);
554 inner.replayed.retain(|(_, _, s)| s != scope);
555 }
556
557 fn unsubscribe_nolock(inner: &mut BrokerInner, route_id: &str, event_name: &str) {
558 let bs = match inner.sub_map.get_mut(event_name) {
559 Some(bs) => bs,
560 None => return,
561 };
562 bs.all_subs.retain(|s| s != route_id);
563 remove_from_all_scopes(&mut bs.scope_subs, route_id);
564 remove_from_all_scopes(&mut bs.star_subs, route_id);
565 if bs.is_empty() {
566 inner.sub_map.remove(event_name);
567 }
568 }
569
570 pub fn publish_event<E: super::mps_events::Event>(&self, payload: &E::Payload, scopes: Vec<String>, persist: usize) {
573 self.publish(MuxEvent {
575 event: E::NAME.to_string(),
576 scopes,
577 sender: String::new(),
578 persist,
579 data: super::mps_events::payload_data(payload),
580 });
581 }
582
583 pub fn publish_event_for<E: super::mps_events::PerIdEvent>(&self, id: &str, payload: &E::Payload, scopes: Vec<String>, persist: usize) {
585 self.publish(MuxEvent {
587 event: format!("{}{id}", E::PREFIX),
588 scopes,
589 sender: String::new(),
590 persist,
591 data: super::mps_events::payload_data(payload),
592 });
593 }
594
595 pub fn publish(&self, event: MuxEvent) {
597 for o in self.observers.read().unwrap_or_else(|e| e.into_inner()).iter() {
598 o(&event);
599 }
600 let mut inner = self.inner.lock().unwrap();
601
602 if event.persist > 0 {
604 Self::persist_event(&mut inner, &event);
605 }
606
607 let client = match &inner.client {
608 Some(c) => c,
609 None => return,
610 };
611
612 let route_ids = Self::get_matching_routes(&inner, &event);
613 for route_id in route_ids {
614 client.send_event(&route_id, event.clone());
615 }
616 }
617
618 pub fn kept_events_census(&self) -> Vec<crate::backend::mem_census::Held> {
622 use crate::backend::mem_census::Held;
623 let inner = self.inner.lock().unwrap();
624 let mut by_event: HashMap<String, Held> = HashMap::new();
625 let mut counted: HashSet<*const MuxEvent> = HashSet::new();
626 for (key, kept) in &inner.persist_map {
627 let held = by_event
628 .entry(key.event.clone())
629 .or_insert_with(|| Held { name: format!("kept events: {}", key.event), ..Held::default() });
630 held.groups += 1;
631 held.bytes += (kept.events.capacity() * std::mem::size_of::<Kept>() + key.event.capacity() + key.scope.capacity()) as u64;
632 for k in &kept.events {
633 if counted.insert(std::sync::Arc::as_ptr(&k.event)) {
634 held.count += 1;
635 held.bytes += k.bytes as u64;
636 }
637 }
638 }
639 drop(inner);
640 by_event.into_values().collect()
641 }
642
643 pub fn read_event_history(
645 &self,
646 event_type: &str,
647 scope: &str,
648 max_items: usize,
649 ) -> Vec<MuxEvent> {
650 if max_items == 0 {
651 return Vec::new();
652 }
653 let inner = self.inner.lock().unwrap();
654 let key = PersistKey {
655 event: event_type.to_string(),
656 scope: scope.to_string(),
657 };
658 match inner.persist_map.get(&key) {
659 Some(pe) if !pe.events.is_empty() => {
660 let n = max_items.min(pe.events.len());
661 pe.events[pe.events.len() - n..].iter().map(|k| MuxEvent::clone(&k.event)).collect()
662 }
663 _ => Vec::new(),
664 }
665 }
666
667 fn persist_event(inner: &mut BrokerInner, event: &MuxEvent) {
668 let num_persist = event.persist.min(MAX_PERSIST);
669 let kept = Kept { bytes: kept_event_bytes(event), event: std::sync::Arc::new(event.clone()) };
670 let mut scope_set: Vec<String> = event.scopes.clone();
671 scope_set.push(String::new()); for scope in scope_set {
674 let key = PersistKey {
675 event: event.event.clone(),
676 scope,
677 };
678 let pe = inner.persist_map.entry(key).or_insert_with(|| PersistEventWrap { arr_total_adds: 0, events: Vec::new(), bytes: 0 });
681 pe.events.push(kept.clone());
682 pe.arr_total_adds += 1;
683 let mut gone = pe.events.len().saturating_sub(num_persist);
685 let mut bytes = pe.bytes + kept.bytes - pe.events[..gone].iter().map(|k| k.bytes).sum::<usize>();
686 while bytes > MAX_KEPT_BYTES_PER_SCOPE && gone + 1 < pe.events.len() {
687 bytes -= pe.events[gone].bytes;
688 gone += 1;
689 }
690 pe.events.drain(..gone);
691 pe.bytes = bytes;
692 if pe.arr_total_adds > REMAKE_ARR_THRESHOLD {
694 let compacted: Vec<Kept> = pe.events.drain(..).collect();
695 pe.events = compacted;
696 pe.arr_total_adds = pe.events.len();
697 }
698 }
699 }
700
701 fn get_matching_routes(inner: &BrokerInner, event: &MuxEvent) -> Vec<String> {
702 let bs = match inner.sub_map.get(&event.event) {
703 Some(bs) => bs,
704 None => return Vec::new(),
705 };
706
707 let mut route_ids: HashMap<&str, ()> = HashMap::new();
708
709 for route_id in &bs.all_subs {
711 route_ids.insert(route_id, ());
712 }
713
714 for scope in &event.scopes {
716 if let Some(routes) = bs.scope_subs.get(scope) {
717 for route_id in routes {
718 route_ids.insert(route_id, ());
719 }
720 }
721 for (star_scope, routes) in &bs.star_subs {
723 if star_match(star_scope, scope, ":") {
724 for route_id in routes {
725 route_ids.insert(route_id, ());
726 }
727 }
728 }
729 }
730
731 route_ids.keys().map(|s| s.to_string()).collect()
732 }
733}
734
735impl Default for Broker {
736 fn default() -> Self {
737 Self::new()
738 }
739}
740
741fn scope_has_star(scope: &str) -> bool {
744 scope.split(':').any(|part| part == "*" || part == "**")
745}
746
747fn star_match(pattern: &str, value: &str, sep: &str) -> bool {
750 let pat_parts: Vec<&str> = pattern.split(sep).collect();
751 let val_parts: Vec<&str> = value.split(sep).collect();
752
753 let mut pi = 0;
754 let mut vi = 0;
755 while pi < pat_parts.len() && vi < val_parts.len() {
756 if pat_parts[pi] == "**" {
757 return true; }
759 if pat_parts[pi] != "*" && pat_parts[pi] != val_parts[vi] {
760 return false;
761 }
762 pi += 1;
763 vi += 1;
764 }
765 pi == pat_parts.len() && vi == val_parts.len()
766}
767
768fn add_unique(vec: &mut Vec<String>, val: &str) {
769 if !vec.iter().any(|s| s == val) {
770 vec.push(val.to_string());
771 }
772}
773
774fn add_to_scope_map(map: &mut HashMap<String, Vec<String>>, scope: &str, route_id: &str) {
775 let entry = map.entry(scope.to_string()).or_default();
776 add_unique(entry, route_id);
777}
778
779fn remove_from_all_scopes(map: &mut HashMap<String, Vec<String>>, route_id: &str) {
780 let empty_scopes: Vec<String> = map
781 .iter_mut()
782 .filter_map(|(scope, routes)| {
783 routes.retain(|r| r != route_id);
784 if routes.is_empty() {
785 Some(scope.clone())
786 } else {
787 None
788 }
789 })
790 .collect();
791 for scope in empty_scopes {
792 map.remove(&scope);
793 }
794}
795
796pub fn publish_install_progress(broker: &Broker, block_id: &str, message: &str) {
800 let scope = format!("block:{}", block_id);
801 let line = super::mps_events::InstallProgressEvent { message: message.to_string() };
802 broker.publish_event::<super::mps_events::InstallProgress>(&line, vec![scope], 0);
803}
804
805pub fn publish_block_activity(broker: &Broker, block_id: &str, activity: &str) {
810 let scope = format!("block:{}", block_id);
811 let event = super::mps_events::BlockActivityEvent { block_id: block_id.to_string(), activity: activity.to_string() };
812 broker.publish_event::<super::mps_events::BlockActivity>(&event, vec![scope], 0);
813}
814
815#[cfg(test)]
820mod tests {
821 #[test]
824 fn the_census_counts_a_kept_event_once_however_many_lists_share_it() {
825 let broker = Broker::new();
826 assert!(broker.kept_events_census().is_empty());
827 let text = "x".repeat(1000);
828 for scope in ["block:a", "block:b"] {
829 for _ in 0..3 {
830 broker.publish(MuxEvent {
831 event: "bash:output".into(),
832 scopes: vec![scope.into()],
833 sender: String::new(),
834 persist: 8,
835 data: Some(serde_json::json!({ "text": text })),
836 });
837 }
838 }
839 broker.publish(MuxEvent { event: "passing".into(), scopes: vec![], sender: String::new(), persist: 0, data: None });
841
842 let census = broker.kept_events_census();
843 assert_eq!(census.len(), 1, "{census:?}");
844 let held = &census[0];
845 assert_eq!(held.name, "kept events: bash:output");
846 assert_eq!(held.groups, 3, "two block scopes and the shared one");
847 assert_eq!(held.count, 6, "6 events, each stored once and in two lists");
848 let stored = 6 * (1000 + std::mem::size_of::<MuxEvent>() as u64);
849 assert!(held.bytes >= stored, "{} bytes for {stored} of events", held.bytes);
850 assert!(held.bytes < 2 * stored, "{} bytes is more than twice the events: a second copy is back", held.bytes);
851 assert_eq!(broker.read_event_history("bash:output", "", 10).len(), 6, "the shared list still has them all");
852 }
853
854 #[test]
855 fn a_scope_keeps_its_newest_events_within_the_byte_cap_and_reserves_nothing() {
856 let broker = Broker::new();
857 let publish = |n: usize, text: &str| {
858 broker.publish(MuxEvent {
859 event: "bash:output".into(),
860 scopes: vec!["block:a".into()],
861 sender: String::new(),
862 persist: 1024,
863 data: Some(serde_json::json!({ "n": n, "text": text })),
864 })
865 };
866 let quarter = "x".repeat(MAX_KEPT_BYTES_PER_SCOPE / 4);
868 for n in 0..10 {
869 publish(n, &quarter);
870 }
871 let kept = broker.read_event_history("bash:output", "block:a", usize::MAX);
872 let ns: Vec<u64> = kept.iter().map(|e| e.data.as_ref().unwrap()["n"].as_u64().unwrap()).collect();
873 assert_eq!(ns, [7, 8, 9]);
874 publish(10, &"y".repeat(2 * MAX_KEPT_BYTES_PER_SCOPE));
876 assert_eq!(broker.read_event_history("bash:output", "block:a", usize::MAX).len(), 1);
877 broker.publish(MuxEvent { event: "tiny".into(), scopes: vec!["block:b".into()], sender: String::new(), persist: 1024, data: None });
879 let tiny = broker.kept_events_census().into_iter().find(|h| h.name == "kept events: tiny").unwrap();
880 assert!(tiny.bytes < 1024, "{tiny:?}");
881 }
882
883 #[test]
884 fn observers_see_every_publish_even_without_a_client() {
885 let b = Broker::new();
886 let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
887 let s2 = seen.clone();
888 b.add_observer(std::sync::Arc::new(move |e: &MuxEvent| s2.lock().unwrap().push(e.event.clone())));
889 for name in ["agentfailure", "config"] {
890 b.publish(MuxEvent { event: name.into(), scopes: vec![], sender: String::new(), persist: 0, data: None });
891 }
892 assert_eq!(*seen.lock().unwrap(), vec!["agentfailure".to_string(), "config".to_string()]);
893 }
894
895 #[test]
896 fn a_signal_event_goes_out_with_no_data_and_a_payload_event_with_its_payload() {
897 use crate::backend::mps_events::{AgentsChanged, FilesChanged, FilesChangedEvent};
898 let b = Broker::new();
899 let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<MuxEvent>::new()));
900 let s2 = seen.clone();
901 b.add_observer(std::sync::Arc::new(move |e: &MuxEvent| s2.lock().unwrap().push(e.clone())));
902 b.publish_event::<AgentsChanged>(&(), vec![], 0);
903 b.publish_event::<FilesChanged>(&FilesChangedEvent { dir: "/tmp".into() }, vec![], 0);
904 let seen = seen.lock().unwrap();
905 let signal = serde_json::to_value(&seen[0]).unwrap();
907 assert_eq!(signal["event"], "agents:changed");
908 assert!(signal.get("data").is_none(), "{signal}");
909 assert_eq!(seen[1].data, Some(serde_json::json!({ "dir": "/tmp" })));
910 }
911
912 #[test]
913 fn a_per_id_event_goes_out_under_its_prefix_and_the_id() {
914 use crate::backend::mps_events::{AgentCredentialsRevoked, AgentMemoryChanged, CredentialsRevokedEvent};
915 let b = Broker::new();
916 let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<MuxEvent>::new()));
917 let s2 = seen.clone();
918 b.add_observer(std::sync::Arc::new(move |e: &MuxEvent| s2.lock().unwrap().push(e.clone())));
919 let revoked = CredentialsRevokedEvent { credentials_revoked: true, provider: "claude".into(), account_id: None };
920 b.publish_event_for::<AgentCredentialsRevoked>("agent-1", &revoked, vec![], 0);
921 b.publish_event_for::<AgentMemoryChanged>("agent-2", &(), vec![], 0);
922 let seen = seen.lock().unwrap();
923 assert_eq!(seen[0].event, "agentcredentials:revoked:agent-1");
924 assert_eq!(seen[0].data, Some(serde_json::json!({ "credentialsRevoked": true, "provider": "claude" })));
926 assert_eq!(seen[1].event, "agent:memory:changed:agent-2");
927 assert_eq!(seen[1].data, None);
928 }
929
930 use super::*;
931 use std::sync::Arc;
932
933 struct TestClient {
934 events: Mutex<Vec<(String, MuxEvent)>>,
935 }
936
937 impl TestClient {
938 fn new() -> Self {
939 Self {
940 events: Mutex::new(Vec::new()),
941 }
942 }
943
944 fn received_events(&self) -> Vec<(String, MuxEvent)> {
945 self.events.lock().unwrap().clone()
946 }
947 }
948
949 impl WpsClient for TestClient {
950 fn send_event(&self, route_id: &str, event: MuxEvent) {
951 self.events
952 .lock()
953 .unwrap()
954 .push((route_id.to_string(), event));
955 }
956 }
957
958 impl WpsClient for Arc<TestClient> {
959 fn send_event(&self, route_id: &str, event: MuxEvent) {
960 self.events
961 .lock()
962 .unwrap()
963 .push((route_id.to_string(), event));
964 }
965 }
966
967 #[test]
968 fn test_subscribe_all_scopes() {
969 let broker = Broker::new();
970 let client = Arc::new(TestClient::new());
971 broker.set_client(Box::new(Arc::clone(&client)));
972
973 broker.subscribe(
974 "route-1",
975 SubscriptionRequest {
976 event: EVENT_MUX_OBJ_UPDATE.to_string(),
977 scopes: vec![],
978 allscopes: true,
979 },
980 );
981
982 broker.publish(MuxEvent {
983 event: EVENT_MUX_OBJ_UPDATE.to_string(),
984 scopes: vec!["block:abc".to_string()],
985 sender: String::new(),
986 persist: 0,
987 data: None,
988 });
989
990 let events = client.received_events();
991 assert_eq!(events.len(), 1);
992 assert_eq!(events[0].0, "route-1");
993 }
994
995 #[test]
996 fn test_subscribe_exact_scope() {
997 let broker = Broker::new();
998 let client = Arc::new(TestClient::new());
999 broker.set_client(Box::new(Arc::clone(&client)));
1000
1001 broker.subscribe(
1002 "route-1",
1003 SubscriptionRequest {
1004 event: EVENT_MUX_OBJ_UPDATE.to_string(),
1005 scopes: vec!["block:abc".to_string()],
1006 allscopes: false,
1007 },
1008 );
1009
1010 broker.publish(MuxEvent {
1012 event: EVENT_MUX_OBJ_UPDATE.to_string(),
1013 scopes: vec!["block:abc".to_string()],
1014 sender: String::new(),
1015 persist: 0,
1016 data: None,
1017 });
1018
1019 broker.publish(MuxEvent {
1021 event: EVENT_MUX_OBJ_UPDATE.to_string(),
1022 scopes: vec!["block:xyz".to_string()],
1023 sender: String::new(),
1024 persist: 0,
1025 data: None,
1026 });
1027
1028 let events = client.received_events();
1029 assert_eq!(events.len(), 1);
1030 }
1031
1032 #[test]
1033 fn test_subscribe_star_scope() {
1034 let broker = Broker::new();
1035 let client = Arc::new(TestClient::new());
1036 broker.set_client(Box::new(Arc::clone(&client)));
1037
1038 broker.subscribe(
1039 "route-1",
1040 SubscriptionRequest {
1041 event: EVENT_MUX_OBJ_UPDATE.to_string(),
1042 scopes: vec!["block:*".to_string()],
1043 allscopes: false,
1044 },
1045 );
1046
1047 broker.publish(MuxEvent {
1048 event: EVENT_MUX_OBJ_UPDATE.to_string(),
1049 scopes: vec!["block:abc".to_string()],
1050 sender: String::new(),
1051 persist: 0,
1052 data: None,
1053 });
1054
1055 broker.publish(MuxEvent {
1056 event: EVENT_MUX_OBJ_UPDATE.to_string(),
1057 scopes: vec!["tab:xyz".to_string()],
1058 sender: String::new(),
1059 persist: 0,
1060 data: None,
1061 });
1062
1063 let events = client.received_events();
1064 assert_eq!(events.len(), 1); }
1066
1067 #[test]
1068 fn test_unsubscribe() {
1069 let broker = Broker::new();
1070 let client = Arc::new(TestClient::new());
1071 broker.set_client(Box::new(Arc::clone(&client)));
1072
1073 broker.subscribe(
1074 "route-1",
1075 SubscriptionRequest {
1076 event: EVENT_BLOCK_CLOSE.to_string(),
1077 scopes: vec![],
1078 allscopes: true,
1079 },
1080 );
1081
1082 broker.unsubscribe("route-1", EVENT_BLOCK_CLOSE);
1083
1084 broker.publish(MuxEvent {
1085 event: EVENT_BLOCK_CLOSE.to_string(),
1086 scopes: vec![],
1087 sender: String::new(),
1088 persist: 0,
1089 data: None,
1090 });
1091
1092 assert!(client.received_events().is_empty());
1093 }
1094
1095 #[test]
1096 fn test_unsubscribe_all() {
1097 let broker = Broker::new();
1098 let client = Arc::new(TestClient::new());
1099 broker.set_client(Box::new(Arc::clone(&client)));
1100
1101 broker.subscribe(
1102 "route-1",
1103 SubscriptionRequest {
1104 event: EVENT_BLOCK_CLOSE.to_string(),
1105 scopes: vec![],
1106 allscopes: true,
1107 },
1108 );
1109 broker.subscribe(
1110 "route-1",
1111 SubscriptionRequest {
1112 event: EVENT_CONFIG.to_string(),
1113 scopes: vec![],
1114 allscopes: true,
1115 },
1116 );
1117
1118 broker.unsubscribe_all("route-1");
1119
1120 broker.publish(MuxEvent {
1121 event: EVENT_BLOCK_CLOSE.to_string(),
1122 scopes: vec![],
1123 sender: String::new(),
1124 persist: 0,
1125 data: None,
1126 });
1127 broker.publish(MuxEvent {
1128 event: EVENT_CONFIG.to_string(),
1129 scopes: vec![],
1130 sender: String::new(),
1131 persist: 0,
1132 data: None,
1133 });
1134
1135 assert!(client.received_events().is_empty());
1136 }
1137
1138 #[test]
1142 fn test_has_subscribers_follows_any_subscription_of_the_event() {
1143 let broker = Broker::new();
1144 assert!(!broker.has_subscribers(EVENT_BLOCK_STATS));
1145 let sub = |event: &str, scopes: Vec<&str>, allscopes: bool| SubscriptionRequest {
1146 event: event.to_string(),
1147 scopes: scopes.into_iter().map(String::from).collect(),
1148 allscopes,
1149 };
1150 broker.subscribe("route-1", sub(EVENT_BLOCK_STATS, vec!["block:abc"], false));
1151 assert!(broker.has_subscribers(EVENT_BLOCK_STATS), "an exact scope counts");
1152 assert!(!broker.has_subscribers(EVENT_SYS_INFO), "another event doesn't");
1153 broker.subscribe("route-2", sub(EVENT_BLOCK_STATS, vec![], true));
1154 broker.unsubscribe("route-1", EVENT_BLOCK_STATS);
1155 assert!(broker.has_subscribers(EVENT_BLOCK_STATS), "route-2 still watches every scope");
1156 broker.subscribe("route-3", sub(EVENT_BLOCK_STATS, vec!["block:*"], false));
1157 broker.unsubscribe_all("route-2");
1158 assert!(broker.has_subscribers(EVENT_BLOCK_STATS), "a wildcard scope counts");
1159 broker.unsubscribe_all("route-3");
1160 assert!(!broker.has_subscribers(EVENT_BLOCK_STATS));
1161 }
1162
1163 #[test]
1167 fn test_replay_on_subscribe_exact_scope() {
1168 let broker = Broker::new();
1169 let client = Arc::new(TestClient::new());
1170 broker.set_client(Box::new(Arc::clone(&client)));
1171
1172 for i in 0..5 {
1174 broker.publish(MuxEvent {
1175 event: "tool_chunk".to_string(),
1176 scopes: vec!["block:abc".to_string()],
1177 sender: String::new(),
1178 persist: 10,
1179 data: Some(serde_json::json!({"tool_id": "t1", "n": i})),
1180 });
1181 }
1182 assert!(
1183 client.received_events().is_empty(),
1184 "no subscriber yet, no delivery"
1185 );
1186
1187 broker.subscribe(
1189 "route-1",
1190 SubscriptionRequest {
1191 event: "tool_chunk".to_string(),
1192 scopes: vec!["block:abc".to_string()],
1193 allscopes: false,
1194 },
1195 );
1196
1197 let events = client.received_events();
1198 assert_eq!(events.len(), 5, "all 5 persisted events replayed");
1199 assert_eq!(events[0].1.data, Some(serde_json::json!({"tool_id": "t1", "n": 0})));
1200 assert_eq!(events[4].1.data, Some(serde_json::json!({"tool_id": "t1", "n": 4})));
1201 }
1202
1203 #[test]
1209 fn test_replay_on_resubscribe_is_idempotent() {
1210 let broker = Broker::new();
1211 let client = Arc::new(TestClient::new());
1212 broker.set_client(Box::new(Arc::clone(&client)));
1213
1214 for i in 0..3 {
1215 broker.publish(MuxEvent {
1216 event: "tool_chunk".to_string(),
1217 scopes: vec!["block:abc".to_string()],
1218 sender: String::new(),
1219 persist: 10,
1220 data: Some(serde_json::json!({"n": i})),
1221 });
1222 }
1223
1224 let sub = SubscriptionRequest {
1225 event: "tool_chunk".to_string(),
1226 scopes: vec!["block:abc".to_string()],
1227 allscopes: false,
1228 };
1229
1230 broker.subscribe("route-1", sub.clone());
1231 assert_eq!(
1232 client.received_events().len(),
1233 3,
1234 "first subscribe replays all 3 persisted events"
1235 );
1236
1237 broker.subscribe("route-1", sub.clone());
1240 assert_eq!(
1241 client.received_events().len(),
1242 3,
1243 "re-subscribe is a no-op for replay; received count stays at 3"
1244 );
1245
1246 broker.publish(MuxEvent {
1248 event: "tool_chunk".to_string(),
1249 scopes: vec!["block:abc".to_string()],
1250 sender: String::new(),
1251 persist: 10,
1252 data: Some(serde_json::json!({"n": "live"})),
1253 });
1254 assert_eq!(
1255 client.received_events().len(),
1256 4,
1257 "live publish after resubscribe is delivered exactly once"
1258 );
1259
1260 broker.unsubscribe_all("route-1");
1262 broker.subscribe("route-1", sub.clone());
1263 assert_eq!(
1264 client.received_events().len(),
1265 8,
1266 "reconnect after unsubscribe_all clears the replayed tracker; \
1267 gets all 4 persisted events again"
1268 );
1269 }
1270
1271 #[test]
1274 fn test_replay_on_subscribe_scope_isolation() {
1275 let broker = Broker::new();
1276 let client = Arc::new(TestClient::new());
1277 broker.set_client(Box::new(Arc::clone(&client)));
1278
1279 broker.publish(MuxEvent {
1280 event: "tool_chunk".to_string(),
1281 scopes: vec!["block:xyz".to_string()],
1282 sender: String::new(),
1283 persist: 10,
1284 data: Some(serde_json::json!({"tool_id": "other"})),
1285 });
1286
1287 broker.subscribe(
1288 "route-1",
1289 SubscriptionRequest {
1290 event: "tool_chunk".to_string(),
1291 scopes: vec!["block:abc".to_string()],
1292 allscopes: false,
1293 },
1294 );
1295
1296 let events = client.received_events();
1297 assert_eq!(events.len(), 0, "scope:abc must not get block:xyz events");
1298 }
1299
1300 #[test]
1301 fn test_event_persistence() {
1302 let broker = Broker::new();
1303 let client = Arc::new(TestClient::new());
1304 broker.set_client(Box::new(Arc::clone(&client)));
1305
1306 broker.subscribe(
1308 "route-1",
1309 SubscriptionRequest {
1310 event: EVENT_SYS_INFO.to_string(),
1311 scopes: vec![],
1312 allscopes: true,
1313 },
1314 );
1315
1316 for i in 0..5 {
1318 broker.publish(MuxEvent {
1319 event: EVENT_SYS_INFO.to_string(),
1320 scopes: vec!["cpu".to_string()],
1321 sender: String::new(),
1322 persist: 3, data: Some(serde_json::json!(i)),
1324 });
1325 }
1326
1327 let history = broker.read_event_history(EVENT_SYS_INFO, "", 10);
1329 assert_eq!(history.len(), 3);
1330 assert_eq!(history[0].data, Some(serde_json::json!(2)));
1331 assert_eq!(history[2].data, Some(serde_json::json!(4)));
1332
1333 let scoped = broker.read_event_history(EVENT_SYS_INFO, "cpu", 2);
1335 assert_eq!(scoped.len(), 2);
1336 }
1337
1338 #[test]
1339 fn test_purge_scope_removes_only_matching_scope() {
1340 let broker = Broker::new();
1341
1342 broker.publish(MuxEvent {
1346 event: "install_progress".to_string(),
1347 scopes: vec!["block:abc".to_string()],
1348 sender: String::new(),
1349 persist: 5,
1350 data: Some(serde_json::json!("a")),
1351 });
1352 broker.publish(MuxEvent {
1353 event: EVENT_BLOCK_ACTIVITY.to_string(),
1354 scopes: vec!["block:abc".to_string()],
1355 sender: String::new(),
1356 persist: 5,
1357 data: Some(serde_json::json!("b")),
1358 });
1359 broker.publish(MuxEvent {
1360 event: "install_progress".to_string(),
1361 scopes: vec!["block:xyz".to_string()],
1362 sender: String::new(),
1363 persist: 5,
1364 data: Some(serde_json::json!("c")),
1365 });
1366
1367 assert_eq!(broker.read_event_history("install_progress", "block:abc", 10).len(), 1);
1368 assert_eq!(broker.read_event_history(EVENT_BLOCK_ACTIVITY, "block:abc", 10).len(), 1);
1369 assert_eq!(broker.read_event_history("install_progress", "block:xyz", 10).len(), 1);
1370
1371 broker.purge_scope("block:abc");
1372
1373 assert_eq!(broker.read_event_history("install_progress", "block:abc", 10).len(), 0);
1375 assert_eq!(broker.read_event_history(EVENT_BLOCK_ACTIVITY, "block:abc", 10).len(), 0);
1376 assert_eq!(broker.read_event_history("install_progress", "block:xyz", 10).len(), 1);
1378 }
1379
1380 #[test]
1381 fn test_purge_scope_on_unknown_scope_is_noop() {
1382 let broker = Broker::new();
1384 broker.purge_scope("block:never-existed");
1385 }
1386
1387 #[test]
1388 fn test_star_match() {
1389 assert!(star_match("block:*", "block:abc", ":"));
1390 assert!(star_match("*:abc", "block:abc", ":"));
1391 assert!(!star_match("block:*", "tab:abc", ":"));
1392 assert!(star_match("**", "block:abc:xyz", ":"));
1393 assert!(!star_match("block:*", "block:abc:xyz", ":")); }
1395
1396 #[test]
1397 fn test_mux_event_serialization() {
1398 let event = MuxEvent {
1399 event: "test".to_string(),
1400 scopes: vec!["scope1".to_string()],
1401 sender: String::new(),
1402 persist: 0,
1403 data: Some(serde_json::json!({"key": "value"})),
1404 };
1405 let json = serde_json::to_string(&event).unwrap();
1406 let parsed: MuxEvent = serde_json::from_str(&json).unwrap();
1407 assert_eq!(parsed.event, "test");
1408 assert_eq!(parsed.scopes, vec!["scope1"]);
1409 assert!(!json.contains("\"sender\""));
1411 assert!(!json.contains("\"persist\""));
1412 }
1413
1414 #[test]
1415 fn test_subscription_request_serialization() {
1416 let req = SubscriptionRequest {
1417 event: "blockclose".to_string(),
1418 scopes: vec!["block:123".to_string()],
1419 allscopes: false,
1420 };
1421 let json = serde_json::to_string(&req).unwrap();
1422 let parsed: SubscriptionRequest = serde_json::from_str(&json).unwrap();
1423 assert_eq!(parsed.event, "blockclose");
1424 }
1425
1426 #[test]
1427 fn test_no_client_publish_does_not_panic() {
1428 let broker = Broker::new();
1429 broker.publish(MuxEvent {
1431 event: "test".to_string(),
1432 scopes: vec![],
1433 sender: String::new(),
1434 persist: 0,
1435 data: None,
1436 });
1437 }
1438
1439 #[test]
1440 fn test_double_star_scope() {
1441 let broker = Broker::new();
1442 let client = Arc::new(TestClient::new());
1443 broker.set_client(Box::new(Arc::clone(&client)));
1444
1445 broker.subscribe(
1446 "route-1",
1447 SubscriptionRequest {
1448 event: EVENT_MUX_OBJ_UPDATE.to_string(),
1449 scopes: vec!["**".to_string()],
1450 allscopes: false,
1451 },
1452 );
1453
1454 broker.publish(MuxEvent {
1455 event: EVENT_MUX_OBJ_UPDATE.to_string(),
1456 scopes: vec!["block:abc:def".to_string()],
1457 sender: String::new(),
1458 persist: 0,
1459 data: None,
1460 });
1461
1462 assert_eq!(client.received_events().len(), 1);
1463 }
1464}