pict-rs/src/repo/notification_map.rs
asonix d97cfe2a64
All checks were successful
/ check (aarch64-unknown-linux-musl) (push) Successful in 1m53s
/ check (armv7-unknown-linux-musleabihf) (push) Successful in 1m54s
/ check (x86_64-unknown-linux-musl) (push) Successful in 1m49s
/ clippy (push) Successful in 1m21s
/ tests (push) Successful in 1m50s
Remove 'armed' from NotificationEntryInner by only creating them when needed
2024-04-03 13:22:34 -05:00

93 lines
2.3 KiB
Rust

use dashmap::{mapref::entry::Entry, DashMap};
use std::{
future::Future,
sync::{Arc, Weak},
time::Duration,
};
use tokio::sync::Notify;
use crate::future::WithTimeout;
type Map = Arc<DashMap<Arc<str>, Weak<NotificationEntryInner>>>;
#[derive(Clone)]
pub(super) struct NotificationMap {
map: Map,
}
pub(crate) struct NotificationEntry {
inner: Arc<NotificationEntryInner>,
}
struct NotificationEntryInner {
key: Arc<str>,
map: Map,
notify: Notify,
}
impl NotificationMap {
pub(super) fn new() -> Self {
Self {
map: Arc::new(DashMap::new()),
}
}
pub(super) fn register_interest(&self, key: Arc<str>) -> NotificationEntry {
match self.map.entry(key.clone()) {
Entry::Occupied(mut occupied) => {
if let Some(inner) = occupied.get().upgrade() {
NotificationEntry { inner }
} else {
let inner = Arc::new(NotificationEntryInner {
key,
map: self.map.clone(),
notify: crate::sync::bare_notify(),
});
occupied.insert(Arc::downgrade(&inner));
NotificationEntry { inner }
}
}
Entry::Vacant(vacant) => {
let inner = Arc::new(NotificationEntryInner {
key,
map: self.map.clone(),
notify: crate::sync::bare_notify(),
});
vacant.insert(Arc::downgrade(&inner));
NotificationEntry { inner }
}
}
}
pub(super) fn notify(&self, key: &str) {
if let Some(notifier) = self.map.get(key).and_then(|v| v.upgrade()) {
notifier.notify.notify_waiters();
}
}
}
impl NotificationEntry {
pub(crate) fn notified_timeout(
&mut self,
duration: Duration,
) -> impl Future<Output = Result<(), tokio::time::error::Elapsed>> + '_ {
self.inner.notify.notified().with_timeout(duration)
}
}
impl Default for NotificationMap {
fn default() -> Self {
Self::new()
}
}
impl Drop for NotificationEntryInner {
fn drop(&mut self) {
self.map.remove(&self.key);
}
}