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