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 /// Start an independent, bounded subscription to Windows interface diagnostics.
132 ///
133 /// Each selected source reports whether it can collect evidence. If all
134 /// sources fail, the receiver returns a terminal error after source diagnostics.
135 /// A slow consumer drains its retained prefix and receives a terminal overflow
136 /// error. Subscribing again starts a fresh observation period without replay.
137 ///
138 /// Subscriptions can start on a stopped client. `stop()` affects only connectivity.
139 /// Dropping or unsubscribing the receiver ends its demand. Client shutdown,
140 /// destruction and engine shutdown retire the collection work. Closed clients
141 /// reject new subscriptions. Other platforms return `Unsupported`. Invalid
142 /// options return a configuration error before those checks.
143 pub fn subscribe_interface_events(
144 &self,
145 options: super::InterfaceEventOptions,
146 ) -> Result<EventReceiver<super::InterfaceEvent>> {
147 self.inner.subscribe_interface_events(options)
148 }
149
150 /// Observe the same ordered events with a serial callback on the shared
151 /// callback pool. Retain the returned Subscription while observing events.
152 pub fn on_event<F>(&self, options: NetworkEventOptions, callback: F) -> Result<Subscription>
153 where
154 F: Fn(CallbackContext, std::result::Result<NetworkEvent, crate::error::ReceiveError>)
155 + Send
156 + Sync
157 + 'static,
158 {
159 self.subscribe_events(options)?.into_callback(callback)
160 }
161
162 /// Observe ordered events and automatically reestablish an atomic baseline
163 /// after a bounded queue overflows. The same logical subscription and
164 /// callback context ID survive every recovery and monitor stop/restart.
165 ///
166 /// The retained prefix is delivered first, then `Reconciled`, then events
167 /// after that baseline. Callbacks are serial across recovery. Only queue
168 /// overflow is recovered; other errors terminate the observer, and callback
169 /// panic stops delivery. Dispatch failures cannot always invoke the callback
170 /// again, but remain observable through `Subscription::close` and logs.
171 ///
172 /// Unsubscribe cancels future callback admission and recovery. On success,
173 /// [`Subscription::close`] additionally confirms that the driver and admitted
174 /// callbacks have retired. Polling close inside a subscription callback
175 /// follows its shared context rule: it unsubscribes and returns `InvalidInput`
176 /// without confirming retirement; use [`CallbackContext::unsubscribe`] there.
177 pub fn on_recoverable_event<F>(
178 &self,
179 options: NetworkEventOptions,
180 callback: F,
181 ) -> Result<Subscription>
182 where
183 F: Fn(CallbackContext, Result<NetworkObservation>) + Send + Sync + 'static,
184 {
185 crate::log_t!(LogType::Engine; "net_status.on_recoverable_event",
186 "capacity|max_bytes|callback", options.capacity, options.max_bytes, "provided");
187 self.inner.on_recoverable_event(options, callback)
188 }
189
190 /// Compatibility alias for [`Self::refresh_reachability`].
191 ///
192 /// This method no longer queries, caches, or publishes network names.
193 #[deprecated(note = "use refresh_reachability; network names require observe_network_names")]
194 pub async fn refresh(&self, timeout: Duration) -> Result<NetworkRefreshResult> {
195 crate::log_t!(LogType::Engine; "net_status.refresh", "timeout", timeout);
196 crate::module::net_status::inner::refresh::refresh(self.inner.clone(), timeout).await
197 }
198
199 /// Query and commit fresh Windows reachability without querying a name.
200 /// Uses a separate bounded worker so a slow or failed network-name query
201 /// cannot block this query or background reachability monitoring. The IP
202 /// stack retains its latest background value. The compatibility name field
203 /// is always None, with NotCollected provenance and no name diagnostics.
204 /// Requires Running and a positive timeout covering admission, sampling and
205 /// commit. Dropping this future invalidates uncommitted results. A newer
206 /// committed reachability sample supersedes an older query with Cancelled.
207 /// After input and lifecycle validation, other platforms return Unsupported.
208 /// As with [`Self::refresh`], the timeout is a result-validity budget, not a
209 /// hard real-time return deadline; success does not await observer callbacks.
210 pub async fn refresh_reachability(&self, timeout: Duration) -> Result<NetworkRefreshResult> {
211 crate::log_t!(LogType::Engine; "net_status.refresh_reachability", "timeout", timeout);
212 crate::module::net_status::inner::refresh::refresh_reachability(self.inner.clone(), timeout)
213 .await
214 }
215
216 /// Compatibility alias for [`Self::refresh_reachability_blocking`].
217 ///
218 /// This no longer queries names. It has the same
219 /// sampling, field provenance and lifecycle checks. A positive timeout is
220 /// required; after input and lifecycle validation, other platforms return
221 /// `Unsupported`. Errors never silently fall back to [`Self::snapshot`].
222 /// Expired samples cannot commit, but scheduling and lock contention can
223 /// delay the return beyond the budget; it is not a hard real-time bound.
224 /// Success means the sample was committed, not that observers have finished.
225 ///
226 /// Blocks the calling thread. Ordinary threads, external Tokio runtimes,
227 /// nested futures executors and the SDK's separate subscription callback
228 /// pool are supported; the SDK drives its own timers and sampling workers.
229 /// Prefer [`Self::refresh_reachability`] in async code and avoid blocking a UI thread.
230 /// SDK management-runtime threads (including its blocking pool) and sampling
231 /// threads are rejected before any query with `InvalidInput`, stage
232 /// `NetworkMonitor`, and field `network_status.refresh_blocking.context`.
233 /// Entering an SDK runtime context alone does not trigger this rejection.
234 #[deprecated(
235 note = "use refresh_reachability_blocking; network names require observe_network_names"
236 )]
237 pub fn refresh_blocking(&self, timeout: Duration) -> Result<NetworkRefreshResult> {
238 crate::log_t!(LogType::Engine; "net_status.refresh_blocking", "timeout", timeout);
239 crate::module::net_status::inner::refresh::refresh_blocking(self.inner.clone(), timeout)
240 }
241
242 /// Synchronously query and commit fresh Windows reachability only.
243 ///
244 /// The blocking counterpart of [`Self::refresh_reachability`], using its
245 /// independent sampling lane. The IP-stack value remains cached; no name
246 /// is queried or returned. Requires Running
247 /// and a positive timeout; other platforms return `Unsupported` after these
248 /// checks. Never substitutes a cached snapshot for a failed fresh query.
249 ///
250 /// The blocking, timeout and SDK-thread restrictions of
251 /// [`Self::refresh_blocking`] apply. Async callers should normally use
252 /// [`Self::refresh_reachability`] instead.
253 ///
254 /// ```no_run
255 /// use open_net::{NetStatusClient, NetworkRefreshResult, Result};
256 /// use std::time::Duration;
257 ///
258 /// // Call from a synchronous integration after start().await has succeeded.
259 /// fn query_now(client: &NetStatusClient) -> Result<NetworkRefreshResult> {
260 /// client.refresh_reachability_blocking(Duration::from_secs(3))
261 /// }
262 /// ```
263 pub fn refresh_reachability_blocking(&self, timeout: Duration) -> Result<NetworkRefreshResult> {
264 crate::log_t!(LogType::Engine; "net_status.refresh_reachability_blocking", "timeout", timeout);
265 crate::module::net_status::inner::refresh::refresh_reachability_blocking(
266 self.inner.clone(),
267 timeout,
268 )
269 }
270
271 pub(crate) fn request_destroy(&self) {
272 self.inner.request_close();
273 }
274
275 pub(crate) async fn destroy(&self) -> Result<()> {
276 self.inner.request_close();
277 self.inner.wait_cleanup().await
278 }
279}
280
281impl fmt::Debug for NetStatusClient {
282 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
283 formatter
284 .debug_struct("NetStatusClient")
285 .finish_non_exhaustive()
286 }
287}