cultmesh-rs: connect_with_wake, a wake handle on the subscription client (cultmesh-subscription-wake)
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

The pump calls the consumer's closure after each event is queued and once
when it ends after close or Drop, so a consumer blocks on what the wake feeds
instead of polling try_drain.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-29 06:40:46 +01:00
commit 1c027bbab8
2 changed files with 334 additions and 4 deletions

View file

@ -11,6 +11,18 @@
//! 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: the pump survives and the event stays queued. It may call
//! `try_drain`, `subscribe`, `unsubscribe` or `resubscribe_all`. It runs once more when the pump thread ends, after
//! `close` or `Drop` has sent the unsubscribes and the goodbye, and never again: a consumer blocked in its own wait
//! on another thread is released within the bounds above (500 ms of acknowledgement wait, a poll interval, and a
//! reconnect abandoned at its next poll) and its next `try_drain` returns what the pump had queued.
//!
//! 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 +244,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> {
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> {
Self::start(options, Some(Arc::new(wake)))
}
fn start(options: CultMeshRudpSubscriptionOptions, wake: Option<Arc<dyn Fn() + Send + Sync>>) -> Result<Self> {
if options.runtime_id.trim().is_empty() {
return Err(anyhow!("runtime_id must be non-empty"));
}
@ -266,6 +295,7 @@ impl CultMeshRudpSubscriptionClient {
commands: command_rx,
events: event_tx,
undrained: undrained.clone(),
wake,
};
let pump = thread::Builder::new()
.name("cultmesh-rudp-subscription".into())
@ -396,6 +426,8 @@ struct Pump {
commands: Receiver<Command>,
events: Sender<(CultMeshSubscriptionEvent, usize)>,
undrained: Arc<AtomicUsize>,
/// Called after an event is queued and once when the pump ends; see the module docs.
wake: Option<Arc<dyn Fn() + Send + Sync>>,
}
impl Pump {
@ -416,7 +448,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 +768,14 @@ 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 {
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| wake()));
}
}
fn next_message_id(&mut self) -> String {

View file

@ -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,280 @@ 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<usize>,
changed: Condvar,
}
impl Wakes {
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<Wakes>, 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.count.lock().unwrap() += 1;
counted.changed.notify_all();
};
(wake, wakes, tokens)
}
type Reports = Receiver<Vec<CultMeshSubscriptionEvent>>;
/// 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<CultMeshRudpSubscriptionClient>, Reports) {
let slot: Arc<OnceLock<Weak<CultMeshRudpSubscriptionClient>>> = 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<CultMeshSubscriptionEvent> {
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<Option<Instant>>) {
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();
let (wake, wakes, tokens) = counting_wake();
let client = CultMeshRudpSubscriptionClient::connect_with_wake(options(&peer), wake).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");
assert_eq!(drain_events(&client, 1).len(), 1);
// The next event lands, and its wake has run, before the consumer waits at all: the token is stored.
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());
assert_eq!(keys(&drain_events(&client, 1)[0]), ["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::<Vec<_>>(), [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 (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));
}
#[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");
}