Skip to main content

open_net/api/net_status/
interface_events.rs

1//! On-demand evidence from the operating system, independent of reachability.
2use super::NetworkEventOptions;
3use crate::NetError;
4use std::time::SystemTime;
5use tokio::sync::Semaphore;
6
7/// Sources and per-subscriber queue limits for interface diagnostics.
8/// Construct with `Default::default()` and set the fields your application needs.
9#[non_exhaustive]
10#[derive(Clone, Copy, Debug)]
11pub struct InterfaceEventOptions {
12    /// Collect Windows WLAN connection and disconnection records.
13    pub wlan: bool,
14    /// Observe preferred IPv4 and IPv6 default-route interfaces independently.
15    pub default_route: bool,
16    /// Maximum queued entries, including source status and route baselines.
17    pub capacity: usize,
18    /// Maximum accounted bytes in the queue, including interface identifiers.
19    pub max_bytes: usize,
20}
21
22impl Default for InterfaceEventOptions {
23    fn default() -> Self {
24        let queue = NetworkEventOptions::default();
25        Self {
26            wlan: true,
27            default_route: true,
28            capacity: queue.capacity,
29            max_bytes: queue.max_bytes,
30        }
31    }
32}
33
34impl InterfaceEventOptions {
35    pub(crate) fn validate(&self) -> Result<(), NetError> {
36        if !self.wlan && !self.default_route {
37            return Err(NetError::config(
38                "interface_events.sources",
39                "select at least one source",
40            ));
41        }
42        if self.capacity == 0 || self.capacity > Semaphore::MAX_PERMITS {
43            return Err(NetError::config(
44                "interface_events.capacity",
45                "must be a positive supported capacity",
46            ));
47        }
48        if self.max_bytes == 0
49            || self.max_bytes > Semaphore::MAX_PERMITS
50            || self.max_bytes > u32::MAX as usize
51        {
52            return Err(NetError::config(
53                "interface_events.max_bytes",
54                "must be a positive supported byte allowance",
55            ));
56        }
57        Ok(())
58    }
59}
60
61/// Independently selectable Windows diagnostic source.
62#[non_exhaustive]
63#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
64pub enum InterfaceEventSource {
65    /// Connection records from Windows WLAN-AutoConfig/Operational.
66    Wlan,
67    /// Preferred default-route observations and per-family collection status.
68    DefaultRoute,
69}
70
71/// IP family of an observed default route.
72#[non_exhaustive]
73#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
74pub enum InterfaceAddressFamily {
75    Ipv4,
76    Ipv6,
77}
78
79/// Result of a successful default-route observation for one IP family.
80#[non_exhaustive]
81#[derive(Clone, Debug, Eq, PartialEq)]
82pub enum DefaultRouteState {
83    /// No eligible default route.
84    NoRoute,
85    /// Several different interfaces share the lowest effective metric.
86    Ambiguous,
87    /// The preferred route(s) resolve to one interface.
88    Unique { interface_id: String },
89}
90
91/// A change, baseline, or source diagnostic in the opt-in interface event stream.
92#[non_exhaustive]
93#[derive(Clone, Debug)]
94pub enum InterfaceEventKind {
95    /// This source started observing.
96    SourceReady,
97    /// This source could not collect evidence. Other selected sources can continue.
98    SourceUnavailable {
99        error: NetError,
100        native_code: Option<i64>,
101    },
102    /// The source detected a gap in its coverage. Historical entries are not replayed.
103    SourceGap {
104        error: NetError,
105        native_code: Option<i64>,
106    },
107    /// A successful WLAN connection. The native code is the provider's event ID.
108    /// The interface GUID is in lower-case hyphenated form, without braces.
109    WlanConnected {
110        interface_id: String,
111        native_code: u32,
112        reason_code: Option<u32>,
113    },
114    /// A WLAN disconnect record, with the native event ID and optional numeric reason.
115    WlanDisconnected {
116        interface_id: String,
117        native_code: u32,
118        reason_code: Option<u32>,
119    },
120    /// Initial baseline, recovery, or a change involving a non-unique or absent route.
121    DefaultRouteObserved {
122        family: InterfaceAddressFamily,
123        state: DefaultRouteState,
124    },
125    /// Two consecutive successful observations uniquely identified different interfaces.
126    DefaultRouteChanged {
127        family: InterfaceAddressFamily,
128        previous: String,
129        current: String,
130    },
131    /// A read failed and invalidated the comparison baseline for this family.
132    DefaultRouteQueryFailed {
133        family: InterfaceAddressFamily,
134        error: NetError,
135        native_code: Option<i64>,
136    },
137}
138
139/// One record from an explicit subscription. Sequence orders SDK delivery within
140/// this subscription. Independent Windows sources can deliver records with delay.
141/// WLAN records omit SSID, BSSID, and profile names.
142#[derive(Clone, Debug)]
143pub struct InterfaceEvent {
144    /// Monotonically increasing sequence for this subscription.
145    pub sequence: u64,
146    /// SDK wall-clock time when this evidence was observed.
147    pub observed_at: SystemTime,
148    /// Windows record time when supplied by the source.
149    pub native_time: Option<SystemTime>,
150    /// Source to which this record or diagnostic belongs.
151    pub source: InterfaceEventSource,
152    /// Change, baseline, or status of this source.
153    pub kind: InterfaceEventKind,
154}
155
156#[cfg(windows)]
157impl InterfaceEvent {
158    pub(crate) fn accounted_bytes(&self) -> usize {
159        use InterfaceEventKind::*;
160        let extra = match &self.kind {
161            WlanConnected { interface_id, .. }
162            | WlanDisconnected { interface_id, .. }
163            | DefaultRouteObserved {
164                state: DefaultRouteState::Unique { interface_id },
165                ..
166            } => interface_id.capacity(),
167            DefaultRouteChanged {
168                previous, current, ..
169            } => previous.capacity().saturating_add(current.capacity()),
170            // Source diagnostics carry an error kind, stage and optional numeric OS code.
171            #[cfg(feature = "ws-client")]
172            SourceUnavailable { .. } | SourceGap { .. } | DefaultRouteQueryFailed { .. } => {
173                std::mem::size_of::<crate::error::ErrorContext>()
174            }
175            _ => 0,
176        };
177        std::mem::size_of::<Self>().saturating_add(extra)
178    }
179}