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