Skip to main content

mln_engine/storage/
network_status.rs

1//! Whether the network is reachable, as the host reports it.
2
3use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4use std::sync::{Arc, Weak};
5
6use mln_vec_map::VecMap;
7use parking_lot::Mutex;
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10#[repr(u8)]
11pub enum Status {
12    Online,
13    Offline,
14}
15
16/// What an observer runs when the network becomes reachable again.
17type Observer = Arc<dyn Fn() + Send + Sync>;
18
19/// The network's reachability, which the host sets and the online file
20/// sources that share it follow: while it's offline, their requests fail
21/// with a connection error without a transfer, and when it comes back
22/// online, the requests that failed for want of a connection retry at once.
23///
24/// It starts online. Two statuses are equal only when they are the same
25/// one.
26pub struct NetworkStatus {
27    online: AtomicBool,
28    observers: Mutex<VecMap<u64, Observer>>,
29    next_id: AtomicU64,
30}
31
32impl Default for NetworkStatus {
33    fn default() -> Self {
34        Self::new()
35    }
36}
37
38impl std::fmt::Debug for NetworkStatus {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        f.debug_struct("NetworkStatus").field("status", &self.get()).finish_non_exhaustive()
41    }
42}
43
44impl PartialEq for NetworkStatus {
45    fn eq(&self, other: &Self) -> bool {
46        std::ptr::eq(self, other)
47    }
48}
49
50impl Eq for NetworkStatus {}
51
52impl NetworkStatus {
53    /// A status that is online.
54    #[must_use]
55    pub const fn new() -> Self {
56        NetworkStatus {
57            online: AtomicBool::new(true),
58            observers: Mutex::new(VecMap::new()),
59            next_id: AtomicU64::new(1),
60        }
61    }
62
63    #[must_use]
64    pub fn get(&self) -> Status {
65        if self.online.load(Ordering::SeqCst) { Status::Online } else { Status::Offline }
66    }
67
68    /// Sets the status. Going from offline to online tells the observers
69    /// that the network is reachable again.
70    pub fn set(&self, status: Status) {
71        if status == Status::Offline {
72            self.online.store(false, Ordering::SeqCst);
73        } else if !self.online.swap(true, Ordering::SeqCst) {
74            self.reachable();
75        }
76    }
77
78    /// Runs `observer` each time the network becomes reachable, on the thread
79    /// that reports it, until the returned subscription drops.
80    pub(crate) fn subscribe(self: &Arc<Self>, observer: impl Fn() + Send + Sync + 'static) -> Subscription {
81        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
82        self.observers.lock().insert(id, Arc::new(observer));
83        Subscription { status: Arc::downgrade(self), id }
84    }
85
86    /// Tells the observers that the network is reachable, unless the status
87    /// is offline.
88    pub(crate) fn reachable(&self) {
89        if !self.online.load(Ordering::SeqCst) {
90            return;
91        }
92        // Not under the lock, so that an observer may subscribe or drop a
93        // subscription.
94        let observers: Vec<Observer> = self.observers.lock().values().cloned().collect();
95        for observer in observers {
96            observer();
97        }
98    }
99}
100
101/// An observer of a [`NetworkStatus`], which stops observing when this
102/// drops.
103pub(crate) struct Subscription {
104    status: Weak<NetworkStatus>,
105    id: u64,
106}
107
108impl Drop for Subscription {
109    fn drop(&mut self) {
110        if let Some(status) = self.status.upgrade() {
111            status.observers.lock().remove(&self.id);
112        }
113    }
114}
115
116#[cfg(test)]
117mod tests {
118    use std::sync::atomic::AtomicUsize;
119
120    use super::*;
121
122    fn counting(status: &Arc<NetworkStatus>) -> (Subscription, Arc<AtomicUsize>) {
123        let count = Arc::new(AtomicUsize::new(0));
124        let counter = Arc::clone(&count);
125        let subscription = status.subscribe(move || {
126            counter.fetch_add(1, Ordering::SeqCst);
127        });
128        (subscription, count)
129    }
130
131    #[test]
132    fn going_back_online_tells_the_observers() {
133        let status = Arc::new(NetworkStatus::new());
134        let (_subscription, count) = counting(&status);
135        assert_eq!(Status::Online, status.get());
136        status.set(Status::Online);
137        assert_eq!(0, count.load(Ordering::SeqCst));
138        status.set(Status::Offline);
139        assert_eq!(Status::Offline, status.get());
140        assert_eq!(0, count.load(Ordering::SeqCst));
141        status.set(Status::Online);
142        assert_eq!(1, count.load(Ordering::SeqCst));
143    }
144
145    #[test]
146    fn an_offline_status_reports_nothing_reachable() {
147        let status = Arc::new(NetworkStatus::new());
148        let (_subscription, count) = counting(&status);
149        status.reachable();
150        status.set(Status::Offline);
151        status.reachable();
152        assert_eq!(1, count.load(Ordering::SeqCst));
153    }
154
155    #[test]
156    fn a_dropped_subscription_hears_nothing() {
157        let status = Arc::new(NetworkStatus::new());
158        let (subscription, count) = counting(&status);
159        drop(subscription);
160        status.reachable();
161        assert_eq!(0, count.load(Ordering::SeqCst));
162    }
163
164    #[test]
165    fn statuses_are_equal_only_to_themselves() {
166        let (a, b) = (Arc::new(NetworkStatus::new()), Arc::new(NetworkStatus::new()));
167        assert_eq!(a, Arc::clone(&a));
168        assert_ne!(a, b);
169    }
170}