diff --git a/packages/cultmesh-rs/src/lib.rs b/packages/cultmesh-rs/src/lib.rs index 987f2dc4..61728331 100644 --- a/packages/cultmesh-rs/src/lib.rs +++ b/packages/cultmesh-rs/src/lib.rs @@ -819,6 +819,7 @@ pub fn request_raw_snapshot_from_rudp_catalog( options.resend_delay_ms, "cultmesh-rudp-snapshot-client", None, + &|| false, )?; let request = cultnet_rs::CultNetMessage::SnapshotRequest { @@ -944,6 +945,7 @@ pub fn publish_cultnet_messages_to_rudp_catalog( options.resend_delay_ms, "cultmesh-rudp-document-publisher", None, + &|| false, )?; let mut receipts = Vec::with_capacity(messages.len()); @@ -1012,6 +1014,7 @@ fn connect_rudp_client( resend_delay_ms: u64, transport_id: &str, connection_id: Option, + cancelled: &dyn Fn() -> bool, ) -> Result { let bind_addr = if target.is_ipv4() { SocketAddr::from(([0, 0, 0, 0], 0)) @@ -1040,6 +1043,9 @@ fn connect_rudp_client( client.connect(Vec::new())?; let connect_deadline = Instant::now() + connect_timeout; while !client.connected() && Instant::now() < connect_deadline { + if cancelled() { + anyhow::bail!("connecting CultMesh RUDP client {runtime_id} to {target} was cancelled"); + } let _ = client.receive_once()?; client.poll_resends()?; thread::sleep(poll_interval); diff --git a/packages/cultmesh-rs/src/rudp_subscription.rs b/packages/cultmesh-rs/src/rudp_subscription.rs index 3db8fc22..aa4f38c0 100644 --- a/packages/cultmesh-rs/src/rudp_subscription.rs +++ b/packages/cultmesh-rs/src/rudp_subscription.rs @@ -36,7 +36,7 @@ use cultnet_rs::{ use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::fmt; use std::net::SocketAddr; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, TryRecvError}; use std::sync::{Arc, Mutex, Weak}; use std::thread::{self, JoinHandle}; @@ -222,6 +222,7 @@ pub struct CultMeshRudpSubscriptionClient { events: Mutex>, undrained: Arc, pump_alive: Weak<()>, + closing: Arc, pump: Option>, } @@ -231,13 +232,15 @@ impl CultMeshRudpSubscriptionClient { if options.runtime_id.trim().is_empty() { return Err(anyhow!("runtime_id must be non-empty")); } - let session = open(&options)?; + let session = open(&options, &|| false)?; + let closing = Arc::new(AtomicBool::new(false)); let (commands, command_rx) = mpsc::channel(); let (event_tx, events) = mpsc::channel(); let undrained = Arc::new(AtomicUsize::new(0)); let alive = Arc::new(()); let pump_alive = Arc::downgrade(&alive); let pump = Pump { + closing: closing.clone(), options, session: Some(session), assembler: SubscriptionAssembler::new(), @@ -259,7 +262,7 @@ impl CultMeshRudpSubscriptionClient { let pump = thread::Builder::new() .name("cultmesh-rudp-subscription".into()) .spawn(move || pump.run())?; - Ok(Self { commands, events: Mutex::new(events), undrained, pump_alive, pump: Some(pump) }) + Ok(Self { commands, events: Mutex::new(events), undrained, pump_alive, closing, pump: Some(pump) }) } /// A weak handle that upgrades while this client's own pump thread exists, and never after it has been joined. @@ -305,6 +308,7 @@ impl CultMeshRudpSubscriptionClient { /// 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 { + self.closing.store(true, Ordering::SeqCst); 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); @@ -319,6 +323,7 @@ impl CultMeshRudpSubscriptionClient { /// [`close`](CultMeshRudpSubscriptionClient::close) to learn whether the peer acknowledged. impl Drop for CultMeshRudpSubscriptionClient { fn drop(&mut self) { + self.closing.store(true, Ordering::SeqCst); let _ = self.commands.send(Command::Close { reply: None }); if let Some(pump) = self.pump.take() { let _ = pump.join(); @@ -326,7 +331,7 @@ impl Drop for CultMeshRudpSubscriptionClient { } } -fn open(options: &CultMeshRudpSubscriptionOptions) -> Result { +fn open(options: &CultMeshRudpSubscriptionOptions, cancelled: &dyn Fn() -> bool) -> Result { connect_rudp_client( options.target, &options.runtime_id, @@ -335,6 +340,7 @@ fn open(options: &CultMeshRudpSubscriptionOptions) -> Result, options: CultMeshRudpSubscriptionOptions, /// `None` after the session ended: the pump reads nothing and waits for a command. session: Option, @@ -450,7 +459,7 @@ impl Pump { self.session = None; } if self.session.is_none() { - match open(&self.options) { + match open(&self.options, &|| self.closing.load(Ordering::SeqCst)) { Ok(session) => { self.session = Some(session); self.last_ping = Instant::now(); diff --git a/packages/cultmesh-rs/tests/rudp_subscription.rs b/packages/cultmesh-rs/tests/rudp_subscription.rs index ecf005aa..ce00e02f 100644 --- a/packages/cultmesh-rs/tests/rudp_subscription.rs +++ b/packages/cultmesh-rs/tests/rudp_subscription.rs @@ -22,14 +22,27 @@ enum PeerCommand { Disconnect, /// Reads nothing and answers nothing (no pong, no ack) until `Disconnect`: a peer that died without a goodbye. Stall, + /// Between sessions, reads and answers no Connect, but reports each one it sees, until `Disconnect`: a peer that + /// is unreachable while a client tries to reconnect. + Refuse, Stop, } +/// What the peer's thread says about itself, so a test waits for a fact and not for a sleep. +#[derive(Debug, PartialEq, Eq)] +enum PeerEvent { + /// `Refuse` has taken effect: no Connect sent from now on is answered. + Refusing, + /// A Connect arrived while refusing. + ConnectSeen, +} + /// A peer that accepts RUDP connects on a loopback socket and reports every schema message it receives. struct Peer { addr: SocketAddr, commands: Sender, received: Receiver, + events: Receiver, thread: Option>, } @@ -39,8 +52,9 @@ impl Peer { let addr = socket.local_addr().unwrap(); let (commands, command_rx) = mpsc::channel(); let (received_tx, received) = mpsc::channel(); - let thread = thread::spawn(move || serve(socket, command_rx, received_tx)); - Self { addr, commands, received, thread: Some(thread) } + let (event_tx, events) = mpsc::channel(); + let thread = thread::spawn(move || serve(socket, command_rx, received_tx, event_tx)); + Self { addr, commands, received, events, thread: Some(thread) } } fn send(&self, message: &CultNetMessage) { @@ -56,6 +70,17 @@ impl Peer { self.commands.send(PeerCommand::Stall).unwrap(); } + fn expect(&self, expected: PeerEvent) { + let event = self.events.recv_timeout(Duration::from_secs(5)).expect("the peer reported an event"); + assert_eq!(event, expected); + } + + /// Returns once the peer is refusing Connects, so none sent after it returns is answered. + fn refuse_connects(&self) { + self.commands.send(PeerCommand::Refuse).unwrap(); + self.expect(PeerEvent::Refusing); + } + fn disconnect(&self) { self.commands.send(PeerCommand::Disconnect).unwrap(); } @@ -84,7 +109,12 @@ impl Drop for Peer { } } -fn serve(socket: UdpSocket, commands: Receiver, received: Sender) { +fn serve( + socket: UdpSocket, + commands: Receiver, + received: Sender, + events: Sender, +) { socket.set_read_timeout(Some(Duration::from_millis(2))).unwrap(); 'sessions: loop { // The client's connection id is its own epoch: read it from the Connect before the session exists. @@ -92,6 +122,23 @@ fn serve(socket: UdpSocket, commands: Receiver, received: Sender return, + Ok(PeerCommand::Refuse) => { + let _ = events.send(PeerEvent::Refusing); + loop { + match commands.try_recv() { + Ok(PeerCommand::Stop) | Err(mpsc::TryRecvError::Disconnected) => return, + Ok(PeerCommand::Disconnect) => continue 'sessions, + _ => {} + } + if let Ok((length, _)) = socket.recv_from(&mut wire) { + if decode_rudp_packet(&wire[..length]) + .is_ok_and(|packet| packet.packet_type == cultnet_rs::CultNetRudpPacketType::Connect) + { + let _ = events.send(PeerEvent::ConnectSeen); + } + } + } + } _ => {} } if let Ok(found) = socket.peek_from(&mut wire) { @@ -140,6 +187,7 @@ fn serve(socket: UdpSocket, commands: Receiver, received: Sender {} } }, + PeerCommand::Refuse => {} PeerCommand::Stop => return, } } @@ -1143,3 +1191,38 @@ fn drop_does_not_wait_for_a_peer_that_acknowledges_nothing() { assert!(started.elapsed() < Duration::from_millis(300), "{:?}", started.elapsed()); assert!(pump.upgrade().is_none(), "the thread still stops"); } + +/// A client whose session ended and whose `resubscribe_all` is inside its reconnect to a peer that answers 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) { + let peer = Peer::start(); + let mut options = options_ending_sessions(&peer); + options.connect_timeout = Duration::from_secs(3); + let client = CultMeshRudpSubscriptionClient::connect(options).unwrap(); + subscribed(&peer, &client); + peer.disconnect(); + drain_events(&client, 1); + peer.refuse_connects(); + client.resubscribe_all().unwrap(); + peer.expect(PeerEvent::ConnectSeen); + (peer, client) +} + +#[test] +fn close_stays_within_its_bound_while_the_pump_reconnects_to_a_silent_peer() { + let (_peer, client) = reconnecting_to_a_silent_peer(); + let started = Instant::now(); + assert!(!client.close(), "there is no session whose unsubscribes could have been acknowledged"); + assert!(started.elapsed() < Duration::from_millis(300), "{:?}", started.elapsed()); +} + +#[test] +fn drop_does_not_wait_for_a_reconnect_to_a_silent_peer() { + let (_peer, client) = reconnecting_to_a_silent_peer(); + 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"); +}