1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
use std::sync::Arc;

use crossbeam::channel::Select;
use parking_lot::Mutex;

use crate::{Receiver, RecvError, SmartChannelSource, SmartMessage};

/// A set of connected [`Receiver`]s.
///
/// Any receiver that gets disconnected is automatically removed from the set.
pub struct ReceiveSet<T: Send> {
    receivers: Mutex<Vec<Receiver<T>>>,
}

impl<T: Send> Default for ReceiveSet<T> {
    fn default() -> Self {
        Self::new(Vec::new())
    }
}

impl<T: Send> ReceiveSet<T> {
    pub fn new(receivers: Vec<Receiver<T>>) -> Self {
        Self {
            receivers: Mutex::new(receivers),
        }
    }

    pub fn add(&self, r: Receiver<T>) {
        re_tracing::profile_function!();
        let mut rx = self.receivers.lock();
        rx.push(r);
    }

    /// Disconnect from any channel with the given source.
    pub fn remove(&self, source: &SmartChannelSource) {
        self.receivers.lock().retain(|r| r.source() != source);
    }

    pub fn retain(&self, mut f: impl FnMut(&Receiver<T>) -> bool) {
        self.receivers.lock().retain(|r| f(r));
    }

    /// Remove all receivers.
    pub fn clear(&self) {
        self.receivers.lock().clear();
    }

    /// Disconnect from any channel with a source pointing at this `uri`.
    #[cfg(target_arch = "wasm32")]
    pub fn remove_by_uri(&self, uri: &str) {
        self.receivers.lock().retain(|r| match r.source() {
            // retain only sources which:
            // - aren't network sources
            // - don't point at the given `uri`
            SmartChannelSource::RrdHttpStream { url, .. } => url != uri,
            SmartChannelSource::WsClient { ws_server_url } => ws_server_url != uri,
            _ => true,
        });
    }

    /// List of connected receiver sources.
    ///
    /// This gets culled after calling one of the `recv` methods.
    pub fn sources(&self) -> Vec<Arc<SmartChannelSource>> {
        re_tracing::profile_function!();
        let mut rx = self.receivers.lock();
        rx.retain(|r| r.is_connected());
        rx.iter().map(|r| r.source.clone()).collect()
    }

    /// Any connected receivers?
    ///
    /// This gets updated after calling one of the `recv` methods.
    pub fn is_connected(&self) -> bool {
        !self.is_empty()
    }

    /// Does this viewer accept inbound TCP connections?
    pub fn accepts_tcp_connections(&self) -> bool {
        re_tracing::profile_function!();
        self.sources()
            .iter()
            .any(|s| matches!(**s, SmartChannelSource::TcpServer { .. }))
    }

    /// No connected receivers?
    ///
    /// This gets updated after calling one of the `recv` methods.
    pub fn is_empty(&self) -> bool {
        re_tracing::profile_function!();
        let mut rx = self.receivers.lock();
        rx.retain(|r| r.is_connected());
        rx.is_empty()
    }

    /// Maximum latency among all receivers (or 0, if none).
    pub fn latency_ns(&self) -> u64 {
        re_tracing::profile_function!();
        let mut latency_ns = 0;
        let rx = self.receivers.lock();
        for r in rx.iter() {
            latency_ns = r.latency_ns().max(latency_ns);
        }
        latency_ns
    }

    /// Sum queue length of all receivers.
    pub fn queue_len(&self) -> usize {
        re_tracing::profile_function!();
        let rx = self.receivers.lock();
        rx.iter().map(|r| r.len()).sum()
    }

    /// Blocks until a message is ready to be received,
    /// or we are empty.
    pub fn recv(&self) -> Result<SmartMessage<T>, RecvError> {
        re_tracing::profile_function!();

        let mut rx = self.receivers.lock();

        loop {
            rx.retain(|r| r.is_connected());
            if rx.is_empty() {
                return Err(RecvError);
            }

            let mut sel = Select::new();
            for r in rx.iter() {
                sel.recv(&r.rx);
            }

            let oper = sel.select();
            let index = oper.index();
            if let Ok(msg) = oper.recv(&rx[index].rx) {
                return Ok(msg);
            }
        }
    }

