use crate::webrtc::WebRtcHandle;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
pub const SUPERSEDED_CLOSE_CODE: u32 = 3;
pub const REVOKED_CLOSE_CODE: u32 = 4;
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>>,
}
#[derive(Clone)]
pub struct SessionRegistry {
inner: Arc<Inner>,
}
impl Default for SessionRegistry {
fn default() -> Self {
Self::new()
}
}
impl SessionRegistry {
pub fn new() -> Self {
Self {
inner: Arc::new(Inner {
next_id: AtomicU64::new(1),
entries: Mutex::new(HashMap::new()),
}),
}
}
pub fn len(&self) -> usize {
self.inner.entries.lock().len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn contains(&self, device_id: &str) -> bool {
self.inner.entries.lock().contains_key(device_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
}
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,
}
}
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,
}
}
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
}
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()
}
}