1use std::sync::OnceLock;
8
9use tokio::sync::watch;
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
12pub enum Connectivity {
13 Online,
14 Offline,
15 Unknown,
17}
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
20#[non_exhaustive]
21pub struct NetStatus {
22 pub connectivity: Connectivity,
23 pub metered: Option<bool>,
26}
27
28impl NetStatus {
29 #[must_use]
30 pub fn online(self) -> bool {
31 self.connectivity != Connectivity::Offline
32 }
33}
34
35#[must_use]
37pub fn current() -> NetStatus {
38 (*host().borrow()).unwrap_or_else(imp::current)
39}
40
41fn host() -> &'static watch::Sender<Option<NetStatus>> {
45 static HOST: OnceLock<watch::Sender<Option<NetStatus>>> = OnceLock::new();
46 HOST.get_or_init(|| watch::channel(None).0)
47}
48
49#[doc(hidden)]
52pub fn set_host_status(available: Option<bool>, metered: Option<bool>) {
53 host().send_replace(Some(NetStatus {
54 connectivity: match available {
55 Some(true) => Connectivity::Online,
56 Some(false) => Connectivity::Offline,
57 None => Connectivity::Unknown,
58 },
59 metered,
60 }));
61}
62
63#[doc(hidden)]
65pub fn clear_host_status() {
66 host().send_replace(None);
67}
68
69#[must_use]
70pub fn online() -> bool {
71 current().online()
72}
73
74pub struct Watch {
75 last: NetStatus,
76 inner: imp::Watch,
77 host: watch::Receiver<Option<NetStatus>>,
78}
79
80impl std::fmt::Debug for Watch {
81 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82 f.debug_struct("Watch")
83 .field("last", &self.last)
84 .finish_non_exhaustive()
85 }
86}
87
88#[must_use]
89pub fn watch() -> Watch {
90 Watch {
91 last: current(),
92 inner: imp::Watch::new(),
93 host: host().subscribe(),
94 }
95}
96
97impl Watch {
98 #[must_use]
99 pub fn last(&self) -> NetStatus {
100 self.last
101 }
102
103 pub async fn changed(&mut self) -> NetStatus {
104 loop {
105 let now = current();
106 if now != self.last {
107 self.last = now;
108 return now;
109 }
110 tokio::select! {
111 changed = self.host.changed() => {
112 if changed.is_err() {
113 self.inner.wait().await;
114 }
115 }
116 () = self.inner.wait() => {}
117 }
118 }
119 }
120}
121
122#[cfg(not(target_family = "wasm"))]
123mod imp {
124 use std::io::ErrorKind;
125 use std::net::{SocketAddr, UdpSocket};
126 use std::time::Duration;
127
128 use super::{Connectivity, NetStatus};
129
130 pub(super) const POLL: Duration = Duration::from_secs(5);
132
133 const PROBES: [&str; 2] = ["198.51.100.1:9", "[2001:db8::1]:9"];
136
137 fn route(probe: &str) -> Option<bool> {
138 let target: SocketAddr = probe.parse().ok()?;
139 let local: SocketAddr = if target.is_ipv4() {
140 "0.0.0.0:0".parse().ok()?
141 } else {
142 "[::]:0".parse().ok()?
143 };
144 let socket = UdpSocket::bind(local).ok()?;
145 match socket.connect(target) {
146 Ok(()) => Some(true),
147 Err(error)
148 if matches!(
149 error.kind(),
150 ErrorKind::NetworkUnreachable | ErrorKind::HostUnreachable
151 ) =>
152 {
153 Some(false)
154 }
155 Err(_) => None,
156 }
157 }
158
159 pub(super) fn fallback() -> NetStatus {
160 let answers = PROBES.map(route);
161 let connectivity = if answers.contains(&Some(true)) {
162 Connectivity::Online
163 } else if answers.iter().all(|answer| *answer == Some(false)) {
164 Connectivity::Offline
165 } else {
166 Connectivity::Unknown
167 };
168 NetStatus {
169 connectivity,
170 metered: None,
171 }
172 }
173
174 #[cfg(all(target_os = "linux", feature = "system-status"))]
175 pub(super) use super::linux::{Watch, current};
176
177 #[cfg(any(
178 not(target_os = "linux"),
179 all(target_os = "linux", not(feature = "system-status"))
180 ))]
181 pub(super) fn current() -> NetStatus {
182 fallback()
183 }
184
185 #[cfg(any(
186 not(target_os = "linux"),
187 all(target_os = "linux", not(feature = "system-status"))
188 ))]
189 pub(super) struct Watch;
190
191 #[cfg(any(
192 not(target_os = "linux"),
193 all(target_os = "linux", not(feature = "system-status"))
194 ))]
195 impl Watch {
196 pub(super) fn new() -> Self {
197 Self
198 }
199
200 #[allow(
201 clippy::needless_pass_by_ref_mut,
202 reason = "the same signature as the page backend"
203 )]
204 pub(super) async fn wait(&mut self) {
205 tokio::time::sleep(POLL).await;
206 }
207 }
208}
209
210#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
211mod imp {
212 use super::{Connectivity, NetStatus};
213
214 pub(super) fn current() -> NetStatus {
215 let navigator = crate::web::global_get("navigator");
216 let connectivity = match navigator
217 .as_ref()
218 .and_then(|navigator| crate::web::get(navigator, "onLine"))
219 .and_then(|online| online.as_bool())
220 {
221 Some(true) => Connectivity::Online,
222 Some(false) => Connectivity::Offline,
223 None => Connectivity::Unknown,
224 };
225 let connection = navigator
226 .as_ref()
227 .and_then(|navigator| crate::web::get(navigator, "connection"));
228 let metered = connection.as_ref().map(|connection| {
229 let save_data = crate::web::get(connection, "saveData")
230 .and_then(|value| value.as_bool())
231 .unwrap_or(false);
232 let cellular = crate::web::get(connection, "type")
233 .and_then(|value| value.as_string())
234 .is_some_and(|kind| kind == "cellular");
235 save_data || cellular
236 });
237 NetStatus {
238 connectivity,
239 metered,
240 }
241 }
242
243 pub(super) struct Watch(crate::web::Events);
244
245 impl Watch {
246 pub(super) fn new() -> Self {
247 let mut events = crate::web::Events::new();
248 if let Some(global) = crate::web::global() {
249 events.listen(&global, &["online", "offline"]);
250 }
251 if let Some(connection) = crate::web::global_get("navigator")
252 .and_then(|navigator| crate::web::get(&navigator, "connection"))
253 {
254 events.listen(&connection, &["change"]);
255 }
256 Self(events)
257 }
258
259 pub(super) async fn wait(&mut self) {
260 self.0.next().await;
261 }
262 }
263}
264
265#[cfg(test)]
266#[cfg(not(target_family = "wasm"))]
267mod tests {
268 use super::*;
269
270 #[test]
271 fn the_route_probe_answers_without_sending() {
272 let status = imp::fallback();
274 assert_eq!(
275 status.metered, None,
276 "an absent reading is unknown, never unmetered"
277 );
278 #[cfg(not(target_os = "linux"))]
279 assert_eq!(watch().last().connectivity, status.connectivity);
280 }
281
282 #[cfg(not(all(target_os = "linux", feature = "system-status")))]
285 #[test]
286 fn a_hosts_hint_is_the_answer_and_its_loss_falls_back() {
287 set_host_status(Some(false), Some(true));
288 assert_eq!(current().connectivity, Connectivity::Offline);
289 assert_eq!(current().metered, Some(true));
290 clear_host_status();
291 assert_eq!(
292 current().metered,
293 None,
294 "the local probe never claims metering"
295 );
296 }
297}
298
299#[cfg(all(target_os = "linux", feature = "system-status"))]
300#[path = "status_linux.rs"]
301mod linux;