cultmesh-rs: close and Drop stay in bounds during a reconnect; close/Drop tests proven, not slept (h4) (#198)

This commit is contained in:
Eureka 2026-11-28 12:59:09 +00:00
commit 453b360f61
5 changed files with 271 additions and 54 deletions

View file

@ -235,6 +235,7 @@ dependencies = [
"anyhow",
"base64",
"cultcache-rs",
"cultmesh-rs",
"cultnet-rs",
"p256",
"pretty_assertions",

View file

@ -9,6 +9,10 @@ publish = false
name = "cultmesh_rs"
path = "src/lib.rs"
[features]
# Seams only this crate's own tests use; not part of the API a consumer builds against.
test-hooks = []
[dependencies]
anyhow = "1"
cultcache-rs = { path = "../cultcache-rs" }
@ -18,6 +22,8 @@ p256 = { version = "0.13", default-features = false, features = ["ecdsa", "std"]
serde = { version = "1", features = ["derive"] }
[dev-dependencies]
# The tests enable the crate's own `test-hooks` feature.
cultmesh-rs = { path = ".", features = ["test-hooks"] }
pretty_assertions = "1.4.1"
rmp-serde = "1"
serde_json = "1"

View file

@ -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<u32>,
cancelled: &dyn Fn() -> bool,
) -> Result<CultNetRudpSocketTransportConnection> {
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);

View file

@ -4,8 +4,11 @@
//! only queues commands and drains events. RUDP acknowledgements and resends keep their cadence while the caller is
//! idle, which is why this is a thread and not a method the caller must tick.
//!
//! Lifetime: dropping the client unsubscribes each live id, disconnects and joins the thread, so no thread outlives
//! its handle. A closed or failed session is an event ([`CultMeshSubscriptionEvent::Disconnected`]), never a hang;
//! Lifetime: [`close`](CultMeshRudpSubscriptionClient::close) unsubscribes each live id, waits up to 500 ms for the
//! peer to acknowledge, disconnects, joins the thread and returns whether the acknowledgement arrived. Dropping the
//! client does the same without the wait: best effort, the unsubscribes are sent and the peer's answer is not
//! awaited. Either way no thread outlives its handle, and a reconnect in progress is abandoned at its next poll
//! 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.
//!
//! Bounds: the assembler bounds what it holds of incomplete commits and faults the connection past that. What the
@ -36,9 +39,9 @@ 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::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
@ -211,18 +214,21 @@ enum Command {
Subscribe(String, Selection),
Unsubscribe(String),
Resubscribe,
/// 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<Sender<bool>> },
/// Ends the session. With `wait`, first waits (bounded) for the unsubscribes to be acknowledged; without it,
/// sends them and goes. The pump thread's result says whether they were acknowledged.
Close { wait: bool },
}
/// A live subscription connection. Methods never block on the network.
/// A live subscription connection. Methods return without waiting on the peer, except `connect`, which waits up to
/// `connect_timeout`, and `close`, which waits up to 500 ms for the unsubscribes to be acknowledged.
pub struct CultMeshRudpSubscriptionClient {
commands: Sender<Command>,
events: Mutex<Receiver<(CultMeshSubscriptionEvent, usize)>>,
undrained: Arc<AtomicUsize>,
pump_alive: Weak<()>,
pump: Option<JoinHandle<()>>,
#[cfg(feature = "test-hooks")]
pump_alive: std::sync::Weak<()>,
closing: Arc<AtomicBool>,
pump: Option<JoinHandle<bool>>,
}
impl CultMeshRudpSubscriptionClient {
@ -231,13 +237,17 @@ 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));
#[cfg(feature = "test-hooks")]
let alive = Arc::new(());
#[cfg(feature = "test-hooks")]
let pump_alive = Arc::downgrade(&alive);
let pump = Pump {
closing: closing.clone(),
options,
session: Some(session),
assembler: SubscriptionAssembler::new(),
@ -246,7 +256,8 @@ impl CultMeshRudpSubscriptionClient {
pending_weight: 0,
awaiting: Vec::new(),
backoff: BTreeMap::new(),
alive,
#[cfg(feature = "test-hooks")]
_alive: alive,
subscriptions: BTreeMap::new(),
receipts: Vec::new(),
epoch: super::fresh_rudp_connection_epoch(),
@ -259,12 +270,22 @@ 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,
#[cfg(feature = "test-hooks")]
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.
/// Tests use it to prove that dropping the client ends its thread.
pub fn pump_liveness(&self) -> Weak<()> {
/// 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 pump_liveness(&self) -> std::sync::Weak<()> {
self.pump_alive.clone()
}
@ -303,15 +324,12 @@ 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.
/// still hold the subscriptions until its own idle timeout. A reconnect in progress is abandoned at once, and
/// then there is nothing to acknowledge.
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
self.closing.store(true, Ordering::SeqCst);
let _ = self.commands.send(Command::Close { wait: true });
self.pump.take().is_some_and(|pump| pump.join().unwrap_or(false))
}
}
@ -319,14 +337,15 @@ impl CultMeshRudpSubscriptionClient {
/// [`close`](CultMeshRudpSubscriptionClient::close) to learn whether the peer acknowledged.
impl Drop for CultMeshRudpSubscriptionClient {
fn drop(&mut self) {
let _ = self.commands.send(Command::Close { reply: None });
self.closing.store(true, Ordering::SeqCst);
let _ = self.commands.send(Command::Close { wait: false });
if let Some(pump) = self.pump.take() {
let _ = pump.join();
}
}
}
fn open(options: &CultMeshRudpSubscriptionOptions) -> Result<CultNetRudpSocketTransportConnection> {
fn open(options: &CultMeshRudpSubscriptionOptions, cancelled: &dyn Fn() -> bool) -> Result<CultNetRudpSocketTransportConnection> {
connect_rudp_client(
options.target,
&options.runtime_id,
@ -335,6 +354,7 @@ fn open(options: &CultMeshRudpSubscriptionOptions) -> Result<CultNetRudpSocketTr
options.resend_delay_ms,
"cultmesh-rudp-subscription-client",
options.connection_id,
cancelled,
)
}
@ -346,6 +366,9 @@ const REASON_CHARS: usize = 200;
const CLOSE_ACK_WAIT: Duration = Duration::from_millis(500);
struct Pump {
/// Set by `close` and `Drop` before they send `Close`: a reconnect in progress gives up at its next poll
/// instead of waiting out `connect_timeout`.
closing: Arc<AtomicBool>,
options: CultMeshRudpSubscriptionOptions,
/// `None` after the session ended: the pump reads nothing and waits for a command.
session: Option<CultNetRudpSocketTransportConnection>,
@ -362,8 +385,8 @@ struct Pump {
/// this passes asks afresh.
backoff: BTreeMap<SchemaKey, Instant>,
/// Held for as long as the pump thread runs; see `pump_liveness`.
#[allow(dead_code)]
alive: Arc<()>,
#[cfg(feature = "test-hooks")]
_alive: Arc<()>,
/// What `resubscribe_all` resends. The assembler owns what is live; it holds no selections.
subscriptions: BTreeMap<String, Selection>,
receipts: Vec<CultNetRudpReliableSendReceipt>,
@ -376,23 +399,24 @@ struct Pump {
}
impl Pump {
fn run(mut self) {
/// Returns whether `close` found every unsubscribe acknowledged; `false` when it was not asked to wait.
fn run(mut self) -> bool {
loop {
let command = if self.session.is_some() {
match self.commands.try_recv() {
Ok(command) => Some(command),
Err(TryRecvError::Empty) => None,
Err(TryRecvError::Disconnected) => Some(Command::Close { reply: None }),
Err(TryRecvError::Disconnected) => Some(Command::Close { wait: false }),
}
} else {
match self.commands.recv_timeout(Duration::from_secs(3600)) {
Ok(command) => Some(command),
Err(RecvTimeoutError::Timeout) => None,
Err(RecvTimeoutError::Disconnected) => Some(Command::Close { reply: None }),
Err(RecvTimeoutError::Disconnected) => Some(Command::Close { wait: false }),
}
};
match command {
Some(Command::Close { reply }) => return self.close(reply),
Some(Command::Close { wait }) => return self.close(wait),
Some(command) => self.apply(command),
None => self.service(),
}
@ -450,7 +474,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();
@ -754,29 +778,27 @@ impl Pump {
}
}
/// 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<Sender<bool>>) {
/// Unsubscribes every live id and ends the session. With `wait`, 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.
/// Says whether they all were; with no wait, `false`.
fn close(&mut self, wait: bool) -> bool {
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);
}
if reply.is_some() {
if wait {
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);
}
}
let acknowledged = self.session.is_some() && self.receipts.is_empty();
let acknowledged = wait && 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);
}
acknowledged
}
}

View file

@ -22,14 +22,31 @@ 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 {
/// `Stall` has taken effect: the peer reads nothing from now on.
Stalled,
/// `Refuse` has taken effect: no Connect sent from now on is answered.
Refusing,
/// A Connect arrived while refusing.
ConnectSeen,
/// The client ended the session and said why.
Goodbye(Vec<u8>),
}
/// A peer that accepts RUDP connects on a loopback socket and reports every schema message it receives.
struct Peer {
addr: SocketAddr,
commands: Sender<PeerCommand>,
received: Receiver<CultNetMessage>,
events: Receiver<PeerEvent>,
thread: Option<JoinHandle<()>>,
}
@ -39,8 +56,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) {
@ -52,8 +70,22 @@ impl Peer {
self.commands.send(PeerCommand::Send(payload)).unwrap();
}
/// Returns once the peer's thread has entered the stall, so what the test does next meets a peer that is
/// silent, not one that has not yet read the command.
fn stall(&self) {
self.commands.send(PeerCommand::Stall).unwrap();
self.expect(PeerEvent::Stalled);
}
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) {
@ -84,7 +116,12 @@ impl Drop for Peer {
}
}
fn serve(socket: UdpSocket, commands: Receiver<PeerCommand>, received: Sender<CultNetMessage>) {
fn serve(
socket: UdpSocket,
commands: Receiver<PeerCommand>,
received: Sender<CultNetMessage>,
events: Sender<PeerEvent>,
) {
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 +129,23 @@ fn serve(socket: UdpSocket, commands: Receiver<PeerCommand>, received: Sender<Cu
let (length, _) = loop {
match commands.try_recv() {
Ok(PeerCommand::Stop) | Err(mpsc::TryRecvError::Disconnected) => 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) {
@ -123,6 +177,7 @@ fn serve(socket: UdpSocket, commands: Receiver<PeerCommand>, received: Sender<Cu
reconnect_policy: None,
})
.unwrap();
let mut said_goodbye = false;
loop {
while let Ok(command) = commands.try_recv() {
match command {
@ -133,13 +188,17 @@ fn serve(socket: UdpSocket, commands: Receiver<PeerCommand>, received: Sender<Cu
session.disconnect(b"scripted-goodbye".to_vec()).unwrap();
continue 'sessions;
}
PeerCommand::Stall => loop {
match commands.recv() {
Ok(PeerCommand::Disconnect) => continue 'sessions,
Ok(PeerCommand::Stop) | Err(_) => return,
Ok(_) => {}
PeerCommand::Stall => {
let _ = events.send(PeerEvent::Stalled);
loop {
match commands.recv() {
Ok(PeerCommand::Disconnect) => continue 'sessions,
Ok(PeerCommand::Stop) | Err(_) => return,
Ok(_) => {}
}
}
},
}
PeerCommand::Refuse => {}
PeerCommand::Stop => return,
}
}
@ -150,6 +209,10 @@ fn serve(socket: UdpSocket, commands: Receiver<PeerCommand>, received: Sender<Cu
}
}
}
if let Some(reason) = session.disconnect_reason().filter(|_| !said_goodbye) {
said_goodbye = true;
let _ = events.send(PeerEvent::Goodbye(reason.to_vec()));
}
session.poll_resends().unwrap();
}
}
@ -575,9 +638,9 @@ fn dropping_the_client_unsubscribes_each_live_id_and_stops_its_thread() {
let started = Instant::now();
assert!(client.close(), "a live peer acknowledges the unsubscribe");
assert!(started.elapsed() < Duration::from_secs(2), "close returns promptly");
assert!(pump.upgrade().is_none(), "close has joined the pump thread when it returns");
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");
}
#[test]
@ -1120,8 +1183,7 @@ fn close_waits_for_the_acknowledgement_and_says_when_it_does_not_come() {
let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap();
client.subscribe("sub-1", vector_selection()).unwrap();
peer.subscribe_id();
peer.stall(); // reads nothing, acknowledges nothing
thread::sleep(Duration::from_millis(100)); // the peer thread has taken the stall before the client closes
peer.stall(); // returns once the peer reads nothing and acknowledges nothing
let started = Instant::now();
assert!(!client.close(), "no acknowledgement came");
let waited = started.elapsed();
@ -1136,10 +1198,130 @@ fn drop_does_not_wait_for_a_peer_that_acknowledges_nothing() {
client.subscribe("sub-1", vector_selection()).unwrap();
peer.subscribe_id();
peer.stall();
thread::sleep(Duration::from_millis(100));
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");
}
/// 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");
}
#[test]
fn drop_sends_an_unsubscribe_for_each_live_id() {
let peer = Peer::start();
let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap();
client.subscribe("one", vector_selection()).unwrap();
client.subscribe("two", vector_selection()).unwrap();
client.subscribe("gone", vector_selection()).unwrap();
client.unsubscribe("gone").unwrap();
for _ in 0..3 {
peer.subscribe_id();
}
assert!(matches!(peer.next(), CultNetMessage::DatabaseUnsubscribe { subscription_id, .. } if subscription_id == "gone"));
drop(client);
let mut unsubscribed: Vec<String> = (0..2)
.map(|_| match peer.next() {
CultNetMessage::DatabaseUnsubscribe { subscription_id, .. } => subscription_id,
other => panic!("expected an unsubscribe, got {other:?}"),
})
.collect();
unsubscribed.sort();
assert_eq!(unsubscribed, ["one", "two"]);
peer.expect(PeerEvent::Goodbye(b"subscription-closed".to_vec()));
assert!(peer.received.recv_timeout(Duration::from_millis(300)).is_err(), "nothing else is sent");
}
#[test]
fn close_returns_when_the_acknowledgement_arrives_and_says_goodbye() {
let peer = Peer::start();
let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap();
client.subscribe("sub-1", vector_selection()).unwrap();
peer.subscribe_id();
let started = Instant::now();
assert!(client.close());
assert!(started.elapsed() < Duration::from_millis(450), "it does not wait out its 500 ms: {:?}", started.elapsed());
assert!(matches!(peer.next(), CultNetMessage::DatabaseUnsubscribe { subscription_id, .. } if subscription_id == "sub-1"));
peer.expect(PeerEvent::Goodbye(b"subscription-closed".to_vec()));
}
#[test]
fn close_reports_false_once_the_session_has_ended() {
let peer = Peer::start();
let client = CultMeshRudpSubscriptionClient::connect(options_ending_sessions(&peer)).unwrap();
subscribed(&peer, &client);
peer.disconnect();
drain_events(&client, 1);
let started = Instant::now();
assert!(!client.close(), "no peer holds a session whose unsubscribes could be acknowledged");
assert!(started.elapsed() < Duration::from_millis(300), "{:?}", started.elapsed());
}
#[test]
fn draining_releases_the_weight_of_every_document_in_an_event() {
let peer = Peer::start();
let mut options = options(&peer);
options.max_undrained = 3;
let client = CultMeshRudpSubscriptionClient::connect(options).unwrap();
subscribed(&peer, &client);
// A two-change commit weighs two. If draining released one per event, each round would leave one more
// counted and the third would pass the bound of three.
for round in 0..4 {
peer.send(&change_part(&format!("a{round}"), "sub-1", &format!("c{round}")));
peer.send(&change_part(&format!("b{round}"), "sub-1", &format!("c{round}")));
assert_eq!(keys(&drain_events(&client, 1)[0]), ["k", "k"], "round {round}");
}
}
#[test]
fn a_refused_subscribe_is_a_fault_while_a_catalog_request_is_in_flight() {
let peer = Peer::start();
let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap();
client.subscribe("sub-1", vector_selection()).unwrap();
client.subscribe("sub-2", vector_selection()).unwrap();
let mut ids = [peer.subscribe_id(), peer.subscribe_id()];
ids.sort_by(|a, b| a.1.cmp(&b.1));
peer.send(&snapshot_answering(&ids[0].0));
let (request_id, _) = catalog_request(&peer); // in flight, not yet answered
peer.send(&CultNetMessage::ErrorV1 { error: "x".into(), code: None, details: None, message_id: Some(ids[1].0.clone()) });
// The fault queues behind the snapshot that waits for its rows.
quiet(&client);
let (schema_id, hash) = vector_schema();
answer_catalog(&peer, &request_id, vec![descriptor(&schema_id, &hash, Some(vector_members()))]);
let events = drain_events(&client, 2);
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.");
}