Skip to main content

agentmux_srv_core/connectivity/
netchange.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The OS's network-change notifications, so a switch of Wi-Fi, a VPN coming up or a cable pulled
5//! shows at once, not at the next probe of a service already believed down (up to a minute) or at
6//! the next failed request.
7//!
8//! A change makes every service due for a probe ([`super::Shared::network_changed_at`]). The OS
9//! reports a change as a burst (the link, then its addresses, then its routes, and a Wi-Fi roam
10//! repeats it), and right after it DNS often can't answer yet, so [`settle`] waits for the burst to
11//! end and probes once.
12//!
13//! **Platforms.** Windows has it (`NotifyIpInterfaceChange`). Linux (netlink) and macOS
14//! (`NWPathMonitor`) don't yet: [`Watch::start`] returns `None` there and the probes run as
15//! before, on their own schedule. This is a known gap, not an error.
16
17use std::future::Future;
18use std::sync::Arc;
19use std::time::Duration;
20
21use tokio::sync::Notify;
22
23use super::Shared;
24
25/// How long after the last notification the network is taken to have settled.
26const SETTLE: Duration = Duration::from_secs(2);
27
28/// Waits for a notification, then for [`SETTLE`] with none, and calls `changed` once for the burst.
29/// Runs until srv exits.
30async fn settle<F, Fut>(signal: Arc<Notify>, mut changed: F)
31where
32    F: FnMut() -> Fut,
33    Fut: Future<Output = ()>,
34{
35    loop {
36        signal.notified().await;
37        // Each notification starts the wait over.
38        while tokio::time::timeout(SETTLE, signal.notified()).await.is_ok() {}
39        changed().await;
40    }
41}
42
43/// Starts watching the OS for network changes, on behalf of `shared`. The watch lasts as long as
44/// srv does.
45pub(super) fn start(shared: Arc<Shared>) {
46    let signal = Arc::new(Notify::new());
47    let Some(watch) = Watch::start(signal.clone()) else {
48        tracing::info!("connectivity: no OS network-change notifications on this platform");
49        return;
50    };
51    // Held by the task, so the registration ends with it.
52    tokio::spawn(async move {
53        let _watch = watch;
54        settle(signal, || {
55            let shared = shared.clone();
56            async move { shared.network_changed_at(agentmux_common::time::now_ms()) }
57        })
58        .await;
59    });
60}
61
62#[cfg(windows)]
63pub(super) use windows_watch::Watch;
64
65#[cfg(not(windows))]
66pub(super) use no_watch::Watch;
67
68#[cfg(not(windows))]
69pub mod no_watch {
70    use std::sync::Arc;
71
72    use tokio::sync::Notify;
73
74    /// The platforms without OS notifications.
75    pub(in super::super) struct Watch;
76
77    impl Watch {
78        pub(in super::super) fn start(_signal: Arc<Notify>) -> Option<Watch> {
79            None
80        }
81    }
82}
83
84#[cfg(windows)]
85pub mod windows_watch {
86    use std::ffi::c_void;
87    use std::sync::Arc;
88
89    use tokio::sync::Notify;
90    use windows_sys::Win32::Foundation::{HANDLE, NO_ERROR};
91    use windows_sys::Win32::NetworkManagement::IpHelper::{CancelMibChangeNotify2, NotifyIpInterfaceChange, MIB_IPINTERFACE_ROW};
92    use windows_sys::Win32::Networking::WinSock::AF_UNSPEC;
93
94    /// A registration with the OS for interface changes; ending it stops the notifications.
95    pub(in super::super) struct Watch {
96        handle: HANDLE,
97        /// The reference the callback reads through its context pointer; given back on drop.
98        context: *const Notify,
99    }
100
101    // The handle and the context are only used to end the registration; the callback never sees `Watch`.
102    unsafe impl Send for Watch {}
103
104    /// Runs on a thread of the OS's: it only sets a flag for the task that waits.
105    unsafe extern "system" fn on_change(context: *const c_void, _row: *const MIB_IPINTERFACE_ROW, _kind: i32) {
106        // SAFETY: `context` is the `Arc<Notify>` leaked in `start`, alive until `Watch` is dropped,
107        // and that cancels the registration (waiting out a running callback) before it is released.
108        if let Some(signal) = unsafe { (context as *const Notify).as_ref() } {
109            signal.notify_one();
110        }
111    }
112
113    impl Watch {
114        pub(in super::super) fn start(signal: Arc<Notify>) -> Option<Watch> {
115            let context = Arc::into_raw(signal);
116            let mut handle: HANDLE = std::ptr::null_mut();
117            // SAFETY: the callback matches the signature, `context` outlives the registration (see
118            // `on_change`), and `handle` is a valid place for the OS to write the registration to.
119            let status = unsafe { NotifyIpInterfaceChange(AF_UNSPEC, Some(on_change), context.cast(), 0, &mut handle) };
120            if status != NO_ERROR || handle.is_null() {
121                tracing::warn!(status, "connectivity: NotifyIpInterfaceChange failed; no OS network-change notifications");
122                // SAFETY: from `into_raw` above; nothing else holds the pointer.
123                drop(unsafe { Arc::from_raw(context) });
124                return None;
125            }
126            Some(Watch { handle, context })
127        }
128    }
129
130    impl Drop for Watch {
131        fn drop(&mut self) {
132            // SAFETY: `handle` came from `NotifyIpInterfaceChange`; cancelling returns only after a
133            // running callback has finished, so the context can be released after it.
134            unsafe {
135                CancelMibChangeNotify2(self.handle);
136                drop(Arc::from_raw(self.context));
137            }
138        }
139    }
140}
141
142#[cfg(test)]
143#[path = "netchange_tests.rs"]
144mod tests;