#[cfg(target_arch = "wasm32")]
use crate::tokio;
use std::collections::BTreeMap;
use std::sync::Arc;
use tokio::sync::Mutex;
pub(super) struct EdgeLockRegistry {
locks: Mutex<BTreeMap<String, Arc<Mutex<()>>>>,
}
impl EdgeLockRegistry {
pub(super) fn new() -> Self {
Self {
locks: Mutex::new(BTreeMap::new()),
}
}
pub(super) async fn acquire(&self, a: &str, b: &str) -> tokio::sync::OwnedMutexGuard<()> {
let key = Self::canonical_key(a, b);
let lock = {
let mut locks = self.locks.lock().await;
locks
.entry(key)
.or_insert_with(|| Arc::new(Mutex::new(())))
.clone()
};
lock.lock_owned().await
}
pub(super) async fn remove(&self, a: &str, b: &str) {
let key = Self::canonical_key(a, b);
self.locks.lock().await.remove(&key);
}
pub(super) async fn prune(&self, member_id: &str) {
let mut locks = self.locks.lock().await;
locks.retain(|key, _| !key.split('|').any(|part| part == member_id));
}
pub(super) async fn clear(&self) {
self.locks.lock().await.clear();
}
fn canonical_key(a: &str, b: &str) -> String {
if a < b {
format!("{a}|{b}")
} else {
format!("{b}|{a}")
}
}
}