diff --git a/packages/cultmesh-rs/src/rudp_subscription.rs b/packages/cultmesh-rs/src/rudp_subscription.rs index bf745435..4ff7c7f5 100644 --- a/packages/cultmesh-rs/src/rudp_subscription.rs +++ b/packages/cultmesh-rs/src/rudp_subscription.rs @@ -13,15 +13,27 @@ //! 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. +//! +//! 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}; @@ -53,6 +65,9 @@ pub struct CultMeshRudpSubscriptionOptions { /// 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, + /// How long events wait for a catalog answer. Past it the records waiting on it are delivered with + /// [`NoMembersReason::CatalogTimedOut`]. + pub catalog_timeout: Duration, } impl CultMeshRudpSubscriptionOptions { @@ -67,14 +82,89 @@ 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 }, } @@ -82,13 +172,47 @@ pub enum CultMeshSubscriptionEvent { 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), + Self::Snapshot { documents, .. } => documents.len().max(1), + Self::Commit { changes, .. } => changes.len().max(1), _ => 1, } } } +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), @@ -118,6 +242,10 @@ impl CultMeshRudpSubscriptionClient { options, session: Some(session), assembler: SubscriptionAssembler::new(), + rows: BTreeMap::new(), + pending: VecDeque::new(), + pending_weight: 0, + awaiting: None, subscriptions: BTreeMap::new(), receipts: Vec::new(), epoch: super::fresh_rudp_connection_epoch(), @@ -196,6 +324,13 @@ struct Pump { /// `None` after the session ended: the pump reads nothing and waits for a command. session: Option, 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, + awaiting: Option, /// What `resubscribe_all` resends. The assembler owns what is live; it holds no selections. subscriptions: BTreeMap, receipts: Vec, @@ -236,12 +371,14 @@ 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); } @@ -293,6 +430,10 @@ impl Pump { } self.assembler.reset(); self.receipts.clear(); + self.pending.clear(); + self.pending_weight = 0; + self.awaiting = None; + self.rows.retain(|_, rows| rows.is_ok()); let ids: Vec<_> = self.subscriptions.keys().cloned().collect(); for id in ids { self.begin(&id); @@ -334,6 +475,9 @@ impl Pump { if failure.is_none() { failure = self.invalidated(); } + if failure.is_none() && self.awaiting.as_ref().is_some_and(|a| a.sent.elapsed() >= self.options.catalog_timeout) { + self.catalog_unanswered(NoMembersReason::CatalogTimedOut); + } if let Some(reason) = failure { self.disconnected(reason); } @@ -343,6 +487,18 @@ 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 } => { + if self.awaiting.as_ref().is_some_and(|a| a.message_id == message_id) { + self.catalog_answered(schemas); + } + return; + } + CultNetMessage::ErrorV1 { error, message_id: Some(id), .. } + if self.awaiting.as_ref().is_some_and(|a| a.message_id == id) => + { + let detail = recognised_refusal(&error); + return self.catalog_unanswered(NoMembersReason::CatalogRefused { 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,29 +506,150 @@ 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; + self.awaiting = None; 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.pending_weight += weight; + self.pending.push_back(event); + } + + /// Delivers pending events in order while their rows are known; at the first that needs rows not yet known, + /// sends one catalog request for what that event lacks and waits for its answer. + fn release(&mut self) { + while self.awaiting.is_none() { + let Some(front) = self.pending.front() else { return }; + let missing: BTreeSet = documents_of(front).into_iter().filter_map(|d| self.lookup(d).err()).collect(); + if !missing.is_empty() { + return self.request_catalog(missing); + } + 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 => 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 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); } + 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 = Some(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: every requested pair is settled, by its rows or by the stated reason it has none. + fn catalog_answered(&mut self, schemas: Vec) { + let Some(awaiting) = self.awaiting.take() else { return }; + 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(); + } + + /// No answer will come (refused, or too slow): every requested pair is settled as absent for this session. + fn catalog_unanswered(&mut self, reason: NoMembersReason) { + let Some(awaiting) = self.awaiting.take() else { return }; + for key in awaiting.keys { + self.rows.insert(key, Err(reason.clone())); + } + 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(); + } + if self.pending.is_empty() { + self.awaiting = None; + } + } + fn push(&self, event: CultMeshSubscriptionEvent) { self.undrained.fetch_add(event.weight(), Ordering::SeqCst); let _ = self.events.send(event); @@ -412,6 +689,12 @@ impl Pump { fn disconnected(&mut self, reason: String) { if self.session.take().is_some() { self.receipts.clear(); + self.awaiting = None; + // 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 }); } } diff --git a/packages/cultmesh-rs/tests/rudp_subscription.rs b/packages/cultmesh-rs/tests/rudp_subscription.rs index c65bc005..39c14528 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}; @@ -221,6 +224,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 +354,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 +363,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 +393,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 +423,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 +442,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,18 +495,16 @@ 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); + subscribed(&peer, &client); peer.disconnect(); let events = drain_events(&client, 1); @@ -460,13 +580,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 +599,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 +653,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 +700,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 +743,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 +760,146 @@ 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(&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" + ); +}