diff --git a/packages/cultmesh-rs/src/rudp_subscription.rs b/packages/cultmesh-rs/src/rudp_subscription.rs index a805f396..3db8fc22 100644 --- a/packages/cultmesh-rs/src/rudp_subscription.rs +++ b/packages/cultmesh-rs/src/rudp_subscription.rs @@ -11,7 +11,7 @@ //! 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 -//! past it gets a [`SubscriptionEvent::Faulted`], delivery +//! past it gets a [`CultMeshSubscriptionEvent::Faulted`], delivery //! stops, and [`resubscribe_all`](CultMeshRudpSubscriptionClient::resubscribe_all) starts over from fresh //! snapshots. Memory never grows without bound. //! @@ -171,16 +171,8 @@ pub enum CultMeshSubscriptionEvent { Disconnected { reason: String }, } -impl CultMeshSubscriptionEvent { - fn weight(&self) -> usize { - match self { - Self::Snapshot { documents, .. } => documents.len().max(1), - Self::Commit { changes, .. } => changes.len().max(1), - _ => 1, - } - } -} - +/// The one weight of an event: its documents or changes, at least one. It is counted when the event is admitted, +/// travels with the event to the consumer's queue, and is released when drained. fn event_weight(event: &SubscriptionEvent) -> usize { match event { SubscriptionEvent::Snapshot { documents, .. } => documents.len().max(1), @@ -219,13 +211,15 @@ enum Command { Subscribe(String, Selection), Unsubscribe(String), Resubscribe, - Close, + /// Ends the session. With a `reply`, waits (bounded) for the unsubscribes to be acknowledged and says whether + /// they were; without one, sends them and goes. + Close { reply: Option> }, } /// A live subscription connection. Methods never block on the network. pub struct CultMeshRudpSubscriptionClient { commands: Sender, - events: Mutex>, + events: Mutex>, undrained: Arc, pump_alive: Weak<()>, pump: Option>, @@ -296,8 +290,8 @@ impl CultMeshRudpSubscriptionClient { /// Everything delivered since the last call, in order. Never blocks. pub fn try_drain(&self) -> Vec { let events = self.events.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - let drained: Vec<_> = events.try_iter().collect(); - self.undrained.fetch_sub(drained.iter().map(CultMeshSubscriptionEvent::weight).sum(), Ordering::SeqCst); + let (drained, weights): (Vec<_>, Vec) = events.try_iter().unzip(); + self.undrained.fetch_sub(weights.iter().sum(), Ordering::SeqCst); drained } @@ -306,9 +300,26 @@ impl CultMeshRudpSubscriptionClient { } } +impl CultMeshRudpSubscriptionClient { + /// The explicit shutdown: unsubscribes each live id, waits up to 500 ms for the peer to acknowledge, ends the + /// session and joins the pump thread. Returns whether the acknowledgement arrived; `false` says the peer may + /// still hold the subscriptions until its own idle timeout. + pub fn close(mut self) -> bool { + let (reply, answer) = mpsc::channel(); + let sent = self.commands.send(Command::Close { reply: Some(reply) }).is_ok(); + let acknowledged = sent && answer.recv_timeout(CLOSE_ACK_WAIT * 2).unwrap_or(false); + if let Some(pump) = self.pump.take() { + let _ = pump.join(); + } + acknowledged + } +} + +/// Best effort: sends the unsubscribes and stops the pump thread without waiting for the peer. Use +/// [`close`](CultMeshRudpSubscriptionClient::close) to learn whether the peer acknowledged. impl Drop for CultMeshRudpSubscriptionClient { fn drop(&mut self) { - let _ = self.commands.send(Command::Close); + let _ = self.commands.send(Command::Close { reply: None }); if let Some(pump) = self.pump.take() { let _ = pump.join(); } @@ -360,7 +371,7 @@ struct Pump { last_ping: Instant, sent: u64, commands: Receiver, - events: Sender, + events: Sender<(CultMeshSubscriptionEvent, usize)>, undrained: Arc, } @@ -371,17 +382,17 @@ impl Pump { match self.commands.try_recv() { Ok(command) => Some(command), Err(TryRecvError::Empty) => None, - Err(TryRecvError::Disconnected) => Some(Command::Close), + Err(TryRecvError::Disconnected) => Some(Command::Close { reply: None }), } } else { match self.commands.recv_timeout(Duration::from_secs(3600)) { Ok(command) => Some(command), Err(RecvTimeoutError::Timeout) => None, - Err(RecvTimeoutError::Disconnected) => Some(Command::Close), + Err(RecvTimeoutError::Disconnected) => Some(Command::Close { reply: None }), } }; match command { - Some(Command::Close) => return self.close(), + Some(Command::Close { reply }) => return self.close(reply), Some(command) => self.apply(command), None => self.service(), } @@ -405,7 +416,7 @@ impl Pump { self.transmit(&message); } Command::Resubscribe => self.resubscribe(), - Command::Close => unreachable!("handled by the loop"), + Command::Close { .. } => unreachable!("handled by the loop"), } } @@ -446,7 +457,7 @@ impl Pump { } Err(error) => { let reason = format!("reconnect failed: {error}"); - return self.push(CultMeshSubscriptionEvent::Disconnected { reason }); + return self.push(CultMeshSubscriptionEvent::Disconnected { reason }, 1); } } } @@ -598,6 +609,7 @@ impl Pump { } fn deliver(&mut self, event: SubscriptionEvent, unknown: &NoMembersReason) { + let weight = event_weight(&event); let event = match event { SubscriptionEvent::Snapshot { subscription_id, documents } => CultMeshSubscriptionEvent::Snapshot { subscription_id, @@ -617,7 +629,7 @@ impl Pump { }, SubscriptionEvent::Faulted { reason } => CultMeshSubscriptionEvent::Faulted { reason }, }; - self.push(event); + self.push(event, weight); } fn request_catalog(&mut self, keys: BTreeSet) { @@ -693,9 +705,9 @@ impl Pump { } } - fn push(&self, event: CultMeshSubscriptionEvent) { - self.undrained.fetch_add(event.weight(), Ordering::SeqCst); - let _ = self.events.send(event); + fn push(&self, event: CultMeshSubscriptionEvent, weight: usize) { + self.undrained.fetch_add(weight, Ordering::SeqCst); + let _ = self.events.send((event, weight)); } fn next_message_id(&mut self) -> String { @@ -738,29 +750,33 @@ impl Pump { self.pending_weight -= event_weight(&event); self.deliver(event, &NoMembersReason::SessionEnded); } - self.push(CultMeshSubscriptionEvent::Disconnected { reason }); + self.push(CultMeshSubscriptionEvent::Disconnected { reason }, 1); } } - fn close(&mut self) { + /// Unsubscribes every live id and ends the session. With `reply`, first waits up to `CLOSE_ACK_WAIT` for every + /// outstanding reliable send to be acknowledged (resending a lost one), since nothing resends after the goodbye, + /// and tells whether they all were. + fn close(&mut self, reply: Option>) { let ids: Vec<_> = self.subscriptions.keys().cloned().collect(); for id in ids { let message = CultNetMessage::DatabaseUnsubscribe { message_id: self.next_message_id(), subscription_id: id }; self.transmit(&message); } - // The unsubscribes are reliable sends: give them a moment to be acknowledged (resending a lost one) before the - // goodbye ends the session, since nothing resends after it. - let deadline = Instant::now() + CLOSE_ACK_WAIT; - while self.session.is_some() && !self.receipts.is_empty() && Instant::now() < deadline { - self.service(); - if self.invalidated().is_some() { - break; + if reply.is_some() { + let deadline = Instant::now() + CLOSE_ACK_WAIT; + while self.session.is_some() && !self.receipts.is_empty() && Instant::now() < deadline { + self.service(); + thread::sleep(self.options.poll_interval); } - thread::sleep(self.options.poll_interval); } + let acknowledged = self.session.is_some() && self.receipts.is_empty(); if let Some(session) = self.session.as_mut() { let _ = session.disconnect(b"subscription-closed".to_vec()); } + if let Some(reply) = reply { + let _ = reply.send(acknowledged); + } } } diff --git a/packages/cultmesh-rs/tests/rudp_subscription.rs b/packages/cultmesh-rs/tests/rudp_subscription.rs index cb1a004c..9018e366 100644 --- a/packages/cultmesh-rs/tests/rudp_subscription.rs +++ b/packages/cultmesh-rs/tests/rudp_subscription.rs @@ -573,8 +573,8 @@ fn dropping_the_client_unsubscribes_each_live_id_and_stops_its_thread() { let pump = client.pump_liveness(); assert!(pump.upgrade().is_some(), "the pump thread runs while its handle lives"); let started = Instant::now(); - drop(client); - assert!(started.elapsed() < Duration::from_secs(2), "drop joins promptly"); + assert!(client.close(), "a live peer acknowledges the unsubscribe"); + assert!(started.elapsed() < Duration::from_secs(2), "close returns promptly"); assert!(matches!(peer.next(), CultNetMessage::DatabaseUnsubscribe { subscription_id, .. } if subscription_id == "one")); assert!(peer.received.recv_timeout(Duration::from_millis(300)).is_err(), "nothing else is sent"); assert!(pump.upgrade().is_none(), "the pump thread is gone with its handle"); @@ -1113,3 +1113,31 @@ fn unsubscribing_releases_the_weight_of_the_events_it_forgets() { assert!(matches!(&events[0], CultMeshSubscriptionEvent::Snapshot { subscription_id, .. } if subscription_id == "two"), "{events:?}"); assert_eq!(keys(&events[1]), ["k"]); } + +#[test] +fn close_waits_for_the_acknowledgement_and_says_when_it_does_not_come() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + peer.subscribe_id(); + peer.stall(); // reads nothing, acknowledges nothing + let started = Instant::now(); + assert!(!client.close(), "no acknowledgement came"); + let waited = started.elapsed(); + assert!(waited >= Duration::from_millis(400), "close waited for the acknowledgement: {waited:?}"); + assert!(waited < Duration::from_secs(2), "and only a bounded time: {waited:?}"); +} + +#[test] +fn drop_does_not_wait_for_a_peer_that_acknowledges_nothing() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + peer.subscribe_id(); + peer.stall(); + let pump = client.pump_liveness(); + let started = Instant::now(); + drop(client); + assert!(started.elapsed() < Duration::from_millis(300), "{:?}", started.elapsed()); + assert!(pump.upgrade().is_none(), "the thread still stops"); +}