Files
continuwuity/src/database/watchers.rs
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

58 lines
1.2 KiB
Rust
Raw Normal View History

use std::{
collections::{HashMap, hash_map},
future::Future,
pin::Pin,
};
2024-03-05 19:48:54 -05:00
use conduwuit::SyncRwLock;
use tokio::sync::watch;
type Watcher = SyncRwLock<HashMap<Vec<u8>, (watch::Sender<()>, watch::Receiver<()>)>>;
#[derive(Default)]
2024-04-22 23:48:57 -04:00
pub(crate) struct Watchers {
watchers: Watcher,
}
impl Watchers {
pub(crate) fn watch<'a>(
&'a self,
prefix: &[u8],
) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
let mut rx = match self.watchers.write().entry(prefix.to_vec()) {
| hash_map::Entry::Occupied(o) => o.get().1.clone(),
| hash_map::Entry::Vacant(v) => {
2024-03-08 09:25:47 -05:00
let (tx, rx) = watch::channel(());
v.insert((tx, rx.clone()));
rx
},
};
2024-03-05 19:48:54 -05:00
Box::pin(async move {
// Tx is never destroyed
rx.changed().await.unwrap();
})
}
2024-03-05 19:48:54 -05:00
2024-04-22 23:48:57 -04:00
pub(crate) fn wake(&self, key: &[u8]) {
let watchers = self.watchers.read();
let mut triggered = Vec::new();
for length in 0..=key.len() {
if watchers.contains_key(&key[..length]) {
triggered.push(&key[..length]);
2024-03-05 19:48:54 -05:00
}
}
2024-03-05 19:48:54 -05:00
drop(watchers);
2024-03-05 19:48:54 -05:00
if !triggered.is_empty() {
let mut watchers = self.watchers.write();
for prefix in triggered {
if let Some(tx) = watchers.remove(prefix) {
2024-05-04 09:45:37 -04:00
tx.0.send(()).expect("channel should still be open");
}
}
2025-02-25 18:38:12 +00:00
}
}
}