Skip to main content

open_net/api/error/
network_monitor.rs

1//! Portable monitor phases and an allowlisted diagnostic event payload.
2
3use super::{ErrorStage, NetError};
4use std::error::Error as _;
5use std::sync::Arc;
6use std::time::Duration;
7
8/// The monitor operation associated with a failure or last observed progress.
9///
10/// These values describe SDK steps. For a timed-out operation, the native call
11/// may still be running; a phase does not imply that it returned a failure.
12#[non_exhaustive]
13#[derive(Clone, Copy, Debug, Eq, PartialEq)]
14pub enum NetworkMonitorPhase {
15    /// Submit the monitor task to the owning runtime.
16    MonitorTaskSubmit,
17    /// Create the dedicated monitor thread.
18    MonitorThreadSpawn,
19    /// Build the monitor generation's asynchronous runtime.
20    RuntimeBuild,
21    /// Create the netwatch detector.
22    NetwatchCreate,
23    /// Create the dedicated reachability-sampling worker.
24    SamplerWorkerSpawn,
25    /// Acquire capacity to submit a sample.
26    SampleAdmission,
27    /// Submit a sample to the worker's bounded queue.
28    SampleQueueSubmit,
29    /// Wait for the worker to begin an accepted sample.
30    SampleQueueWait,
31    /// Execute a native sampling provider.
32    NativeSample,
33    /// Initialize the sampling thread's COM apartment.
34    ComInit,
35    /// Create the Network List Manager interface.
36    NlmCreate,
37    /// Read connectivity from Network List Manager.
38    NlmGetConnectivity,
39    /// Validate a completed sample before returning it.
40    SampleComplete,
41    /// Receive a worker's sampling result.
42    SampleResultReceive,
43    /// Receive the monitor's initial result.
44    InitialResultReceive,
45    /// Validate and publish a collected observation.
46    ObservationCommit,
47    /// Exit or retire the monitor task before initialization completed.
48    MonitorTaskExit,
49}
50
51impl NetworkMonitorPhase {
52    /// Returns the stable identifier used in diagnostic event fields.
53    pub const fn as_str(self) -> &'static str {
54        match self {
55            Self::MonitorTaskSubmit => "monitor_task_submit",
56            Self::MonitorThreadSpawn => "monitor_thread_spawn",
57            Self::RuntimeBuild => "runtime_build",
58            Self::NetwatchCreate => "netwatch_create",
59            Self::SamplerWorkerSpawn => "sampler_worker_spawn",
60            Self::SampleAdmission => "sample_admission",
61            Self::SampleQueueSubmit => "sample_queue_submit",
62            Self::SampleQueueWait => "sample_queue_wait",
63            Self::NativeSample => "native_sample",
64            Self::ComInit => "com_init",
65            Self::NlmCreate => "nlm_create",
66            Self::NlmGetConnectivity => "nlm_get_connectivity",
67            Self::SampleComplete => "sample_complete",
68            Self::SampleResultReceive => "sample_result_receive",
69            Self::InitialResultReceive => "initial_result_receive",
70            Self::ObservationCommit => "observation_commit",
71            Self::MonitorTaskExit => "monitor_task_exit",
72        }
73    }
74}
75
76/// Safe monitor failure context, without system messages or network identities.
77#[non_exhaustive]
78#[derive(Clone, Copy, Debug, Eq, PartialEq)]
79pub struct NetworkMonitorDiagnostic {
80    /// Failure step, or last observed progress when a deadline expired.
81    pub phase: NetworkMonitorPhase,
82    /// Time spent in the observed operation, when measured.
83    pub elapsed: Option<Duration>,
84    /// Remaining budget when timing of the observed operation began, when known.
85    /// This can be slightly shorter than the caller's configured timeout.
86    pub timeout: Option<Duration>,
87}
88
89impl NetError {
90    /// Add a fallback monitor step without replacing a more specific one.
91    #[cfg_attr(not(any(feature = "net-status", test)), allow(dead_code))]
92    pub(crate) fn with_network_monitor_phase(self, phase: NetworkMonitorPhase) -> Self {
93        self.with_network_monitor_diagnostic(NetworkMonitorDiagnostic {
94            phase,
95            elapsed: None,
96            timeout: None,
97        })
98    }
99
100    /// Keep the original step and fill only timing evidence not already present.
101    #[cfg_attr(not(any(feature = "net-status", test)), allow(dead_code))]
102    pub(crate) fn with_network_monitor_diagnostic(
103        mut self,
104        diagnostic: NetworkMonitorDiagnostic,
105    ) -> Self {
106        self.context.stage.get_or_insert(ErrorStage::NetworkMonitor);
107        match &mut self.context.network_monitor {
108            Some(current) => {
109                if (current.elapsed.is_none() && diagnostic.elapsed.is_some())
110                    || (current.timeout.is_none() && diagnostic.timeout.is_some())
111                {
112                    let current = Arc::make_mut(current);
113                    current.elapsed = current.elapsed.or(diagnostic.elapsed);
114                    current.timeout = current.timeout.or(diagnostic.timeout);
115                }
116            }
117            None => self.context.network_monitor = Some(Arc::new(diagnostic)),
118        }
119        self
120    }
121
122    /// Collect fixed, privacy-safe fields for a network monitor failure event.
123    ///
124    /// Returns `None` for an error without a monitor stage or diagnostic. The
125    /// JSON object always contains `kind`, `stage`, `phase`, `elapsed_ms`,
126    /// `timeout_ms`, `operation`, `hresult` and `os_error_code`; unknown values
127    /// are JSON `null`. Phases and operations use their stable `as_str()` names,
128    /// while kind and stage use the existing enum names. Milliseconds truncate
129    /// submillisecond values and saturate at `u64::MAX`.
130    ///
131    /// `hresult` comes only from a returned Windows reachability failure and is
132    /// formatted as `0xXXXXXXXX`. `os_error_code` comes only from an original
133    /// [`std::io::Error::raw_os_error`] in the bounded source chain. These are
134    /// different error-code namespaces; this method never converts one into the
135    /// other or invents a HRESULT for a timed-out native call.
136    ///
137    /// No arbitrary source message, network name, machine name or application
138    /// metadata is formatted or included. This method does not enable logging
139    /// or send events; call it before replacing this error with its string.
140    pub fn network_monitor_diagnostics(&self) -> Option<serde_json::Value> {
141        let context = self.context();
142        if context.network_monitor.is_none()
143            && context.windows_reachability.is_none()
144            && context.stage != Some(ErrorStage::NetworkMonitor)
145        {
146            return None;
147        }
148        let diagnostic = context.network_monitor.as_deref();
149        let native = context.windows_reachability;
150        let mut source = self.source();
151        let mut os_error_code = None;
152        // Application source chains can cycle. Do not format their Debug or
153        // Display implementations, and cap traversal just like io_kind().
154        for _ in 0..64 {
155            let Some(current) = source else { break };
156            if let Some(code) = current
157                .downcast_ref::<std::io::Error>()
158                .and_then(std::io::Error::raw_os_error)
159            {
160                os_error_code = Some(code);
161                break;
162            }
163            source = current.source();
164        }
165        Some(serde_json::json!({
166            "kind": format!("{:?}", self.kind()),
167            "stage": context.stage.map(|stage| format!("{stage:?}")),
168            "phase": diagnostic.map(|value| value.phase.as_str()),
169            "elapsed_ms": diagnostic.and_then(|value| value.elapsed).map(milliseconds),
170            "timeout_ms": diagnostic.and_then(|value| value.timeout).map(milliseconds),
171            "operation": native.map(|value| value.operation.as_str()),
172            "hresult": native.map(|value| format!("0x{:08X}", value.hresult)),
173            "os_error_code": os_error_code,
174        }))
175    }
176}
177
178fn milliseconds(value: Duration) -> u64 {
179    value.as_millis().min(u128::from(u64::MAX)) as u64
180}
181
182#[cfg(test)]
183#[path = "network_monitor_tests.rs"]
184mod tests;