From 911c3b8a0eb3995f37d303d08452b46f1b79ba7c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 04:35:10 +0100 Subject: [PATCH] cultnet-rs: typed database_change_raw.v0 and database_unsubscribe.v0, and a transport-free SubscriptionAssembler with the C# client's commit bound and fault Co-Authored-By: Claude Sonnet 5.5 --- packages/cultnet-rs/src/contracts.rs | 137 ++++++++ packages/cultnet-rs/src/lib.rs | 2 + packages/cultnet-rs/src/subscription.rs | 239 +++++++++++++ .../tests/database_change_commit_vector.rs | 60 ++-- packages/cultnet-rs/tests/subscription.rs | 320 ++++++++++++++++++ 5 files changed, 734 insertions(+), 24 deletions(-) create mode 100644 packages/cultnet-rs/src/subscription.rs create mode 100644 packages/cultnet-rs/tests/subscription.rs diff --git a/packages/cultnet-rs/src/contracts.rs b/packages/cultnet-rs/src/contracts.rs index bf907806..93190264 100644 --- a/packages/cultnet-rs/src/contracts.rs +++ b/packages/cultnet-rs/src/contracts.rs @@ -440,6 +440,31 @@ pub enum CultNetMessage { #[serde(default, skip_serializing_if = "Option::is_none")] supported_body_transports: Option>, }, + /// Mirrors `CultNetDatabaseUnsubscribeMessage`. + #[serde(rename = "cultnet.database_unsubscribe.v0", rename_all = "camelCase")] + DatabaseUnsubscribe { + message_id: String, + subscription_id: String, + }, + /// One change of a live subscription. Mirrors `CultNetDatabaseChangeRawMessage`: the writer + /// sends every key, nil where unset; the decoder refuses what the reference's receiver + /// refuses (see `validate_message`). + #[serde(rename = "cultnet.database_change_raw.v0", rename_all = "camelCase")] + DatabaseChangeRaw { + message_id: String, + subscription_id: String, + change_kind: DatabaseChangeKind, + #[serde(default)] + document: Option, + #[serde(default)] + record_key: Option, + #[serde(default)] + schema_id: Option, + #[serde(default)] + commit_id: Option, + #[serde(default)] + commit_count: Option, + }, /// `cultnet.snapshot_response_raw.v1` (section 2: `SelectionPage`). Decoded by the derive from /// the message bytes in one pass (rows and scalars, a duplicated key refused); encoded by /// `encode_raw_cultnet_schema_message` for the reference's fixed nil-keyed shape. Mirrors @@ -552,6 +577,25 @@ fn messagepack_base64_encoding() -> String { "messagepack-base64".to_string() } +/// The `changeKind` of a `cultnet.database_change_raw.v0` message. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum DatabaseChangeKind { + Added, + Updated, + Removed, +} + +impl DatabaseChangeKind { + fn wire(self) -> &'static str { + match self { + Self::Added => "added", + Self::Updated => "updated", + Self::Removed => "removed", + } + } +} + fn true_default() -> bool { true } @@ -566,6 +610,8 @@ pub fn encode_cultnet_message_for_wire( CultNetMessage::DocumentPutRaw { .. } | CultNetMessage::SnapshotResponseRaw { .. } | CultNetMessage::SnapshotResponseRawV1 { .. } + | CultNetMessage::DatabaseChangeRaw { .. } + | CultNetMessage::DatabaseUnsubscribe { .. } | CultNetMessage::ContentChunkRequest { .. } | CultNetMessage::ContentChunkResponse { .. } | CultNetMessage::Error { .. } @@ -754,6 +800,60 @@ fn validate_message(message: &CultNetMessage) -> Result<()> { "supportedBodyTransports", )?; } + CultNetMessage::DatabaseUnsubscribe { message_id, subscription_id } => { + require_non_empty(message_id, "messageId")?; + require_non_empty(subscription_id, "subscriptionId")?; + } + CultNetMessage::DatabaseChangeRaw { + message_id, + subscription_id, + change_kind, + document, + record_key, + schema_id, + commit_id, + commit_count, + } => { + require_non_empty(message_id, "messageId")?; + require_non_empty(subscription_id, "subscriptionId")?; + match change_kind { + DatabaseChangeKind::Removed => { + if record_key.as_deref().is_none_or(|key| key.is_empty()) + || schema_id.as_deref().is_none_or(|id| id.is_empty()) + { + return Err(anyhow!( + "CultNet database change 'removed' must carry recordKey and schemaId" + )); + } + } + DatabaseChangeKind::Added | DatabaseChangeKind::Updated => { + if document.is_none() { + return Err(anyhow!( + "CultNet database change '{}' must carry a document", + change_kind.wire() + )); + } + } + } + match (commit_id.as_deref(), commit_count) { + (None, None) => {} + (Some(id), Some(count)) => { + if id.is_empty() { + return Err(anyhow!("CultNet field commitId must be non-empty")); + } + if *count < 2 { + return Err(anyhow!( + "CultNet field commitCount must be at least 2, received {count}" + )); + } + } + _ => { + return Err(anyhow!( + "CultNet fields commitId and commitCount are set together or not at all" + )); + } + } + } CultNetMessage::SnapshotResponseRawV1 { message_id, matched: _, @@ -1286,6 +1386,43 @@ fn encode_raw_cultnet_schema_message(message: &CultNetMessage) -> Result vec![ + (rmpv::Value::from("schemaVersion"), rmpv::Value::from("cultnet.database_unsubscribe.v0")), + (rmpv::Value::from("messageId"), rmpv::Value::from(message_id.as_str())), + (rmpv::Value::from("subscriptionId"), rmpv::Value::from(subscription_id.as_str())), + ], + // The C# writer's key order, every key present, nil where unset. + CultNetMessage::DatabaseChangeRaw { + message_id, + subscription_id, + change_kind, + document, + record_key, + schema_id, + commit_id, + commit_count, + } => { + let text = |value: &Option| { + value.as_deref().map(rmpv::Value::from).unwrap_or(rmpv::Value::Nil) + }; + vec![ + (rmpv::Value::from("schemaVersion"), rmpv::Value::from("cultnet.database_change_raw.v0")), + (rmpv::Value::from("messageId"), rmpv::Value::from(message_id.as_str())), + (rmpv::Value::from("subscriptionId"), rmpv::Value::from(subscription_id.as_str())), + (rmpv::Value::from("changeKind"), rmpv::Value::from(change_kind.wire())), + ( + rmpv::Value::from("document"), + document.as_ref().map(encode_typed).unwrap_or(rmpv::Value::Nil), + ), + (rmpv::Value::from("recordKey"), text(record_key)), + (rmpv::Value::from("schemaId"), text(schema_id)), + (rmpv::Value::from("commitId"), text(commit_id)), + ( + rmpv::Value::from("commitCount"), + commit_count.map(rmpv::Value::from).unwrap_or(rmpv::Value::Nil), + ), + ] + } CultNetMessage::ContentChunkRequest { message_id, chunk_hash, diff --git a/packages/cultnet-rs/src/lib.rs b/packages/cultnet-rs/src/lib.rs index e008a2ba..59a95726 100644 --- a/packages/cultnet-rs/src/lib.rs +++ b/packages/cultnet-rs/src/lib.rs @@ -21,6 +21,7 @@ mod schema_discovery; mod security; mod selection; mod shard_catalog; +mod subscription; mod transport; pub use content::*; @@ -45,4 +46,5 @@ pub use schema_discovery::*; pub use security::*; pub use selection::*; pub use shard_catalog::*; +pub use subscription::*; pub use transport::*; diff --git a/packages/cultnet-rs/src/subscription.rs b/packages/cultnet-rs/src/subscription.rs new file mode 100644 index 00000000..f429c1e7 --- /dev/null +++ b/packages/cultnet-rs/src/subscription.rs @@ -0,0 +1,239 @@ +//! The subscriber's side of `cultnet.database_subscribe.v1`, with no transport, clock or threads: it is fed decoded +//! messages and returns events. It mirrors `CultNetDatabaseSubscriptionClient.HandleChange` (commit assembly, the +//! buffer bound, the fault) so that a driver cannot decide commit completeness, bounds or fault itself. + +use crate::{CultNetMessage, DatabaseChangeKind, SelectionDocumentRecord}; +use anyhow::{Result, anyhow}; +use std::collections::{HashMap, HashSet}; + +/// The most commits that may be incomplete at once (`MaxPendingCommits` in the C# client). +pub const MAX_PENDING_COMMITS: usize = 64; +/// The most changes the incomplete commits may announce between them (`MaxBufferedChanges` in the C# client). +pub const MAX_BUFFERED_CHANGES: u64 = 1_000_000; + +/// One record change. `record_key` and `schema_id` are the document's for added and updated changes, the message's +/// for removed ones; `document` is `None` for a removal. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Change { + pub kind: DatabaseChangeKind, + pub record_key: String, + pub schema_id: String, + pub document: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum SubscriptionEvent { + /// The answer to a subscribe the driver began. + Snapshot { subscription_id: String, documents: Vec }, + /// One change, or every change of one commit in arrival order; a partial commit is never emitted. + Commit { subscription_id: String, changes: Vec }, + /// The connection's replica no longer matches its source. Nothing more is emitted until `reset`. + Faulted { reason: String }, +} + +struct PendingCommit { + announced: u32, + ids: HashSet, + changes: Vec, +} + +#[derive(Default)] +struct Subscription { + snapshotted: bool, + /// Complete commits that arrived before the snapshot, in arrival order. + waiting: Vec>, +} + +/// The one owner of subscription state for a connection. +#[derive(Default)] +pub struct SubscriptionAssembler { + outstanding: HashMap, + subscriptions: HashMap, + commits: HashMap<(String, String), PendingCommit>, + fault: Option, +} + +impl SubscriptionAssembler { + pub fn new() -> Self { + Self::default() + } + + /// Records a subscribe the driver sent. Refused once faulted, and for a message id already outstanding. + pub fn begin(&mut self, subscription_id: &str, message_id: &str) -> Result<()> { + if self.fault.is_some() { + return Err(anyhow!( + "the replica refused a commit and differs from its source; reset before subscribing" + )); + } + if self.outstanding.contains_key(message_id) { + return Err(anyhow!("Duplicate database subscription message id '{message_id}'.")); + } + self.outstanding.insert(message_id.to_owned(), subscription_id.to_owned()); + self.subscriptions.entry(subscription_id.to_owned()).or_default(); + Ok(()) + } + + /// Forgets a subscription and evicts its buffered commits. + pub fn end(&mut self, subscription_id: &str) { + self.subscriptions.remove(subscription_id); + self.outstanding.retain(|_, id| id != subscription_id); + self.commits.retain(|(id, _), _| id != subscription_id); + } + + /// Clears every subscription and the fault. + pub fn reset(&mut self) { + *self = Self::default(); + } + + pub fn fault(&self) -> Option<&str> { + self.fault.as_deref() + } + + /// Feeds one decoded message. Messages that are not a snapshot response or a change (an error, a hello) are + /// not this assembler's and return nothing. + pub fn accept(&mut self, message: CultNetMessage) -> Vec { + if self.fault.is_some() { + return Vec::new(); + } + match message { + CultNetMessage::SnapshotResponseRawV1 { message_id, documents, .. } => { + self.snapshot(&message_id, documents.unwrap_or_default()) + } + CultNetMessage::DatabaseChangeRaw { + message_id, + subscription_id, + change_kind, + document, + record_key, + schema_id, + commit_id, + commit_count, + } => { + let change = Change { + kind: change_kind, + record_key: document + .as_ref() + .map(|document| document.record_key.clone()) + .or(record_key) + .unwrap_or_default(), + schema_id: document + .as_ref() + .map(|document| document.schema_id.clone()) + .or(schema_id) + .unwrap_or_default(), + document, + }; + self.change(message_id, subscription_id, change, commit_id, commit_count) + } + _ => Vec::new(), + } + } + + fn snapshot(&mut self, message_id: &str, documents: Vec) -> Vec { + let Some(subscription_id) = self.outstanding.remove(message_id) else { + return Vec::new(); + }; + let Some(subscription) = self.subscriptions.get_mut(&subscription_id) else { + return Vec::new(); + }; + subscription.snapshotted = true; + let mut events = vec![SubscriptionEvent::Snapshot { subscription_id: subscription_id.clone(), documents }]; + events.extend(subscription.waiting.drain(..).map(|changes| SubscriptionEvent::Commit { + subscription_id: subscription_id.clone(), + changes, + })); + events + } + + fn change( + &mut self, + message_id: String, + subscription_id: String, + change: Change, + commit_id: Option, + commit_count: Option, + ) -> Vec { + // A straggler of a subscription that was ended, or never made, is not buffered. + if !self.subscriptions.contains_key(&subscription_id) { + return Vec::new(); + } + let complete = match (commit_id, commit_count) { + (Some(commit_id), Some(count)) if count > 1 => { + match self.add_to_commit(&subscription_id, commit_id, count, message_id, change) { + Ok(Some(complete)) => complete, + Ok(None) => return Vec::new(), + Err(refusal) => { + return self.fault_with(format!("CultNet subscription '{subscription_id}': {refusal}.")); + } + } + } + _ => vec![change], + }; + let subscription = self.subscriptions.get_mut(&subscription_id).expect("checked live above"); + if subscription.snapshotted { + vec![SubscriptionEvent::Commit { subscription_id, changes: complete }] + } else { + subscription.waiting.push(complete); + Vec::new() + } + } + + /// Adds one part; returns the whole commit once its last part arrives, a refusal text when a bound or a + /// consistency check fails. The buffered total is derived from the announced counts of the incomplete commits. + fn add_to_commit( + &mut self, + subscription_id: &str, + commit_id: String, + count: u32, + message_id: String, + change: Change, + ) -> std::result::Result>, String> { + let held = (subscription_id.to_owned(), commit_id); + match self.commits.get(&held) { + None => { + if self.commits.len() >= MAX_PENDING_COMMITS { + return Err(format!("more than {MAX_PENDING_COMMITS} commits are incomplete at once")); + } + let announced: u64 = self.commits.values().map(|commit| u64::from(commit.announced)).sum(); + if u64::from(count) + announced > MAX_BUFFERED_CHANGES { + return Err(format!( + "commit '{}' announces {count} changes; the incomplete commits may announce {MAX_BUFFERED_CHANGES} between them", + held.1 + )); + } + } + Some(pending) => { + if pending.announced != count { + return Err(format!( + "commit '{}' announces {} and {count} changes", + held.1, pending.announced + )); + } + if pending.ids.contains(&message_id) { + return Err(format!("commit '{}' delivered message '{message_id}' twice", held.1)); + } + } + } + let pending = self.commits.entry(held.clone()).or_insert_with(|| PendingCommit { + announced: count, + ids: HashSet::new(), + changes: Vec::new(), + }); + pending.ids.insert(message_id); + pending.changes.push(change); + if pending.changes.len() < count as usize { + return Ok(None); + } + Ok(self.commits.remove(&held).map(|commit| commit.changes)) + } + + /// The one fault path: drop what was waiting, latch, say so once. + fn fault_with(&mut self, reason: String) -> Vec { + self.commits.clear(); + for subscription in self.subscriptions.values_mut() { + subscription.waiting.clear(); + } + self.fault = Some(reason.clone()); + vec![SubscriptionEvent::Faulted { reason }] + } +} diff --git a/packages/cultnet-rs/tests/database_change_commit_vector.rs b/packages/cultnet-rs/tests/database_change_commit_vector.rs index 322227dc..a1f1eea5 100644 --- a/packages/cultnet-rs/tests/database_change_commit_vector.rs +++ b/packages/cultnet-rs/tests/database_change_commit_vector.rs @@ -1,43 +1,55 @@ //! `tests/vectors/database-change-commit/two-change-commit.msgpack` is written only by the C# reference: two -//! `cultnet.database_change_raw.v0` messages of one commit, every key present, nil where unset. cultnet-rs has no typed -//! `database_change_raw` message yet, so this walks the stream with the same `rmpv` values its wire decoder builds on and -//! pins the keys and values a Rust adopter will read. A rename of `commitId` or `commitCount` in the C# writer fails here. +//! `cultnet.database_change_raw.v0` messages of one commit, every key present, nil where unset. This decodes each into +//! the typed message and re-encodes it to the same bytes, so a rename of `commitId` or `commitCount` in the C# writer, or +//! a drift in the Rust writer's key order, fails here. -use rmpv::Value; +use cultnet_rs::*; +use serde::Deserialize; use std::io::Cursor; -fn messages() -> Vec { +/// The stream's messages as byte slices, split by skipping one value at a time. +fn messages() -> Vec> { let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/vectors/database-change-commit/two-change-commit.msgpack"); let bytes = std::fs::read(path).expect("the vector is committed"); let mut cursor = Cursor::new(bytes.as_slice()); let mut out = Vec::new(); while (cursor.position() as usize) < bytes.len() { - out.push(rmpv::decode::read_value(&mut cursor).expect("a msgpack value")); + let start = cursor.position() as usize; + let mut de = rmp_serde::Deserializer::new(&mut cursor); + serde::de::IgnoredAny::deserialize(&mut de).expect("a msgpack value"); + out.push(bytes[start..cursor.position() as usize].to_vec()); } out } -fn field<'a>(message: &'a Value, key: &str) -> &'a Value { - message - .as_map() - .and_then(|entries| entries.iter().find(|(k, _)| k.as_str() == Some(key))) - .map(|(_, v)| v) - .unwrap_or_else(|| panic!("the C# writer wrote no key {key}")) -} - #[test] -fn a_two_change_commit_written_by_csharp_carries_its_commit_id_count_and_changes() { +fn a_two_change_commit_written_by_csharp_decodes_typed_and_re_encodes_byte_for_byte() { let messages = messages(); assert_eq!(messages.len(), 2); - for message in &messages { - assert_eq!(field(message, "schemaVersion").as_str(), Some("cultnet.database_change_raw.v0")); - assert_eq!(field(message, "commitId").as_str(), Some("9f1c0f0e4b7a4c1f9d2e")); - assert_eq!(field(message, "commitCount").as_u64(), Some(2)); - assert_eq!(field(message, "changeKind").as_str(), Some("removed")); - assert_eq!(field(message, "subscriptionId").as_str(), Some("sub-1")); - assert_eq!(field(message, "schemaId").as_str(), Some("schema-note")); - assert!(field(message, "document").is_nil(), "a removed change's document is nil"); + let mut keys = Vec::new(); + for bytes in &messages { + let message = decode_cultnet_message_from_slice(bytes, CultNetWireContract::CultNetSchemaV0).unwrap(); + let CultNetMessage::DatabaseChangeRaw { + subscription_id, + change_kind, + document, + record_key, + schema_id, + commit_id, + commit_count, + .. + } = &message + else { + panic!("expected database_change_raw, got {message:?}"); + }; + assert_eq!(subscription_id, "sub-1"); + assert_eq!(*change_kind, DatabaseChangeKind::Removed); + assert_eq!(schema_id.as_deref(), Some("schema-note")); + assert_eq!(commit_id.as_deref(), Some("9f1c0f0e4b7a4c1f9d2e")); + assert_eq!(*commit_count, Some(2)); + assert!(document.is_none(), "a removed change's document is nil"); + keys.push(record_key.clone().unwrap()); + assert_eq!(&encode_cultnet_message_to_vec(&message, CultNetWireContract::CultNetSchemaV0).unwrap(), bytes); } - let keys: Vec<_> = messages.iter().map(|m| field(m, "recordKey").as_str().unwrap().to_string()).collect(); assert_eq!(keys, ["note:a", "note:b"]); } diff --git a/packages/cultnet-rs/tests/subscription.rs b/packages/cultnet-rs/tests/subscription.rs new file mode 100644 index 00000000..2175095e --- /dev/null +++ b/packages/cultnet-rs/tests/subscription.rs @@ -0,0 +1,320 @@ +//! The two subscription messages and the transport-free assembler. The bounds and faults mirror the C# client's +//! `HandleChange`; each has a test that fails without it. + +use cultnet_rs::*; +use rmpv::Value; + +fn s(text: &str) -> Value { + Value::from(text) +} + +fn decode(entries: Vec<(&str, Value)>) -> anyhow::Result { + let map = Value::Map(entries.into_iter().map(|(key, value)| (s(key), value)).collect()); + decode_cultnet_message_from_slice(&rmp_serde::to_vec(&map).unwrap(), CultNetWireContract::CultNetSchemaV0) +} + +fn removed(extra: Vec<(&str, Value)>) -> anyhow::Result { + let mut entries = vec![ + ("schemaVersion", s("cultnet.database_change_raw.v0")), + ("messageId", s("m1")), + ("subscriptionId", s("sub")), + ("changeKind", s("removed")), + ("recordKey", s("k")), + ("schemaId", s("note")), + ]; + entries.extend(extra); + decode(entries) +} + +fn error_text(result: anyhow::Result) -> String { + format!("{:#}", result.expect_err("the decoder refuses this")) +} + +fn record(key: &str) -> SelectionDocumentRecord { + SelectionDocumentRecord { + schema_id: "note".into(), + schema_name: None, + schema_version: None, + schema_content_hash: None, + record_key: key.into(), + stored_at: "2026-11-28T00:00:00Z".into(), + payload_encoding: "messagepack".into(), + payload: vec![0x90], + source_runtime_id: None, + source_agent_id: None, + source_role: None, + tags: None, + } +} + +fn change(message_id: &str, subscription: &str, key: &str, commit: Option<(&str, u32)>) -> CultNetMessage { + CultNetMessage::DatabaseChangeRaw { + message_id: message_id.into(), + subscription_id: subscription.into(), + change_kind: DatabaseChangeKind::Updated, + document: Some(record(key)), + record_key: None, + schema_id: None, + commit_id: commit.map(|(id, _)| id.into()), + commit_count: commit.map(|(_, count)| count), + } +} + +fn snapshot(message_id: &str, keys: &[&str]) -> CultNetMessage { + CultNetMessage::SnapshotResponseRawV1 { + message_id: message_id.into(), + matched: keys.len() as u32, + as_of: 1, + next: None, + headers: None, + documents: Some(keys.iter().map(|key| record(key)).collect()), + edges: None, + shard_id: None, + shard_epoch: None, + shard_log_sequence: None, + } +} + +fn live(subscription: &str) -> SubscriptionAssembler { + let mut assembler = SubscriptionAssembler::new(); + assembler.begin(subscription, &format!("begin-{subscription}")).unwrap(); + assert_eq!(assembler.accept(snapshot(&format!("begin-{subscription}"), &[])).len(), 1); + assembler +} + +fn keys(event: &SubscriptionEvent) -> Vec { + match event { + SubscriptionEvent::Commit { changes, .. } => changes.iter().map(|change| change.record_key.clone()).collect(), + other => panic!("expected a commit, got {other:?}"), + } +} + +fn faulted(events: &[SubscriptionEvent]) -> &str { + match events { + [SubscriptionEvent::Faulted { reason }] => reason, + other => panic!("expected one fault, got {other:?}"), + } +} + +#[test] +fn a_removal_unsubscribe_and_a_change_round_trip_in_the_writers_key_order() { + for message in [ + change("m", "sub", "k", Some(("c", 2))), + change("m", "sub", "k", None), + CultNetMessage::DatabaseUnsubscribe { message_id: "m".into(), subscription_id: "sub".into() }, + ] { + let bytes = encode_cultnet_message_to_vec(&message, CultNetWireContract::CultNetSchemaV0).unwrap(); + assert_eq!(decode_cultnet_message_from_slice(&bytes, CultNetWireContract::CultNetSchemaV0).unwrap(), message); + } +} + +#[test] +fn a_change_encodes_every_key_with_nil_where_unset() { + let value = encode_cultnet_message_for_wire(&change("m", "sub", "k", None), CultNetWireContract::CultNetSchemaV0).unwrap(); + let keys: Vec<_> = value.as_map().unwrap().iter().map(|(key, _)| key.as_str().unwrap().to_string()).collect(); + assert_eq!( + keys, + ["schemaVersion", "messageId", "subscriptionId", "changeKind", "document", "recordKey", "schemaId", "commitId", "commitCount"] + ); + let nil: Vec<_> = value.as_map().unwrap().iter().filter(|(_, v)| v.is_nil()).map(|(k, _)| k.as_str().unwrap()).collect(); + assert_eq!(nil, ["recordKey", "schemaId", "commitId", "commitCount"]); +} + +#[test] +fn decode_refuses_an_added_or_updated_change_without_a_document() { + for kind in ["added", "updated"] { + let result = decode(vec![ + ("schemaVersion", s("cultnet.database_change_raw.v0")), + ("messageId", s("m")), + ("subscriptionId", s("sub")), + ("changeKind", s(kind)), + ("document", Value::Nil), + ]); + assert!(error_text(result).contains("must carry a document")); + } +} + +#[test] +fn decode_refuses_a_removal_without_record_key_or_schema_id() { + for dropped in ["recordKey", "schemaId"] { + let mut entries = vec![ + ("schemaVersion", s("cultnet.database_change_raw.v0")), + ("messageId", s("m")), + ("subscriptionId", s("sub")), + ("changeKind", s("removed")), + ("recordKey", s("k")), + ("schemaId", s("note")), + ]; + entries.retain(|(key, _)| *key != dropped); + assert!(error_text(decode(entries)).contains("recordKey and schemaId")); + } +} + +#[test] +fn decode_refuses_a_commit_count_below_two_an_empty_commit_id_and_a_half_set_pair() { + assert!(error_text(removed(vec![("commitId", s("c")), ("commitCount", Value::from(1))])).contains("commitCount")); + assert!(error_text(removed(vec![("commitId", s("")), ("commitCount", Value::from(2))])).contains("commitId")); + assert!(error_text(removed(vec![("commitCount", Value::from(2))])).contains("together")); + assert!(error_text(removed(vec![("commitId", s("c"))])).contains("together")); + removed(vec![("commitId", s("c")), ("commitCount", Value::from(2))]).expect("a well-formed commit part decodes"); +} + +#[test] +fn decode_refuses_a_duplicate_key_and_an_unknown_change_kind() { + let text = error_text(removed(vec![("recordKey", s("other"))])); assert!(text.contains("duplicate field"), "{text}"); + let result = decode(vec![ + ("schemaVersion", s("cultnet.database_change_raw.v0")), + ("messageId", s("m")), + ("subscriptionId", s("sub")), + ("changeKind", s("renamed")), + ]); + assert!(result.is_err()); +} + +#[test] +fn a_two_part_commit_is_one_commit_in_arrival_order_and_never_partial() { + let mut assembler = live("sub"); + assert!(assembler.accept(change("a", "sub", "k1", Some(("c", 2)))).is_empty(), "the first part is held"); + let events = assembler.accept(change("b", "sub", "k2", Some(("c", 2)))); + assert_eq!(events.len(), 1); + assert_eq!(keys(&events[0]), ["k1", "k2"]); +} + +#[test] +fn a_single_change_is_a_one_change_commit() { + let mut assembler = live("sub"); + let events = assembler.accept(change("a", "sub", "k1", None)); + assert_eq!(keys(&events[0]), ["k1"]); +} + +#[test] +fn a_removal_reports_the_messages_key_and_schema() { + let mut assembler = live("sub"); + let events = assembler.accept(removed(vec![]).unwrap()); + let SubscriptionEvent::Commit { changes, .. } = &events[0] else { panic!("{events:?}") }; + assert_eq!((changes[0].kind, changes[0].record_key.as_str(), changes[0].schema_id.as_str()), (DatabaseChangeKind::Removed, "k", "note")); + assert!(changes[0].document.is_none()); +} + +#[test] +fn the_sixty_fifth_incomplete_commit_faults_and_the_sixty_fourth_does_not() { + let mut assembler = live("sub"); + for index in 0..MAX_PENDING_COMMITS { + let id = format!("c{index}"); + assert!(assembler.accept(change(&format!("m{index}"), "sub", "k", Some((&id, 2)))).is_empty()); + } + let events = assembler.accept(change("overflow", "sub", "k", Some(("c-over", 2)))); + assert_eq!( + faulted(&events), + "CultNet subscription 'sub': more than 64 commits are incomplete at once." + ); + assert!(assembler.fault().is_some()); +} + +#[test] +fn announced_totals_up_to_the_bound_are_held_and_one_change_past_it_faults() { + let mut assembler = live("sub"); + assert!(assembler.accept(change("a", "sub", "k", Some(("one", 999_998)))).is_empty()); + assert!(assembler.accept(change("b", "sub", "k", Some(("two", 2)))).is_empty(), "exactly 1_000_000 is within the bound"); + assert!(assembler.fault().is_none()); + let events = assembler.accept(change("c", "sub", "k", Some(("three", 2)))); + assert_eq!( + faulted(&events), + "CultNet subscription 'sub': commit 'three' announces 2 changes; the incomplete commits may announce 1000000 between them." + ); +} + +#[test] +fn a_completed_commit_stops_counting_against_the_bound() { + let mut assembler = live("sub"); + assert!(assembler.accept(change("a", "sub", "k", Some(("one", 2)))).is_empty()); + assert_eq!(assembler.accept(change("b", "sub", "k", Some(("one", 2)))).len(), 1); + assert!(assembler.accept(change("c", "sub", "k", Some(("big", 1_000_000)))).is_empty()); + assert!(assembler.fault().is_none()); +} + +#[test] +fn a_commit_that_announces_two_different_counts_faults() { + let mut assembler = live("sub"); + assert!(assembler.accept(change("a", "sub", "k", Some(("c", 3)))).is_empty()); + let events = assembler.accept(change("b", "sub", "k", Some(("c", 2)))); + assert_eq!(faulted(&events), "CultNet subscription 'sub': commit 'c' announces 3 and 2 changes."); +} + +#[test] +fn a_message_id_delivered_twice_in_one_commit_faults() { + let mut assembler = live("sub"); + assert!(assembler.accept(change("a", "sub", "k", Some(("c", 3)))).is_empty()); + let events = assembler.accept(change("a", "sub", "k2", Some(("c", 3)))); + assert_eq!(faulted(&events), "CultNet subscription 'sub': commit 'c' delivered message 'a' twice."); +} + +#[test] +fn after_a_fault_accept_returns_nothing_until_reset_and_the_buffers_are_gone() { + let mut assembler = live("sub"); + assert!(assembler.accept(change("a", "sub", "k", Some(("c", 3)))).is_empty()); + assembler.accept(change("b", "sub", "k", Some(("c", 2)))); + assert!(assembler.accept(change("x", "sub", "k", None)).is_empty()); + assert!(assembler.begin("other", "m").is_err()); + assembler.reset(); + assert!(assembler.fault().is_none()); + // The old commit was dropped by the fault and the subscription by the reset. + assert!(assembler.accept(change("c3", "sub", "k", Some(("c", 3)))).is_empty()); + assembler.begin("sub", "again").unwrap(); + assert_eq!(assembler.accept(snapshot("again", &["r"])).len(), 1); + assert_eq!(keys(&assembler.accept(change("y", "sub", "k", None))[0]), ["k"]); +} + +#[test] +fn a_change_for_an_ended_or_never_begun_subscription_yields_nothing_and_is_not_buffered() { + let mut assembler = live("sub"); + assert!(assembler.accept(change("a", "ghost", "k", None)).is_empty()); + assert!(assembler.accept(change("b", "ghost", "k", Some(("c", 2)))).is_empty()); + assembler.end("sub"); + assert!(assembler.accept(change("c", "sub", "k", None)).is_empty()); + // Not buffered: 64 stragglers of distinct commits would fault if they were. + for index in 0..=MAX_PENDING_COMMITS { + let id = format!("s{index}"); + assert!(assembler.accept(change(&format!("m{index}"), "sub", "k", Some((&id, 2)))).is_empty()); + } + assert!(assembler.fault().is_none()); +} + +#[test] +fn ending_a_subscription_evicts_its_incomplete_commits() { + let mut assembler = live("sub"); + for index in 0..MAX_PENDING_COMMITS { + let id = format!("c{index}"); + assert!(assembler.accept(change(&format!("m{index}"), "sub", "k", Some((&id, 2)))).is_empty()); + } + assembler.end("sub"); + let mut other = assembler; + other.begin("sub", "b2").unwrap(); + other.accept(snapshot("b2", &[])); + assert!(other.accept(change("z", "sub", "k", Some(("fresh", 2)))).is_empty()); + assert!(other.fault().is_none(), "the evicted commits no longer count against the bound"); +} + +#[test] +fn a_snapshot_whose_message_id_was_never_begun_yields_nothing() { + let mut assembler = SubscriptionAssembler::new(); + assert!(assembler.accept(snapshot("nobody", &["r"])).is_empty()); + assembler.begin("sub", "m").unwrap(); + let events = assembler.accept(snapshot("m", &["r"])); + assert!(matches!(&events[0], SubscriptionEvent::Snapshot { subscription_id, documents } if subscription_id == "sub" && documents.len() == 1)); + assert!(assembler.accept(snapshot("m", &["r"])).is_empty(), "a snapshot answers its begin once"); +} + +#[test] +fn changes_that_arrive_before_the_snapshot_follow_it_in_order() { + let mut assembler = SubscriptionAssembler::new(); + assembler.begin("sub", "m").unwrap(); + assert!(assembler.accept(change("a", "sub", "first", None)).is_empty()); + assert!(assembler.accept(change("b", "sub", "second-a", Some(("c", 2)))).is_empty()); + assert!(assembler.accept(change("c", "sub", "second-b", Some(("c", 2)))).is_empty()); + assert!(assembler.accept(change("d", "sub", "third", None)).is_empty()); + let events = assembler.accept(snapshot("m", &["r"])); + assert!(matches!(events[0], SubscriptionEvent::Snapshot { .. })); + let order: Vec<_> = events[1..].iter().map(keys).collect(); + assert_eq!(order, [vec!["first"], vec!["second-a", "second-b"], vec!["third"]]); +}