cultmesh-rs: close's result is the pump's; pin close and drain weight; docs; test seam off the API
Some checks failed
Rust crates / cargo test, fmt, clippy (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled

- close() takes the acknowledgement from the pump thread's join result: no reply
  channel, no second 1 s give-up, and returning before the pump ended is not
  expressible (close-survivors-untested). Tests pin the early return on
  acknowledgement, the goodbye, the join, and false after the session ended.
- A test pins that try_drain releases the weight of each event (drain-weight-untested)
  and that a refused subscribe is a fault while a catalog request is in flight
  (refusal-during-wait-untested).
- The module Lifetime paragraph names close() and Drop's best effort; the struct doc
  no longer says methods never block on the network (module-doc-omits-close).
- pump_liveness is behind the crate's own test-hooks feature, enabled for its tests by
  a dev-dependency on itself, so a consumer's API does not carry it
  (pump-liveness-public-hook).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-28 13:00:45 +01:00
commit 1d06c3bdf8
4 changed files with 125 additions and 36 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

@ -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
@ -38,7 +41,7 @@ use std::fmt;
use std::net::SocketAddr;
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,19 +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<()>,
#[cfg(feature = "test-hooks")]
pump_alive: std::sync::Weak<()>,
closing: Arc<AtomicBool>,
pump: Option<JoinHandle<()>>,
pump: Option<JoinHandle<bool>>,
}
impl CultMeshRudpSubscriptionClient {
@ -237,7 +242,9 @@ impl CultMeshRudpSubscriptionClient {
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(),
@ -249,6 +256,7 @@ impl CultMeshRudpSubscriptionClient {
pending_weight: 0,
awaiting: Vec::new(),
backoff: BTreeMap::new(),
#[cfg(feature = "test-hooks")]
alive,
subscriptions: BTreeMap::new(),
receipts: Vec::new(),
@ -262,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, closing, 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()
}
@ -306,16 +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 {
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);
if let Some(pump) = self.pump.take() {
let _ = pump.join();
}
acknowledged
let _ = self.commands.send(Command::Close { wait: true });
self.pump.take().is_some_and(|pump| pump.join().unwrap_or(false))
}
}
@ -324,7 +338,7 @@ impl CultMeshRudpSubscriptionClient {
impl Drop for CultMeshRudpSubscriptionClient {
fn drop(&mut self) {
self.closing.store(true, Ordering::SeqCst);
let _ = self.commands.send(Command::Close { reply: None });
let _ = self.commands.send(Command::Close { wait: false });
if let Some(pump) = self.pump.take() {
let _ = pump.join();
}
@ -371,7 +385,7 @@ 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)]
#[cfg(feature = "test-hooks")]
alive: Arc<()>,
/// What `resubscribe_all` resends. The assembler owns what is live; it holds no selections.
subscriptions: BTreeMap<String, Selection>,
@ -385,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(),
}
@ -763,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

@ -37,6 +37,8 @@ enum PeerEvent {
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.
@ -175,6 +177,7 @@ fn serve(
reconnect_policy: None,
})
.unwrap();
let mut said_goodbye = false;
loop {
while let Ok(command) = commands.try_recv() {
match command {
@ -206,6 +209,10 @@ fn serve(
}
}
}
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();
}
}
@ -631,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]
@ -1254,5 +1261,67 @@ fn drop_sends_an_unsubscribe_for_each_live_id() {
.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.");
}