use std::collections::HashMap;
use std::ptr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use super::node::is_at_or_below;
pub(super) fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(super) async fn acquire_some<'a, L, F: Future>(
lock: Option<&'a L>,
acquire: impl FnOnce(&'a L) -> F,
) -> Option<F::Output> {
match lock {
Some(lock) => Some(acquire(lock).await),
None => None,
}
}
pub(super) struct Locks {
pub(super) tree: RwLock<()>,
directories: Arc<DirTable>,
}
#[derive(Default)]
struct DirTable {
entries: Mutex<HashMap<String, Weak<DirLock>>>,
}
pub(super) struct DirLock {
key: String,
table: Arc<DirTable>,
lock: RwLock<()>,
changes: AtomicU64,
}
pub(super) enum DirGuard<'a> {
Shared { _held: RwLockReadGuard<'a, ()> },
Exclusive { _held: RwLockWriteGuard<'a, ()> },
}
impl Locks {
pub(super) fn new() -> Self {
Self {
tree: RwLock::new(()),
directories: Arc::default(),
}
}
pub(super) fn directory(&self, key: String) -> Arc<DirLock> {
let mut entries = lock(&self.directories.entries);
if let Some(dir) = entries.get(&key).and_then(Weak::upgrade) {
return dir;
}
let dir = Arc::new(DirLock {
key: key.clone(),
table: Arc::clone(&self.directories),
lock: RwLock::new(()),
changes: AtomicU64::new(0),
});
entries.insert(key, Arc::downgrade(&dir));
dir
}
pub(super) fn directories_below(&self, key: &str) -> Vec<Arc<DirLock>> {
lock(&self.directories.entries)
.iter()
.filter(|(held, _)| is_at_or_below(held, key))
.filter_map(|(_, entry)| entry.upgrade())
.collect()
}
#[cfg(test)]
pub(super) fn directory_count(&self) -> usize {
lock(&self.directories.entries).len()
}
}
impl DirLock {
pub(super) fn key(&self) -> &str {
&self.key
}
pub(super) async fn acquire(&self, exclusive: bool) -> DirGuard<'_> {
if exclusive {
DirGuard::Exclusive {
_held: self.lock.write().await,
}
} else {
DirGuard::Shared {
_held: self.lock.read().await,
}
}
}
pub(super) fn changes(&self) -> u64 {
self.changes.load(Ordering::Acquire)
}
pub(super) fn count_change(&self) {
self.changes.fetch_add(1, Ordering::AcqRel);
}
#[cfg(test)]
pub(super) fn is_free(&self) -> bool {
self.lock.try_write().is_ok()
}
#[cfg(test)]
pub(super) fn is_exclusive(&self) -> bool {
self.lock.try_read().is_err()
}
}
impl Drop for DirLock {
fn drop(&mut self) {
let mut entries = lock(&self.table.entries);
if entries
.get(&self.key)
.is_some_and(|entry| ptr::eq(entry.as_ptr(), self))
{
entries.remove(&self.key);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn one_key_is_one_lock_while_it_is_in_use() {
let locks = Locks::new();
let first = locks.directory("a".to_string());
let again = locks.directory("a".to_string());
let other = locks.directory("b".to_string());
assert!(Arc::ptr_eq(&first, &again));
assert!(!Arc::ptr_eq(&first, &other));
assert_eq!(locks.directory_count(), 2);
}
#[tokio::test]
async fn a_lock_nobody_holds_leaves_the_table() {
let locks = Locks::new();
let first = locks.directory("a".to_string());
let again = locks.directory("a".to_string());
drop(first);
assert_eq!(locks.directory_count(), 1);
drop(again);
assert_eq!(locks.directory_count(), 0);
}
#[tokio::test]
async fn the_count_of_changes_lives_as_long_as_the_entry() {
let locks = Locks::new();
let held = locks.directory("a".to_string());
assert_eq!(held.changes(), 0);
held.count_change();
locks.directory("a".to_string()).count_change();
assert_eq!(held.changes(), 2, "one entry while it is held");
assert_eq!(locks.directory("b".to_string()).changes(), 0);
drop(held);
assert_eq!(
locks.directory("a".to_string()).changes(),
0,
"an entry nobody holds starts over"
);
}
#[tokio::test]
async fn the_entries_at_and_below_a_directory_are_found_without_its_siblings() {
let locks = Locks::new();
let held: Vec<_> = ["a", "a\\b", "a\\b\\c", "ab", "b", "b\\a"]
.map(|key| locks.directory(key.to_string()))
.into();
let keys = |below: &str| {
let mut keys: Vec<_> = locks
.directories_below(below)
.iter()
.map(|dir| dir.key().to_string())
.collect();
keys.sort();
keys
};
assert_eq!(keys("a"), ["a", "a\\b", "a\\b\\c"]);
assert_eq!(keys("a\\b"), ["a\\b", "a\\b\\c"]);
assert_eq!(keys("b"), ["b", "b\\a"]);
assert_eq!(keys("zz"), Vec::<String>::new());
assert_eq!(keys("").len(), 6);
drop(held);
assert!(locks.directories_below("a").is_empty());
assert_eq!(locks.directory_count(), 0);
}
}