From b2a10b833dd6eee8efd53c91013e36b3b69c0fda Mon Sep 17 00:00:00 2001 From: Eureka Date: Sun, 29 Nov 2026 06:58:59 +0000 Subject: [PATCH] cultmesh-rs: connect_with_wake, a wake handle on the subscription client (#200) --- packages/cultmesh-rs/src/rudp_subscription.rs | 73 +++- .../cultmesh-rs/tests/rudp_subscription.rs | 397 +++++++++++++++++- 2 files changed, 465 insertions(+), 5 deletions(-) diff --git a/packages/cultmesh-rs/src/rudp_subscription.rs b/packages/cultmesh-rs/src/rudp_subscription.rs index 1cda8563..d5db7cf4 100644 --- a/packages/cultmesh-rs/src/rudp_subscription.rs +++ b/packages/cultmesh-rs/src/rudp_subscription.rs @@ -11,6 +11,27 @@ //! instead of waiting out `connect_timeout`. A closed or failed session is an event ([`CultMeshSubscriptionEvent::Disconnected`]), never a hang; //! after it the thread reads nothing and waits for `resubscribe_all` or the drop. //! +//! Wake: a consumer that cannot poll `try_drain` on a timer connects with +//! [`connect_with_wake`](CultMeshRudpSubscriptionClient::connect_with_wake) and blocks on whatever its closure +//! feeds (a channel, a condvar, an OS event loop). The closure carries no data: it says "drain now". It runs on the +//! pump thread after the event is in the queue and counted, so a `try_drain` made inside or after the call sees the +//! event; once per delivered event (a snapshot, a commit, `Faulted`, `Disconnected`), not once per batch, so +//! coalescing is the consumer's; and it must not block, because a slow wake delays the pump and so RUDP acks and +//! resends. A panic in it is caught and discarded, payload included even when the payload's own drop panics: the +//! pump survives and the event stays queued. (Under `panic = "abort"` a panicking wake aborts the process: nothing +//! can catch it.) It may call `try_drain`, `subscribe`, `unsubscribe` or `resubscribe_all`. The closure exists +//! before the client does, so it reaches the client through a `Weak` (or a slot filled after `connect_with_wake` +//! returns) and should hold it only weakly: if the owner drops its handle while the wake holds an upgraded one, +//! the wake's handle is the last, and `Drop` then runs on the pump thread. There it signals the pump to end and +//! does not join (a thread cannot join itself), so the pump ends once the wake returns. A wake that held a strong +//! handle for good would keep the client, and so the pump, alive forever. +//! +//! The wake runs once more when the pump thread ends, after `close` or `Drop` has sent the unsubscribes and the +//! goodbye, and never again. Both consume the client, so by then there is nothing left to `try_drain`: that last +//! wake only releases a consumer blocked on its own wait (on another thread, within the bounds above: 500 ms of +//! acknowledgement wait, a poll interval, and a reconnect abandoned at its next poll), which learns the client is +//! gone from its own handle, a `Weak` that no longer upgrades. What the pump had queued ends with the client. +//! //! Bounds: the assembler bounds what it holds of incomplete commits and faults the connection past that. What the //! caller has not drained is bounded too, by [`CultMeshRudpSubscriptionOptions::max_undrained`], counted in //! documents and changes, those still waiting in the pump for their rows included: a caller that stops draining @@ -232,8 +253,25 @@ pub struct CultMeshRudpSubscriptionClient { } impl CultMeshRudpSubscriptionClient { - /// Connects (blocking up to `connect_timeout`) and starts the pump thread. + /// Connects (blocking up to `connect_timeout`) and starts the pump thread. Nothing signals the caller when an + /// event arrives: it polls `try_drain`. See [`connect_with_wake`](Self::connect_with_wake) to block instead. pub fn connect(options: CultMeshRudpSubscriptionOptions) -> Result { + Self::start(options, None) + } + + /// As `connect`, and `wake` is called on the pump thread once for every event it queues (after the event is + /// queued, so `try_drain` already holds it) and once more when the pump thread ends after `close` or `Drop`. + /// The closure is installed before the pump starts, so no event is queued without it. It carries no data, must + /// not block, and may call this client's methods; a panic in it is caught and discarded. The module docs state + /// the whole contract. + pub fn connect_with_wake( + options: CultMeshRudpSubscriptionOptions, + wake: impl Fn() + Send + Sync + 'static, + ) -> Result { + Self::start(options, Some(Arc::new(wake))) + } + + fn start(options: CultMeshRudpSubscriptionOptions, wake: Option>) -> Result { if options.runtime_id.trim().is_empty() { return Err(anyhow!("runtime_id must be non-empty")); } @@ -266,6 +304,7 @@ impl CultMeshRudpSubscriptionClient { commands: command_rx, events: event_tx, undrained: undrained.clone(), + wake, }; let pump = thread::Builder::new() .name("cultmesh-rudp-subscription".into()) @@ -289,6 +328,13 @@ impl CultMeshRudpSubscriptionClient { self.pump_alive.clone() } + /// The weight (documents and changes) delivered and not yet drained, which `max_undrained` bounds. Only under + /// the `test-hooks` feature, which this crate's own tests enable: not part of the API a consumer builds against. + #[cfg(feature = "test-hooks")] + pub fn undrained_weight(&self) -> usize { + self.undrained.load(Ordering::SeqCst) + } + /// Queues a subscribe with a snapshot and returns; the snapshot arrives as an event. Subscribing an id that is /// live replaces it. While the session is disconnected or faulted the subscription is kept and sent by /// `resubscribe_all`. @@ -340,7 +386,11 @@ impl Drop for CultMeshRudpSubscriptionClient { self.closing.store(true, Ordering::SeqCst); let _ = self.commands.send(Command::Close { wait: false }); if let Some(pump) = self.pump.take() { - let _ = pump.join(); + // The last handle can be dropped by a wake, on the pump thread, which cannot join itself: the Close + // just sent ends the pump once that wake returns. + if pump.thread().id() != thread::current().id() { + let _ = pump.join(); + } } } } @@ -396,6 +446,8 @@ struct Pump { commands: Receiver, events: Sender<(CultMeshSubscriptionEvent, usize)>, undrained: Arc, + /// Called after an event is queued and once when the pump ends; see the module docs. + wake: Option>, } impl Pump { @@ -416,7 +468,11 @@ impl Pump { } }; match command { - Some(Command::Close { wait }) => return self.close(wait), + Some(Command::Close { wait }) => { + let acknowledged = self.close(wait); + self.notify(); + return acknowledged; + } Some(command) => self.apply(command), None => self.service(), } @@ -732,6 +788,17 @@ impl Pump { fn push(&self, event: CultMeshSubscriptionEvent, weight: usize) { self.undrained.fetch_add(weight, Ordering::SeqCst); let _ = self.events.send((event, weight)); + self.notify(); + } + + /// Runs the wake, if any. A panic in it is the consumer's, and the pump survives it. + fn notify(&self) { + if let Some(wake) = &self.wake { + // The payload is dropped inside its own catch: a payload whose drop panics must not end the pump. + if let Err(payload) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| wake())) { + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || drop(payload))); + } + } } fn next_message_id(&mut self) -> String { diff --git a/packages/cultmesh-rs/tests/rudp_subscription.rs b/packages/cultmesh-rs/tests/rudp_subscription.rs index bdc23809..0d2a6052 100644 --- a/packages/cultmesh-rs/tests/rudp_subscription.rs +++ b/packages/cultmesh-rs/tests/rudp_subscription.rs @@ -12,7 +12,9 @@ use cultnet_rs::{ }; use pretty_assertions::assert_eq; use std::net::{SocketAddr, UdpSocket}; -use std::sync::mpsc::{self, Receiver, Sender}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::mpsc::{self, Receiver, Sender, SyncSender}; +use std::sync::{Arc, Condvar, Mutex, OnceLock, Weak}; use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant}; @@ -1209,10 +1211,17 @@ fn drop_does_not_wait_for_a_peer_that_acknowledges_nothing() { /// proven so: the peer has seen the client's Connect, and the client would wait out `connect_timeout` (3 s) for an /// answer that never comes. fn reconnecting_to_a_silent_peer() -> (Peer, CultMeshRudpSubscriptionClient) { + reconnecting_with(|options| CultMeshRudpSubscriptionClient::connect(options).unwrap()) +} + +/// `reconnecting_to_a_silent_peer` for a client the caller connects (with a wake, say). +fn reconnecting_with( + connect: impl FnOnce(CultMeshRudpSubscriptionOptions) -> CultMeshRudpSubscriptionClient, +) -> (Peer, CultMeshRudpSubscriptionClient) { let peer = Peer::start(); let mut options = options_ending_sessions(&peer); options.connect_timeout = Duration::from_secs(3); - let client = CultMeshRudpSubscriptionClient::connect(options).unwrap(); + let client = connect(options); subscribed(&peer, &client); peer.disconnect(); drain_events(&client, 1); @@ -1325,3 +1334,387 @@ fn a_refused_subscribe_is_a_fault_while_a_catalog_request_is_in_flight() { assert!(matches!(&events[0], CultMeshSubscriptionEvent::Snapshot { subscription_id, .. } if subscription_id == "sub-1"), "{events:?}"); assert_eq!(faulted(&events[1]), "CultNet subscription 'sub-2' was refused by the peer."); } + +/// The wakes a client's closure has run, counted after it has signalled its token, so a test waits for a fact (the +/// n-th wake has happened) and not for a sleep. +#[derive(Default)] +struct Wakes { + count: Mutex, + changed: Condvar, +} + +impl Wakes { + fn bump(&self) { + *self.count.lock().unwrap() += 1; + self.changed.notify_all(); + } + + fn get(&self) -> usize { + *self.count.lock().unwrap() + } + + fn wait_for(&self, wakes: usize) { + let guard = self.count.lock().unwrap(); + let (guard, timeout) = self.changed.wait_timeout_while(guard, Duration::from_secs(5), |count| *count < wakes).unwrap(); + assert!(!timeout.timed_out(), "expected {wakes} wakes, saw {}", *guard); + } +} + +/// A wake that stores one token in a one-slot channel (a permit that survives until a waiter takes it) and counts +/// itself. +fn counting_wake() -> (impl Fn() + Send + Sync + 'static, Arc, Receiver<()>) { + let (token, tokens): (SyncSender<()>, Receiver<()>) = mpsc::sync_channel(1); + let wakes = Arc::new(Wakes::default()); + let counted = wakes.clone(); + let wake = move || { + let _ = token.try_send(()); + counted.bump(); + }; + (wake, wakes, tokens) +} + +type Reports = Receiver>; + +/// A client whose wake runs `also` and then drains the client, and reports what the drain held, one report per wake. +/// Every event is queued before its wake runs and the pump is the only thing that queues, so a wake's drain holds +/// exactly the event it was called for. The wake holds the client weakly and lets go of it before it reports, so a +/// test that has read a report owns the last strong handle. +fn draining_client( + options: CultMeshRudpSubscriptionOptions, + also: impl Fn(&CultMeshRudpSubscriptionClient) + Send + Sync + 'static, +) -> (Arc, Reports) { + let slot: Arc>> = Arc::new(OnceLock::new()); + let (report, reports) = mpsc::channel(); + let wake_slot = slot.clone(); + let client = Arc::new( + CultMeshRudpSubscriptionClient::connect_with_wake(options, move || { + let events = { + let Some(client) = wake_slot.get().and_then(Weak::upgrade) else { return }; + also(&client); + client.try_drain() + }; + let _ = report.send(events); + }) + .unwrap(), + ); + slot.set(Arc::downgrade(&client)).unwrap(); + (client, reports) +} + +fn report(reports: &Reports) -> Vec { + reports.recv_timeout(Duration::from_secs(5)).expect("a wake reported") +} + +/// Subscribes, answers the snapshot with its rows and returns once the wake for the snapshot has reported it. +fn subscribed_via_wake(peer: &Peer, client: &CultMeshRudpSubscriptionClient, reports: &Reports) { + client.subscribe("sub-1", vector_selection()).unwrap(); + let (message_id, _) = peer.subscribe_id(); + peer.send(&snapshot_answering(&message_id)); + serve_rows(peer); + let held = report(reports); + assert!(matches!(held.as_slice(), [CultMeshSubscriptionEvent::Snapshot { .. }]), "{held:?}"); +} + +/// A thread that says it is about to block and then blocks on `tokens`, with the instant it was released (`None` +/// when it timed out instead). +fn blocked_waiter(tokens: Receiver<()>) -> (Receiver<()>, JoinHandle>) { + let (about_to_block, ready) = mpsc::channel(); + let waiter = thread::spawn(move || { + about_to_block.send(()).unwrap(); + tokens.recv_timeout(Duration::from_secs(5)).ok().map(|()| Instant::now()) + }); + (ready, waiter) +} + +#[test] +fn a_wake_runs_after_the_event_is_queued() { + let peer = Peer::start(); + let (client, reports) = draining_client(options(&peer), |_| {}); + subscribed_via_wake(&peer, &client, &reports); +} + +#[test] +fn a_wake_before_the_wait_is_not_lost() { + let peer = Peer::start(); + // The wake drains what the pump has queued into an inbox and then stores a permit: what a consumer that waits + // on the permit and then reads the inbox sees is exactly what the queue held when the wake ran. + let inbox: Arc>> = Arc::default(); + let (token, tokens) = mpsc::sync_channel::<()>(1); + let wakes = Arc::new(Wakes::default()); + let slot: Arc>> = Arc::new(OnceLock::new()); + let (wake_inbox, wake_wakes, wake_slot) = (inbox.clone(), wakes.clone(), slot.clone()); + let client = Arc::new( + CultMeshRudpSubscriptionClient::connect_with_wake(options(&peer), move || { + let events = { + let Some(client) = wake_slot.get().and_then(Weak::upgrade) else { return }; + client.try_drain() + }; + wake_inbox.lock().unwrap().extend(events); + let _ = token.try_send(()); + wake_wakes.bump(); + }) + .unwrap(), + ); + slot.set(Arc::downgrade(&client)).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + let (message_id, _) = peer.subscribe_id(); + peer.send(&snapshot_answering(&message_id)); + serve_rows(&peer); + tokens.recv_timeout(Duration::from_secs(5)).expect("the snapshot woke"); + let held = std::mem::take(&mut *inbox.lock().unwrap()); + assert!(matches!(held.as_slice(), [CultMeshSubscriptionEvent::Snapshot { .. }]), "{held:?}"); + // The next event lands, and its wake has run, before the consumer waits at all: the permit is stored, and the + // inbox the wake filled holds the event. + peer.send(&single_change("later", "sub-1")); + wakes.wait_for(2); + let started = Instant::now(); + tokens.recv_timeout(Duration::from_secs(5)).expect("the stored wake is still there"); + assert!(started.elapsed() < Duration::from_millis(500), "{:?}", started.elapsed()); + let held = std::mem::take(&mut *inbox.lock().unwrap()); + assert_eq!(held.iter().map(keys).collect::>(), [["k"]]); +} + +#[test] +fn a_wake_runs_once_per_delivered_event_and_none_for_a_catalog_request_in_flight() { + let peer = Peer::start(); + let (client, reports) = draining_client(options(&peer), |_| {}); + client.subscribe("sub-1", vector_selection()).unwrap(); + let (message_id, _) = peer.subscribe_id(); + peer.send(&snapshot_answering(&message_id)); + let (request_id, _) = catalog_request(&peer); + assert!(reports.try_recv().is_err(), "the snapshot waits for its rows and has not been delivered"); + for bytes in session().into_iter().skip(2) { + peer.send_raw(bytes); + } + let (schema_id, hash) = vector_schema(); + answer_catalog(&peer, &request_id, vec![descriptor(&schema_id, &hash, Some(vector_members()))]); + let held: Vec<_> = (0..4).map(|_| report(&reports)).collect(); + assert_eq!(held.iter().map(Vec::len).collect::>(), [1, 1, 1, 1], "one event, one wake: {held:?}"); + assert!(matches!(held[0][0], CultMeshSubscriptionEvent::Snapshot { .. }), "{held:?}"); + assert_eq!(keys(&held[1][0]), ["c"]); + assert_eq!(keys(&held[2][0]), ["a", "b"]); + assert_eq!(keys(&held[3][0]), ["c"]); + assert!(reports.try_recv().is_err(), "no wake past the last event"); +} + +#[test] +fn a_disconnect_wakes_once_and_the_drain_holds_it() { + let peer = Peer::start(); + let (client, reports) = draining_client(options_ending_sessions(&peer), |_| {}); + subscribed_via_wake(&peer, &client, &reports); + peer.disconnect(); + let held = report(&reports); + assert_eq!(held.len(), 1, "{held:?}"); + disconnect_reason(&held[0]); + assert!(reports.try_recv().is_err(), "one disconnect, one wake"); +} + +#[test] +fn a_fault_wakes_once_and_the_drain_holds_it() { + let peer = Peer::start(); + let (client, reports) = draining_client(options(&peer), |_| {}); + subscribed_via_wake(&peer, &client, &reports); + for index in 0..65 { + peer.send(&change_part(&format!("m{index}"), "sub-1", &format!("c{index}"))); + } + let held = report(&reports); + assert_eq!(held.len(), 1, "{held:?}"); + assert_eq!(faulted(&held[0]), "CultNet subscription 'sub-1': more than 64 commits are incomplete at once."); + assert!(reports.try_recv().is_err(), "the incomplete commits woke nothing, and the fault woke once"); +} + +#[test] +fn close_wakes_a_blocked_waiter_after_the_acknowledgement_wait() { + let peer = Peer::start(); + let (wake, wakes, tokens) = counting_wake(); + let client = CultMeshRudpSubscriptionClient::connect_with_wake(options(&peer), wake).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + peer.subscribe_id(); + peer.stall(); + let (ready, waiter) = blocked_waiter(tokens); + ready.recv_timeout(Duration::from_secs(5)).unwrap(); + let started = Instant::now(); + assert!(!client.close(), "no acknowledgement came"); + let released = waiter.join().unwrap().expect("the pump's last wake released the waiter"); + let after = released.duration_since(started); + assert!(after >= Duration::from_millis(400), "the wake comes after the pump ends, not before: {after:?}"); + assert!(after < Duration::from_millis(750), "within the acknowledgement wait and a quarter second: {after:?}"); + assert_eq!(wakes.get(), 1, "the one wake is the last one"); +} + +#[test] +fn close_wakes_a_blocked_waiter_promptly_against_a_live_peer() { + let peer = Peer::start(); + let (wake, wakes, tokens) = counting_wake(); + let client = CultMeshRudpSubscriptionClient::connect_with_wake(options(&peer), wake).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + peer.subscribe_id(); + let (ready, waiter) = blocked_waiter(tokens); + ready.recv_timeout(Duration::from_secs(5)).unwrap(); + let started = Instant::now(); + assert!(client.close()); + let released = waiter.join().unwrap().expect("the pump's last wake released the waiter"); + assert!(released.duration_since(started) < Duration::from_secs(2), "{:?}", released.duration_since(started)); + assert_eq!(wakes.get(), 1); +} + +#[test] +fn drop_wakes_a_blocked_waiter_once_and_nothing_follows() { + let peer = Peer::start(); + let (wake, wakes, tokens) = counting_wake(); + let client = CultMeshRudpSubscriptionClient::connect_with_wake(options(&peer), wake).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + peer.subscribe_id(); + peer.stall(); + let pump = client.pump_liveness(); + let (ready, waiter) = blocked_waiter(tokens); + ready.recv_timeout(Duration::from_secs(5)).unwrap(); + let started = Instant::now(); + drop(client); + let released = waiter.join().unwrap().expect("the pump's last wake released the waiter"); + assert!(released.duration_since(started) < Duration::from_millis(300), "{:?}", released.duration_since(started)); + assert!(pump.upgrade().is_none(), "the thread has ended"); + assert_eq!(wakes.get(), 1, "joined, so the count is final"); + peer.send(&single_change("late", "sub-1")); + thread::sleep(Duration::from_millis(200)); + assert_eq!(wakes.get(), 1, "nothing wakes after the last wake"); +} + +#[test] +fn close_during_a_reconnect_wakes_a_blocked_waiter_within_the_same_bound() { + let (wake, wakes, tokens) = counting_wake(); + let (_peer, client) = reconnecting_with(|options| CultMeshRudpSubscriptionClient::connect_with_wake(options, wake).unwrap()); + // The snapshot and the disconnect have each woken and been drained; their stored token is not this test's wake. + wakes.wait_for(2); + while tokens.try_recv().is_ok() {} + let before = wakes.get(); + let (ready, waiter) = blocked_waiter(tokens); + ready.recv_timeout(Duration::from_secs(5)).unwrap(); + let started = Instant::now(); + assert!(!client.close()); + let released = waiter.join().unwrap().expect("the pump's last wake released the waiter"); + assert!(released.duration_since(started) < Duration::from_millis(300), "{:?}", released.duration_since(started)); + assert_eq!(wakes.get(), before + 2, "the abandoned reconnect's Disconnected woke, and then the pump's last wake"); +} + +#[test] +fn a_panicking_wake_does_not_stop_the_pump() { + let peer = Peer::start(); + let (counted, wakes, _tokens) = counting_wake(); + let calls = AtomicUsize::new(0); + let wake = move || { + if calls.fetch_add(1, Ordering::SeqCst) == 0 { + panic!("the first wake panics"); + } + counted(); + }; + let client = CultMeshRudpSubscriptionClient::connect_with_wake(options_ending_sessions(&peer), wake).unwrap(); + subscribed(&peer, &client); // the snapshot was queued before its wake panicked + peer.send(&single_change("later", "sub-1")); + wakes.wait_for(1); + assert_eq!(keys(&drain_events(&client, 1)[0]), ["k"]); + peer.disconnect(); + wakes.wait_for(2); + disconnect_reason(&drain_events(&client, 1)[0]); +} + +#[test] +fn a_wake_may_drain_unsubscribe_and_resubscribe_without_deadlock() { + let peer = Peer::start(); + let once = AtomicBool::new(false); + let (client, reports) = draining_client(options(&peer), move |client| { + if !once.swap(true, Ordering::SeqCst) { + client.unsubscribe("other").unwrap(); + client.resubscribe_all().unwrap(); + } + }); + subscribed_via_wake(&peer, &client, &reports); + assert!(matches!(peer.next(), CultNetMessage::DatabaseUnsubscribe { subscription_id, .. } if subscription_id == "other")); + let (message_id, subscription_id) = peer.subscribe_id(); + assert_eq!(subscription_id, "sub-1", "the pump went on to resend the subscription"); + peer.send(&snapshot_answering(&message_id)); + let held = report(&reports); + assert!(matches!(held.as_slice(), [CultMeshSubscriptionEvent::Snapshot { .. }]), "{held:?}"); + let client = Arc::try_unwrap(client).ok().expect("no wake holds the client"); + assert!(client.close(), "and the pump still shuts down"); +} + +#[test] +fn the_last_handle_dropped_on_the_pump_thread_ends_the_pump_cleanly() { + let peer = Peer::start(); + let slot: Arc>> = Arc::new(OnceLock::new()); + let (upgraded, upgraded_seen) = mpsc::channel(); + let (owner_dropped, owner_dropped_seen) = mpsc::channel::<()>(); + let owner_dropped_seen = Mutex::new(owner_dropped_seen); + let finished = Arc::new(AtomicBool::new(false)); + let first = AtomicBool::new(true); + let (wake_slot, wake_finished) = (slot.clone(), finished.clone()); + let client = Arc::new( + CultMeshRudpSubscriptionClient::connect_with_wake(options(&peer), move || { + if !first.swap(false, Ordering::SeqCst) { + return; + } + let Some(held) = wake_slot.get().and_then(Weak::upgrade) else { return }; + upgraded.send(()).unwrap(); + owner_dropped_seen.lock().unwrap().recv_timeout(Duration::from_secs(5)).expect("the owner dropped its handle"); + // The owner's handle is gone: this is the last one, and it drops on the pump thread. + drop(held); + wake_finished.store(true, Ordering::SeqCst); + }) + .unwrap(), + ); + slot.set(Arc::downgrade(&client)).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + let (message_id, _) = peer.subscribe_id(); + peer.send(&snapshot_answering(&message_id)); + serve_rows(&peer); + upgraded_seen.recv_timeout(Duration::from_secs(5)).expect("the wake upgraded its handle"); + drop(client); + owner_dropped.send(()).unwrap(); + // The pump ends after the wake returns: it sends the unsubscribes and the goodbye. + peer.expect(PeerEvent::Goodbye(b"subscription-closed".to_vec())); + assert!(finished.load(Ordering::SeqCst), "the wake ran to its end: dropping the last handle did not panic"); +} + +/// A panic payload whose own drop panics. +struct PayloadBomb; + +impl Drop for PayloadBomb { + fn drop(&mut self) { + panic!("the payload's drop panics"); + } +} + +#[test] +fn a_wake_that_panics_with_a_payload_whose_drop_panics_does_not_stop_the_pump() { + let peer = Peer::start(); + let (counted, wakes, _tokens) = counting_wake(); + let calls = AtomicUsize::new(0); + let wake = move || { + if calls.fetch_add(1, Ordering::SeqCst) == 0 { + std::panic::panic_any(PayloadBomb); + } + counted(); + }; + let client = CultMeshRudpSubscriptionClient::connect_with_wake(options(&peer), wake).unwrap(); + let pump = client.pump_liveness(); + subscribed(&peer, &client); // the snapshot was queued before its wake panicked + peer.send(&single_change("later", "sub-1")); + wakes.wait_for(1); + assert!(pump.upgrade().is_some(), "the pump is alive"); + assert_eq!(keys(&drain_events(&client, 1)[0]), ["k"]); +} + +#[test] +fn the_event_is_counted_before_its_wake_runs() { + let peer = Peer::start(); + let (weights, seen) = mpsc::channel(); + let (client, reports) = draining_client(options(&peer), move |client| { + let _ = weights.send(client.undrained_weight()); + }); + subscribed_via_wake(&peer, &client, &reports); + assert_eq!(seen.recv_timeout(Duration::from_secs(5)).unwrap(), 2, "the snapshot's two documents"); + peer.send(&single_change("later", "sub-1")); + assert_eq!(keys(&report(&reports)[0]), ["k"]); + assert_eq!(seen.recv_timeout(Duration::from_secs(5)).unwrap(), 1, "the one change"); +}