open_net/api/net_status/
names.rs1use 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#[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 pub fn with_interval(mut self, interval: Duration) -> Self {
33 self.interval = interval;
34 self
35 }
36
37 pub fn with_timeout(mut self, timeout: Duration) -> Self {
43 self.timeout = timeout;
44 self
45 }
46
47 pub fn interval(&self) -> Duration {
49 self.interval
50 }
51
52 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#[non_exhaustive]
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum NetworkNameState {
73 Pending,
75 Ready,
77 Failed,
79 Closed,
81}
82
83#[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 pub fn state(&self) -> NetworkNameState {
116 self.state
117 }
118
119 pub fn name(&self) -> Option<&str> {
121 self.name.as_deref()
122 }
123
124 pub fn source(&self) -> NetworkNameSource {
126 self.source
127 }
128
129 pub fn sampled_at(&self) -> Option<SystemTime> {
131 self.sampled_at
132 }
133
134 pub fn error(&self) -> Option<&NetError> {
136 self.error.as_ref()
137 }
138
139 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 NetError::from(error.kind()).with_stage(ErrorStage::NetworkMonitor)
193}
194
195pub 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 pub fn snapshot(&self) -> Result<NetworkNameSnapshot, NetError> {
223 self.inner.snapshot().map(|(_, snapshot)| snapshot)
224 }
225
226 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 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}