node-device-session 7.7.55

Shared server for /econ-v1/device-session/1 behind transport-neutral traits (C-5)
Documentation
//! Live device sessions, one per `device_id`.
//!
//! A newer session replaces an older one (a device that switched networks
//! reconnects before the old path times out). Teardown removes a session only
//! if it is still the one that ended, so a late close of the old connection
//! cannot evict the new one. Ported from `node-app-iroh`'s device-session
//! registry into the shared, transport-neutral form.

use crate::webrtc::WebRtcHandle;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

/// Application close code when a newer session supersedes an older one.
pub const SUPERSEDED_CLOSE_CODE: u32 = 3;
/// Application close code when revalidation (or explicit revoke) tears a session down.
pub const REVOKED_CLOSE_CODE: u32 = 4;

/// Closes the underlying [`crate::SessionStreams`] connection.
pub type SessionClose = Arc<dyn Fn(u32, &[u8]) + Send + Sync>;

struct Entry {
    session_id: u64,
    credential: String,
    endpoint_hex: String,
    close: SessionClose,
    webrtc: Option<WebRtcHandle>,
    /// False once the carrier connection ended while a connected WebRTC
    /// session still runs. The entry stays so revalidation and revocation
    /// still reach that WebRTC session (ADR-154 Amendment, punch outlives
    /// signaling).
    carrier_open: bool,
}

impl Entry {
    fn webrtc_live(&self) -> bool {
        self.webrtc
            .as_ref()
            .is_some_and(|handle| !handle.is_closed())
    }
}

/// Drop entries whose carrier ended and whose WebRTC session is gone too.
fn prune(entries: &mut HashMap<String, Entry>) {
    entries.retain(|_, entry| entry.carrier_open || entry.webrtc_live());
}

impl Drop for Entry {
    fn drop(&mut self) {
        if let Some(handle) = &self.webrtc {
            handle.close();
        }
    }
}

struct Inner {
    next_id: AtomicU64,
    entries: Mutex<HashMap<String, Entry>>,
}

/// Registry of live full-mode device sessions for periodic revalidation.
///
/// Clone is cheap (`Arc`); all clones share the same map.
#[derive(Clone)]
pub struct SessionRegistry {
    inner: Arc<Inner>,
}

impl Default for SessionRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl SessionRegistry {
    /// Empty registry.
    pub fn new() -> Self {
        Self {
            inner: Arc::new(Inner {
                next_id: AtomicU64::new(1),
                entries: Mutex::new(HashMap::new()),
            }),
        }
    }

    /// Number of live sessions (open carrier connections).
    pub fn len(&self) -> usize {
        self.inner
            .entries
            .lock()
            .values()
            .filter(|entry| entry.carrier_open)
            .count()
    }

    /// Whether no sessions are registered.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Whether `device_id` currently has a live session.
    pub fn contains(&self, device_id: &str) -> bool {
        self.inner
            .entries
            .lock()
            .get(device_id)
            .is_some_and(|entry| entry.carrier_open)
    }

    /// Register a newly opened full-mode session.
    ///
    /// If `device_id` already has a session, the previous one is closed with
    /// [`SUPERSEDED_CLOSE_CODE`]. A WebRTC session still running from the
    /// previous entry moves to the new one: it is the same device, and the new
    /// session's credential now covers it. Returns the new session id.
    pub fn insert(
        &self,
        device_id: String,
        credential: String,
        endpoint_hex: String,
        close: SessionClose,
    ) -> u64 {
        let session_id = self.inner.next_id.fetch_add(1, Ordering::Relaxed);
        let previous = {
            let mut entries = self.inner.entries.lock();
            prune(&mut entries);
            let mut previous = entries.remove(&device_id);
            let webrtc = previous
                .as_mut()
                .and_then(|old| old.webrtc.take())
                .filter(|handle| !handle.is_closed());
            entries.insert(
                device_id,
                Entry {
                    session_id,
                    credential,
                    endpoint_hex,
                    close,
                    webrtc,
                    carrier_open: true,
                },
            );
            previous
        };
        if let Some(old) = previous {
            if old.carrier_open {
                (old.close)(SUPERSEDED_CLOSE_CODE, b"superseded");
            }
        }
        session_id
    }

    /// Remove the session only if `session_id` is still the live one for `device_id`.
    ///
    /// A connected WebRTC session bound to it keeps running: the entry stays,
    /// marked carrier-closed, so revalidation and revocation still close it,
    /// and the device's next session takes it over.
    pub fn remove_if(&self, device_id: &str, session_id: u64) -> bool {
        let mut entries = self.inner.entries.lock();
        match entries.get_mut(device_id) {
            Some(entry) if entry.session_id == session_id => {
                if entry.webrtc_live() {
                    entry.carrier_open = false;
                } else {
                    entries.remove(device_id);
                }
                true
            }
            _ => false,
        }
    }

    /// Close and remove the matching live session (revocation / expiry).
    pub fn close(&self, device_id: &str, session_id: u64, reason: &'static [u8]) -> bool {
        let removed = {
            let mut entries = self.inner.entries.lock();
            match entries.get(device_id) {
                Some(entry) if entry.session_id == session_id => entries.remove(device_id),
                _ => None,
            }
        };
        match removed {
            Some(entry) => {
                (entry.close)(REVOKED_CLOSE_CODE, reason);
                true
            }
            None => false,
        }
    }

    /// Bind a WebRTC answerer handle into the live session for `device_id`.
    ///
    /// Returns `false` (and closes `handle`) when no session is registered.
    /// A later bind replaces the previous handle and closes it.
    pub fn bind_webrtc(&self, device_id: &str, handle: WebRtcHandle) -> bool {
        let mut entries = self.inner.entries.lock();
        let Some(entry) = entries.get_mut(device_id) else {
            handle.close();
            return false;
        };
        if let Some(old) = entry.webrtc.replace(handle) {
            old.close();
        }
        true
    }

    /// Snapshot of `(device_id, session_id, credential, endpoint_hex)` for revalidation.
    pub(crate) fn credentials(&self) -> Vec<(String, u64, String, String)> {
        let mut entries = self.inner.entries.lock();
        prune(&mut entries);
        entries
            .iter()
            .map(|(device_id, e)| {
                (
                    device_id.clone(),
                    e.session_id,
                    e.credential.clone(),
                    e.endpoint_hex.clone(),
                )
            })
            .collect()
    }
}