Skip to main content

node_device_session/
registry.rs

1//! Live device sessions, one per `device_id`.
2//!
3//! A newer session replaces an older one (a device that switched networks
4//! reconnects before the old path times out). Teardown removes a session only
5//! if it is still the one that ended, so a late close of the old connection
6//! cannot evict the new one. Ported from `node-app-iroh`'s device-session
7//! registry into the shared, transport-neutral form.
8
9use crate::webrtc::WebRtcHandle;
10use parking_lot::Mutex;
11use std::collections::HashMap;
12use std::sync::atomic::{AtomicU64, Ordering};
13use std::sync::Arc;
14
15/// Application close code when a newer session supersedes an older one.
16pub const SUPERSEDED_CLOSE_CODE: u32 = 3;
17/// Application close code when revalidation (or explicit revoke) tears a session down.
18pub const REVOKED_CLOSE_CODE: u32 = 4;
19
20/// Closes the underlying [`crate::SessionStreams`] connection.
21pub type SessionClose = Arc<dyn Fn(u32, &[u8]) + Send + Sync>;
22
23struct Entry {
24    session_id: u64,
25    credential: String,
26    endpoint_hex: String,
27    close: SessionClose,
28    webrtc: Option<WebRtcHandle>,
29}
30
31impl Drop for Entry {
32    fn drop(&mut self) {
33        if let Some(handle) = &self.webrtc {
34            handle.close();
35        }
36    }
37}
38
39struct Inner {
40    next_id: AtomicU64,
41    entries: Mutex<HashMap<String, Entry>>,
42}
43
44/// Registry of live full-mode device sessions for periodic revalidation.
45///
46/// Clone is cheap (`Arc`); all clones share the same map.
47#[derive(Clone)]
48pub struct SessionRegistry {
49    inner: Arc<Inner>,
50}
51
52impl Default for SessionRegistry {
53    fn default() -> Self {
54        Self::new()
55    }
56}
57
58impl SessionRegistry {
59    /// Empty registry.
60    pub fn new() -> Self {
61        Self {
62            inner: Arc::new(Inner {
63                next_id: AtomicU64::new(1),
64                entries: Mutex::new(HashMap::new()),
65            }),
66        }
67    }
68
69    /// Number of live sessions.
70    pub fn len(&self) -> usize {
71        self.inner.entries.lock().len()
72    }
73
74    /// Whether no sessions are registered.
75    pub fn is_empty(&self) -> bool {
76        self.len() == 0
77    }
78
79    /// Whether `device_id` currently has a live session.
80    pub fn contains(&self, device_id: &str) -> bool {
81        self.inner.entries.lock().contains_key(device_id)
82    }
83
84    /// Register a newly opened full-mode session.
85    ///
86    /// If `device_id` already has a session, the previous one is closed with
87    /// [`SUPERSEDED_CLOSE_CODE`]. Returns the new session id.
88    pub fn insert(
89        &self,
90        device_id: String,
91        credential: String,
92        endpoint_hex: String,
93        close: SessionClose,
94    ) -> u64 {
95        let session_id = self.inner.next_id.fetch_add(1, Ordering::Relaxed);
96        let previous = self.inner.entries.lock().insert(
97            device_id,
98            Entry {
99                session_id,
100                credential,
101                endpoint_hex,
102                close,
103                webrtc: None,
104            },
105        );
106        if let Some(old) = previous {
107            (old.close)(SUPERSEDED_CLOSE_CODE, b"superseded");
108        }
109        session_id
110    }
111
112    /// Remove the session only if `session_id` is still the live one for `device_id`.
113    pub fn remove_if(&self, device_id: &str, session_id: u64) -> bool {
114        let mut entries = self.inner.entries.lock();
115        match entries.get(device_id) {
116            Some(entry) if entry.session_id == session_id => {
117                entries.remove(device_id);
118                true
119            }
120            _ => false,
121        }
122    }
123
124    /// Close and remove the matching live session (revocation / expiry).
125    pub fn close(&self, device_id: &str, session_id: u64, reason: &'static [u8]) -> bool {
126        let removed = {
127            let mut entries = self.inner.entries.lock();
128            match entries.get(device_id) {
129                Some(entry) if entry.session_id == session_id => entries.remove(device_id),
130                _ => None,
131            }
132        };
133        match removed {
134            Some(entry) => {
135                (entry.close)(REVOKED_CLOSE_CODE, reason);
136                true
137            }
138            None => false,
139        }
140    }
141
142    /// Bind a WebRTC answerer handle into the live session for `device_id`.
143    ///
144    /// Returns `false` (and closes `handle`) when no session is registered.
145    /// A later bind replaces the previous handle and closes it.
146    pub fn bind_webrtc(&self, device_id: &str, handle: WebRtcHandle) -> bool {
147        let mut entries = self.inner.entries.lock();
148        let Some(entry) = entries.get_mut(device_id) else {
149            handle.close();
150            return false;
151        };
152        if let Some(old) = entry.webrtc.replace(handle) {
153            old.close();
154        }
155        true
156    }
157
158    /// Snapshot of `(device_id, session_id, credential, endpoint_hex)` for revalidation.
159    pub(crate) fn credentials(&self) -> Vec<(String, u64, String, String)> {
160        self.inner
161            .entries
162            .lock()
163            .iter()
164            .map(|(device_id, e)| {
165                (
166                    device_id.clone(),
167                    e.session_id,
168                    e.credential.clone(),
169                    e.endpoint_hex.clone(),
170                )
171            })
172            .collect()
173    }
174}