Skip to main content

labstream_net/
resolver.rs

1//! The background resolver.
2//!
3//! A one-shot resolve sends a wave of queries, waits, and returns what it
4//! found. A background resolver keeps sending waves and keeps a list that
5//! grows when a stream appears and shrinks when one stops answering
6//! (`src/resolver_impl.cpp:130-168`).
7//!
8//! An application uses this to show a live list of streams. `GetAllStreams`,
9//! one of the example programs of liblsl, does exactly that.
10
11use crate::info::StreamInfo;
12use std::collections::HashMap;
13use std::sync::atomic::{AtomicBool, Ordering};
14use std::sync::{Arc, Mutex};
15use std::time::Duration;
16
17/// How long to wait between two waves.
18///
19/// `src/resolver_impl.cpp` adds `ContinuousResolveInterval` to
20/// `MulticastMinRTT`, whose defaults are 0.5 and 0.5 (`src/api_config.cpp:307`
21/// and `:311`).
22fn wave_interval() -> Duration {
23    let cfg = crate::config::get();
24    Duration::from_secs_f64(cfg.continuous_resolve_interval + cfg.multicast_min_rtt)
25}
26
27struct Shared {
28    /// One entry for each stream, with the clock reading of the last answer.
29    found: Mutex<HashMap<String, (StreamInfo, f64)>>,
30    stop: AtomicBool,
31}
32
33/// A resolver that keeps looking.
34pub struct ContinuousResolver {
35    shared: Arc<Shared>,
36    /// How long a stream stays in the list after its last answer, in seconds.
37    forget_after: f64,
38}
39
40impl ContinuousResolver {
41    /// Start looking for streams that match a query.
42    ///
43    /// The thread stops when the resolver is dropped.
44    pub fn new(query: &str, forget_after: f64) -> ContinuousResolver {
45        let shared = Arc::new(Shared {
46            found: Mutex::new(HashMap::new()),
47            stop: AtomicBool::new(false),
48        });
49        let worker = Arc::clone(&shared);
50        let q = query.to_string();
51        std::thread::spawn(move || wave_loop(&q, worker));
52        ContinuousResolver {
53            shared,
54            forget_after,
55        }
56    }
57
58    /// The streams that answered lately.
59    ///
60    /// A stream whose last answer is older than `forget_after` is removed
61    /// here, not by the thread. liblsl does the same
62    /// (`src/resolver_impl.cpp:151-168`), so a caller that never asks keeps
63    /// every entry.
64    pub fn results(&self, max: usize) -> Vec<StreamInfo> {
65        let now = crate::clock();
66        let mut map = self.shared.found.lock().unwrap();
67        map.retain(|_, (_, seen)| *seen >= now - self.forget_after);
68        map.values().take(max).map(|(i, _)| i.clone()).collect()
69    }
70
71    /// How many streams the resolver holds, without removing any.
72    pub fn len(&self) -> usize {
73        self.shared.found.lock().unwrap().len()
74    }
75
76    /// True when the resolver holds no stream.
77    pub fn is_empty(&self) -> bool {
78        self.len() == 0
79    }
80}
81
82impl Drop for ContinuousResolver {
83    fn drop(&mut self) {
84        self.shared.stop.store(true, Ordering::SeqCst);
85    }
86}
87
88/// Send a wave, collect the answers, wait, and repeat.
89fn wave_loop(query: &str, shared: Arc<Shared>) {
90    let cfg = crate::config::get();
91    let mut wave = match crate::inlet::QueryWave::open() {
92        Ok(w) => w,
93        Err(_) => return,
94    };
95    let mut round: u32 = 0;
96    while !shared.stop.load(Ordering::SeqCst) {
97        wave.send(query);
98        let empty = shared.found.lock().unwrap().is_empty();
99        let run_fallback = match cfg.fallback_discovery {
100            crate::config::FallbackDiscovery::Off => false,
101            crate::config::FallbackDiscovery::Subnet => true,
102            crate::config::FallbackDiscovery::Auto => round > 0 && empty,
103        };
104        if run_fallback {
105            wave.send_fallback(query, round.saturating_sub(1));
106        }
107        let mut answers = wave.collect(Duration::from_millis(400), |_| false);
108        if answers.is_empty() && run_fallback && !cfg.known_peers.is_empty() {
109            answers =
110                crate::inlet::probe_peers_tcp(&cfg.known_peers, query, Duration::from_millis(400));
111        }
112        if !answers.is_empty() {
113            let now = crate::clock();
114            let mut map = shared.found.lock().unwrap();
115            for info in answers {
116                map.insert(info.uid.clone(), (info, now));
117            }
118        }
119        round = round.saturating_add(1);
120        // Sleep in short steps, so a dropped resolver stops without a wait.
121        let mut left = wave_interval();
122        while left > Duration::ZERO && !shared.stop.load(Ordering::SeqCst) {
123            let step = left.min(Duration::from_millis(100));
124            std::thread::sleep(step);
125            left -= step;
126        }
127    }
128}