open_net/api/net_status/net_status_client.rs
1use std::fmt;
2use std::sync::Arc;
3use std::time::Duration;
4
5use crate::net_status::NetworkSnapshot;
6use crate::net_status::NetworkStatusContext;
7use crate::net_status::{
8 NetworkEvent, NetworkEventOptions, NetworkObservation, NetworkRefreshResult,
9};
10use crate::subscription::{CallbackContext, EventReceiver, StateReceiver, Subscription};
11use crate::{LogType, Result};
12
13use crate::module::net_status::inner::facade::NetworkObservationOwner;
14
15/// An independent view of the engine's shared network monitor.
16/// Clones share this view's lifecycle; other named views remain independent.
17#[derive(Clone)]
18pub struct NetStatusClient {
19 inner: Arc<NetworkObservationOwner>,
20}
21
22impl NetStatusClient {
23 pub(crate) fn new(context: NetworkStatusContext) -> Result<Self> {
24 Ok(Self {
25 inner: NetworkObservationOwner::new(context)?,
26 })
27 }
28
29 /// Start monitoring and await the first coherent observation.
30 /// Repeated calls share the active monitor and its initialization result.
31 pub async fn start(&self) -> Result<NetworkSnapshot> {
32 crate::log_t!(LogType::Engine; "net_status.start");
33 self.inner.start().await
34 }
35
36 /// Stop monitoring while keeping subscriptions alive for a later restart.
37 pub async fn stop(&self) -> Result<()> {
38 crate::log_t!(LogType::Engine; "net_status.stop");
39 self.inner.request_stop()?;
40 self.inner.wait_cleanup().await
41 }
42
43 /// Permanently close monitoring and publish its final Closed snapshot.
44 pub async fn shutdown(&self) -> Result<()> {
45 crate::log_t!(LogType::Engine; "net_status.shutdown");
46 self.inner.request_close();
47 self.inner.wait_cleanup().await
48 }
49
50 /// Read the latest coherent snapshot, including an inactive or final state.
51 pub fn snapshot(&self) -> Result<NetworkSnapshot> {
52 self.inner.snapshot()
53 }
54
55 /// Explicitly observe Windows Wi-Fi SSID or NLM network display names.
56 ///
57 /// This is the only monitoring API that enables name collection. It does
58 /// not start connectivity monitoring or modify connectivity snapshots,
59 /// HTTP observations, or network events. The returned observer owns its
60 /// name demand and exposes a separate latest-value stream.
61 ///
62 /// A stopped connectivity client can observe names. `stop()` affects only
63 /// connectivity; client shutdown/destroy and engine shutdown close names
64 /// too. Drop requests cancellation; await the observer's `close()` to
65 /// confirm that cached/pending values and in-flight work have retired.
66 /// Already returned application-owned copies cannot be recalled.
67 ///
68 /// Invalid options are rejected before lifecycle checks. Closed clients
69 /// reject admission; other platforms return `Unsupported`. Creation on
70 /// Windows does not wait for an OS query. `recv()` starts with Pending
71 /// unless the observer has already closed; `snapshot()` reads the latest
72 /// state, which may already contain a result. Sampling errors are delivered
73 /// on the name stream.
74 pub fn observe_network_names(
75 &self,
76 options: crate::net_status::NetworkNameOptions,
77 ) -> Result<crate::net_status::NetworkNameObserver> {
78 self.inner.observe_network_names(options)
79 }
80
81 /// Collect a fresh LAN IPv4 inventory using [`crate::network::lan_ipv4_snapshot`].
82 ///
83 /// Synchronous OS query: it blocks this caller and needs no caller runtime.
84 /// Stopped, Starting, Running and ordinary monitoring Failed states permit
85 /// the query; it neither starts monitoring nor requires Internet access.
86 /// It never changes the cached network snapshot, revisions or event stream.
87 /// Existing network events do not guarantee notification of LAN-only changes.
88 ///
89 /// A closed client (including its clones), destroyed named client, or closing
90 /// engine rejects new queries with Closed. A query admitted before closing
91 /// may finish normally; shutdown does not wait for this caller's read-only
92 /// query, which owns no monitored resources. Prefer a blocking worker when
93 /// calling from async/UI code.
94 pub fn query_lan_ipv4(&self) -> Result<crate::network::LanIpv4Snapshot> {
95 self.inner.admit_lan_query()?;
96 crate::network::lan_ipv4_snapshot()
97 }
98
99 /// Subscribe to the current snapshot and later changes across stop/restart.
100 pub fn subscribe(&self) -> Result<StateReceiver<NetworkSnapshot>> {
101 crate::log_t!(LogType::Engine; "net_status.subscribe");
102 self.inner.subscribe_terminal()
103 }
104
105 /// Observe the same snapshots as an asynchronous subscription on the shared
106 /// callback pool. Keep the returned owner alive while observing changes.
107 pub fn on_change<F>(&self, callback: F) -> Result<Subscription>
108 where
109 F: Fn(CallbackContext, Result<NetworkSnapshot>) + Send + Sync + 'static,
110 {
111 self.subscribe()?.into_callback(callback)
112 }
113
114 /// Subscribe atomically to an initial baseline and ordered committed events.
115 /// Each subscription has its own bounded queue. Overflow drains the queued
116 /// prefix, reports a failure, and ends that subscription; subscribe again to
117 /// establish a fresh baseline. Initial and lifecycle entries use capacity.
118 pub fn subscribe_events(
119 &self,
120 options: NetworkEventOptions,
121 ) -> Result<EventReceiver<NetworkEvent>> {
122 crate::log_t!(LogType::Engine; "net_status.subscribe_events",
123 "capacity|max_bytes", options.capacity, options.max_bytes);
124 self.inner.subscribe_events(options)
125 }
126
127 /// Observe the same ordered events with a serial callback on the shared
128 /// callback pool. Retain the returned Subscription while observing events.
129 pub fn on_event<F>(&self, options: NetworkEventOptions, callback: F) -> Result<Subscription>
130 where
131 F: Fn(CallbackContext, std::result::Result<NetworkEvent, crate::error::ReceiveError>)
132 + Send
133 + Sync
134 + 'static,
135 {
136 self.subscribe_events(options)?.into_callback(callback)
137 }
138
139 /// Observe ordered events and automatically reestablish an atomic baseline
140 /// after a bounded queue overflows. The same logical subscription and
141 /// callback context ID survive every recovery and monitor stop/restart.
142 ///
143 /// The retained prefix is delivered first, then `Reconciled`, then events
144 /// after that baseline. Callbacks are serial across recovery. Only queue
145 /// overflow is recovered; other errors terminate the observer, and callback
146 /// panic stops delivery. Dispatch failures cannot always invoke the callback
147 /// again, but remain observable through `Subscription::close` and logs.
148 ///
149 /// Unsubscribe cancels future callback admission and recovery. On success,
150 /// [`Subscription::close`] additionally confirms that the driver and admitted
151 /// callbacks have retired. Polling close inside a subscription callback
152 /// follows its shared context rule: it unsubscribes and returns `InvalidInput`
153 /// without confirming retirement; use [`CallbackContext::unsubscribe`] there.
154 pub fn on_recoverable_event<F>(
155 &self,
156 options: NetworkEventOptions,
157 callback: F,
158 ) -> Result<Subscription>
159 where
160 F: Fn(CallbackContext, Result<NetworkObservation>) + Send + Sync + 'static,
161 {
162 crate::log_t!(LogType::Engine; "net_status.on_recoverable_event",
163 "capacity|max_bytes|callback", options.capacity, options.max_bytes, "provided");
164 self.inner.on_recoverable_event(options, callback)
165 }
166
167 /// Compatibility alias for [`Self::refresh_reachability`].
168 ///
169 /// This method no longer queries, caches, or publishes network names.
170 #[deprecated(note = "use refresh_reachability; network names require observe_network_names")]
171 pub async fn refresh(&self, timeout: Duration) -> Result<NetworkRefreshResult> {
172 crate::log_t!(LogType::Engine; "net_status.refresh", "timeout", timeout);
173 crate::module::net_status::inner::refresh::refresh(self.inner.clone(), timeout).await
174 }
175
176 /// Query and commit fresh Windows reachability without querying a name.
177 /// Uses a separate bounded worker so a slow or failed network-name query
178 /// cannot block this query or background reachability monitoring. The IP
179 /// stack retains its latest background value. The compatibility name field
180 /// is always None, with NotCollected provenance and no name diagnostics.
181 /// Requires Running and a positive timeout covering admission, sampling and
182 /// commit. Dropping this future invalidates uncommitted results. A newer
183 /// committed reachability sample supersedes an older query with Cancelled.
184 /// After input and lifecycle validation, other platforms return Unsupported.
185 /// As with [`Self::refresh`], the timeout is a result-validity budget, not a
186 /// hard real-time return deadline; success does not await observer callbacks.
187 pub async fn refresh_reachability(&self, timeout: Duration) -> Result<NetworkRefreshResult> {
188 crate::log_t!(LogType::Engine; "net_status.refresh_reachability", "timeout", timeout);
189 crate::module::net_status::inner::refresh::refresh_reachability(self.inner.clone(), timeout)
190 .await
191 }
192
193 /// Compatibility alias for [`Self::refresh_reachability_blocking`].
194 ///
195 /// This no longer queries names. It has the same
196 /// sampling, field provenance and lifecycle checks. A positive timeout is
197 /// required; after input and lifecycle validation, other platforms return
198 /// `Unsupported`. Errors never silently fall back to [`Self::snapshot`].
199 /// Expired samples cannot commit, but scheduling and lock contention can
200 /// delay the return beyond the budget; it is not a hard real-time bound.
201 /// Success means the sample was committed, not that observers have finished.
202 ///
203 /// Blocks the calling thread. Ordinary threads, external Tokio runtimes,
204 /// nested futures executors and the SDK's separate subscription callback
205 /// pool are supported; the SDK drives its own timers and sampling workers.
206 /// Prefer [`Self::refresh_reachability`] in async code and avoid blocking a UI thread.
207 /// SDK management-runtime threads (including its blocking pool) and sampling
208 /// threads are rejected before any query with `InvalidInput`, stage
209 /// `NetworkMonitor`, and field `network_status.refresh_blocking.context`.
210 /// Entering an SDK runtime context alone does not trigger this rejection.
211 #[deprecated(
212 note = "use refresh_reachability_blocking; network names require observe_network_names"
213 )]
214 pub fn refresh_blocking(&self, timeout: Duration) -> Result<NetworkRefreshResult> {
215 crate::log_t!(LogType::Engine; "net_status.refresh_blocking", "timeout", timeout);
216 crate::module::net_status::inner::refresh::refresh_blocking(self.inner.clone(), timeout)
217 }
218
219 /// Synchronously query and commit fresh Windows reachability only.
220 ///
221 /// The blocking counterpart of [`Self::refresh_reachability`], using its
222 /// independent sampling lane. The IP-stack value remains cached; no name
223 /// is queried or returned. Requires Running
224 /// and a positive timeout; other platforms return `Unsupported` after these
225 /// checks. Never substitutes a cached snapshot for a failed fresh query.
226 ///
227 /// The blocking, timeout and SDK-thread restrictions of
228 /// [`Self::refresh_blocking`] apply. Async callers should normally use
229 /// [`Self::refresh_reachability`] instead.
230 ///
231 /// ```no_run
232 /// use open_net::{NetStatusClient, NetworkRefreshResult, Result};
233 /// use std::time::Duration;
234 ///
235 /// // Call from a synchronous integration after start().await has succeeded.
236 /// fn query_now(client: &NetStatusClient) -> Result<NetworkRefreshResult> {
237 /// client.refresh_reachability_blocking(Duration::from_secs(3))
238 /// }
239 /// ```
240 pub fn refresh_reachability_blocking(&self, timeout: Duration) -> Result<NetworkRefreshResult> {
241 crate::log_t!(LogType::Engine; "net_status.refresh_reachability_blocking", "timeout", timeout);
242 crate::module::net_status::inner::refresh::refresh_reachability_blocking(
243 self.inner.clone(),
244 timeout,
245 )
246 }
247
248 pub(crate) fn request_destroy(&self) {
249 self.inner.request_close();
250 }
251
252 pub(crate) async fn destroy(&self) -> Result<()> {
253 self.inner.request_close();
254 self.inner.wait_cleanup().await
255 }
256}
257
258impl fmt::Debug for NetStatusClient {
259 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
260 formatter
261 .debug_struct("NetStatusClient")
262 .finish_non_exhaustive()
263 }
264}