    /// Returns immediately if there is nothing to receive.
    pub fn try_recv(&self) -> Option<(Arc<SmartChannelSource>, SmartMessage<T>)> {
        re_tracing::profile_function!();

        let mut rx = self.receivers.lock();

        rx.retain(|r| r.is_connected());
        if rx.is_empty() {
            return None;
        }

        let mut sel = Select::new();
        for r in rx.iter() {
            sel.recv(&r.rx);
        }

        let oper = sel.try_select().ok()?;
        let index = oper.index();
        if let Ok(msg) = oper.recv(&rx[index].rx) {
            return Some((rx[index].source.clone(), msg));
        }

        // Nothing ready to receive, but we must poll all receivers to update their `connected` status.
        // Why use `select` first? Because `select` is fair (random) when there is contention.
        for rx in rx.iter() {
            if let Ok(msg) = rx.try_recv() {
                return Some((rx.source.clone(), msg));
            }
        }

        None
    }

    pub fn recv_timeout(
        &self,
        timeout: std::time::Duration,
    ) -> Option<(Arc<SmartChannelSource>, SmartMessage<T>)> {
        re_tracing::profile_function!();

        let mut rx = self.receivers.lock();

        rx.retain(|r| r.is_connected());
        if rx.is_empty() {
            return None;
        }

        let mut sel = Select::new();
        for r in rx.iter() {
            sel.recv(&r.rx);
        }

        let oper = sel.select_timeout(timeout).ok()?;
        let index = oper.index();
        if let Ok(msg) = oper.recv(&rx[index].rx) {
            return Some((rx[index].source.clone(), msg));
        }

        // Nothing ready to receive, but we must poll all receivers to update their `connected` status.
        // Why use `select` first? Because `select` is fair (random) when there is contention.
        for rx in rx.iter() {
            if let Ok(msg) = rx.try_recv() {
                return Some((rx.source.clone(), msg));
            }
        }

        None
    }
}

#[test]
fn test_receive_set() {
    use crate::{smart_channel, SmartMessageSource};

    let timeout = std::time::Duration::from_millis(100);

    let (tx_file, rx_file) = smart_channel::<i32>(
        SmartMessageSource::File("path".into()),
        SmartChannelSource::File("path".into()),
    );
    let (tx_sdk, rx_sdk) = smart_channel::<i32>(SmartMessageSource::Sdk, SmartChannelSource::Sdk);

    let set = ReceiveSet::default();

    assert_eq!(set.try_recv(), None);
    assert_eq!(set.recv_timeout(timeout), None);
    assert_eq!(set.sources(), vec![]);

    set.add(rx_file);

    assert_eq!(set.try_recv(), None);
    assert_eq!(set.recv_timeout(timeout), None);
    assert_eq!(
        set.sources(),
        vec![Arc::new(SmartChannelSource::File("path".into()))]
    );

    set.add(rx_sdk);

    assert_eq!(set.try_recv(), None);
    assert_eq!(set.recv_timeout(timeout), None);
    assert_eq!(
        set.sources(),
        vec![
            Arc::new(SmartChannelSource::File("path".into())),
            Arc::new(SmartChannelSource::Sdk)
        ]
    );

    tx_sdk.send(42).unwrap();
    assert_eq!(set.try_recv().unwrap().0, Arc::new(SmartChannelSource::Sdk));

    assert_eq!(set.try_recv(), None);
    assert_eq!(set.recv_timeout(timeout), None);
    assert_eq!(set.sources().len(), 2);

    drop(tx_sdk);

    assert_eq!(set.try_recv(), None);
    assert_eq!(set.recv_timeout(timeout), None);
    assert_eq!(
        set.sources(),
        vec![Arc::new(SmartChannelSource::File("path".into()))]
    );

    drop(tx_file);

    assert_eq!(set.try_recv(), None);
    assert_eq!(set.recv_timeout(timeout), None);
    assert_eq!(set.sources(), vec![]);
}