feat(managed): automatically unregister dropped event subscriptions

This commit is contained in:
Nils Andreas Svee committed 2026-04-29 01:14:36 +07:00
1 parent e04caaca8d
commit a925dc61f0
1 file changed
+20 -2
+20 -2
View File
@@ -2,7 +2,7 @@ use std::{
collections::{HashMap, VecDeque}, collections::{HashMap, VecDeque},
sync::{ sync::{
atomic::{AtomicU64, Ordering}, atomic::{AtomicU64, Ordering},
Arc, Condvar, Mutex, Arc, Condvar, Mutex, Weak,
}, },
}; };
@@ -43,6 +43,8 @@ struct HubInner {
#[derive(Debug)] #[derive(Debug)]
pub struct EventSubscription { pub struct EventSubscription {
id: u64,
hub: Weak<HubInner>,
inner: Arc<SubscriberInner>, inner: Arc<SubscriberInner>,
} }
@@ -94,7 +96,11 @@ impl EventHub {
.expect("event hub mutex poisoned") .expect("event hub mutex poisoned")
.insert(id, inner.clone()); .insert(id, inner.clone());
Ok(EventSubscription { inner }) Ok(EventSubscription {
id,
hub: Arc::downgrade(&self.inner),
inner,
})
} }
pub fn publish(&self, event: ClientEvent) { pub fn publish(&self, event: ClientEvent) {
@@ -180,6 +186,18 @@ impl EventSubscription {
} }
} }
impl Drop for EventSubscription {
fn drop(&mut self) {
self.inner.disconnect();
if let Some(hub) = self.hub.upgrade() {
hub.subscribers
.lock()
.expect("event hub mutex poisoned")
.remove(&self.id);
}
}
}
impl SubscriberInner { impl SubscriberInner {
fn publish(&self, event: ClientEvent) -> bool { fn publish(&self, event: ClientEvent) -> bool {
let mut state = self.state.lock().expect("subscriber mutex poisoned"); let mut state = self.state.lock().expect("subscriber mutex poisoned");