use super::{ErrorStage, NetError};
use std::error::Error as _;
use std::sync::Arc;
use std::time::Duration;
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum NetworkMonitorPhase {
MonitorTaskSubmit,
MonitorThreadSpawn,
RuntimeBuild,
NetwatchCreate,
SamplerWorkerSpawn,
SampleAdmission,
SampleQueueSubmit,
SampleQueueWait,
NativeSample,
ComInit,
NlmCreate,
NlmGetConnectivity,
SampleComplete,
SampleResultReceive,
InitialResultReceive,
ObservationCommit,
MonitorTaskExit,
}
impl NetworkMonitorPhase {
pub const fn as_str(self) -> &'static str {
match self {
Self::MonitorTaskSubmit => "monitor_task_submit",
Self::MonitorThreadSpawn => "monitor_thread_spawn",
Self::RuntimeBuild => "runtime_build",
Self::NetwatchCreate => "netwatch_create",
Self::SamplerWorkerSpawn => "sampler_worker_spawn",
Self::SampleAdmission => "sample_admission",
Self::SampleQueueSubmit => "sample_queue_submit",
Self::SampleQueueWait => "sample_queue_wait",
Self::NativeSample => "native_sample",
Self::ComInit => "com_init",
Self::NlmCreate => "nlm_create",
Self::NlmGetConnectivity => "nlm_get_connectivity",
Self::SampleComplete => "sample_complete",
Self::SampleResultReceive => "sample_result_receive",
Self::InitialResultReceive => "initial_result_receive",
Self::ObservationCommit => "observation_commit",
Self::MonitorTaskExit => "monitor_task_exit",
}
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct NetworkMonitorDiagnostic {
pub phase: NetworkMonitorPhase,
pub elapsed: Option<Duration>,
pub timeout: Option<Duration>,
}
impl NetError {
#[cfg_attr(not(any(feature = "net-status", test)), allow(dead_code))]
pub(crate) fn with_network_monitor_phase(self, phase: NetworkMonitorPhase) -> Self {
self.with_network_monitor_diagnostic(NetworkMonitorDiagnostic {
phase,
elapsed: None,
timeout: None,
})
}
#[cfg_attr(not(any(feature = "net-status", test)), allow(dead_code))]
pub(crate) fn with_network_monitor_diagnostic(
mut self,
diagnostic: NetworkMonitorDiagnostic,
) -> Self {
self.context.stage.get_or_insert(ErrorStage::NetworkMonitor);
match &mut self.context.network_monitor {
Some(current) => {
if (current.elapsed.is_none() && diagnostic.elapsed.is_some())
|| (current.timeout.is_none() && diagnostic.timeout.is_some())
{
let current = Arc::make_mut(current);
current.elapsed = current.elapsed.or(diagnostic.elapsed);
current.timeout = current.timeout.or(diagnostic.timeout);
}
}
None => self.context.network_monitor = Some(Arc::new(diagnostic)),
}
self
}
pub fn network_monitor_diagnostics(&self) -> Option<serde_json::Value> {
let context = self.context();
if context.network_monitor.is_none()
&& context.windows_reachability.is_none()
&& context.stage != Some(ErrorStage::NetworkMonitor)
{
return None;
}
let diagnostic = context.network_monitor.as_deref();
let native = context.windows_reachability;
let mut source = self.source();
let mut os_error_code = None;
for _ in 0..64 {
let Some(current) = source else { break };
if let Some(code) = current
.downcast_ref::<std::io::Error>()
.and_then(std::io::Error::raw_os_error)
{
os_error_code = Some(code);
break;
}
source = current.source();
}
Some(serde_json::json!({
"kind": format!("{:?}", self.kind()),
"stage": context.stage.map(|stage| format!("{stage:?}")),
"phase": diagnostic.map(|value| value.phase.as_str()),
"elapsed_ms": diagnostic.and_then(|value| value.elapsed).map(milliseconds),
"timeout_ms": diagnostic.and_then(|value| value.timeout).map(milliseconds),
"operation": native.map(|value| value.operation.as_str()),
"hresult": native.map(|value| format!("0x{:08X}", value.hresult)),
"os_error_code": os_error_code,
}))
}
}
fn milliseconds(value: Duration) -> u64 {
value.as_millis().min(u128::from(u64::MAX)) as u64
}
#[cfg(test)]
#[path = "network_monitor_tests.rs"]
mod tests;