Skip to main content

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