node-device-session 7.7.11

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>,
}

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.
    pub fn len(&self) -> usize {
        self.inner.entries.lock().len()
    }

    /// 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().contains_key(device_id)
    }

    /// Register a newly opened full-mode session.
    ///
    /// If `device_id` already has a session, the previous one is closed with
    /// [`SUPERSEDED_CLOSE_CODE`]. 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 = self.inner.entries.lock().insert(
            device_id,
            Entry {
                session_id,
                credential,
                endpoint_hex,
                close,
                webrtc: None,
            },
        );
        if let Some(old) = previous {
            (old.close)(SUPERSEDED_CLOSE_CODE, b"superseded");
        }
        session_id
    }

    /// Remove the session only if `session_id` is still the live one for `device_id`.
    pub fn remove_if(&self, device_id: &str, session_id: u64) -> bool {
        let mut entries = self.inner.entries.lock();
        match entries.get(device_id) {
            Some(entry) if entry.session_id == session_id => {
                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)> {
        self.inner
            .entries
            .lock()
            .iter()
            .map(|(device_id, e)| {
                (
                    device_id.clone(),
                    e.session_id,
                    e.credential.clone(),
                    e.endpoint_hex.clone(),
                )
            })
            .collect()
    }
}