Skip to main content

open_net/api/net_status/
names.rs

1//! Explicit, isolated observation of potentially identifying network names.
2use std::fmt;
3use std::time::{Duration, SystemTime};
4
5use crate::error::{ErrorKind, ErrorStage, NetError};
6use crate::module::net_status::inner::names::NameConsumer;
7use crate::net_status::NetworkNameSource;
8use std::sync::Arc;
9
10/// Sampling options for an explicitly requested network-name observer.
11///
12/// This policy is independent of connection availability policies. Compiling
13/// network monitoring support does not enable name collection.
14#[derive(Clone, Copy, Debug)]
15pub struct NetworkNameOptions {
16    interval: Duration,
17    timeout: Duration,
18}
19
20impl Default for NetworkNameOptions {
21    fn default() -> Self {
22        Self {
23            interval: Duration::from_secs(30),
24            timeout: Duration::from_secs(10),
25        }
26    }
27}
28
29impl NetworkNameOptions {
30    /// Set the delay after one sample completes before this observer samples again.
31    /// Valid values range from one second through one hour, inclusive.
32    pub fn with_interval(mut self, interval: Duration) -> Self {
33        self.interval = interval;
34        self
35    }
36
37    /// Set the validity budget for a native sampling operation.
38    /// Valid values range from 100 milliseconds through 30 seconds, inclusive.
39    /// The budget begins when the serial worker starts this observer's query;
40    /// it does not impose a deadline on waiting behind other observers.
41    /// Native calls may finish after this budget, but expired values are discarded.
42    pub fn with_timeout(mut self, timeout: Duration) -> Self {
43        self.timeout = timeout;
44        self
45    }
46
47    /// Delay between completed sampling operations for this observer.
48    pub fn interval(&self) -> Duration {
49        self.interval
50    }
51
52    /// Validity budget for each native query.
53    pub fn timeout(&self) -> Duration {
54        self.timeout
55    }
56
57    pub(crate) fn validate(&self) -> Result<(), NetError> {
58        if !(Duration::from_secs(1)..=Duration::from_secs(3600)).contains(&self.interval)
59            || !(Duration::from_millis(100)..=Duration::from_secs(30)).contains(&self.timeout)
60        {
61            return Err(
62                NetError::from(ErrorKind::InvalidInput).with_stage(ErrorStage::NetworkMonitor)
63            );
64        }
65        Ok(())
66    }
67}
68
69/// Lifecycle of a dedicated name observation.
70#[non_exhaustive]
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum NetworkNameState {
73    /// The observer has not received a completed sample.
74    Pending,
75    /// A query completed, possibly without an available name.
76    Ready,
77    /// The latest query failed. No previous name is retained.
78    Failed,
79    /// Collection stopped and the SDK's retained values were cleared.
80    Closed,
81}
82
83/// An owned network-name observation, separate from ordinary connectivity state.
84///
85/// Names may identify a person or location. Only `name()` exposes the raw value;
86/// `Debug` excludes it. Values already returned to the application are owned by
87/// that application and cannot be revoked by closing the observer.
88#[derive(Clone)]
89pub struct NetworkNameSnapshot {
90    state: NetworkNameState,
91    name: Option<String>,
92    source: NetworkNameSource,
93    sampled_at: Option<SystemTime>,
94    error: Option<NetError>,
95    diagnostics: Vec<NetError>,
96    #[cfg(test)]
97    retention_probe: Option<Arc<()>>,
98}
99
100impl fmt::Debug for NetworkNameSnapshot {
101    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102        f.debug_struct("NetworkNameSnapshot")
103            .field("state", &self.state)
104            .field("name_present", &self.name.is_some())
105            .field("source", &self.source)
106            .field("sampled_at", &self.sampled_at)
107            .field("error_kind", &self.error.as_ref().map(NetError::kind))
108            .field("diagnostic_count", &self.diagnostics.len())
109            .finish()
110    }
111}
112
113impl NetworkNameSnapshot {
114    /// Current collection state.
115    pub fn state(&self) -> NetworkNameState {
116        self.state
117    }
118
119    /// The raw network name, available only after a successful query.
120    pub fn name(&self) -> Option<&str> {
121        self.name.as_deref()
122    }
123
124    /// Native source of the name, or NotCollected for an empty lifecycle state.
125    pub fn source(&self) -> NetworkNameSource {
126        self.source
127    }
128
129    /// Wall-clock completion time of a successful query.
130    pub fn sampled_at(&self) -> Option<SystemTime> {
131        self.sampled_at
132    }
133
134    /// A classified failure without raw native source text.
135    pub fn error(&self) -> Option<&NetError> {
136        self.error.as_ref()
137    }
138
139    /// Classified faults bypassed by a successful name fallback.
140    pub fn diagnostics(&self) -> &[NetError] {
141        &self.diagnostics
142    }
143
144    pub(crate) fn empty(state: NetworkNameState) -> Self {
145        Self {
146            state,
147            name: None,
148            source: NetworkNameSource::NotCollected,
149            sampled_at: None,
150            error: None,
151            diagnostics: Vec::new(),
152            #[cfg(test)]
153            retention_probe: None,
154        }
155    }
156
157    #[cfg(any(windows, test))]
158    pub(crate) fn ready(
159        name: Option<String>,
160        source: NetworkNameSource,
161        sampled_at: SystemTime,
162        diagnostics: Vec<NetError>,
163    ) -> Self {
164        Self {
165            state: NetworkNameState::Ready,
166            name,
167            source,
168            sampled_at: Some(sampled_at),
169            error: None,
170            diagnostics: diagnostics.iter().map(classified).collect(),
171            #[cfg(test)]
172            retention_probe: None,
173        }
174    }
175
176    pub(crate) fn failed(error: &NetError) -> Self {
177        Self {
178            error: Some(classified(error)),
179            ..Self::empty(NetworkNameState::Failed)
180        }
181    }
182
183    #[cfg(test)]
184    pub(crate) fn retain_probe_for_test(&mut self, probe: Arc<()>) {
185        self.retention_probe = Some(probe);
186    }
187}
188
189fn classified(error: &NetError) -> NetError {
190    // Neither arbitrary source objects nor potentially identifying context are
191    // retained by the name observer, including successful fallback diagnostics.
192    NetError::from(error.kind()).with_stage(ErrorStage::NetworkMonitor)
193}
194
195/// An explicitly enabled, independently cancellable network-name observer.
196///
197/// At most 32 observers may be active in one engine. Sampling uses a bounded,
198/// serial native worker and does not update ordinary network snapshots/events.
199/// This handle is intentionally not clonable. `recv` coalesces intermediate
200/// observations: after its initial Pending value it returns the latest version.
201///
202/// Dropping the handle stops admission and clears retained names immediately;
203/// use `close().await` to also wait for this observer's in-flight native query to
204/// retire. The SDK cannot revoke values already returned to the application.
205pub struct NetworkNameObserver {
206    pub(crate) inner: Arc<NameConsumer>,
207    pub(crate) changes: tokio::sync::watch::Receiver<()>,
208    pub(crate) initial: bool,
209    pub(crate) seen: u64,
210    pub(crate) terminal: bool,
211}
212
213impl fmt::Debug for NetworkNameObserver {
214    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215        f.debug_struct("NetworkNameObserver")
216            .finish_non_exhaustive()
217    }
218}
219
220impl NetworkNameObserver {
221    /// Read this observer's latest value without querying the operating system.
222    pub fn snapshot(&self) -> Result<NetworkNameSnapshot, NetError> {
223        self.inner.snapshot().map(|(_, snapshot)| snapshot)
224    }
225
226    /// Receive the latest observation. Closed is delivered once, followed by None.
227    /// The initial Pending value is discarded if the observer closes first.
228    pub async fn recv(&mut self) -> Result<Option<NetworkNameSnapshot>, NetError> {
229        if self.terminal {
230            return Ok(None);
231        }
232        loop {
233            self.changes.borrow_and_update();
234            if let Some((revision, snapshot)) = self.inner.next_snapshot(self.seen, self.initial) {
235                self.initial = false;
236                self.terminal = snapshot.state() == NetworkNameState::Closed;
237                self.seen = revision;
238                return Ok(Some(snapshot));
239            }
240            self.changes
241                .changed()
242                .await
243                .map_err(|_| NetError::from(ErrorKind::Closed))?;
244        }
245    }
246
247    /// Stop collection, clear retained values, and wait for native work to retire.
248    /// Idempotent. Cancellation of this wait does not undo the requested close.
249    pub async fn close(&mut self) -> Result<(), NetError> {
250        self.inner.request_close();
251        self.inner.wait_cleanup().await
252    }
253}
254
255impl Drop for NetworkNameObserver {
256    fn drop(&mut self) {
257        self.inner.request_close();
258    }
259}