Skip to main content

useceleris_client/
events.rs

1//! Events are listener registrations that return a [`Registration`] to remove
2//! the listener (DEV-01). Delivery is ordered, with no queue on the consumer's
3//! side: a slow listener holds up the next event rather than letting events
4//! pile up.
5//!
6//! Every event is queued under the channel's lock at the moment of the change
7//! that causes it. One task at a time on Tokio's blocking thread pool delivers
8//! the queue, and releases the lock around each listener. An event reaches the
9//! listeners registered when its turn comes. Listeners therefore observe
10//! events in the order that the state changed, never run under an SDK lock,
11//! never hold up the runtime's worker threads, and may call back into the
12//! channel.
13
14use std::collections::{HashMap, VecDeque};
15use std::fmt;
16use std::panic::{AssertUnwindSafe, catch_unwind};
17use std::sync::atomic::{AtomicBool, Ordering};
18use std::sync::{Arc, Weak};
19
20use crate::channel::{ChannelInner, ChannelShared};
21use crate::errors::CelerisError;
22use crate::values::{ChannelState, MessageMetadata, PresenceEvent, RecoveryEvent, ServerNotice};
23
24pub(crate) type MessageListener = dyn Fn(&[u8], &MessageMetadata) + Send + Sync;
25
26pub(crate) type PresenceListener = dyn Fn(&PresenceEvent) + Send + Sync;
27
28pub(crate) type StateListener = dyn Fn(ChannelState) + Send + Sync;
29
30pub(crate) type RecoveryListener = dyn Fn(&RecoveryEvent) + Send + Sync;
31
32pub(crate) type NoticeListener = dyn Fn(&ServerNotice) + Send + Sync;
33
34pub(crate) type ErrorListener = dyn Fn(&CelerisError) + Send + Sync;
35
36/// One delivery, run without the lock.
37type Delivery = Box<dyn FnOnce() + Send>;
38
39/// One queued event. The drainer prepares it under the lock: it takes the
40/// snapshot of the listeners and returns the delivery to run without the lock.
41pub(crate) type Event = Box<dyn FnOnce(&ChannelInner) -> Delivery + Send>;
42
43/// The queued events and whether a task is delivering them. Guarded by the
44/// channel's lock.
45#[derive(Default)]
46pub(crate) struct EventQueue {
47    events: VecDeque<Event>,
48    draining: bool,
49} // end struct EventQueue
50
51impl EventQueue {
52    /// No event is queued or being delivered.
53    pub(crate) fn is_quiet(&self) -> bool {
54        !self.draining && self.events.is_empty()
55    } // end method is_quiet
56} // end impl EventQueue
57
58/// Removes one listener. Call [`Registration::remove`] to remove it; calling it
59/// again does nothing.
60///
61/// Dropping a `Registration` keeps the listener registered, so a listener that
62/// stays for the life of the channel needs no binding.
63#[derive(Debug)]
64pub struct Registration {
65    channel: Weak<ChannelShared>,
66    location: ListenerLocation,
67    identifier: u64,
68    removed: Arc<AtomicBool>,
69} // end struct Registration
70
71impl Registration {
72    /// Removes the listener at once. The other listeners and the subscriptions
73    /// do not change, and nothing is sent to the server.
74    pub fn remove(&self) {
75        // Set first, so that a delivery in progress skips the listener.
76        if self.removed.swap(true, Ordering::SeqCst) {
77            return;
78        }
79
80        if let Some(channel) = self.channel.upgrade() {
81            channel
82                .lock()
83                .listeners
84                .remove(&self.location, self.identifier);
85        }
86    } // end method remove
87} // end impl Registration
88
89/// Registers channel-wide listeners. Obtain one with
90/// [`Channel::events`](crate::Channel::events).
91#[derive(Clone)]
92pub struct ChannelEventHandler {
93    pub(crate) channel: Arc<ChannelShared>,
94} // end struct ChannelEventHandler
95
96impl fmt::Debug for ChannelEventHandler {
97    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
98        formatter.write_str("ChannelEventHandler")
99    } // end method fmt
100} // end impl Debug for ChannelEventHandler
101
102impl ChannelEventHandler {
103    /// Registers a listener for every state transition.
104    pub fn on_state_change(
105        &self,
106        listener: impl Fn(ChannelState) + Send + Sync + 'static,
107    ) -> Registration {
108        let listener: Arc<StateListener> = Arc::new(listener);
109
110        self.channel.register(
111            ListenerLocation::State,
112            |listeners| &mut listeners.states,
113            listener,
114        )
115    } // end method on_state_change
116
117    /// Registers a listener for every successful reconnect.
118    pub fn on_recovery(
119        &self,
120        listener: impl Fn(&RecoveryEvent) + Send + Sync + 'static,
121    ) -> Registration {
122        let listener: Arc<RecoveryListener> = Arc::new(listener);
123
124        self.channel.register(
125            ListenerLocation::Recovery,
126            |listeners| &mut listeners.recoveries,
127            listener,
128        )
129    } // end method on_recovery
130
131    /// Registers a listener for the server's raw notices.
132    pub fn on_notice(
133        &self,
134        listener: impl Fn(&ServerNotice) + Send + Sync + 'static,
135    ) -> Registration {
136        let listener: Arc<NoticeListener> = Arc::new(listener);
137
138        self.channel.register(
139            ListenerLocation::Notice,
140            |listeners| &mut listeners.notices,
141            listener,
142        )
143    } // end method on_notice
144
145    /// Registers a listener for failures that no caller waits for: a
146    /// [`CelerisError::Server`] that the server sent, or an SDK error such as
147    /// an undecodable message, a failed reconnect, or a listener that panicked.
148    pub fn on_error(
149        &self,
150        listener: impl Fn(&CelerisError) + Send + Sync + 'static,
151    ) -> Registration {
152        let listener: Arc<ErrorListener> = Arc::new(listener);
153
154        self.channel.register(
155            ListenerLocation::Error,
156            |listeners| &mut listeners.errors,
157            listener,
158        )
159    } // end method on_error
160
161    /// Registers a listener for every delivery from any segment that the
162    /// connection is a member of, also when that segment has no listeners of
163    /// its own. For each delivery it runs after the segment's listeners
164    /// (MSG-02).
165    ///
166    /// Removing it removes only this listener: the other listeners and the
167    /// subscriptions do not change, and nothing is sent to the server.
168    pub fn on_message(
169        &self,
170        listener: impl Fn(&[u8], &MessageMetadata) + Send + Sync + 'static,
171    ) -> Registration {
172        let listener: Arc<MessageListener> = Arc::new(listener);
173
174        self.channel.register(
175            ListenerLocation::ChannelMessage,
176            |listeners| &mut listeners.channel_messages,
177            listener,
178        )
179    } // end method on_message
180} // end impl ChannelEventHandler
181
182/// Where a listener is registered.
183#[derive(Clone, Debug, PartialEq, Eq)]
184pub(crate) enum ListenerLocation {
185    State,
186    Recovery,
187    Notice,
188    Error,
189    ChannelMessage,
190    SegmentMessage(String),
191    Presence(String),
192} // end enum ListenerLocation
193
194struct ListenerEntry<Listener: ?Sized> {
195    identifier: u64,
196
197    // Read without the lock while events are delivered, so an entry removed
198    // before its turn is skipped.
199    removed: Arc<AtomicBool>,
200
201    listener: Arc<Listener>,
202} // end struct ListenerEntry
203
204pub(crate) struct ListenerSet<Listener: ?Sized> {
205    entries: Vec<Arc<ListenerEntry<Listener>>>,
206} // end struct ListenerSet
207
208impl<Listener: ?Sized> Default for ListenerSet<Listener> {
209    fn default() -> ListenerSet<Listener> {
210        ListenerSet {
211            entries: Vec::new(),
212        }
213    } // end fn default
214} // end impl Default for ListenerSet
215
216impl<Listener: ?Sized> ListenerSet<Listener> {
217    fn remove(&mut self, identifier: u64) {
218        self.entries.retain(|entry| entry.identifier != identifier);
219    } // end method remove
220
221    fn snapshot(&self) -> Vec<Arc<ListenerEntry<Listener>>> {
222        self.entries.clone()
223    } // end method snapshot
224} // end impl ListenerSet
225
226/// Every listener of a channel. Guarded by the channel's lock.
227#[derive(Default)]
228pub(crate) struct Listeners {
229    pub(crate) segment_messages: HashMap<String, ListenerSet<MessageListener>>,
230    pub(crate) presence: HashMap<String, ListenerSet<PresenceListener>>,
231    pub(crate) channel_messages: ListenerSet<MessageListener>,
232    pub(crate) states: ListenerSet<StateListener>,
233    pub(crate) recoveries: ListenerSet<RecoveryListener>,
234    pub(crate) notices: ListenerSet<NoticeListener>,
235    pub(crate) errors: ListenerSet<ErrorListener>,
236    last_identifier: u64,
237} // end struct Listeners
238
239impl Listeners {
240    fn remove(&mut self, location: &ListenerLocation, identifier: u64) {
241        match location {
242            ListenerLocation::State => self.states.remove(identifier),
243            ListenerLocation::Recovery => self.recoveries.remove(identifier),
244            ListenerLocation::Notice => self.notices.remove(identifier),
245            ListenerLocation::Error => self.errors.remove(identifier),
246            ListenerLocation::ChannelMessage => self.channel_messages.remove(identifier),
247            ListenerLocation::SegmentMessage(segment_id) => {
248                if let Some(set) = self.segment_messages.get_mut(segment_id) {
249                    set.remove(identifier);
250                }
251            }
252            ListenerLocation::Presence(segment_id) => {
253                if let Some(set) = self.presence.get_mut(segment_id) {
254                    set.remove(identifier);
255                }
256            }
257        }
258    } // end method remove
259} // end impl Listeners
260
261impl ChannelShared {
262    /// Adds a listener to the set that `choose` picks, which must be the set
263    /// that `location` names.
264    pub(crate) fn register<Listener: ?Sized>(
265        self: &Arc<Self>,
266        location: ListenerLocation,
267        choose: impl FnOnce(&mut Listeners) -> &mut ListenerSet<Listener>,
268        listener: Arc<Listener>,
269    ) -> Registration {
270        let removed = Arc::new(AtomicBool::new(false));
271        let mut inner = self.lock();
272        inner.listeners.last_identifier += 1;
273        let identifier = inner.listeners.last_identifier;
274
275        choose(&mut inner.listeners)
276            .entries
277            .push(Arc::new(ListenerEntry {
278                identifier,
279                removed: Arc::clone(&removed),
280                listener,
281            }));
282
283        Registration {
284            channel: Arc::downgrade(self),
285            location,
286            identifier,
287            removed,
288        }
289    } // end method register
290
291    /// Delivers queued events in order until none remain. Only one task
292    /// delivers at a time; a call while one delivers returns at once, and the
293    /// events it queued are delivered by the one already delivering.
294    pub(crate) fn dispatch_events(self: &Arc<Self>) {
295        let mut inner = self.lock();
296
297        if inner.events.draining || inner.events.events.is_empty() {
298            return;
299        }
300
301        let Some(runtime) = inner.runtime.clone() else {
302            return;
303        };
304
305        inner.events.draining = true;
306        drop(inner);
307
308        let channel = Arc::clone(self);
309        runtime.spawn_blocking(move || channel.drain_events());
310    } // end method dispatch_events
311
312    fn drain_events(&self) {
313        loop {
314            let delivery = {
315                let mut inner = self.lock();
316
317                let Some(event) = inner.events.events.pop_front() else {
318                    inner.events.draining = false;
319                    drop(inner);
320                    self.idle.notify_waiters();
321
322                    return;
323                };
324
325                event(&inner)
326            };
327
328            delivery();
329        }
330    } // end method drain_events
331
332    /// Waits until no event is queued or being delivered.
333    #[cfg(test)]
334    pub(crate) async fn quiesce(&self) {
335        loop {
336            let idle = self.idle.notified();
337            tokio::pin!(idle);
338            idle.as_mut().enable();
339
340            if self.lock().events.is_quiet() {
341                return;
342            }
343
344            idle.await;
345        }
346    } // end method quiesce
347} // end impl ChannelShared
348
349impl ChannelInner {
350    /// Queues delivery of one event to the listeners that `choose` picks when
351    /// its turn comes, as the reference dispatches to the listeners registered
352    /// at dispatch. A listener that panics is reported through the error
353    /// listeners; an error listener that panics is not, since that would
354    /// report into the dispatch that failed.
355    pub(crate) fn queue_event<Listener: ?Sized + Send + Sync + 'static>(
356        &mut self,
357        choose: impl FnOnce(&Listeners) -> Option<&ListenerSet<Listener>> + Send + 'static,
358        invoke: impl Fn(&Listener) + Send + 'static,
359        report_panics: bool,
360    ) {
361        self.events
362            .events
363            .push_back(Box::new(move |inner: &ChannelInner| {
364                let entries = choose(&inner.listeners)
365                    .map(ListenerSet::snapshot)
366                    .unwrap_or_default();
367                let channel = inner.this.clone();
368
369                Box::new(move || deliver_entries(&channel, &entries, &invoke, report_panics))
370                    as Delivery
371            }));
372    } // end method queue_event
373
374    pub(crate) fn queue_state_change(&mut self, state: ChannelState) {
375        self.state = state;
376        self.queue_event(
377            |listeners| Some(&listeners.states),
378            move |listener| listener(state),
379            true,
380        );
381    } // end method queue_state_change
382
383    pub(crate) fn queue_error(&mut self, error: CelerisError) {
384        self.queue_event(
385            |listeners| Some(&listeners.errors),
386            move |listener| listener(&error),
387            false,
388        );
389    } // end method queue_error
390} // end impl ChannelInner
391
392fn deliver_entries<Listener: ?Sized>(
393    channel: &Weak<ChannelShared>,
394    entries: &[Arc<ListenerEntry<Listener>>],
395    invoke: &impl Fn(&Listener),
396    report_panics: bool,
397) {
398    for entry in entries {
399        if entry.removed.load(Ordering::SeqCst) {
400            continue;
401        }
402
403        let panicked = catch_unwind(AssertUnwindSafe(|| invoke(&entry.listener))).is_err();
404
405        if panicked && report_panics {
406            report_listener_panic(channel);
407        }
408    }
409} // end fn deliver_entries
410
411/// Reports a listener's panic next, ahead of the events already queued, as the
412/// reference reports it before dispatch moves on.
413fn report_listener_panic(channel: &Weak<ChannelShared>) {
414    let Some(channel) = channel.upgrade() else {
415        return;
416    };
417
418    let failure = CelerisError::Transport(
419        "A listener callback panicked; the channel recovered and kept running.".to_owned(),
420    );
421    let mut inner = channel.lock();
422    inner.queue_error(failure);
423
424    // queue_error appends; the report belongs at the front.
425    if let Some(report) = inner.events.events.pop_back() {
426        inner.events.events.push_front(report);
427    }
428} // end fn report_listener_panic