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    /// False once the carrier connection ended while a connected WebRTC
30    /// session still runs. The entry stays so revalidation and revocation
31    /// still reach that WebRTC session (ADR-154 Amendment, punch outlives
32    /// signaling).
33    carrier_open: bool,
34}
35
36impl Entry {
37    fn webrtc_live(&self) -> bool {
38        self.webrtc
39            .as_ref()
40            .is_some_and(|handle| !handle.is_closed())
41    }
42}
43
44/// Drop entries whose carrier ended and whose WebRTC session is gone too.
45fn prune(entries: &mut HashMap<String, Entry>) {
46    entries.retain(|_, entry| entry.carrier_open || entry.webrtc_live());
47}
48
49impl Drop for Entry {
50    fn drop(&mut self) {
51        if let Some(handle) = &self.webrtc {
52            handle.close();
53        }
54    }
55}
56
57struct Inner {
58    next_id: AtomicU64,
59    entries: Mutex<HashMap<String, Entry>>,
60}
61
62/// Registry of live full-mode device sessions for periodic revalidation.
63///
64/// Clone is cheap (`Arc`); all clones share the same map.
65#[derive(Clone)]
66pub struct SessionRegistry {
67    inner: Arc<Inner>,
68}
69
70impl Default for SessionRegistry {
71    fn default() -> Self {
72        Self::new()
73    }
74}
75
76impl SessionRegistry {
77    /// Empty registry.
78    pub fn new() -> Self {
79        Self {
80            inner: Arc::new(Inner {
81                next_id: AtomicU64::new(1),
82                entries: Mutex::new(HashMap::new()),
83            }),
84        }
85    }
86
87    /// Number of live sessions (open carrier connections).
88    pub fn len(&self) -> usize {
89        self.inner
90            .entries
91            .lock()
92            .values()
93            .filter(|entry| entry.carrier_open)
94            .count()
95    }
96
97    /// Whether no sessions are registered.
98    pub fn is_empty(&self) -> bool {
99        self.len() == 0
100    }
101
102    /// Whether `device_id` currently has a live session.
103    pub fn contains(&self, device_id: &str) -> bool {
104        self.inner
105            .entries
106            .lock()
107            .get(device_id)
108            .is_some_and(|entry| entry.carrier_open)
109    }
110
111    /// Register a newly opened full-mode session.
112    ///
113    /// If `device_id` already has a session, the previous one is closed with
114    /// [`SUPERSEDED_CLOSE_CODE`]. A WebRTC session still running from the
115    /// previous entry moves to the new one: it is the same device, and the new
116    /// session's credential now covers it. Returns the new session id.
117    pub fn insert(
118        &self,
119        device_id: String,
120        credential: String,
121        endpoint_hex: String,
122        close: SessionClose,
123    ) -> u64 {
124        let session_id = self.inner.next_id.fetch_add(1, Ordering::Relaxed);
125        let previous = {
126            let mut entries = self.inner.entries.lock();
127            prune(&mut entries);
128            let mut previous = entries.remove(&device_id);
129            let webrtc = previous
130                .as_mut()
131                .and_then(|old| old.webrtc.take())
132                .filter(|handle| !handle.is_closed());
133            entries.insert(
134                device_id,
135                Entry {
136                    session_id,
137                    credential,
138                    endpoint_hex,
139                    close,
140                    webrtc,
141                    carrier_open: true,
142                },
143            );
144            previous
145        };
146        if let Some(old) = previous {
147            if old.carrier_open {
148                (old.close)(SUPERSEDED_CLOSE_CODE, b"superseded");
149            }
150        }
151        session_id
152    }
153
154    /// Remove the session only if `session_id` is still the live one for `device_id`.
155    ///
156    /// A connected WebRTC session bound to it keeps running: the entry stays,
157    /// marked carrier-closed, so revalidation and revocation still close it,
158    /// and the device's next session takes it over.
159    pub fn remove_if(&self, device_id: &str, session_id: u64) -> bool {
160        let mut entries = self.inner.entries.lock();
161        match entries.get_mut(device_id) {
162            Some(entry) if entry.session_id == session_id => {
163                if entry.webrtc_live() {
164                    entry.carrier_open = false;
165                } else {
166                    entries.remove(device_id);
167                }
168                true
169            }
170            _ => false,
171        }
172    }
173
174    /// Close and remove the matching live session (revocation / expiry).
175    pub fn close(&self, device_id: &str, session_id: u64, reason: &'static [u8]) -> bool {
176        let removed = {
177            let mut entries = self.inner.entries.lock();
178            match entries.get(device_id) {
179                Some(entry) if entry.session_id == session_id => entries.remove(device_id),
180                _ => None,
181            }
182        };
183        match removed {
184            Some(entry) => {
185                (entry.close)(REVOKED_CLOSE_CODE, reason);
186                true
187            }
188            None => false,
189        }
190    }
191
192    /// Bind a WebRTC answerer handle into the live session for `device_id`.
193    ///
194    /// Returns `false` (and closes `handle`) when no session is registered.
195    /// A later bind replaces the previous handle and closes it.
196    pub fn bind_webrtc(&self, device_id: &str, handle: WebRtcHandle) -> bool {
197        let mut entries = self.inner.entries.lock();
198        let Some(entry) = entries.get_mut(device_id) else {
199            handle.close();
200            return false;
201        };
202        if let Some(old) = entry.webrtc.replace(handle) {
203            old.close();
204        }
205        true
206    }
207
208    /// Snapshot of `(device_id, session_id, credential, endpoint_hex)` for revalidation.
209    pub(crate) fn credentials(&self) -> Vec<(String, u64, String, String)> {
210        let mut entries = self.inner.entries.lock();
211        prune(&mut entries);
212        entries
213            .iter()
214            .map(|(device_id, e)| {
215                (
216                    device_id.clone(),
217                    e.session_id,
218                    e.credential.clone(),
219                    e.endpoint_hex.clone(),
220                )
221            })
222            .collect()
223    }
224}