Skip to content

Visual Studio Code, rebuilt in Rust

Rust
4.2 KB
Raw Blame
//! platform/meteredConnection on macOS and Linux: whether the OS reports the network path as metered, the native side of
//! meteredConnection.ts `getIsBrowserConnectionMetered`, and the `network.meteredConnection` setting over it.

#[cfg(target_os = "macos")]
use std::ffi::c_void;
#[cfg(target_os = "macos")]
use std::sync::OnceLock;

#[cfg(target_os = "macos")]
use block2::RcBlock;
use futures::channel::mpsc::UnboundedSender;

#[cfg(target_os = "macos")]
#[link(name = "Network", kind = "framework")]
unsafe extern "C" {
    fn nw_path_monitor_create() -> *mut c_void;
    fn nw_path_monitor_set_queue(monitor: *mut c_void, queue: *const c_void);
    fn nw_path_monitor_set_update_handler(monitor: *mut c_void, handler: &block2::DynBlock<dyn Fn(*mut c_void)>);
    fn nw_path_monitor_start(monitor: *mut c_void);
    fn nw_path_is_expensive(path: *mut c_void) -> bool;
    fn nw_path_is_constrained(path: *mut c_void) -> bool;
}

#[cfg(target_os = "macos")]
unsafe extern "C" {
    static _dispatch_main_q: c_void;
}

#[cfg(target_os = "macos")]
static UPDATES: OnceLock<UnboundedSender<bool>> = OnceLock::new();

/// Sends whether the current path is metered, first when the monitor starts, then on every path change.
/// Chromium's `navigator.connection` on macOS reports neither `metered` nor `saveData`; the OS knows a path is
/// metered when it is expensive (cellular, a personal hotspot) or constrained (Low Data Mode).
#[cfg(target_os = "macos")]
pub fn watch(updates: UnboundedSender<bool>) {
    if UPDATES.set(updates).is_err() {
        return;
    }
    let handler = RcBlock::new(|path: *mut c_void| {
        // SAFETY: Network.framework passes the handler a valid nw_path_t for the length of the call.
        let metered = unsafe { nw_path_is_expensive(path) || nw_path_is_constrained(path) };
        if let Some(updates) = UPDATES.get() {
            let _ = updates.unbounded_send(metered);
        }
    });
    // SAFETY: the monitor is created here and never released; the main queue is a static, and the monitor copies the block.
    unsafe {
        let monitor = nw_path_monitor_create();
        nw_path_monitor_set_queue(monitor, &_dispatch_main_q as *const _);
        nw_path_monitor_set_update_handler(monitor, &handler);
        // The monitor runs as long as the app; it is never cancelled or released.
        nw_path_monitor_start(monitor);
    }
}

/// Chromium's `navigator.connection` on Linux reports no metered state either; as on macOS the OS decides:
/// NetworkManager's `Metered` (NMMetered) is `YES` or `GUESS_YES`. Sent first, then on every change.
#[cfg(target_os = "linux")]
pub fn watch(updates: UnboundedSender<bool>) {
    std::thread::spawn(move || {
        let manager = zbus::blocking::Connection::system().and_then(|system| zbus::blocking::Proxy::new(&system, "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager", "org.freedesktop.NetworkManager"));
        let Ok(manager) = manager else { return };
        let is_metered = |metered: u32| matches!(metered, 1 | 3);
        if let Ok(metered) = manager.get_property::<u32>("Metered") {
            drop(updates.unbounded_send(is_metered(metered)));
        }
        for change in manager.receive_property_changed::<u32>("Metered") {
            let Ok(metered) = change.get() else { continue };
            if updates.unbounded_send(is_metered(metered)).is_err() {
                return;
            }
        }
    });
}

// shortcut: never metered on Windows yet; port/ledger.md M24 row app/src/metered_connection.rs:57 (INetworkCostManager).
#[cfg(target_os = "windows")]
pub fn watch(_updates: UnboundedSender<bool>) {}

/// `AbstractMeteredConnectionService`: `on` always, `off` never, `auto` (or any other value) the OS state.
pub fn is_metered(setting: Option<&str>, os_metered: bool) -> bool {
    setting == Some("on") || (setting != Some("off") && os_metered)
}

#[cfg(test)]
mod tests {
    use super::is_metered;

    #[test]
    fn the_setting_overrides_the_os() {
        assert!(is_metered(Some("on"), false));
        assert!(!is_metered(Some("off"), true));
        assert!(is_metered(Some("auto"), true));
        assert!(!is_metered(Some("auto"), false));
        assert!(is_metered(None, true));
    }
}