From 0c890c79ccfe8b54f7710c7c4dc834de5fb70e48 Mon Sep 17 00:00:00 2001 From: Eureka Date: Sat, 28 Nov 2026 11:35:41 +0000 Subject: [PATCH] cultmesh-rs: subscription events carry member rows from the schema catalog (#196) --- packages/cultmesh-rs/src/rudp_subscription.rs | 436 +++++++++++-- .../cultmesh-rs/tests/rudp_subscription.rs | 590 ++++++++++++++++-- 2 files changed, 945 insertions(+), 81 deletions(-) diff --git a/packages/cultmesh-rs/src/rudp_subscription.rs b/packages/cultmesh-rs/src/rudp_subscription.rs index bf745435..3db8fc22 100644 --- a/packages/cultmesh-rs/src/rudp_subscription.rs +++ b/packages/cultmesh-rs/src/rudp_subscription.rs @@ -10,22 +10,35 @@ //! //! 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 +//! documents and changes, those still waiting in the pump for their rows included: a caller that stops draining +//! past it gets a [`CultMeshSubscriptionEvent::Faulted`], delivery //! stops, and [`resubscribe_all`](CultMeshRudpSubscriptionClient::resubscribe_all) starts over from fresh //! snapshots. Memory never grows without bound. +//! +//! Member rows: a consumer decodes a record by member name, so every delivered record carries the rows of its +//! schema ([`RecordWithRows`]). The pump asks the peer for them with `schema_catalog_request{includeMembers}` the +//! first time it meets a (`schemaId`, `schemaContentHash`) pair and keeps the answer by that pair: the hash is +//! computed over the rows, so an entry cannot go stale unnoticed, and it is compared here as an opaque string. Events +//! whose rows are not yet known wait in the pump, in arrival order, behind the one catalog request in flight, and are +//! delivered when the answer arrives; the answer, a refusal, or +//! [`catalog_timeout`](CultMeshRudpSubscriptionOptions::catalog_timeout) releases them. They count toward +//! `max_undrained`. A record whose rows the peer does not serve is delivered with [`MemberRows::NoMembers`] and the +//! reason, never dropped and never decoded by position. 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, + CultNetSchemaDescriptor, CultNetSchemaMember, CultNetWireContract, DatabaseChangeKind, Selection, + SelectionDocumentRecord, SubscriptionAssembler, SubscriptionEvent, decode_cultnet_message_from_slice, encode_cultnet_message_to_vec, }; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::fmt; 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::sync::{Arc, Mutex, Weak}; use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant}; @@ -50,9 +63,13 @@ pub struct CultMeshRudpSubscriptionOptions { /// 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. + /// The most documents and changes that may sit undrained, or wait in the pump for their member rows, before the + /// subscription faults. A single snapshot larger than this always faults, however promptly it is drained. pub max_undrained: usize, + /// How long events wait for a catalog answer. Past it the records waiting on it are delivered with + /// [`NoMembersReason::CatalogTimedOut`], and a later record of the same schema asks again once this long has + /// passed since (a timeout never latches for the session). + pub catalog_timeout: Duration, } impl CultMeshRudpSubscriptionOptions { @@ -67,40 +84,144 @@ impl CultMeshRudpSubscriptionOptions { resend_delay_ms: 50, connection_id: None, max_undrained: 1_000_000, + catalog_timeout: Duration::from_secs(5), } } } -/// What a subscription client delivers: the assembler's events, and the end of the session. +/// Why a record arrived without its member rows. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum NoMembersReason { + /// The record names no `schemaContentHash`, so no rows can be keyed for it. + RecordNamesNoHash, + /// The catalog answered without a descriptor for the record's schema id. + NotInCatalog, + /// The descriptor carries no member rows: a peer that predates `includeMembers`, or a schema with none. + MembersAbsent, + /// The catalog serves rows for another content hash than the record names. + ContentHashDiffers { served: String }, + /// The peer refused the catalog request (the text only when it is a recognised refusal). + CatalogRefused { detail: String }, + /// No answer came within `catalog_timeout`. + CatalogTimedOut, + /// The session ended while the record waited for its rows. + SessionEnded, +} + +impl fmt::Display for NoMembersReason { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::RecordNamesNoHash => f.write_str("the record names no schema content hash"), + Self::NotInCatalog => f.write_str("the peer's schema catalog has no descriptor for the record's schema"), + Self::MembersAbsent => f.write_str("the peer's schema descriptor carries no member rows"), + Self::ContentHashDiffers { served } => { + write!(f, "the peer serves member rows for content hash '{served}', not the record's") + } + Self::CatalogRefused { detail } => write!(f, "the peer refused the schema catalog request{detail}"), + Self::CatalogTimedOut => f.write_str("the schema catalog request was not answered in time"), + Self::SessionEnded => f.write_str("the session ended before the member rows arrived"), + } + } +} + +/// The member rows of a record's schema, or the stated reason there are none. A consumer that cannot decode by name +/// refuses on `NoMembers`; it never decodes the payload by position. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum MemberRows { + Served(Arc<[CultNetSchemaMember]>), + NoMembers(NoMembersReason), +} + +impl MemberRows { + pub fn rows(&self) -> Option<&[CultNetSchemaMember]> { + match self { + Self::Served(rows) => Some(rows), + Self::NoMembers(_) => None, + } + } +} + +/// A delivered record with the member rows of its schema. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RecordWithRows { + pub document: SelectionDocumentRecord, + pub members: MemberRows, +} + +/// One change of a commit. `record` is `None` for a removal, which has no document. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RowChange { + pub kind: DatabaseChangeKind, + pub record_key: String, + pub schema_id: String, + pub record: Option, +} + +/// What a subscription client delivers: the assembler's events with each record joined to its rows, and the end of +/// the session. #[derive(Clone, Debug, PartialEq, Eq)] pub enum CultMeshSubscriptionEvent { - Subscription(SubscriptionEvent), + /// The answer to a subscribe. + Snapshot { subscription_id: String, documents: Vec }, + /// One change, or every change of one commit in arrival order; a partial commit is never delivered. + Commit { subscription_id: String, changes: Vec }, + /// The connection's replica no longer matches its source. Nothing more is delivered until `resubscribe_all`. + Faulted { reason: String }, /// 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, - } +/// The one weight of an event: its documents or changes, at least one. It is counted when the event is admitted, +/// travels with the event to the consumer's queue, and is released when drained. +fn event_weight(event: &SubscriptionEvent) -> usize { + match event { + SubscriptionEvent::Snapshot { documents, .. } => documents.len().max(1), + SubscriptionEvent::Commit { changes, .. } => changes.len().max(1), + SubscriptionEvent::Faulted { .. } => 1, } } +fn documents_of(event: &SubscriptionEvent) -> Vec<&SelectionDocumentRecord> { + match event { + SubscriptionEvent::Snapshot { documents, .. } => documents.iter().collect(), + SubscriptionEvent::Commit { changes, .. } => changes.iter().filter_map(|change| change.document.as_ref()).collect(), + SubscriptionEvent::Faulted { .. } => Vec::new(), + } +} + +fn subscription_of(event: &SubscriptionEvent) -> Option<&str> { + match event { + SubscriptionEvent::Snapshot { subscription_id, .. } | SubscriptionEvent::Commit { subscription_id, .. } => { + Some(subscription_id) + } + SubscriptionEvent::Faulted { .. } => None, + } +} + +type SchemaKey = (String, String); + +/// The one catalog request in flight and the (schemaId, hash) pairs it was sent for. +struct Awaiting { + message_id: String, + keys: BTreeSet, + sent: Instant, +} + enum Command { Subscribe(String, Selection), Unsubscribe(String), Resubscribe, - Close, + /// Ends the session. With a `reply`, waits (bounded) for the unsubscribes to be acknowledged and says whether + /// they were; without one, sends them and goes. + Close { reply: Option> }, } /// A live subscription connection. Methods never block on the network. pub struct CultMeshRudpSubscriptionClient { commands: Sender, - events: Mutex>, + events: Mutex>, undrained: Arc, + pump_alive: Weak<()>, pump: Option>, } @@ -114,10 +235,18 @@ impl CultMeshRudpSubscriptionClient { let (commands, command_rx) = mpsc::channel(); let (event_tx, events) = mpsc::channel(); let undrained = Arc::new(AtomicUsize::new(0)); + let alive = Arc::new(()); + let pump_alive = Arc::downgrade(&alive); let pump = Pump { options, session: Some(session), assembler: SubscriptionAssembler::new(), + rows: BTreeMap::new(), + pending: VecDeque::new(), + pending_weight: 0, + awaiting: Vec::new(), + backoff: BTreeMap::new(), + alive, subscriptions: BTreeMap::new(), receipts: Vec::new(), epoch: super::fresh_rudp_connection_epoch(), @@ -130,7 +259,13 @@ impl CultMeshRudpSubscriptionClient { let pump = thread::Builder::new() .name("cultmesh-rudp-subscription".into()) .spawn(move || pump.run())?; - Ok(Self { commands, events: Mutex::new(events), undrained, pump: Some(pump) }) + Ok(Self { commands, events: Mutex::new(events), undrained, pump_alive, pump: Some(pump) }) + } + + /// A weak handle that upgrades while this client's own pump thread exists, and never after it has been joined. + /// Tests use it to prove that dropping the client ends its thread. + pub fn pump_liveness(&self) -> Weak<()> { + self.pump_alive.clone() } /// Queues a subscribe with a snapshot and returns; the snapshot arrives as an event. Subscribing an id that is @@ -155,8 +290,8 @@ impl CultMeshRudpSubscriptionClient { /// 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); + let (drained, weights): (Vec<_>, Vec) = events.try_iter().unzip(); + self.undrained.fetch_sub(weights.iter().sum(), Ordering::SeqCst); drained } @@ -165,9 +300,26 @@ impl CultMeshRudpSubscriptionClient { } } +impl CultMeshRudpSubscriptionClient { + /// The explicit shutdown: unsubscribes each live id, waits up to 500 ms for the peer to acknowledge, ends the + /// session and joins the pump thread. Returns whether the acknowledgement arrived; `false` says the peer may + /// still hold the subscriptions until its own idle timeout. + pub fn close(mut self) -> bool { + let (reply, answer) = mpsc::channel(); + let sent = self.commands.send(Command::Close { reply: Some(reply) }).is_ok(); + let acknowledged = sent && answer.recv_timeout(CLOSE_ACK_WAIT * 2).unwrap_or(false); + if let Some(pump) = self.pump.take() { + let _ = pump.join(); + } + acknowledged + } +} + +/// Best effort: sends the unsubscribes and stops the pump thread without waiting for the peer. Use +/// [`close`](CultMeshRudpSubscriptionClient::close) to learn whether the peer acknowledged. impl Drop for CultMeshRudpSubscriptionClient { fn drop(&mut self) { - let _ = self.commands.send(Command::Close); + let _ = self.commands.send(Command::Close { reply: None }); if let Some(pump) = self.pump.take() { let _ = pump.join(); } @@ -190,12 +342,28 @@ fn open(options: &CultMeshRudpSubscriptionOptions) -> Result, assembler: SubscriptionAssembler, + /// Member rows by (schemaId, schemaContentHash); an entry is immutable for its hash. A stated absence is kept + /// too, so a missing row is not refetched in a loop; absences end with the session, rows never do. + rows: BTreeMap, NoMembersReason>>, + /// Assembled events whose rows are not all known yet, in arrival order, and their weight. + pending: VecDeque, + pending_weight: usize, + /// The catalog requests in flight; their keys are not asked for again. + awaiting: Vec, + /// When a pair whose request timed out may be asked for again. Not an absence: the record that arrives after + /// this passes asks afresh. + backoff: BTreeMap, + /// Held for as long as the pump thread runs; see `pump_liveness`. + #[allow(dead_code)] + alive: Arc<()>, /// What `resubscribe_all` resends. The assembler owns what is live; it holds no selections. subscriptions: BTreeMap, receipts: Vec, @@ -203,7 +371,7 @@ struct Pump { last_ping: Instant, sent: u64, commands: Receiver, - events: Sender, + events: Sender<(CultMeshSubscriptionEvent, usize)>, undrained: Arc, } @@ -214,17 +382,17 @@ impl Pump { match self.commands.try_recv() { Ok(command) => Some(command), Err(TryRecvError::Empty) => None, - Err(TryRecvError::Disconnected) => Some(Command::Close), + Err(TryRecvError::Disconnected) => Some(Command::Close { reply: None }), } } else { match self.commands.recv_timeout(Duration::from_secs(3600)) { Ok(command) => Some(command), Err(RecvTimeoutError::Timeout) => None, - Err(RecvTimeoutError::Disconnected) => Some(Command::Close), + Err(RecvTimeoutError::Disconnected) => Some(Command::Close { reply: None }), } }; match command { - Some(Command::Close) => return self.close(), + Some(Command::Close { reply }) => return self.close(reply), Some(command) => self.apply(command), None => self.service(), } @@ -236,17 +404,19 @@ impl Pump { Command::Subscribe(id, selection) => { if self.subscriptions.insert(id.clone(), selection).is_some() { self.assembler.end(&id); + self.drop_pending(&id); } self.begin(&id); } Command::Unsubscribe(id) => { self.subscriptions.remove(&id); self.assembler.end(&id); + self.drop_pending(&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"), + Command::Close { .. } => unreachable!("handled by the loop"), } } @@ -287,12 +457,17 @@ impl Pump { } Err(error) => { let reason = format!("reconnect failed: {error}"); - return self.push(CultMeshSubscriptionEvent::Disconnected { reason }); + return self.push(CultMeshSubscriptionEvent::Disconnected { reason }, 1); } } } self.assembler.reset(); self.receipts.clear(); + self.pending.clear(); + self.pending_weight = 0; + self.awaiting.clear(); + self.backoff.clear(); + self.rows.retain(|_, rows| rows.is_ok()); let ids: Vec<_> = self.subscriptions.keys().cloned().collect(); for id in ids { self.begin(&id); @@ -334,6 +509,9 @@ impl Pump { if failure.is_none() { failure = self.invalidated(); } + if failure.is_none() { + self.expire_requests(); + } if let Some(reason) = failure { self.disconnected(reason); } @@ -343,6 +521,14 @@ impl Pump { fn receive(&mut self, payload: &[u8]) { let Ok(message) = decode_cultnet_message_from_slice(payload, CultNetWireContract::CultNetSchemaV0) else { return }; let events = match message { + CultNetMessage::SchemaCatalogResponse { message_id, schemas } => { + self.catalog_answered(&message_id, schemas); + return; + } + CultNetMessage::ErrorV1 { error, message_id: Some(id), .. } if self.awaiting.iter().any(|a| a.message_id == id) => { + let detail = recognised_refusal(&error); + return self.catalog_refused(&id, detail); + } 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)) @@ -350,32 +536,178 @@ impl Pump { other => self.assembler.accept(other), }; for event in events { - self.deliver(event); + self.admit(event); } + self.release(); } - /// 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 { + /// Past `max_undrained` (delivered but undrained, plus waiting for rows) the event is not queued: the connection + /// faults instead, once, and the consumer resubscribes for a snapshot. + fn admit(&mut self, event: SubscriptionEvent) { + let weight = event_weight(&event); + let fault = matches!(event, SubscriptionEvent::Faulted { .. }); + let held = self.undrained.load(Ordering::SeqCst).saturating_add(self.pending_weight); + if !fault && held.saturating_add(weight) > self.options.max_undrained { let reason = format!( "the consumer left more than {} documents and changes undrained; drain, then resubscribe", self.options.max_undrained ); + self.pending.clear(); + self.pending_weight = 0; for fault in self.assembler.latch_fault(reason) { - self.push(CultMeshSubscriptionEvent::Subscription(fault)); + self.pending_weight += event_weight(&fault); + self.pending.push_back(fault); } return; } - self.push(event); + self.pending_weight += weight; + self.pending.push_back(event); } - fn push(&self, event: CultMeshSubscriptionEvent) { - self.undrained.fetch_add(event.weight(), Ordering::SeqCst); - let _ = self.events.send(event); + /// Delivers pending events in order while their rows are known. Whatever the waiting events lack, across all + /// of them and not already asked for, goes out in one catalog request, so that N unseen schemas wait one + /// timeout, not N. + fn release(&mut self) { + let lacking: BTreeSet = + self.pending.iter().flat_map(documents_of).filter_map(|d| self.lookup(d).err()).collect(); + let unasked: BTreeSet = + lacking.into_iter().filter(|key| !self.awaiting.iter().any(|a| a.keys.contains(key))).collect(); + if !unasked.is_empty() { + self.request_catalog(unasked); + } + while let Some(front) = self.pending.front() { + if documents_of(front).into_iter().any(|d| self.lookup(d).is_err()) { + return; + } + let event = self.pending.pop_front().expect("front was just read"); + self.pending_weight -= event_weight(&event); + self.deliver(event, &NoMembersReason::SessionEnded); + } + } + + /// The rows for a document, or the (schemaId, hash) pair that must be fetched to know them. + fn lookup(&self, document: &SelectionDocumentRecord) -> Result { + let Some(hash) = &document.schema_content_hash else { + return Ok(MemberRows::NoMembers(NoMembersReason::RecordNamesNoHash)); + }; + let key = (document.schema_id.clone(), hash.clone()); + match self.rows.get(&key) { + Some(Ok(rows)) => Ok(MemberRows::Served(rows.clone())), + Some(Err(reason)) => Ok(MemberRows::NoMembers(reason.clone())), + None if self.backoff.get(&key).is_some_and(|until| Instant::now() < *until) => { + Ok(MemberRows::NoMembers(NoMembersReason::CatalogTimedOut)) + } + None => Err(key), + } + } + + /// The one join of a record to its rows, for snapshot documents and commit changes alike. A pair not yet + /// known takes `unknown`. + fn join(&self, document: SelectionDocumentRecord, unknown: &NoMembersReason) -> RecordWithRows { + let members = self.lookup(&document).unwrap_or_else(|_| MemberRows::NoMembers(unknown.clone())); + RecordWithRows { document, members } + } + + fn deliver(&mut self, event: SubscriptionEvent, unknown: &NoMembersReason) { + let weight = event_weight(&event); + let event = match event { + SubscriptionEvent::Snapshot { subscription_id, documents } => CultMeshSubscriptionEvent::Snapshot { + subscription_id, + documents: documents.into_iter().map(|document| self.join(document, unknown)).collect(), + }, + SubscriptionEvent::Commit { subscription_id, changes } => CultMeshSubscriptionEvent::Commit { + subscription_id, + changes: changes + .into_iter() + .map(|change| RowChange { + kind: change.kind, + record_key: change.record_key, + schema_id: change.schema_id, + record: change.document.map(|document| self.join(document, unknown)), + }) + .collect(), + }, + SubscriptionEvent::Faulted { reason } => CultMeshSubscriptionEvent::Faulted { reason }, + }; + self.push(event, weight); + } + + fn request_catalog(&mut self, keys: BTreeSet) { + let message_id = self.next_message_id(); + let schema_ids: BTreeSet = keys.iter().map(|(id, _)| id.clone()).collect(); + self.awaiting.push(Awaiting { message_id: message_id.clone(), keys, sent: Instant::now() }); + let message = CultNetMessage::SchemaCatalogRequest { + message_id, + include_schema_json: None, + include_members: Some(true), + schema_ids: Some(schema_ids.into_iter().collect()), + kinds: None, + }; + self.transmit(&message); + } + + /// The answer to a request in flight: every pair it asked for is settled, by its rows or by the stated reason + /// it has none. An answer to nothing in flight is ignored. + fn catalog_answered(&mut self, message_id: &str, schemas: Vec) { + let Some(at) = self.awaiting.iter().position(|a| a.message_id == message_id) else { return }; + let awaiting = self.awaiting.remove(at); + for descriptor in &schemas { + if let Some(members) = descriptor.members.as_ref().filter(|members| !members.is_empty()) { + let key = (descriptor.schema_id.clone(), descriptor.content_hash.clone()); + self.rows.insert(key, Ok(members.as_slice().into())); + } + } + for (id, hash) in awaiting.keys { + if self.rows.contains_key(&(id.clone(), hash.clone())) { + continue; + } + let reason = match schemas.iter().find(|d| d.schema_id == id) { + None => NoMembersReason::NotInCatalog, + Some(d) if d.content_hash != hash => NoMembersReason::ContentHashDiffers { served: d.content_hash.clone() }, + Some(_) => NoMembersReason::MembersAbsent, + }; + self.rows.insert((id, hash), Err(reason)); + } + self.release(); + } + + /// The peer refused the request: its pairs are absent for this session. + fn catalog_refused(&mut self, message_id: &str, detail: String) { + let Some(at) = self.awaiting.iter().position(|a| a.message_id == message_id) else { return }; + for key in self.awaiting.remove(at).keys { + self.rows.insert(key, Err(NoMembersReason::CatalogRefused { detail: detail.clone() })); + } + self.release(); + } + + /// A request past `catalog_timeout` is given up: its records are delivered without rows, and its pairs may be + /// asked for again by a record arriving once the same time has passed. + fn expire_requests(&mut self) { + let timeout = self.options.catalog_timeout; + let (expired, live): (Vec<_>, Vec<_>) = + std::mem::take(&mut self.awaiting).into_iter().partition(|a| a.sent.elapsed() >= timeout); + self.awaiting = live; + if expired.is_empty() { + return; + } + let until = Instant::now() + timeout; + for key in expired.into_iter().flat_map(|a| a.keys) { + self.backoff.insert(key, until); + } + self.release(); + } + + fn drop_pending(&mut self, subscription_id: &str) { + let before = self.pending.len(); + self.pending.retain(|event| subscription_of(event) != Some(subscription_id)); + if self.pending.len() != before { + self.pending_weight = self.pending.iter().map(event_weight).sum(); + } + } + + fn push(&self, event: CultMeshSubscriptionEvent, weight: usize) { + self.undrained.fetch_add(weight, Ordering::SeqCst); + let _ = self.events.send((event, weight)); } fn next_message_id(&mut self) -> String { @@ -412,19 +744,39 @@ impl Pump { fn disconnected(&mut self, reason: String) { if self.session.take().is_some() { self.receipts.clear(); - self.push(CultMeshSubscriptionEvent::Disconnected { reason }); + self.awaiting.clear(); + // Records already received are delivered, with the stated reason they have no rows, not dropped. + while let Some(event) = self.pending.pop_front() { + self.pending_weight -= event_weight(&event); + self.deliver(event, &NoMembersReason::SessionEnded); + } + self.push(CultMeshSubscriptionEvent::Disconnected { reason }, 1); } } - fn close(&mut self) { + /// Unsubscribes every live id and ends the session. With `reply`, first waits up to `CLOSE_ACK_WAIT` for every + /// outstanding reliable send to be acknowledged (resending a lost one), since nothing resends after the goodbye, + /// and tells whether they all were. + fn close(&mut self, reply: Option>) { let ids: Vec<_> = self.subscriptions.keys().cloned().collect(); for id in ids { let message = CultNetMessage::DatabaseUnsubscribe { message_id: self.next_message_id(), subscription_id: id }; self.transmit(&message); } + if reply.is_some() { + let deadline = Instant::now() + CLOSE_ACK_WAIT; + while self.session.is_some() && !self.receipts.is_empty() && Instant::now() < deadline { + self.service(); + thread::sleep(self.options.poll_interval); + } + } + let acknowledged = self.session.is_some() && self.receipts.is_empty(); if let Some(session) = self.session.as_mut() { let _ = session.disconnect(b"subscription-closed".to_vec()); } + if let Some(reply) = reply { + let _ = reply.send(acknowledged); + } } } diff --git a/packages/cultmesh-rs/tests/rudp_subscription.rs b/packages/cultmesh-rs/tests/rudp_subscription.rs index c65bc005..ecf005aa 100644 --- a/packages/cultmesh-rs/tests/rudp_subscription.rs +++ b/packages/cultmesh-rs/tests/rudp_subscription.rs @@ -1,11 +1,14 @@ //! 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 cultmesh_rs::{ + CultMeshRudpSubscriptionClient, CultMeshRudpSubscriptionOptions, CultMeshSubscriptionEvent, MemberRows, NoMembersReason, + RowChange, +}; 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, + CultNetErrorCode, CultNetMessage, CultNetRudpSocketMode, CultNetRudpSocketTransportConnection, + CultNetRudpSocketTransportOptions, CultNetSchemaDescriptor, CultNetSchemaKind, CultNetSchemaMember, CultNetWireContract, + DatabaseChangeKind, Selection, decode_cultnet_message_from_slice, decode_rudp_packet, encode_cultnet_message_to_vec, }; use pretty_assertions::assert_eq; use std::net::{SocketAddr, UdpSocket}; @@ -159,6 +162,22 @@ fn options(peer: &Peer) -> CultMeshRudpSubscriptionOptions { options } +/// Options for a test that ends the session. The peer's goodbye is one unreliable datagram that may never arrive, so +/// `Disconnected` must come either from it or from the client's own idle timeout, which these options make short. +fn options_ending_sessions(peer: &Peer) -> CultMeshRudpSubscriptionOptions { + let mut options = options(peer); + options.keepalive_interval = Duration::from_millis(100); + options.idle_timeout = Duration::from_millis(800); + options +} + +fn disconnect_reason(event: &CultMeshSubscriptionEvent) -> &str { + match event { + CultMeshSubscriptionEvent::Disconnected { reason } => reason, + other => panic!("expected a disconnect, got {other:?}"), + } +} + /// The C#-written session, one message per entry: subscribe, snapshot, a single change, a two-change commit (two /// messages), a removal. fn session() -> Vec> { @@ -221,6 +240,117 @@ fn single_change(message_id: &str, subscription: &str) -> CultNetMessage { } } +/// The schema id and content hash every record of the vector names. +fn vector_schema() -> (String, String) { + match decode(&session()[1]) { + CultNetMessage::SnapshotResponseRawV1 { documents, .. } => { + let document = &documents.expect("the vector snapshot has documents")[0]; + (document.schema_id.clone(), document.schema_content_hash.clone().expect("the vector names a hash")) + } + other => panic!("{other:?}"), + } +} + +fn member(slot: u32, name: &str) -> CultNetSchemaMember { + CultNetSchemaMember { + slot, + name: name.into(), + type_name: "string".into(), + is_reference: false, + is_many: false, + target_schema_name: None, + is_name: slot == 0, + index_alias: None, + } +} + +fn vector_members() -> Vec { + vec![member(0, "id"), member(1, "title")] +} + +fn descriptor(schema_id: &str, hash: &str, members: Option>) -> CultNetSchemaDescriptor { + CultNetSchemaDescriptor { + schema_id: schema_id.into(), + kind: CultNetSchemaKind::DocumentPayload, + schema_version: None, + document_type: None, + title: None, + wire_contracts: vec![CultNetWireContract::CultNetSchemaV0], + content_hash: hash.into(), + schema_json: None, + members, + } +} + +/// The next message the peer receives, which must be a catalog request that asks for members: its id and schema ids. +fn catalog_request(peer: &Peer) -> (String, Vec) { + match peer.next() { + CultNetMessage::SchemaCatalogRequest { message_id, include_members, schema_ids, .. } => { + assert_eq!(include_members, Some(true)); + (message_id, schema_ids.expect("the request names the schemas it needs")) + } + other => panic!("expected a catalog request, got {other:?}"), + } +} + +fn answer_catalog(peer: &Peer, message_id: &str, schemas: Vec) { + peer.send(&CultNetMessage::SchemaCatalogResponse { message_id: message_id.into(), schemas }); +} + +/// Answers the next catalog request with the vector schema's rows. +fn serve_rows(peer: &Peer) { + let (message_id, ids) = catalog_request(peer); + let (schema_id, hash) = vector_schema(); + assert_eq!(ids, [schema_id.clone()]); + answer_catalog(peer, &message_id, vec![descriptor(&schema_id, &hash, Some(vector_members()))]); +} + +fn no_more_requests(peer: &Peer) { + assert!(peer.received.recv_timeout(Duration::from_millis(200)).is_err(), "no further request"); +} + +fn served(rows: Vec) -> MemberRows { + MemberRows::Served(rows.into()) +} + +/// A copy of the vector's first change message with its own id, naming `hash` when given. +fn change_naming(message_id: &str, hash: Option<&str>) -> CultNetMessage { + let mut message = decode(&session()[2]); + let CultNetMessage::DatabaseChangeRaw { message_id: id, document: Some(document), .. } = &mut message else { + panic!("{message:?}") + }; + *id = message_id.into(); + if let Some(hash) = hash { + document.schema_content_hash = Some(hash.into()); + } + message +} + +fn commit_rows(event: &CultMeshSubscriptionEvent) -> Vec<&MemberRows> { + match event { + CultMeshSubscriptionEvent::Commit { changes, .. } => { + changes.iter().map(|c| &c.record.as_ref().expect("a document").members).collect() + } + other => panic!("expected a commit, got {other:?}"), + } +} + +fn snapshot_rows(event: &CultMeshSubscriptionEvent) -> Vec<&MemberRows> { + match event { + CultMeshSubscriptionEvent::Snapshot { documents, .. } => documents.iter().map(|d| &d.members).collect(), + other => panic!("expected a snapshot, got {other:?}"), + } +} + +/// Subscribes, answers the snapshot and returns once the client has delivered it with its rows served. +fn subscribed(peer: &Peer, client: &CultMeshRudpSubscriptionClient) { + client.subscribe("sub-1", vector_selection()).unwrap(); + let (message_id, _) = peer.subscribe_id(); + peer.send(&snapshot_answering(&message_id)); + serve_rows(peer); + assert_eq!(drain_events(client, 1).len(), 1); +} + /// 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); @@ -240,8 +370,8 @@ fn quiet(client: &CultMeshRudpSubscriptionClient) { fn keys(event: &CultMeshSubscriptionEvent) -> Vec<&str> { match event { - CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Commit { changes, .. }) => { - changes.iter().map(|Change { record_key, .. }| record_key.as_str()).collect() + CultMeshSubscriptionEvent::Commit { changes, .. } => { + changes.iter().map(|RowChange { record_key, .. }| record_key.as_str()).collect() } other => panic!("expected a commit, got {other:?}"), } @@ -249,7 +379,7 @@ fn keys(event: &CultMeshSubscriptionEvent) -> Vec<&str> { fn faulted(event: &CultMeshSubscriptionEvent) -> &str { match event { - CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Faulted { reason }) => reason, + CultMeshSubscriptionEvent::Faulted { reason } => reason, other => panic!("expected a fault, got {other:?}"), } } @@ -279,13 +409,19 @@ fn the_vector_session_yields_a_snapshot_two_commits_and_a_removal_in_order() { for bytes in session().into_iter().skip(2) { peer.send_raw(bytes); } + serve_rows(&peer); let events = drain_events(&client, 4); - let CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { subscription_id, documents }) = &events[0] - else { - panic!("{events:?}") - }; + let CultMeshSubscriptionEvent::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!(documents.iter().map(|d| d.document.record_key.as_str()).collect::>(), ["a", "b"]); + // Rows joined: every snapshot document and every changed document carries the catalog's rows. + assert_eq!(snapshot_rows(&events[0]), [&served(vector_members()), &served(vector_members())]); + assert_eq!(commit_rows(&events[1]), [&served(vector_members())]); + assert_eq!(commit_rows(&events[2]), [&served(vector_members()), &served(vector_members())]); + let CultMeshSubscriptionEvent::Commit { changes, .. } = &events[3] else { panic!("{events:?}") }; + assert_eq!(changes[0].record, None, "a removal has no document and so no rows"); + // One request served the whole session: the rows are cached by (schema id, hash). + no_more_requests(&peer); assert_eq!(keys(&events[1]), ["c"]); assert_eq!(keys(&events[2]), ["a", "b"]); assert_eq!(keys(&events[3]), ["c"]); @@ -303,6 +439,7 @@ fn a_sixty_fifth_incomplete_commit_faults_then_nothing_and_resubscribe_all_snaps for (message_id, _) in &first { peer.send(&snapshot_answering(message_id)); } + serve_rows(&peer); assert_eq!(drain_events(&client, 2).len(), 2); for index in 0..65 { peer.send(&change_part(&format!("m{index}"), "one", &format!("c{index}"))); @@ -321,7 +458,8 @@ fn a_sixty_fifth_incomplete_commit_faults_then_nothing_and_resubscribe_all_snaps peer.send(&snapshot_answering(message_id)); } let events = drain_events(&client, 2); - assert!(events.iter().all(|e| matches!(e, CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { .. })))); + assert!(events.iter().all(|e| matches!(e, CultMeshSubscriptionEvent::Snapshot { .. }))); + no_more_requests(&peer); } #[test] @@ -373,25 +511,21 @@ fn an_error_for_something_else_leaves_the_subscription_alone() { 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)); + serve_rows(&peer); let events = drain_events(&client, 1); - assert!(matches!(&events[0], CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { .. }))); + assert!(matches!(&events[0], CultMeshSubscriptionEvent::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); + let client = CultMeshRudpSubscriptionClient::connect(options_ending_sessions(&peer)).unwrap(); + subscribed(&peer, &client); peer.disconnect(); let events = drain_events(&client, 1); - assert!( - matches!(&events[0], CultMeshSubscriptionEvent::Disconnected { reason } if reason.contains("scripted-goodbye")), - "{events:?}" - ); + let reason = disconnect_reason(&events[0]); + assert!(reason.contains("scripted-goodbye") || reason.contains("no packet"), "{events:?}"); quiet(&client); // A subscribe while disconnected is kept, not lost and not a hang. client.subscribe("late", vector_selection()).unwrap(); @@ -410,7 +544,7 @@ fn the_peer_going_away_is_one_disconnected_and_resubscribe_all_reconnects() { #[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); + let mut options = options_ending_sessions(&peer); options.connect_timeout = Duration::from_millis(200); let client = CultMeshRudpSubscriptionClient::connect(options).unwrap(); client.subscribe("sub-1", vector_selection()).unwrap(); @@ -436,19 +570,14 @@ fn dropping_the_client_unsubscribes_each_live_id_and_stops_its_thread() { // 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 pump = client.pump_liveness(); + assert!(pump.upgrade().is_some(), "the pump thread runs while its handle lives"); let started = Instant::now(); - drop(client); - assert!(started.elapsed() < Duration::from_secs(2), "drop joins promptly"); + assert!(client.close(), "a live peer acknowledges the unsubscribe"); + assert!(started.elapsed() < Duration::from_secs(2), "close returns 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"); - } -} - -fn thread_count() -> usize { - std::fs::read_dir("/proc/self/task").map(|tasks| tasks.count()).unwrap_or(usize::MAX) + assert!(pump.upgrade().is_none(), "the pump thread is gone with its handle"); } #[test] @@ -460,13 +589,14 @@ fn what_the_caller_leaves_undrained_is_bounded_and_past_it_the_subscription_faul client.subscribe("sub-1", vector_selection()).unwrap(); let (message_id, _) = peer.subscribe_id(); peer.send(&snapshot_answering(&message_id)); // two documents + serve_rows(&peer); 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!(matches!(&events[0], CultMeshSubscriptionEvent::Snapshot { .. })); assert_eq!(keys(&events[1]), ["k"]); assert_eq!( faulted(&events[2]), @@ -478,7 +608,7 @@ fn what_the_caller_leaves_undrained_is_bounded_and_past_it_the_subscription_faul 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 { .. }))); + assert!(matches!(&drain_events(&client, 1)[0], CultMeshSubscriptionEvent::Snapshot { .. })); } struct Csharp { @@ -532,14 +662,14 @@ impl Drop for Csharp { } fn is_snapshot(event: &CultMeshSubscriptionEvent) -> bool { - matches!(event, CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { subscription_id, .. }) if subscription_id == "live") + matches!(event, CultMeshSubscriptionEvent::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()), + CultMeshSubscriptionEvent::Commit { changes, .. } => Some(changes.len()), _ => None, }) .collect() @@ -579,6 +709,13 @@ fn live_csharp_subscription() { 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:?}"); + // Every record arrives with the member rows the C# catalog serves for its schema, so it decodes by name. + for event in events.iter().filter(|e| matches!(e, CultMeshSubscriptionEvent::Commit { .. })) { + for rows in commit_rows(event) { + let names: Vec<_> = rows.rows().unwrap_or_else(|| panic!("no rows: {rows:?}")).iter().map(|m| m.name.as_str()).collect(); + assert_eq!(names, ["Text"], "{events:?}"); + } + } csharp.kill(); let started = Instant::now(); @@ -615,7 +752,8 @@ fn a_silent_peer_is_disconnected_after_the_idle_timeout_and_resubscribe_all_hand 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 { .. }))); + serve_rows(&peer); + assert!(matches!(&drain_events(&client, 1)[0], CultMeshSubscriptionEvent::Snapshot { .. })); } /// A live peer's pongs keep a quiet session open past the idle timeout. @@ -631,3 +769,377 @@ fn a_quiet_but_live_peer_is_not_disconnected() { thread::sleep(Duration::from_millis(1200)); assert_eq!(client.try_drain(), vec![]); } + +#[test] +fn an_unseen_content_hash_holds_later_events_behind_one_catalog_request_and_releases_them_in_order() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap(); + subscribed(&peer, &client); + let (schema_id, _) = vector_schema(); + let other_rows = vec![member(0, "id"), member(1, "title"), member(2, "added")]; + + peer.send(&change_naming("known", None)); + assert_eq!(commit_rows(&drain_events(&client, 1)[0]), [&served(vector_members())], "known rows deliver at once"); + no_more_requests(&peer); + + peer.send(&change_naming("held-new", Some("hash-two"))); + peer.send(&change_naming("held-old", None)); + peer.send(&change_naming("held-new-again", Some("hash-two"))); + let (message_id, ids) = catalog_request(&peer); + assert_eq!(ids, [schema_id.clone()]); + quiet(&client); + no_more_requests(&peer); + + answer_catalog(&peer, &message_id, vec![descriptor(&schema_id, "hash-two", Some(other_rows.clone()))]); + let events = drain_events(&client, 3); + // Arrival order, each with the rows of its own hash; the first hash's rows were not re-requested. + assert_eq!(commit_rows(&events[0]), [&served(other_rows.clone())]); + assert_eq!(commit_rows(&events[1]), [&served(vector_members())]); + assert_eq!(commit_rows(&events[2]), [&served(other_rows)]); + no_more_requests(&peer); +} + +/// A server that answers a catalog request in one of the ways that leave a record without rows. +fn delivered_without_rows(answer: impl FnOnce(&Peer, &str, &str, &str)) -> (Vec, Peer) { + let peer = Peer::start(); + let mut options = options(&peer); + options.catalog_timeout = Duration::from_millis(300); + 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)); + let (request_id, _) = catalog_request(&peer); + let (schema_id, hash) = vector_schema(); + answer(&peer, &request_id, &schema_id, &hash); + let mut events = drain_events(&client, 1); + // The next record of that schema is settled the same way, without a second request. + peer.send(&change_naming("again", None)); + events.extend(drain_events(&client, 1)); + no_more_requests(&peer); + (events, peer) +} + +fn assert_absent(events: &[CultMeshSubscriptionEvent], reason: NoMembersReason) { + let absent = MemberRows::NoMembers(reason); + assert_eq!(snapshot_rows(&events[0]), [&absent, &absent], "documents arrive, never dropped: {events:?}"); + assert_eq!(commit_rows(&events[1]), [&absent]); +} + +#[test] +fn a_server_without_member_rows_yields_documents_with_a_stated_absence() { + // An old server: the descriptor has no `members`. + let (events, _peer) = delivered_without_rows(|peer, request, schema, hash| { + answer_catalog(peer, request, vec![descriptor(schema, hash, None)]); + }); + assert_absent(&events, NoMembersReason::MembersAbsent); + // The same, a server that answers `members: []`. + let (events, _peer) = delivered_without_rows(|peer, request, schema, hash| { + answer_catalog(peer, request, vec![descriptor(schema, hash, Some(vec![]))]); + }); + assert_absent(&events, NoMembersReason::MembersAbsent); +} + +#[test] +fn a_schema_the_catalog_lacks_or_serves_under_another_hash_is_a_stated_absence_not_a_guess() { + let (events, _peer) = delivered_without_rows(|peer, request, _, _| answer_catalog(peer, request, vec![])); + assert_absent(&events, NoMembersReason::NotInCatalog); + // Rows for another hash are never taken for this record's. + let (events, _peer) = delivered_without_rows(|peer, request, schema, _| { + answer_catalog(peer, request, vec![descriptor(schema, "some-other-hash", Some(vector_members()))]); + }); + assert_absent(&events, NoMembersReason::ContentHashDiffers { served: "some-other-hash".into() }); +} + +#[test] +fn a_refused_or_unanswered_catalog_request_releases_the_records_without_rows() { + let (events, _peer) = delivered_without_rows(|peer, request, _, _| { + peer.send(&CultNetMessage::ErrorV1 { + error: "CANARY-secret".into(), + code: None, + details: None, + message_id: Some(request.into()), + }); + }); + assert_absent(&events, NoMembersReason::CatalogRefused { detail: String::new() }); + let (events, _peer) = delivered_without_rows(|_, _, _, _| {}); + assert_absent(&events, NoMembersReason::CatalogTimedOut); +} + +#[test] +fn a_record_that_names_no_hash_is_delivered_without_rows_and_asks_for_nothing() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + let (message_id, _) = peer.subscribe_id(); + let mut snapshot = snapshot_answering(&message_id); + let CultNetMessage::SnapshotResponseRawV1 { documents, .. } = &mut snapshot else { panic!("{snapshot:?}") }; + documents.iter_mut().flatten().for_each(|d| d.schema_content_hash = None); + peer.send(&snapshot); + let absent = MemberRows::NoMembers(NoMembersReason::RecordNamesNoHash); + assert_eq!(snapshot_rows(&drain_events(&client, 1)[0]), [&absent, &absent]); + no_more_requests(&peer); +} + +#[test] +fn records_waiting_for_rows_when_the_session_ends_are_delivered_not_dropped() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options_ending_sessions(&peer)).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + let (message_id, _) = peer.subscribe_id(); + peer.send(&snapshot_answering(&message_id)); + catalog_request(&peer); + peer.disconnect(); + let events = drain_events(&client, 2); + let ended = MemberRows::NoMembers(NoMembersReason::SessionEnded); + assert_eq!(snapshot_rows(&events[0]), [&ended, &ended]); + assert!(matches!(&events[1], CultMeshSubscriptionEvent::Disconnected { .. }), "{events:?}"); +} + +#[test] +fn events_waiting_for_rows_count_toward_the_undrained_bound() { + 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, held: no answer comes + peer.send(&single_change("c1", "sub-1")); // three + peer.send(&single_change("c2", "sub-1")); // four: past the bound + let events = drain_events(&client, 1); + assert_eq!( + faulted(&events[0]), + "the consumer left more than 3 documents and changes undrained; drain, then resubscribe" + ); +} + +#[test] +fn only_the_answer_to_the_request_in_flight_releases_waiting_events() { + 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)); + let (request_id, _) = catalog_request(&peer); + let (schema_id, hash) = vector_schema(); + answer_catalog(&peer, "someone-elses-request", vec![descriptor(&schema_id, &hash, Some(vec![member(0, "stray")]))]); + quiet(&client); + answer_catalog(&peer, &request_id, vec![descriptor(&schema_id, &hash, Some(vector_members()))]); + assert_eq!(snapshot_rows(&drain_events(&client, 1)[0]), [&served(vector_members()), &served(vector_members())]); +} + +#[test] +fn an_unsubscribed_id_forgets_the_events_waiting_for_rows() { + 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)); + let (request_id, _) = catalog_request(&peer); + client.unsubscribe("sub-1").unwrap(); + assert!(matches!(peer.next(), CultNetMessage::DatabaseUnsubscribe { .. })); + let (schema_id, hash) = vector_schema(); + answer_catalog(&peer, &request_id, vec![descriptor(&schema_id, &hash, Some(vector_members()))]); + quiet(&client); +} + +#[test] +fn a_new_session_asks_again_for_rows_that_were_absent_but_keeps_the_rows_it_has() { + 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)); + let (request_id, _) = catalog_request(&peer); + let (schema_id, hash) = vector_schema(); + answer_catalog(&peer, &request_id, vec![descriptor(&schema_id, &hash, None)]); // an old server + assert_eq!(drain_events(&client, 1).len(), 1); + + // The server was upgraded: after resubscribing, the absence is not remembered. + client.resubscribe_all().unwrap(); + let (message_id, _) = peer.subscribe_id(); + peer.send(&snapshot_answering(&message_id)); + serve_rows(&peer); + assert_eq!(snapshot_rows(&drain_events(&client, 1)[0]), [&served(vector_members()), &served(vector_members())]); + + // Rows already held are kept across the resubscribe. + client.resubscribe_all().unwrap(); + let (message_id, _) = peer.subscribe_id(); + peer.send(&snapshot_answering(&message_id)); + assert_eq!(drain_events(&client, 1).len(), 1); + no_more_requests(&peer); +} + +/// Both ways a session ends. A peer's goodbye is one unreliable datagram: when it arrives the client says so at +/// once, however long its idle timeout; when it is lost (here: never sent) the client's own idle timeout ends the +/// session. Neither test needs the other's datagram. +#[test] +fn a_goodbye_that_arrives_ends_the_session_at_once() { + let peer = Peer::start(); + // A goodbye may be lost on a loaded host; the claim is that one which arrives is not waited out, so a lost one is + // tried again on a fresh session, and only five losses in a row fail. + for _ in 0..5 { + let mut options = options(&peer); + options.idle_timeout = Duration::from_secs(30); + let client = CultMeshRudpSubscriptionClient::connect(options).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + peer.subscribe_id(); + peer.disconnect(); + let deadline = Instant::now() + Duration::from_secs(2); + let mut events = Vec::new(); + while events.is_empty() && Instant::now() < deadline { + events = client.try_drain(); + thread::sleep(Duration::from_millis(5)); + } + if let Some(event) = events.first() { + assert!(disconnect_reason(event).contains("scripted-goodbye"), "{events:?}"); + return; + } + } + panic!("no goodbye arrived in five sessions"); +} + +#[test] +fn a_goodbye_that_never_arrives_is_the_idle_timeout() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options_ending_sessions(&peer)).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + peer.subscribe_id(); + peer.stall(); // the peer is gone and said nothing + let started = Instant::now(); + let events = drain_events(&client, 1); + assert!(disconnect_reason(&events[0]).contains("no packet"), "{events:?}"); + assert!(started.elapsed() >= Duration::from_millis(600), "not before the idle timeout: {:?}", started.elapsed()); +} + +/// A change of the vector naming another schema (and the hash of its own). +fn change_for_schema(message_id: &str, schema_id: &str) -> CultNetMessage { + let mut message = change_naming(message_id, None); + let CultNetMessage::DatabaseChangeRaw { document: Some(document), .. } = &mut message else { panic!("{message:?}") }; + document.schema_id = schema_id.into(); + message +} + +#[test] +fn unseen_schemas_behind_a_silent_peer_wait_one_timeout_not_one_each() { + let peer = Peer::start(); + let mut options = options(&peer); + options.catalog_timeout = Duration::from_millis(500); + let client = CultMeshRudpSubscriptionClient::connect(options).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + let (message_id, _) = peer.subscribe_id(); + let mut snapshot = snapshot_answering(&message_id); + let CultNetMessage::SnapshotResponseRawV1 { documents, .. } = &mut snapshot else { panic!("{snapshot:?}") }; + for (index, document) in documents.iter_mut().flatten().enumerate() { + document.schema_id = format!("schema-{index}"); + } + let started = Instant::now(); + peer.send(&snapshot); + peer.send(&change_for_schema("later", "schema-9")); + let (_, mut first) = catalog_request(&peer); + first.sort(); + assert_eq!(first, ["schema-0", "schema-1"], "one request lists every unseen schema of the event"); + let (_, second) = catalog_request(&peer); + assert_eq!(second, ["schema-9"], "a later unseen schema is asked for at once, not after the first times out"); + let events = drain_events(&client, 2); + assert!(started.elapsed() < Duration::from_millis(900), "{:?}", started.elapsed()); + let absent = MemberRows::NoMembers(NoMembersReason::CatalogTimedOut); + assert_eq!(snapshot_rows(&events[0]), [&absent, &absent]); + assert_eq!(commit_rows(&events[1]), [&absent]); +} + +#[test] +fn a_catalog_timeout_is_not_latched_a_later_record_asks_again() { + let peer = Peer::start(); + let mut options = options(&peer); + options.catalog_timeout = Duration::from_millis(300); + 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)); + catalog_request(&peer); // never answered + let absent = MemberRows::NoMembers(NoMembersReason::CatalogTimedOut); + assert_eq!(snapshot_rows(&drain_events(&client, 1)[0]), [&absent, &absent]); + // Within the backoff the pair is not asked for again. + peer.send(&change_naming("soon", None)); + assert_eq!(commit_rows(&drain_events(&client, 1)[0]), [&absent]); + no_more_requests(&peer); + // After it a record asks afresh, and the answer is served. + thread::sleep(Duration::from_millis(350)); + peer.send(&change_naming("after", None)); + serve_rows(&peer); + assert_eq!(commit_rows(&drain_events(&client, 1)[0]), [&served(vector_members())]); +} + +#[test] +fn an_error_for_another_request_does_not_release_events_waiting_for_rows() { + 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)); + let (request_id, _) = catalog_request(&peer); + peer.send(&CultNetMessage::ErrorV1 { error: "x".into(), code: None, details: None, message_id: Some("other".into()) }); + quiet(&client); + let (schema_id, hash) = vector_schema(); + answer_catalog(&peer, &request_id, vec![descriptor(&schema_id, &hash, Some(vector_members()))]); + assert_eq!(snapshot_rows(&drain_events(&client, 1)[0]), [&served(vector_members()), &served(vector_members())]); +} + +#[test] +fn unsubscribing_releases_the_weight_of_the_events_it_forgets() { + let peer = Peer::start(); + let mut options = options(&peer); + options.max_undrained = 3; + let client = CultMeshRudpSubscriptionClient::connect(options).unwrap(); + client.subscribe("one", vector_selection()).unwrap(); + let (message_id, _) = peer.subscribe_id(); + let mut snapshot = snapshot_answering(&message_id); + let CultNetMessage::SnapshotResponseRawV1 { .. } = &snapshot else { panic!() }; + peer.send(&snapshot); // two documents wait for rows + let (request_id, _) = catalog_request(&peer); + client.unsubscribe("one").unwrap(); + assert!(matches!(peer.next(), CultNetMessage::DatabaseUnsubscribe { .. })); + client.subscribe("two", vector_selection()).unwrap(); + let (message_id, _) = peer.subscribe_id(); + if let CultNetMessage::SnapshotResponseRawV1 { message_id: id, .. } = &mut snapshot { + *id = message_id; + } + peer.send(&snapshot); // two more: with the forgotten two still counted this would be four, past the bound + peer.send(&single_change("c", "two")); // three + let (schema_id, hash) = vector_schema(); + answer_catalog(&peer, &request_id, vec![descriptor(&schema_id, &hash, Some(vector_members()))]); + let events = drain_events(&client, 2); + assert!(matches!(&events[0], CultMeshSubscriptionEvent::Snapshot { subscription_id, .. } if subscription_id == "two"), "{events:?}"); + assert_eq!(keys(&events[1]), ["k"]); +} + +#[test] +fn close_waits_for_the_acknowledgement_and_says_when_it_does_not_come() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + peer.subscribe_id(); + peer.stall(); // reads nothing, acknowledges nothing + thread::sleep(Duration::from_millis(100)); // the peer thread has taken the stall before the client closes + let started = Instant::now(); + assert!(!client.close(), "no acknowledgement came"); + let waited = started.elapsed(); + assert!(waited >= Duration::from_millis(400), "close waited for the acknowledgement: {waited:?}"); + assert!(waited < Duration::from_secs(2), "and only a bounded time: {waited:?}"); +} + +#[test] +fn drop_does_not_wait_for_a_peer_that_acknowledges_nothing() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + peer.subscribe_id(); + peer.stall(); + thread::sleep(Duration::from_millis(100)); + let pump = client.pump_liveness(); + let started = Instant::now(); + drop(client); + assert!(started.elapsed() < Duration::from_millis(300), "{:?}", started.elapsed()); + assert!(pump.upgrade().is_none(), "the thread still stops"); +}