From bc861a45af676764a727ab238175a53f6bc6ea83 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 05:05:22 +0100 Subject: [PATCH 01/11] cultmesh-rs: a non-blocking RUDP subscription client over the cultnet-rs assembler; an error answering a subscribe faults it (rs-subscribe-rudp) Co-Authored-By: Claude Sonnet 5.5 --- packages/cultmesh-rs/src/lib.rs | 2 + packages/cultmesh-rs/src/rudp_subscription.rs | 399 ++++++++++++++ .../cultmesh-rs/tests/rudp_subscription.rs | 509 ++++++++++++++++++ packages/cultnet-rs/src/subscription.rs | 36 +- packages/cultnet-rs/tests/subscription.rs | 33 ++ 5 files changed, 974 insertions(+), 5 deletions(-) create mode 100644 packages/cultmesh-rs/src/rudp_subscription.rs create mode 100644 packages/cultmesh-rs/tests/rudp_subscription.rs diff --git a/packages/cultmesh-rs/src/lib.rs b/packages/cultmesh-rs/src/lib.rs index e3132ece..5b4981b5 100644 --- a/packages/cultmesh-rs/src/lib.rs +++ b/packages/cultmesh-rs/src/lib.rs @@ -25,9 +25,11 @@ use std::time::Duration; use std::time::Instant; mod rudp_document_server; +mod rudp_subscription; pub mod authority; pub use rudp_document_server::*; +pub use rudp_subscription::*; pub const CULTMESH_RUDP_DOCUMENT_CATALOG_CONNECTION_ID: u32 = 0x0d1d_0002; diff --git a/packages/cultmesh-rs/src/rudp_subscription.rs b/packages/cultmesh-rs/src/rudp_subscription.rs new file mode 100644 index 00000000..3449bfa8 --- /dev/null +++ b/packages/cultmesh-rs/src/rudp_subscription.rs @@ -0,0 +1,399 @@ +//! A live `cultnet.database_subscribe.v1` subscription over RUDP, for a caller that cannot block on the network. +//! +//! One background thread owns the RUDP session and the cultnet-rs [`SubscriptionAssembler`]; the caller's handle +//! 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; +//! 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 +//! caller has not drained is bounded too, by [`CultMeshRudpSubscriptionOptions::max_undrained`], counted in +//! documents and changes: a caller that stops draining past it gets a [`SubscriptionEvent::Faulted`], delivery +//! stops, and [`resubscribe_all`](CultMeshRudpSubscriptionClient::resubscribe_all) starts over from fresh +//! snapshots. Memory never grows without bound. + +use super::{connect_rudp_client, recognised_refusal}; +use anyhow::{Result, anyhow}; +use cultnet_rs::{ + CultNetMessage, CultNetRudpReliableSendReceipt, CultNetRudpReliableSendStatus, CultNetRudpSocketTransportConnection, + CultNetWireContract, Selection, SubscriptionAssembler, SubscriptionEvent, decode_cultnet_message_from_slice, + encode_cultnet_message_to_vec, +}; +use std::collections::BTreeMap; +use std::net::SocketAddr; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, TryRecvError}; +use std::sync::{Arc, Mutex}; +use std::thread::{self, JoinHandle}; +use std::time::Duration; + +/// How a subscription client reaches its peer. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CultMeshRudpSubscriptionOptions { + pub target: SocketAddr, + pub runtime_id: String, + /// How long `connect` (and a reconnecting `resubscribe_all`) waits for the peer to accept. + pub connect_timeout: Duration, + /// The pump's cadence: how long it waits on the socket, and so how soon it sees a command. + pub poll_interval: Duration, + pub resend_delay_ms: u64, + /// The most documents and changes that may sit undrained before the subscription faults. + pub max_undrained: usize, +} + +impl CultMeshRudpSubscriptionOptions { + pub fn new(target: SocketAddr, runtime_id: impl Into) -> Self { + Self { + target, + runtime_id: runtime_id.into(), + connect_timeout: Duration::from_secs(5), + poll_interval: Duration::from_millis(5), + resend_delay_ms: 50, + max_undrained: 1_000_000, + } + } +} + +/// What a subscription client delivers: the assembler's events, and the end of the session. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum CultMeshSubscriptionEvent { + Subscription(SubscriptionEvent), + /// The session ended or failed. Delivered once; nothing follows until `resubscribe_all` reconnects. + Disconnected { reason: String }, +} + +impl CultMeshSubscriptionEvent { + fn weight(&self) -> usize { + match self { + Self::Subscription(SubscriptionEvent::Snapshot { documents, .. }) => documents.len().max(1), + Self::Subscription(SubscriptionEvent::Commit { changes, .. }) => changes.len().max(1), + _ => 1, + } + } +} + +enum Command { + Subscribe(String, Selection), + Unsubscribe(String), + Resubscribe, + Close, +} + +/// A live subscription connection. Methods never block on the network. +pub struct CultMeshRudpSubscriptionClient { + commands: Sender, + events: Mutex>, + undrained: Arc, + pump: Option>, +} + +impl CultMeshRudpSubscriptionClient { + /// Connects (blocking up to `connect_timeout`) and starts the pump thread. + pub fn connect(options: CultMeshRudpSubscriptionOptions) -> Result { + if options.runtime_id.trim().is_empty() { + return Err(anyhow!("runtime_id must be non-empty")); + } + let session = open(&options)?; + let (commands, command_rx) = mpsc::channel(); + let (event_tx, events) = mpsc::channel(); + let undrained = Arc::new(AtomicUsize::new(0)); + let pump = Pump { + options, + session: Some(session), + assembler: SubscriptionAssembler::new(), + subscriptions: BTreeMap::new(), + receipts: Vec::new(), + epoch: super::fresh_rudp_connection_epoch(), + sent: 0, + commands: command_rx, + events: event_tx, + undrained: undrained.clone(), + }; + let pump = thread::Builder::new() + .name("cultmesh-rudp-subscription".into()) + .spawn(move || pump.run())?; + Ok(Self { commands, events: Mutex::new(events), undrained, pump: Some(pump) }) + } + + /// Queues a subscribe with a snapshot and returns; the snapshot arrives as an event. Subscribing an id that is + /// live replaces it. While the session is disconnected or faulted the subscription is kept and sent by + /// `resubscribe_all`. + pub fn subscribe(&self, subscription_id: impl Into, selection: Selection) -> Result<()> { + self.send(Command::Subscribe(subscription_id.into(), selection)) + } + + /// Queues an unsubscribe and forgets the subscription, so `resubscribe_all` no longer resends it. + pub fn unsubscribe(&self, subscription_id: impl Into) -> Result<()> { + self.send(Command::Unsubscribe(subscription_id.into())) + } + + /// After a `Faulted` or `Disconnected` event: reconnects if the session ended, starts the assembler over, and + /// resends every subscription with a fresh message id. Each is answered by a new snapshot, which replaces what + /// the consumer held for that id. + pub fn resubscribe_all(&self) -> Result<()> { + self.send(Command::Resubscribe) + } + + /// 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); + drained + } + + fn send(&self, command: Command) -> Result<()> { + self.commands.send(command).map_err(|_| anyhow!("the subscription pump has stopped")) + } +} + +impl Drop for CultMeshRudpSubscriptionClient { + fn drop(&mut self) { + let _ = self.commands.send(Command::Close); + if let Some(pump) = self.pump.take() { + let _ = pump.join(); + } + } +} + +fn open(options: &CultMeshRudpSubscriptionOptions) -> Result { + connect_rudp_client( + options.target, + &options.runtime_id, + options.connect_timeout, + options.poll_interval, + options.resend_delay_ms, + "cultmesh-rudp-subscription-client", + ) +} + +/// The most frames one pump pass reads before it looks at commands again. +const FRAMES_PER_PASS: usize = 64; +/// The longest peer-supplied goodbye text an event carries. +const REASON_CHARS: usize = 200; + +struct Pump { + options: CultMeshRudpSubscriptionOptions, + /// `None` after the session ended: the pump reads nothing and waits for a command. + session: Option, + assembler: SubscriptionAssembler, + /// What `resubscribe_all` resends. The assembler owns what is live; it holds no selections. + subscriptions: BTreeMap, + receipts: Vec, + epoch: u32, + sent: u64, + commands: Receiver, + events: Sender, + undrained: Arc, +} + +impl Pump { + fn run(mut self) { + 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), + } + } else { + match self.commands.recv_timeout(Duration::from_secs(3600)) { + Ok(command) => Some(command), + Err(RecvTimeoutError::Timeout) => None, + Err(RecvTimeoutError::Disconnected) => Some(Command::Close), + } + }; + match command { + Some(Command::Close) => return self.close(), + Some(command) => self.apply(command), + None => self.service(), + } + } + } + + fn apply(&mut self, command: Command) { + match command { + Command::Subscribe(id, selection) => { + if self.subscriptions.insert(id.clone(), selection).is_some() { + self.assembler.end(&id); + } + self.begin(&id); + } + Command::Unsubscribe(id) => { + self.subscriptions.remove(&id); + self.assembler.end(&id); + let message = CultNetMessage::DatabaseUnsubscribe { message_id: self.next_message_id(), subscription_id: id }; + self.transmit(&message); + } + Command::Resubscribe => self.resubscribe(), + Command::Close => unreachable!("handled by the loop"), + } + } + + /// The one subscribe path: the first subscribe and every resubscribe send through here, each with a fresh + /// message id. A faulted assembler refuses, and the subscription waits for `resubscribe_all`. + fn begin(&mut self, id: &str) { + let Some(selection) = self.subscriptions.get(id).cloned() else { return }; + if self.session.is_none() { + return; + } + let message_id = self.next_message_id(); + if self.assembler.begin(id, &message_id).is_err() { + return; + } + let message = CultNetMessage::DatabaseSubscribeV1 { + message_id, + subscription_id: id.to_owned(), + selection, + include_snapshot: true, + consumer_runtime_id: Some(self.options.runtime_id.clone()), + body_ids: None, + supported_body_transports: None, + }; + self.transmit(&message); + } + + fn resubscribe(&mut self) { + if self.session.is_none() { + match open(&self.options) { + Ok(session) => self.session = Some(session), + Err(error) => { + let reason = format!("reconnect failed: {error}"); + return self.push(CultMeshSubscriptionEvent::Disconnected { reason }); + } + } + } + self.assembler.reset(); + self.receipts.clear(); + let ids: Vec<_> = self.subscriptions.keys().cloned().collect(); + for id in ids { + self.begin(&id); + } + } + + /// One pass over the session: resends, frames, receipts, goodbye. + fn service(&mut self) { + let Some(session) = self.session.as_mut() else { return }; + let mut frames = Vec::new(); + let mut failure = None; + if let Err(error) = session.poll_resends() { + failure = Some(error.to_string()); + } + while failure.is_none() && frames.len() < FRAMES_PER_PASS { + match session.receive_once() { + Ok(Some(frame)) => frames.push(frame), + Ok(None) => break, + Err(error) => failure = Some(error.to_string()), + } + } + if failure.is_none() { + failure = session.disconnect_reason().map(goodbye_text); + } + for frame in frames { + if frame.channel_id == "schema" { + self.receive(&frame.payload); + } + } + if failure.is_none() { + failure = self.invalidated(); + } + if let Some(reason) = failure { + self.disconnected(reason); + } + } + + /// A frame that does not decode is the sender's business: dropped, as the transport drops a malformed datagram. + fn receive(&mut self, payload: &[u8]) { + let Ok(message) = decode_cultnet_message_from_slice(payload, CultNetWireContract::CultNetSchemaV0) else { return }; + let events = match message { + CultNetMessage::Error { error, .. } => self.assembler.refused(None, &recognised_refusal(&error)), + CultNetMessage::ErrorV1 { error, message_id, .. } => { + self.assembler.refused(message_id.as_deref(), &recognised_refusal(&error)) + } + other => self.assembler.accept(other), + }; + for event in events { + self.deliver(event); + } + } + + /// Past `max_undrained` the event is not queued: the connection faults instead, once, and the consumer + /// resubscribes for a snapshot. + fn deliver(&mut self, event: SubscriptionEvent) { + let event = CultMeshSubscriptionEvent::Subscription(event); + let queued = self.undrained.load(Ordering::SeqCst); + let fault = matches!(event, CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Faulted { .. })); + if !fault && queued.saturating_add(event.weight()) > self.options.max_undrained { + let reason = format!( + "the consumer left more than {} documents and changes undrained; drain, then resubscribe", + self.options.max_undrained + ); + for fault in self.assembler.latch_fault(reason) { + self.push(CultMeshSubscriptionEvent::Subscription(fault)); + } + return; + } + self.push(event); + } + + fn push(&self, event: CultMeshSubscriptionEvent) { + self.undrained.fetch_add(event.weight(), Ordering::SeqCst); + let _ = self.events.send(event); + } + + fn next_message_id(&mut self) -> String { + self.sent += 1; + format!("{}-{:08x}-{}", self.options.runtime_id, self.epoch, self.sent) + } + + /// Sends one reliable frame; a failed send ends the session. + fn transmit(&mut self, message: &CultNetMessage) { + let Some(session) = self.session.as_mut() else { return }; + let result = encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0) + .and_then(|payload| session.send_reliable("schema", payload)); + match result { + Ok(receipt) => self.receipts.push(receipt), + Err(error) => self.disconnected(format!("send failed: {error}")), + } + } + + /// Forgets acknowledged sends; a send the session gave up on is a lost session. + fn invalidated(&mut self) -> Option { + let session = self.session.as_ref()?; + let mut lost = false; + self.receipts.retain(|receipt| match session.reliable_send_status(receipt) { + CultNetRudpReliableSendStatus::Acknowledged => false, + CultNetRudpReliableSendStatus::Invalidated => { + lost = true; + false + } + CultNetRudpReliableSendStatus::Pending => true, + }); + lost.then(|| "a reliable send was invalidated".to_owned()) + } + + fn disconnected(&mut self, reason: String) { + if self.session.take().is_some() { + self.receipts.clear(); + self.push(CultMeshSubscriptionEvent::Disconnected { reason }); + } + } + + fn close(&mut self) { + 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 let Some(session) = self.session.as_mut() { + let _ = session.disconnect(b"subscription-closed".to_vec()); + } + } +} + +fn goodbye_text(reason: &[u8]) -> String { + let text: String = String::from_utf8_lossy(reason).chars().take(REASON_CHARS).collect(); + format!("the peer ended the session: {text}") +} diff --git a/packages/cultmesh-rs/tests/rudp_subscription.rs b/packages/cultmesh-rs/tests/rudp_subscription.rs new file mode 100644 index 00000000..2061dfd0 --- /dev/null +++ b/packages/cultmesh-rs/tests/rudp_subscription.rs @@ -0,0 +1,509 @@ +//! The RUDP subscription client against a scripted peer (a real RUDP session on a loopback socket that replays the +//! C#-written `database-subscription` vector), and against a live C# subscription server when asked to. + +use cultmesh_rs::{CultMeshRudpSubscriptionClient, CultMeshRudpSubscriptionOptions, CultMeshSubscriptionEvent}; +use cultnet_rs::{ + Change, CultNetErrorCode, CultNetMessage, CultNetRudpSocketMode, CultNetRudpSocketTransportConnection, + CultNetRudpSocketTransportOptions, CultNetWireContract, DatabaseChangeKind, Selection, SubscriptionEvent, + decode_cultnet_message_from_slice, decode_rudp_packet, encode_cultnet_message_to_vec, +}; +use pretty_assertions::assert_eq; +use std::net::{SocketAddr, UdpSocket}; +use std::sync::mpsc::{self, Receiver, Sender}; +use std::thread::{self, JoinHandle}; +use std::time::{Duration, Instant}; + +enum PeerCommand { + Send(Vec), + /// Ends the session and waits for a new Connect. + Disconnect, + Stop, +} + +/// 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, + thread: Option>, +} + +impl Peer { + fn start() -> Self { + let socket = UdpSocket::bind("127.0.0.1:0").unwrap(); + 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) } + } + + fn send(&self, message: &CultNetMessage) { + let payload = encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0).unwrap(); + self.commands.send(PeerCommand::Send(payload)).unwrap(); + } + + fn send_raw(&self, payload: Vec) { + self.commands.send(PeerCommand::Send(payload)).unwrap(); + } + + fn disconnect(&self) { + self.commands.send(PeerCommand::Disconnect).unwrap(); + } + + fn next(&self) -> CultNetMessage { + self.received.recv_timeout(Duration::from_secs(5)).expect("the peer received a message") + } + + fn subscribe_id(&self) -> (String, String) { + match self.next() { + CultNetMessage::DatabaseSubscribeV1 { message_id, subscription_id, include_snapshot, .. } => { + assert!(include_snapshot); + (message_id, subscription_id) + } + other => panic!("expected a subscribe, got {other:?}"), + } + } +} + +impl Drop for Peer { + fn drop(&mut self) { + let _ = self.commands.send(PeerCommand::Stop); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +fn serve(socket: UdpSocket, commands: Receiver, received: 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. + let mut wire = vec![0_u8; 65_535]; + let (length, _) = loop { + match commands.try_recv() { + Ok(PeerCommand::Stop) | Err(mpsc::TryRecvError::Disconnected) => return, + _ => {} + } + if let Ok(found) = socket.peek_from(&mut wire) { + break found; + } + }; + let Ok(packet) = decode_rudp_packet(&wire[..length]) else { + let _ = socket.recv_from(&mut wire); + continue; + }; + let mut session = CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { + media_delivery: None, + runtime_id: "scripted-peer".into(), + socket: socket.try_clone().unwrap(), + mode: CultNetRudpSocketMode::Server, + remote_addr: None, + connection_id: packet.connection_id, + initial_sequence: Some(1), + resend_delay_ms: 10, + transport_id: None, + max_payload_bytes: None, + max_fragment_bytes: Some(1200), + max_pending_reliable_packets: Some(1024), + media_reliable_expire_after_ms: None, + reconnect_policy: None, + }) + .unwrap(); + loop { + while let Ok(command) = commands.try_recv() { + match command { + PeerCommand::Send(payload) => { + session.send_reliable("schema", payload).unwrap(); + } + PeerCommand::Disconnect => { + session.disconnect(b"scripted-goodbye".to_vec()).unwrap(); + continue 'sessions; + } + PeerCommand::Stop => return, + } + } + while let Ok(Some(frame)) = session.receive_once() { + if frame.channel_id == "schema" { + if let Ok(message) = decode_cultnet_message_from_slice(&frame.payload, CultNetWireContract::CultNetSchemaV0) { + let _ = received.send(message); + } + } + } + session.poll_resends().unwrap(); + } + } +} + +fn options(peer: &Peer) -> CultMeshRudpSubscriptionOptions { + let mut options = CultMeshRudpSubscriptionOptions::new(peer.addr, "subscription-test"); + options.poll_interval = Duration::from_millis(2); + options.resend_delay_ms = 10; + options +} + +/// The C#-written session, one message per entry: subscribe, snapshot, a single change, a two-change commit (two +/// messages), a removal. +fn session() -> Vec> { + use serde::Deserialize; + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/vectors/database-subscription/session.msgpack"); + let bytes = std::fs::read(path).expect("the vector is committed"); + let mut cursor = std::io::Cursor::new(bytes.as_slice()); + let mut out = Vec::new(); + while (cursor.position() as usize) < bytes.len() { + let start = cursor.position() as usize; + let mut de = rmp_serde::Deserializer::new(&mut cursor); + serde::de::IgnoredAny::deserialize(&mut de).expect("a msgpack value"); + out.push(bytes[start..cursor.position() as usize].to_vec()); + } + out +} + +fn decode(bytes: &[u8]) -> CultNetMessage { + decode_cultnet_message_from_slice(bytes, CultNetWireContract::CultNetSchemaV0).unwrap() +} + +fn vector_selection() -> Selection { + match decode(&session()[0]) { + CultNetMessage::DatabaseSubscribeV1 { selection, .. } => selection, + other => panic!("{other:?}"), + } +} + +/// The vector's snapshot, answering `message_id`. +fn snapshot_answering(message_id: &str) -> CultNetMessage { + match decode(&session()[1]) { + CultNetMessage::SnapshotResponseRawV1 { matched, as_of, next, headers, documents, .. } => { + CultNetMessage::SnapshotResponseRawV1 { message_id: message_id.into(), matched, as_of, next, headers, documents } + } + other => panic!("{other:?}"), + } +} + +fn change_part(message_id: &str, subscription: &str, commit: &str) -> CultNetMessage { + CultNetMessage::DatabaseChangeRaw { + message_id: message_id.into(), + subscription_id: subscription.into(), + change_kind: DatabaseChangeKind::Removed, + document: None, + record_key: Some("k".into()), + schema_id: Some("note".into()), + commit_id: Some(commit.into()), + commit_count: Some(2), + } +} + +fn single_change(message_id: &str, subscription: &str) -> CultNetMessage { + CultNetMessage::DatabaseChangeRaw { + message_id: message_id.into(), + subscription_id: subscription.into(), + change_kind: DatabaseChangeKind::Removed, + document: None, + record_key: Some("k".into()), + schema_id: Some("note".into()), + commit_id: None, + commit_count: None, + } +} + +/// Drains until `count` events have arrived, or fails after five seconds. +fn drain_events(client: &CultMeshRudpSubscriptionClient, count: usize) -> Vec { + let deadline = Instant::now() + Duration::from_secs(5); + let mut events = Vec::new(); + while events.len() < count && Instant::now() < deadline { + events.extend(client.try_drain()); + thread::sleep(Duration::from_millis(2)); + } + assert_eq!(events.len(), count, "{events:?}"); + events +} + +fn quiet(client: &CultMeshRudpSubscriptionClient) { + thread::sleep(Duration::from_millis(150)); + assert_eq!(client.try_drain(), vec![]); +} + +fn keys(event: &CultMeshSubscriptionEvent) -> Vec<&str> { + match event { + CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Commit { changes, .. }) => { + changes.iter().map(|Change { record_key, .. }| record_key.as_str()).collect() + } + other => panic!("expected a commit, got {other:?}"), + } +} + +fn faulted(event: &CultMeshSubscriptionEvent) -> &str { + match event { + CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Faulted { reason }) => reason, + other => panic!("expected a fault, got {other:?}"), + } +} + +#[test] +fn subscribe_and_try_drain_return_at_once_against_a_peer_that_never_answers() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap(); + assert_eq!(client.try_drain(), vec![]); + let started = Instant::now(); + client.subscribe("sub-1", vector_selection()).unwrap(); + assert_eq!(client.try_drain(), vec![]); + client.unsubscribe("never-made").unwrap(); + client.resubscribe_all().unwrap(); + assert!(started.elapsed() < Duration::from_millis(100), "{:?}", started.elapsed()); + let (_, subscription_id) = peer.subscribe_id(); + assert_eq!(subscription_id, "sub-1"); +} + +#[test] +fn the_vector_session_yields_a_snapshot_two_commits_and_a_removal_in_order() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + let (message_id, _) = peer.subscribe_id(); + peer.send(&snapshot_answering(&message_id)); + for bytes in session().into_iter().skip(2) { + peer.send_raw(bytes); + } + let events = drain_events(&client, 4); + let CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { subscription_id, documents }) = &events[0] + else { + panic!("{events:?}") + }; + assert_eq!(subscription_id, "sub-1"); + assert_eq!(documents.iter().map(|d| d.record_key.as_str()).collect::>(), ["a", "b"]); + assert_eq!(keys(&events[1]), ["c"]); + assert_eq!(keys(&events[2]), ["a", "b"]); + assert_eq!(keys(&events[3]), ["c"]); + quiet(&client); +} + +#[test] +fn a_sixty_fifth_incomplete_commit_faults_then_nothing_and_resubscribe_all_snapshots_every_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(); + let mut first = [peer.subscribe_id(), peer.subscribe_id()]; + first.sort_by(|a, b| a.1.cmp(&b.1)); + for (message_id, _) in &first { + peer.send(&snapshot_answering(message_id)); + } + assert_eq!(drain_events(&client, 2).len(), 2); + for index in 0..65 { + peer.send(&change_part(&format!("m{index}"), "one", &format!("c{index}"))); + } + let events = drain_events(&client, 1); + assert_eq!(faulted(&events[0]), "CultNet subscription 'one': more than 64 commits are incomplete at once."); + peer.send(&single_change("after", "one")); + quiet(&client); + + client.resubscribe_all().unwrap(); + let mut again = [peer.subscribe_id(), peer.subscribe_id()]; + again.sort_by(|a, b| a.1.cmp(&b.1)); + assert_eq!(again.iter().map(|(_, id)| id.as_str()).collect::>(), ["one", "two"]); + assert!(again.iter().all(|(id, _)| first.iter().all(|(old, _)| old != id)), "fresh message ids"); + for (message_id, _) in &again { + peer.send(&snapshot_answering(message_id)); + } + let events = drain_events(&client, 2); + assert!(events.iter().all(|e| matches!(e, CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { .. })))); +} + +#[test] +fn an_error_answering_a_subscribe_is_a_fault_and_only_a_recognised_text_is_quoted() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + let (message_id, _) = peer.subscribe_id(); + peer.send(&CultNetMessage::ErrorV1 { + error: "the catalog refused the document".into(), + code: Some(CultNetErrorCode::LimitReached), + details: None, + message_id: Some(message_id.clone()), + }); + let events = drain_events(&client, 1); + assert_eq!(faulted(&events[0]), "CultNet subscription 'sub-1' was refused by the peer: the catalog refused the document."); + // Answered, so a snapshot for the refused subscribe is nobody's. + peer.send(&snapshot_answering(&message_id)); + quiet(&client); + + client.resubscribe_all().unwrap(); + let (message_id, _) = peer.subscribe_id(); + peer.send(&CultNetMessage::ErrorV1 { + error: "CANARY-secret".into(), + code: None, + details: None, + message_id: Some(message_id), + }); + let events = drain_events(&client, 1); + assert_eq!(faulted(&events[0]), "CultNet subscription 'sub-1' was refused by the peer."); +} + +#[test] +fn an_error_for_something_else_leaves_the_subscription_alone() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + let (message_id, _) = peer.subscribe_id(); + peer.send(&CultNetMessage::ErrorV1 { error: "x".into(), code: None, details: None, message_id: Some("other".into()) }); + peer.send(&snapshot_answering(&message_id)); + let events = drain_events(&client, 1); + assert!(matches!(&events[0], CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { .. }))); +} + +#[test] +fn the_peer_going_away_is_one_disconnected_and_resubscribe_all_reconnects() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + let (message_id, _) = peer.subscribe_id(); + peer.send(&snapshot_answering(&message_id)); + assert_eq!(drain_events(&client, 1).len(), 1); + + peer.disconnect(); + let events = drain_events(&client, 1); + assert!( + matches!(&events[0], CultMeshSubscriptionEvent::Disconnected { reason } if reason.contains("scripted-goodbye")), + "{events:?}" + ); + quiet(&client); + // A subscribe while disconnected is kept, not lost and not a hang. + client.subscribe("late", vector_selection()).unwrap(); + quiet(&client); + + client.resubscribe_all().unwrap(); + let mut again = [peer.subscribe_id(), peer.subscribe_id()]; + again.sort_by(|a, b| a.1.cmp(&b.1)); + assert_eq!(again.iter().map(|(_, id)| id.as_str()).collect::>(), ["late", "sub-1"]); + for (message_id, _) in &again { + peer.send(&snapshot_answering(message_id)); + } + assert_eq!(drain_events(&client, 2).len(), 2); +} + +#[test] +fn a_reconnect_to_a_peer_that_is_gone_is_a_disconnected_not_a_hang() { + let peer = Peer::start(); + let mut options = options(&peer); + options.connect_timeout = Duration::from_millis(200); + let client = CultMeshRudpSubscriptionClient::connect(options).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + peer.subscribe_id(); + peer.disconnect(); + drain_events(&client, 1); + drop(peer); + client.resubscribe_all().unwrap(); + let events = drain_events(&client, 1); + assert!(matches!(&events[0], CultMeshSubscriptionEvent::Disconnected { reason } if reason.starts_with("reconnect failed")), "{events:?}"); +} + +#[test] +fn dropping_the_client_unsubscribes_each_live_id_and_stops_its_thread() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap(); + client.subscribe("one", vector_selection()).unwrap(); + client.subscribe("two", vector_selection()).unwrap(); + client.unsubscribe("two").unwrap(); + peer.subscribe_id(); + peer.subscribe_id(); + assert!(matches!(peer.next(), CultNetMessage::DatabaseUnsubscribe { subscription_id, .. } if subscription_id == "two")); + let before = thread_count(); + let started = Instant::now(); + drop(client); + assert!(started.elapsed() < Duration::from_secs(2), "drop joins promptly"); + assert!(matches!(peer.next(), CultNetMessage::DatabaseUnsubscribe { subscription_id, .. } if subscription_id == "one")); + if cfg!(target_os = "linux") { + assert!(thread_count() < before, "the pump thread is gone with its handle"); + } +} + +fn thread_count() -> usize { + std::fs::read_dir("/proc/self/task").map(|tasks| tasks.count()).unwrap_or(usize::MAX) +} + +#[test] +fn what_the_caller_leaves_undrained_is_bounded_and_past_it_the_subscription_faults() { + let peer = Peer::start(); + let mut options = options(&peer); + options.max_undrained = 3; + let client = CultMeshRudpSubscriptionClient::connect(options).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + let (message_id, _) = peer.subscribe_id(); + peer.send(&snapshot_answering(&message_id)); // two documents + peer.send(&single_change("c1", "sub-1")); // three: at the bound + peer.send(&single_change("c2", "sub-1")); // four: past it + peer.send(&single_change("c3", "sub-1")); + thread::sleep(Duration::from_millis(400)); // the caller is not draining + let events = client.try_drain(); + assert_eq!(events.len(), 3, "{events:?}"); + assert!(matches!(&events[0], CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { .. }))); + assert_eq!(keys(&events[1]), ["k"]); + assert_eq!( + faulted(&events[2]), + "the consumer left more than 3 documents and changes undrained; drain, then resubscribe" + ); + peer.send(&single_change("c4", "sub-1")); + quiet(&client); + + client.resubscribe_all().unwrap(); + let (message_id, _) = peer.subscribe_id(); + peer.send(&snapshot_answering(&message_id)); + assert!(matches!(&drain_events(&client, 1)[0], CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { .. }))); +} + +/// Needs `dotnet` and a built CultLib: `CULTLIB_CS_SUBSCRIPTION_PEER=1`. The C# `rudp-subscription-serve` mode of the +/// interop peer serves a `CultNetDatabase` over RUDP and, once the first subscribe is answered, commits a record +/// and then two records in one commit. +#[test] +fn live_csharp_subscription() { + if std::env::var_os("CULTLIB_CS_SUBSCRIPTION_PEER").is_none() { + return; + } + use std::io::{BufRead, BufReader}; + use std::process::{Command, Stdio}; + let project = concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/GameCult.Networking.InteropPeer"); + let mut peer = Command::new("dotnet") + .args(["run", "--project", project, "-c", "Release", "--", "rudp-subscription-serve"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .expect("dotnet runs the interop peer"); + struct Kill(std::process::Child); + impl Drop for Kill { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + let stdout = peer.stdout.take().unwrap(); + let peer = Kill(peer); + let mut lines = BufReader::new(stdout).lines(); + let port = loop { + let line = lines.next().expect("the peer announces its port").unwrap(); + if let Some(rest) = line.strip_prefix("listening ") { + break rest.trim().parse::().unwrap(); + } + }; + let mut options = CultMeshRudpSubscriptionOptions::new(SocketAddr::from(([127, 0, 0, 1], port)), "rust-subscriber"); + options.connect_timeout = Duration::from_secs(10); + let client = CultMeshRudpSubscriptionClient::connect(options).unwrap(); + client.subscribe("live", Selection::default()).unwrap(); + // snapshot (empty), then the peer's scripted commits: one record, then two records in one commit. + let deadline = Instant::now() + Duration::from_secs(30); + let mut events = Vec::new(); + while Instant::now() < deadline && !events.iter().any(|e| matches!(e, CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Commit { changes, .. }) if changes.len() == 2)) { + events.extend(client.try_drain()); + thread::sleep(Duration::from_millis(10)); + } + assert!(matches!(&events[0], CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { subscription_id, .. }) if subscription_id == "live"), "{events:?}"); + let commits: Vec<_> = events + .iter() + .filter_map(|e| match e { + CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Commit { changes, .. }) => Some(changes.len()), + _ => None, + }) + .collect(); + assert_eq!(commits, [1, 2], "{events:?}"); + drop(client); + drop(peer); +} diff --git a/packages/cultnet-rs/src/subscription.rs b/packages/cultnet-rs/src/subscription.rs index f429c1e7..759639f6 100644 --- a/packages/cultnet-rs/src/subscription.rs +++ b/packages/cultnet-rs/src/subscription.rs @@ -89,8 +89,9 @@ impl SubscriptionAssembler { self.fault.as_deref() } - /// Feeds one decoded message. Messages that are not a snapshot response or a change (an error, a hello) are - /// not this assembler's and return nothing. + /// Feeds one decoded message. Messages that are not a snapshot response or a change (a hello; an error, which + /// the driver reports through [`refused`](Self::refused), because only the driver may quote its text) are not + /// this assembler's and return nothing. pub fn accept(&mut self, message: CultNetMessage) -> Vec { if self.fault.is_some() { return Vec::new(); @@ -129,6 +130,27 @@ impl SubscriptionAssembler { } } + /// The peer answered a subscribe with an error. `answering` is the error's request id when it carries one + /// (`cultnet.error.v1`): an id that is not an outstanding subscribe is not this assembler's and returns nothing, + /// and an outstanding one stops being outstanding. An error with no request id (`cultnet.error.v0`) faults only + /// while some subscribe is outstanding, since a subscribe is the only request a subscription connection makes. + /// The fault is the connection's, like every other: the consumer resubscribes, or ends the subscription and + /// gives up. `detail` is the driver's quotable text for the refusal (empty, or `": text"`). + pub fn refused(&mut self, answering: Option<&str>, detail: &str) -> Vec { + if self.fault.is_some() { + return Vec::new(); + } + let named = match answering { + Some(message_id) => match self.outstanding.remove(message_id) { + Some(subscription_id) => format!(" '{subscription_id}'"), + None => return Vec::new(), + }, + None if self.outstanding.is_empty() => return Vec::new(), + None => String::new(), + }; + self.latch_fault(format!("CultNet subscription{named} was refused by the peer{detail}.")) + } + fn snapshot(&mut self, message_id: &str, documents: Vec) -> Vec { let Some(subscription_id) = self.outstanding.remove(message_id) else { return Vec::new(); @@ -163,7 +185,7 @@ impl SubscriptionAssembler { Ok(Some(complete)) => complete, Ok(None) => return Vec::new(), Err(refusal) => { - return self.fault_with(format!("CultNet subscription '{subscription_id}': {refusal}.")); + return self.latch_fault(format!("CultNet subscription '{subscription_id}': {refusal}.")); } } } @@ -227,8 +249,12 @@ impl SubscriptionAssembler { Ok(self.commits.remove(&held).map(|commit| commit.changes)) } - /// The one fault path: drop what was waiting, latch, say so once. - fn fault_with(&mut self, reason: String) -> Vec { + /// The one fault path: drop what was waiting, latch, say so once. A driver whose own bound is exceeded uses it + /// too, so that the replica a consumer holds and its source never silently differ. + pub fn latch_fault(&mut self, reason: String) -> Vec { + if self.fault.is_some() { + return Vec::new(); + } self.commits.clear(); for subscription in self.subscriptions.values_mut() { subscription.waiting.clear(); diff --git a/packages/cultnet-rs/tests/subscription.rs b/packages/cultnet-rs/tests/subscription.rs index b81c4e01..1411f98f 100644 --- a/packages/cultnet-rs/tests/subscription.rs +++ b/packages/cultnet-rs/tests/subscription.rs @@ -410,3 +410,36 @@ fn a_one_change_announcement_never_counts_against_a_full_buffer() { assert_eq!(keys(&events[0]), ["k1"], "a single change is not a buffered commit, so the full cap does not refuse it"); assert!(assembler.fault().is_none()); } + +#[test] +fn an_error_answering_a_subscribe_faults_it_and_the_subscribe_is_no_longer_outstanding() { + let mut assembler = SubscriptionAssembler::new(); + assembler.begin("sub", "m1").unwrap(); + assembler.begin("other", "m2").unwrap(); + assert!(assembler.refused(Some("unrelated"), ": nope").is_empty(), "an id that is no subscribe's is not ours"); + assert!(assembler.fault().is_none()); + let events = assembler.refused(Some("m1"), ": denied"); + assert_eq!(faulted(&events), "CultNet subscription 'sub' was refused by the peer: denied."); + assert!(assembler.refused(Some("m2"), "").is_empty(), "one fault, said once"); + assembler.reset(); + assembler.begin("sub", "m1").unwrap(); + assert!( + assembler.accept(snapshot("m1", &["r"])).iter().any(|e| matches!(e, SubscriptionEvent::Snapshot { .. })), + "a reset starts clean, so the refused id can be asked again" + ); +} + +#[test] +fn an_error_without_a_request_id_faults_only_while_a_subscribe_is_outstanding() { + let mut assembler = SubscriptionAssembler::new(); + assert!(assembler.refused(None, "").is_empty()); + assembler.begin("sub", "m").unwrap(); + assert_eq!(faulted(&assembler.refused(None, "")), "CultNet subscription was refused by the peer."); +} + +#[test] +fn an_answered_subscribe_is_not_refused_afterwards() { + let mut assembler = live("sub"); + assert!(assembler.refused(Some("begin-sub"), "").is_empty(), "the snapshot already answered it"); + assert!(assembler.fault().is_none()); +} -- 2.47.3 From 61381338ac924f1ff42b7a6c0fefabc419d443f4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 05:06:17 +0100 Subject: [PATCH 02/11] cultmesh-rs tests: answer a subscribe by editing the vector's snapshot Co-Authored-By: Claude Sonnet 5.5 --- packages/cultmesh-rs/tests/rudp_subscription.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/packages/cultmesh-rs/tests/rudp_subscription.rs b/packages/cultmesh-rs/tests/rudp_subscription.rs index 2061dfd0..d655ea43 100644 --- a/packages/cultmesh-rs/tests/rudp_subscription.rs +++ b/packages/cultmesh-rs/tests/rudp_subscription.rs @@ -171,13 +171,11 @@ fn vector_selection() -> Selection { } /// The vector's snapshot, answering `message_id`. -fn snapshot_answering(message_id: &str) -> CultNetMessage { - match decode(&session()[1]) { - CultNetMessage::SnapshotResponseRawV1 { matched, as_of, next, headers, documents, .. } => { - CultNetMessage::SnapshotResponseRawV1 { message_id: message_id.into(), matched, as_of, next, headers, documents } - } - other => panic!("{other:?}"), - } +fn snapshot_answering(answered: &str) -> CultNetMessage { + let mut message = decode(&session()[1]); + let CultNetMessage::SnapshotResponseRawV1 { message_id, .. } = &mut message else { panic!("{message:?}") }; + *message_id = answered.into(); + message } fn change_part(message_id: &str, subscription: &str, commit: &str) -> CultNetMessage { -- 2.47.3 From 2917d016dc614094beeca5739e09620638911db3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 05:07:05 +0100 Subject: [PATCH 03/11] cultmesh-rs tests: the scripted peer queues frames past its send window Co-Authored-By: Claude Sonnet 5.5 --- packages/cultmesh-rs/tests/rudp_subscription.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/cultmesh-rs/tests/rudp_subscription.rs b/packages/cultmesh-rs/tests/rudp_subscription.rs index d655ea43..1c124bd4 100644 --- a/packages/cultmesh-rs/tests/rudp_subscription.rs +++ b/packages/cultmesh-rs/tests/rudp_subscription.rs @@ -114,7 +114,7 @@ fn serve(socket: UdpSocket, commands: Receiver, received: Sender { - session.send_reliable("schema", payload).unwrap(); + session.send("schema", payload).unwrap(); } PeerCommand::Disconnect => { session.disconnect(b"scripted-goodbye".to_vec()).unwrap(); -- 2.47.3 From 1f4bd83ab304c2e5537f71ee21b7fa431d50378b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 05:08:05 +0100 Subject: [PATCH 04/11] interop: a C# RUDP subscription server mode; the subscription client can name the connection id a fixed-id peer serves Co-Authored-By: Claude Sonnet 5.5 --- packages/cultmesh-rs/src/lib.rs | 5 +- packages/cultmesh-rs/src/rudp_subscription.rs | 6 ++ .../cultmesh-rs/tests/rudp_subscription.rs | 1 + .../Program.cs | 6 +- .../SubscriptionHarness.cs | 68 +++++++++++++++++++ 5 files changed, 84 insertions(+), 2 deletions(-) create mode 100644 tests/GameCult.Networking.InteropPeer/SubscriptionHarness.cs diff --git a/packages/cultmesh-rs/src/lib.rs b/packages/cultmesh-rs/src/lib.rs index 5b4981b5..3f97cf6a 100644 --- a/packages/cultmesh-rs/src/lib.rs +++ b/packages/cultmesh-rs/src/lib.rs @@ -818,6 +818,7 @@ pub fn request_raw_snapshot_from_rudp_catalog( options.poll_interval, options.resend_delay_ms, "cultmesh-rudp-snapshot-client", + None, )?; let request = cultnet_rs::CultNetMessage::SnapshotRequest { @@ -942,6 +943,7 @@ pub fn publish_cultnet_messages_to_rudp_catalog( options.poll_interval, options.resend_delay_ms, "cultmesh-rudp-document-publisher", + None, )?; let mut receipts = Vec::with_capacity(messages.len()); @@ -1009,6 +1011,7 @@ fn connect_rudp_client( poll_interval: Duration, resend_delay_ms: u64, transport_id: &str, + connection_id: Option, ) -> Result { let bind_addr = if target.is_ipv4() { SocketAddr::from(([0, 0, 0, 0], 0)) @@ -1024,7 +1027,7 @@ fn connect_rudp_client( socket, mode: cultnet_rs::CultNetRudpSocketMode::Client, remote_addr: Some(target), - connection_id: fresh_rudp_connection_epoch(), + connection_id: connection_id.unwrap_or_else(fresh_rudp_connection_epoch), initial_sequence: None, resend_delay_ms, transport_id: Some(transport_id.to_string()), diff --git a/packages/cultmesh-rs/src/rudp_subscription.rs b/packages/cultmesh-rs/src/rudp_subscription.rs index 3449bfa8..0d054087 100644 --- a/packages/cultmesh-rs/src/rudp_subscription.rs +++ b/packages/cultmesh-rs/src/rudp_subscription.rs @@ -39,6 +39,10 @@ pub struct CultMeshRudpSubscriptionOptions { /// The pump's cadence: how long it waits on the socket, and so how soon it sees a command. pub poll_interval: Duration, pub resend_delay_ms: u64, + /// The RUDP connection id every packet carries. `None` picks a fresh one per connection, which a CultMesh + /// catalog adopts; a peer that serves one fixed id (the C# `RudpCultNetSchemaServer` serves `0x43554c54` unless + /// configured) is reached by naming it. + pub connection_id: Option, /// The most documents and changes that may sit undrained before the subscription faults. pub max_undrained: usize, } @@ -51,6 +55,7 @@ impl CultMeshRudpSubscriptionOptions { connect_timeout: Duration::from_secs(5), poll_interval: Duration::from_millis(5), resend_delay_ms: 50, + connection_id: None, max_undrained: 1_000_000, } } @@ -166,6 +171,7 @@ fn open(options: &CultMeshRudpSubscriptionOptions) -> Result ProgramMainAsync(string[] args) { if (args.Length == 0) { - throw new InvalidOperationException("Expected mode: serve | probe | dial | rudp-serve-once | rudp-dial-once | rudp-serve-message-once | rudp-dial-message-once | quic-realtime-serve | receipt-serve | receipt-relay"); + throw new InvalidOperationException("Expected mode: serve | probe | dial | rudp-serve-once | rudp-dial-once | rudp-serve-message-once | rudp-dial-message-once | quic-realtime-serve | receipt-serve | receipt-relay | rudp-subscription-serve"); } var mode = args[0]; @@ -56,6 +56,10 @@ static async Task ProgramMainAsync(string[] args) case "receipt-serve": await GameCult.Networking.InteropPeer.ReceiptHarness.ServeAsync(); return 0; + case "rudp-subscription-serve": + await GameCult.Networking.InteropPeer.SubscriptionHarness.ServeAsync( + options.TryGetValue("connection-id", out var connectionId) ? uint.Parse(connectionId, CultureInfo.InvariantCulture) : 0x43554c54); + return 0; case "receipt-relay": await GameCult.Networking.InteropPeer.ReceiptHarness.RelayAsync(int.Parse(options["port"], CultureInfo.InvariantCulture)); return 0; diff --git a/tests/GameCult.Networking.InteropPeer/SubscriptionHarness.cs b/tests/GameCult.Networking.InteropPeer/SubscriptionHarness.cs new file mode 100644 index 00000000..faf4dafe --- /dev/null +++ b/tests/GameCult.Networking.InteropPeer/SubscriptionHarness.cs @@ -0,0 +1,68 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using GameCult.Caching; +using GameCult.Networking; + +// A real C# subscription server on RUDP for the Rust subscription client (packages/cultmesh-rs/tests/rudp_subscription.rs, +// live_csharp_subscription). It serves a CultNetDatabase with one document type; once the first subscribe is active it +// commits one record, then two records in one commit, so the client sees a snapshot, a single change and a two-change commit. +namespace GameCult.Networking.InteropPeer +{ + [CultDocument("subscription.interop_note", SubscriptionHarness.SchemaId)] + [MessagePack.MessagePackObject] + public sealed class SubscriptionInteropNote + { + [MessagePack.Key(0)] + public string Text { get; set; } = string.Empty; + } + + internal static class SubscriptionHarness + { + public const string SchemaId = "subscription.interop_note.v1"; + + // stdout: `listening `; runs until stdin closes. + public static async Task ServeAsync(uint connectionId) + { + var cache = new CultCache(); + cache.Registry.GetRequired(); + using var database = new CultNetDatabase(cache); + using var server = new RudpCultNetSchemaServer(new RudpCultNetSchemaServerOptions + { + RuntimeId = "csharp-subscription-peer", + ConnectionId = connectionId + }); + using var subscriptions = new CultNetDatabaseSubscriptionServer(server, database); + var committed = 0; + subscriptions.DemandChanged += demand => + { + if (!demand.Active || Interlocked.Exchange(ref committed, 1) == 1) return; + _ = Task.Run(async () => + { + await Task.Delay(300).ConfigureAwait(false); + cache.Commit(batch => batch.Upsert(typeof(SubscriptionInteropNote), new SubscriptionInteropNote { Text = "one" }, new CultRecordKey("one"))); + await Task.Delay(100).ConfigureAwait(false); + cache.Commit(batch => + { + batch.Upsert(typeof(SubscriptionInteropNote), new SubscriptionInteropNote { Text = "two" }, new CultRecordKey("two")); + batch.Upsert(typeof(SubscriptionInteropNote), new SubscriptionInteropNote { Text = "three" }, new CultRecordKey("three")); + }); + }); + }; + using var stop = new CancellationTokenSource(); + var pump = Task.Run(async () => + { + while (!stop.IsCancellationRequested) + { + var worked = (await server.PollAvailableAsync(64).ConfigureAwait(false)).TransportItemsConsumed > 0; + server.PollResends(); + if (!worked) await Task.Delay(1).ConfigureAwait(false); + } + }); + lock (Console.Out) Console.Out.WriteLine($"listening {server.LocalEndPoint.Port}"); + await Task.Run(() => Console.In.ReadToEnd()); + stop.Cancel(); + await pump.ConfigureAwait(false); + } + } +} -- 2.47.3 From 92281a5a476b607dd8b095bf9d1dbc8a20406f62 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 05:11:34 +0100 Subject: [PATCH 05/11] cultmesh-rs tests: a request-less error faults the outstanding subscribe Co-Authored-By: Claude Sonnet 5.5 --- packages/cultmesh-rs/tests/rudp_subscription.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/cultmesh-rs/tests/rudp_subscription.rs b/packages/cultmesh-rs/tests/rudp_subscription.rs index 32d6d01b..b0c9162a 100644 --- a/packages/cultmesh-rs/tests/rudp_subscription.rs +++ b/packages/cultmesh-rs/tests/rudp_subscription.rs @@ -337,6 +337,17 @@ fn an_error_answering_a_subscribe_is_a_fault_and_only_a_recognised_text_is_quote assert_eq!(faulted(&events[0]), "CultNet subscription 'sub-1' was refused by the peer."); } +#[test] +fn an_error_without_a_request_id_faults_the_outstanding_subscribe() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + peer.subscribe_id(); + peer.send(&CultNetMessage::Error { error: "the snapshot source failed".into(), code: None, details: None }); + let events = drain_events(&client, 1); + assert_eq!(faulted(&events[0]), "CultNet subscription was refused by the peer: the snapshot source failed."); +} + #[test] fn an_error_for_something_else_leaves_the_subscription_alone() { let peer = Peer::start(); -- 2.47.3 From c7aedf5494cd61fe15a4a2e0e8d7f1643d3628a0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 05:14:57 +0100 Subject: [PATCH 06/11] cultmesh-rs tests: an unsubscribed id is neither resent nor unsubscribed again Co-Authored-By: Claude Sonnet 5.5 --- packages/cultmesh-rs/tests/rudp_subscription.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/cultmesh-rs/tests/rudp_subscription.rs b/packages/cultmesh-rs/tests/rudp_subscription.rs index b0c9162a..0118acb0 100644 --- a/packages/cultmesh-rs/tests/rudp_subscription.rs +++ b/packages/cultmesh-rs/tests/rudp_subscription.rs @@ -416,11 +416,15 @@ fn dropping_the_client_unsubscribes_each_live_id_and_stops_its_thread() { peer.subscribe_id(); peer.subscribe_id(); assert!(matches!(peer.next(), CultNetMessage::DatabaseUnsubscribe { subscription_id, .. } if subscription_id == "two")); + // An unsubscribed id is forgotten: not resent, not unsubscribed again. + client.resubscribe_all().unwrap(); + assert_eq!(peer.subscribe_id().1, "one"); let before = thread_count(); let started = Instant::now(); drop(client); assert!(started.elapsed() < Duration::from_secs(2), "drop joins 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"); if cfg!(target_os = "linux") { assert!(thread_count() < before, "the pump thread is gone with its handle"); } -- 2.47.3 From 20004e91e283627d7289f07c54658f562aff452f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 05:29:54 +0100 Subject: [PATCH 07/11] cultmesh-rs: an idle timeout and keepalive end a dead session; resubscribe_all handshakes afresh; the live test is ignored until asked for Co-Authored-By: Claude Sonnet 5.5 --- packages/cultmesh-rs/src/lib.rs | 7 +- packages/cultmesh-rs/src/rudp_subscription.rs | 44 +++- .../cultmesh-rs/tests/rudp_subscription.rs | 199 +++++++++++++----- .../Program.cs | 3 +- .../SubscriptionHarness.cs | 7 +- 5 files changed, 202 insertions(+), 58 deletions(-) diff --git a/packages/cultmesh-rs/src/lib.rs b/packages/cultmesh-rs/src/lib.rs index 3f97cf6a..987f2dc4 100644 --- a/packages/cultmesh-rs/src/lib.rs +++ b/packages/cultmesh-rs/src/lib.rs @@ -1045,7 +1045,12 @@ fn connect_rudp_client( thread::sleep(poll_interval); } if !client.connected() { - anyhow::bail!("timed out connecting CultMesh RUDP client {runtime_id} to {target}"); + let hint = if connection_id.is_none() { + "; a peer that serves one fixed RUDP connection id (the default C# RudpCultNetSchemaServer serves 0x43554c54) is reached by naming it in connection_id" + } else { + "" + }; + anyhow::bail!("timed out connecting CultMesh RUDP client {runtime_id} to {target}{hint}"); } Ok(client) } diff --git a/packages/cultmesh-rs/src/rudp_subscription.rs b/packages/cultmesh-rs/src/rudp_subscription.rs index 0d054087..40e53d48 100644 --- a/packages/cultmesh-rs/src/rudp_subscription.rs +++ b/packages/cultmesh-rs/src/rudp_subscription.rs @@ -27,7 +27,7 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, TryRecvError}; use std::sync::{Arc, Mutex}; use std::thread::{self, JoinHandle}; -use std::time::Duration; +use std::time::{Duration, Instant}; /// How a subscription client reaches its peer. #[derive(Clone, Debug, PartialEq, Eq)] @@ -40,11 +40,18 @@ pub struct CultMeshRudpSubscriptionOptions { pub poll_interval: Duration, pub resend_delay_ms: u64, /// The RUDP connection id every packet carries. `None` picks a fresh one per connection, which a CultMesh - /// catalog adopts; a peer that serves one fixed id (the C# `RudpCultNetSchemaServer` serves `0x43554c54` unless - /// configured) is reached by naming it. + /// catalog adopts; a peer that serves one fixed id is reached only by naming it. The default C# + /// `RudpCultNetSchemaServer` serves `0x43554c54`, so against it `None` times out connecting (the error says so). pub connection_id: Option, - /// The most documents and changes that may sit undrained before the subscription faults. - pub max_undrained: usize, + /// A ping goes to the peer this often while the session is quiet, so a live peer's pong keeps the idle clock + /// reset. The C# transport offers `Ping` but never sends one itself; this client does. + pub keepalive_interval: Duration, + /// A session in which no packet arrives for this long ends as `Disconnected`, and `resubscribe_all` opens a + /// fresh one. The C# transport's `CheckTimeout(timeoutMs)` is the same rule, but its caller must drive it and + /// no default exists there; this one is stated here. + pub idle_timeout: Duration, + /// The most documents and changes that may sit undrained before the subscription faults. A single snapshot + /// larger than this always faults, however promptly it is drained. } impl CultMeshRudpSubscriptionOptions { @@ -54,6 +61,8 @@ impl CultMeshRudpSubscriptionOptions { runtime_id: runtime_id.into(), connect_timeout: Duration::from_secs(5), poll_interval: Duration::from_millis(5), + keepalive_interval: Duration::from_secs(2), + idle_timeout: Duration::from_secs(10), resend_delay_ms: 50, connection_id: None, max_undrained: 1_000_000, @@ -111,6 +120,7 @@ impl CultMeshRudpSubscriptionClient { subscriptions: BTreeMap::new(), receipts: Vec::new(), epoch: super::fresh_rudp_connection_epoch(), + last_ping: Instant::now(), sent: 0, commands: command_rx, events: event_tx, @@ -189,6 +199,7 @@ struct Pump { subscriptions: BTreeMap, receipts: Vec, epoch: u32, + last_ping: Instant, sent: u64, commands: Receiver, events: Sender, @@ -262,9 +273,17 @@ impl Pump { } fn resubscribe(&mut self) { + // A session that has been silent past the idle timeout is dead, though no goodbye said so: it is not + // reused for the resend. + if self.session.as_mut().is_some_and(|session| session.check_timeout(idle_ms(&self.options))) { + self.session = None; + } if self.session.is_none() { match open(&self.options) { - Ok(session) => self.session = Some(session), + Ok(session) => { + self.session = Some(session); + self.last_ping = Instant::now(); + } Err(error) => { let reason = format!("reconnect failed: {error}"); return self.push(CultMeshSubscriptionEvent::Disconnected { reason }); @@ -297,6 +316,15 @@ impl Pump { if failure.is_none() { failure = session.disconnect_reason().map(goodbye_text); } + if failure.is_none() && self.last_ping.elapsed() >= self.options.keepalive_interval { + self.last_ping = Instant::now(); + if let Err(error) = session.ping(Vec::new()) { + failure = Some(error.to_string()); + } + } + if failure.is_none() && session.check_timeout(idle_ms(&self.options)) { + failure = Some(format!("no packet from the peer for {:?}", self.options.idle_timeout)); + } for frame in frames { if frame.channel_id == "schema" { self.receive(&frame.payload); @@ -399,6 +427,10 @@ impl Pump { } } +fn idle_ms(options: &CultMeshRudpSubscriptionOptions) -> u64 { + options.idle_timeout.as_millis() as u64 +} + fn goodbye_text(reason: &[u8]) -> String { let text: String = String::from_utf8_lossy(reason).chars().take(REASON_CHARS).collect(); format!("the peer ended the session: {text}") diff --git a/packages/cultmesh-rs/tests/rudp_subscription.rs b/packages/cultmesh-rs/tests/rudp_subscription.rs index 0118acb0..0af9d8e5 100644 --- a/packages/cultmesh-rs/tests/rudp_subscription.rs +++ b/packages/cultmesh-rs/tests/rudp_subscription.rs @@ -17,6 +17,8 @@ enum PeerCommand { Send(Vec), /// Ends the session and waits for a new Connect. Disconnect, + /// Reads nothing and answers nothing (no pong, no ack) until `Disconnect`: a peer that died without a goodbye. + Stall, Stop, } @@ -47,6 +49,10 @@ impl Peer { self.commands.send(PeerCommand::Send(payload)).unwrap(); } + fn stall(&self) { + self.commands.send(PeerCommand::Stall).unwrap(); + } + fn disconnect(&self) { self.commands.send(PeerCommand::Disconnect).unwrap(); } @@ -120,6 +126,13 @@ fn serve(socket: UdpSocket, commands: Receiver, received: Sender loop { + match commands.recv() { + Ok(PeerCommand::Disconnect) => continue 'sessions, + Ok(PeerCommand::Stop) | Err(_) => return, + Ok(_) => {} + } + }, PeerCommand::Stop => return, } } @@ -464,60 +477,150 @@ fn what_the_caller_leaves_undrained_is_bounded_and_past_it_the_subscription_faul assert!(matches!(&drain_events(&client, 1)[0], CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { .. }))); } -/// Needs `dotnet` and a built CultLib: `CULTLIB_CS_SUBSCRIPTION_PEER=1`. The C# `rudp-subscription-serve` mode of the -/// interop peer serves a `CultNetDatabase` over RUDP and, once the first subscribe is answered, commits a record -/// and then two records in one commit. -#[test] -fn live_csharp_subscription() { - if std::env::var_os("CULTLIB_CS_SUBSCRIPTION_PEER").is_none() { - return; - } - use std::io::{BufRead, BufReader}; - use std::process::{Command, Stdio}; - let project = concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/GameCult.Networking.InteropPeer"); - let mut peer = Command::new("dotnet") - .args(["run", "--project", project, "-c", "Release", "--", "rudp-subscription-serve"]) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn() - .expect("dotnet runs the interop peer"); - struct Kill(std::process::Child); - impl Drop for Kill { - fn drop(&mut self) { - let _ = self.0.kill(); - let _ = self.0.wait(); +struct Csharp { + child: std::process::Child, + port: u16, +} + +impl Csharp { + /// The interop peer, built once and run directly (not through `dotnet run`, whose host would outlive a kill of + /// it), in its `rudp-subscription-serve` mode. `port` None binds any port. + fn start(port: Option) -> Self { + use std::io::{BufRead, BufReader}; + use std::process::{Command, Stdio}; + let project = concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/GameCult.Networking.InteropPeer"); + let build = Command::new("dotnet") + .args(["build", project, "-c", "Release", "-v", "q", "--nologo"]) + .status() + .expect("dotnet builds the interop peer"); + assert!(build.success()); + let dll = format!("{project}/bin/Release/net10.0/GameCult.Networking.InteropPeer.dll"); + let mut command = Command::new("dotnet"); + command.args([dll.as_str(), "rudp-subscription-serve"]); + if let Some(port) = port { + command.args(["--port", &port.to_string()]); } + let mut child = command.stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().expect("dotnet runs the interop peer"); + let mut lines = BufReader::new(child.stdout.take().unwrap()).lines(); + let port = loop { + let line = lines.next().expect("the peer announces its port").unwrap(); + if let Some(rest) = line.strip_prefix("listening ") { + break rest.trim().parse::().unwrap(); + } + }; + Self { child, port } } - let stdout = peer.stdout.take().unwrap(); - let peer = Kill(peer); - let mut lines = BufReader::new(stdout).lines(); - let port = loop { - let line = lines.next().expect("the peer announces its port").unwrap(); - if let Some(rest) = line.strip_prefix("listening ") { - break rest.trim().parse::().unwrap(); - } - }; - let mut options = CultMeshRudpSubscriptionOptions::new(SocketAddr::from(([127, 0, 0, 1], port)), "rust-subscriber"); - options.connect_timeout = Duration::from_secs(10); - options.connection_id = Some(0x4355_4c54); - let client = CultMeshRudpSubscriptionClient::connect(options).unwrap(); - client.subscribe("live", Selection::default()).unwrap(); - // snapshot (empty), then the peer's scripted commits: one record, then two records in one commit. - let deadline = Instant::now() + Duration::from_secs(30); - let mut events = Vec::new(); - while Instant::now() < deadline && !events.iter().any(|e| matches!(e, CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Commit { changes, .. }) if changes.len() == 2)) { - events.extend(client.try_drain()); - thread::sleep(Duration::from_millis(10)); + + /// Ends the process with no goodbye on the wire. + fn kill(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); } - assert!(matches!(&events[0], CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { subscription_id, .. }) if subscription_id == "live"), "{events:?}"); - let commits: Vec<_> = events +} + +impl Drop for Csharp { + fn drop(&mut self) { + self.kill(); + } +} + +fn is_snapshot(event: &CultMeshSubscriptionEvent) -> bool { + matches!(event, CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { subscription_id, .. }) if subscription_id == "live") +} + +fn commit_sizes(events: &[CultMeshSubscriptionEvent]) -> Vec { + events .iter() .filter_map(|e| match e { CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Commit { changes, .. }) => Some(changes.len()), _ => None, }) - .collect(); - assert_eq!(commits, [1, 2], "{events:?}"); - drop(client); - drop(peer); + .collect() +} + +/// Drains until `done` holds for what has arrived, or fails after `seconds`. +fn drain_until( + client: &CultMeshRudpSubscriptionClient, + seconds: u64, + done: impl Fn(&[CultMeshSubscriptionEvent]) -> bool, +) -> Vec { + let deadline = Instant::now() + Duration::from_secs(seconds); + let mut events = Vec::new(); + while Instant::now() < deadline && !done(&events) { + events.extend(client.try_drain()); + thread::sleep(Duration::from_millis(10)); + } + assert!(done(&events), "{events:?}"); + events +} + +/// A real C# subscription server over RUDP: the snapshot and a two-change commit arrive; the server then dies with no +/// goodbye, the client says `Disconnected` within its idle timeout, and once a server is back on the same port +/// `resubscribe_all` handshakes afresh and the snapshot arrives again. +#[test] +#[ignore = "needs dotnet and the C# interop peer; run with `cargo test --test rudp_subscription -- --ignored`"] +fn live_csharp_subscription() { + let mut csharp = Csharp::start(None); + let port = csharp.port; + let mut options = CultMeshRudpSubscriptionOptions::new(SocketAddr::from(([127, 0, 0, 1], port)), "rust-subscriber"); + options.connect_timeout = Duration::from_secs(10); + options.connection_id = Some(0x4355_4c54); + options.keepalive_interval = Duration::from_millis(200); + options.idle_timeout = Duration::from_secs(1); + let client = CultMeshRudpSubscriptionClient::connect(options).unwrap(); + client.subscribe("live", Selection::default()).unwrap(); + let events = drain_until(&client, 30, |events| commit_sizes(events).contains(&2)); + assert!(is_snapshot(&events[0]), "{events:?}"); + assert_eq!(commit_sizes(&events), [1, 2], "{events:?}"); + + csharp.kill(); + let started = Instant::now(); + let events = drain_until(&client, 10, |events| !events.is_empty()); + assert!(matches!(&events[0], CultMeshSubscriptionEvent::Disconnected { reason } if reason.contains("no packet")), "{events:?}"); + assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed()); + quiet(&client); + + let _restarted = Csharp::start(Some(port)); + client.resubscribe_all().unwrap(); + let events = drain_until(&client, 30, |events| commit_sizes(events).contains(&2)); + assert!(is_snapshot(&events[0]), "{events:?}"); +} + +/// A peer that goes silent without a goodbye is a `Disconnected` after the idle timeout, and `resubscribe_all` then +/// handshakes afresh. +#[test] +fn a_silent_peer_is_disconnected_after_the_idle_timeout_and_resubscribe_all_handshakes_afresh() { + let peer = Peer::start(); + let mut options = options(&peer); + options.keepalive_interval = Duration::from_millis(50); + options.idle_timeout = Duration::from_millis(400); + let client = CultMeshRudpSubscriptionClient::connect(options).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + peer.subscribe_id(); + peer.stall(); + let started = Instant::now(); + let events = drain_events(&client, 1); + assert!(matches!(&events[0], CultMeshSubscriptionEvent::Disconnected { reason } if reason.contains("no packet")), "{events:?}"); + assert!(started.elapsed() >= Duration::from_millis(300), "not before the idle timeout: {:?}", started.elapsed()); + quiet(&client); + peer.disconnect(); + client.resubscribe_all().unwrap(); + let (message_id, subscription_id) = peer.subscribe_id(); + assert_eq!(subscription_id, "sub-1"); + peer.send(&snapshot_answering(&message_id)); + assert!(matches!(&drain_events(&client, 1)[0], CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { .. }))); +} + +/// A live peer's pongs keep a quiet session open past the idle timeout. +#[test] +fn a_quiet_but_live_peer_is_not_disconnected() { + let peer = Peer::start(); + let mut options = options(&peer); + options.keepalive_interval = Duration::from_millis(50); + options.idle_timeout = Duration::from_millis(400); + let client = CultMeshRudpSubscriptionClient::connect(options).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + peer.subscribe_id(); + thread::sleep(Duration::from_millis(1200)); + assert_eq!(client.try_drain(), vec![]); } diff --git a/tests/GameCult.Networking.InteropPeer/Program.cs b/tests/GameCult.Networking.InteropPeer/Program.cs index 6d962f4b..f43c1c3f 100644 --- a/tests/GameCult.Networking.InteropPeer/Program.cs +++ b/tests/GameCult.Networking.InteropPeer/Program.cs @@ -58,7 +58,8 @@ static async Task ProgramMainAsync(string[] args) return 0; case "rudp-subscription-serve": await GameCult.Networking.InteropPeer.SubscriptionHarness.ServeAsync( - options.TryGetValue("connection-id", out var connectionId) ? uint.Parse(connectionId, CultureInfo.InvariantCulture) : 0x43554c54); + options.TryGetValue("connection-id", out var connectionId) ? uint.Parse(connectionId, CultureInfo.InvariantCulture) : 0x43554c54, + options.TryGetValue("port", out var port) ? int.Parse(port, CultureInfo.InvariantCulture) : 0); return 0; case "receipt-relay": await GameCult.Networking.InteropPeer.ReceiptHarness.RelayAsync(int.Parse(options["port"], CultureInfo.InvariantCulture)); diff --git a/tests/GameCult.Networking.InteropPeer/SubscriptionHarness.cs b/tests/GameCult.Networking.InteropPeer/SubscriptionHarness.cs index faf4dafe..79d0e392 100644 --- a/tests/GameCult.Networking.InteropPeer/SubscriptionHarness.cs +++ b/tests/GameCult.Networking.InteropPeer/SubscriptionHarness.cs @@ -21,14 +21,17 @@ namespace GameCult.Networking.InteropPeer { public const string SchemaId = "subscription.interop_note.v1"; - // stdout: `listening `; runs until stdin closes. - public static async Task ServeAsync(uint connectionId) + // `--port N` binds that port (0 or absent: any). stdout: `listening `; runs until stdin closes. + public static async Task ServeAsync(uint connectionId, int port) { var cache = new CultCache(); cache.Registry.GetRequired(); using var database = new CultNetDatabase(cache); + var socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp); + socket.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Loopback, port)); using var server = new RudpCultNetSchemaServer(new RudpCultNetSchemaServerOptions { + Socket = socket, RuntimeId = "csharp-subscription-peer", ConnectionId = connectionId }); -- 2.47.3 From 9095a96e6e1b3814d6e576de527bf8c4c97e08a3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 05:30:30 +0100 Subject: [PATCH 08/11] cultmesh-rs: restore the max_undrained field Co-Authored-By: Claude Sonnet 5.5 --- packages/cultmesh-rs/src/rudp_subscription.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/cultmesh-rs/src/rudp_subscription.rs b/packages/cultmesh-rs/src/rudp_subscription.rs index 40e53d48..bf745435 100644 --- a/packages/cultmesh-rs/src/rudp_subscription.rs +++ b/packages/cultmesh-rs/src/rudp_subscription.rs @@ -52,6 +52,7 @@ pub struct CultMeshRudpSubscriptionOptions { pub idle_timeout: Duration, /// The most documents and changes that may sit undrained before the subscription faults. A single snapshot /// larger than this always faults, however promptly it is drained. + pub max_undrained: usize, } impl CultMeshRudpSubscriptionOptions { -- 2.47.3 From d0a28918ce04a635197ff44b1483d7611b1c63a7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 05:31:16 +0100 Subject: [PATCH 09/11] cultmesh-rs tests: the scripted peer starts a session only on a Connect Co-Authored-By: Claude Sonnet 5.5 --- packages/cultmesh-rs/tests/rudp_subscription.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/cultmesh-rs/tests/rudp_subscription.rs b/packages/cultmesh-rs/tests/rudp_subscription.rs index 0af9d8e5..a4ad57f8 100644 --- a/packages/cultmesh-rs/tests/rudp_subscription.rs +++ b/packages/cultmesh-rs/tests/rudp_subscription.rs @@ -95,9 +95,13 @@ fn serve(socket: UdpSocket, commands: Receiver, received: Sender packet, + _ => { + let _ = socket.recv_from(&mut wire); + continue; + } }; let mut session = CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { media_delivery: None, -- 2.47.3 From 278238cf683148bdcaa0c2acfaa9f841fc55b5a9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 05:33:00 +0100 Subject: [PATCH 10/11] cultmesh-rs tests: say what the interop peer said when it dies early Co-Authored-By: Claude Sonnet 5.5 --- packages/cultmesh-rs/tests/rudp_subscription.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/cultmesh-rs/tests/rudp_subscription.rs b/packages/cultmesh-rs/tests/rudp_subscription.rs index a4ad57f8..718271d0 100644 --- a/packages/cultmesh-rs/tests/rudp_subscription.rs +++ b/packages/cultmesh-rs/tests/rudp_subscription.rs @@ -506,11 +506,13 @@ impl Csharp { } let mut child = command.stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().expect("dotnet runs the interop peer"); let mut lines = BufReader::new(child.stdout.take().unwrap()).lines(); + let mut said = Vec::new(); let port = loop { - let line = lines.next().expect("the peer announces its port").unwrap(); + let line = lines.next().unwrap_or_else(|| panic!("the peer ended without announcing its port; it said {said:?}")).unwrap(); if let Some(rest) = line.strip_prefix("listening ") { break rest.trim().parse::().unwrap(); } + said.push(line); }; Self { child, port } } -- 2.47.3 From c1122bcdd376eb4256e37bcd3923e78cf7530c37 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 05:34:06 +0100 Subject: [PATCH 11/11] cultmesh-rs tests: build the interop peer into the crate target directory and run that Co-Authored-By: Claude Sonnet 5.5 --- packages/cultmesh-rs/tests/rudp_subscription.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/cultmesh-rs/tests/rudp_subscription.rs b/packages/cultmesh-rs/tests/rudp_subscription.rs index 718271d0..c65bc005 100644 --- a/packages/cultmesh-rs/tests/rudp_subscription.rs +++ b/packages/cultmesh-rs/tests/rudp_subscription.rs @@ -493,12 +493,13 @@ impl Csharp { use std::io::{BufRead, BufReader}; use std::process::{Command, Stdio}; let project = concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/GameCult.Networking.InteropPeer"); + let out = concat!(env!("CARGO_MANIFEST_DIR"), "/target/interop-peer"); let build = Command::new("dotnet") - .args(["build", project, "-c", "Release", "-v", "q", "--nologo"]) + .args(["build", project, "-c", "Release", "-v", "q", "--nologo", "-o", out]) .status() .expect("dotnet builds the interop peer"); assert!(build.success()); - let dll = format!("{project}/bin/Release/net10.0/GameCult.Networking.InteropPeer.dll"); + let dll = format!("{out}/GameCult.Networking.InteropPeer.dll"); let mut command = Command::new("dotnet"); command.args([dll.as_str(), "rudp-subscription-serve"]); if let Some(port) = port { -- 2.47.3