BlueGit

ict rusty-teams

Files

rusty-teams / crates / webview / src / fanout.rs

fanout.rs

Initial commit
metis Daniel Däschle · pushed by metis · 7 weeks ago
06e0ae51 History
fanout.rs 2.0 KiB Download Raw
1use std::collections::HashMap;
2
3use session::{App, TabEvent};
4use tokio::sync::mpsc::UnboundedSender;
5
6#[derive(Default)]
7pub(crate) struct Subscribers {
8 sinks: HashMap<App, Vec<UnboundedSender<TabEvent>>>,
9}
10
11impl Subscribers {
12 pub(crate) fn add(&mut self, app: App, sink: UnboundedSender<TabEvent>) {
13 self.sinks.entry(app).or_default().push(sink);
14 }
15
16 pub(crate) fn publish(&mut self, app: App, event: &TabEvent) {
17 if let Some(sinks) = self.sinks.get_mut(&app) {
18 sinks.retain(|sink| sink.send(event.clone()).is_ok());
19 }
20 }
21
22 /// Ends every event stream, so subscribers attach again to the new webviews.
23 pub(crate) fn clear(&mut self) {
24 self.sinks.clear();
25 }
26}
27
28#[cfg(test)]
29mod tests {
30 use serde_json::json;
31 use tokio::sync::mpsc::unbounded_channel;
32
33 use super::*;
34
35 fn event() -> TabEvent {
36 TabEvent {
37 method: "Page.frameNavigated".into(),
38 params: json!({}),
39 }
40 }
41
42 #[test]
43 fn publishes_to_the_app_only_and_drops_closed_sinks() {
44 let mut subscribers = Subscribers::default();
45 let (teams, mut teams_events) = unbounded_channel();
46 let (closed, closed_events) = unbounded_channel();
47 let (outlook, mut outlook_events) = unbounded_channel();
48 subscribers.add(App::Teams, teams);
49 subscribers.add(App::Teams, closed);
50 subscribers.add(App::Outlook, outlook);
51 drop(closed_events);
52 subscribers.publish(App::Teams, &event());
53 assert_eq!(teams_events.try_recv().unwrap(), event());
54 assert!(outlook_events.try_recv().is_err());
55 assert_eq!(subscribers.sinks[&App::Teams].len(), 1);
56 }
57
58 #[test]
59 fn clear_ends_the_streams() {
60 let mut subscribers = Subscribers::default();
61 let (teams, mut teams_events) = unbounded_channel();
62 subscribers.add(App::Teams, teams);
63 subscribers.clear();
64 assert!(teams_events.try_recv().is_err());
65 assert!(teams_events.is_closed());
66 }
67}