diff --git a/packages/cultnet-rs/README.md b/packages/cultnet-rs/README.md index 18cb3d7f..7ade81dc 100644 --- a/packages/cultnet-rs/README.md +++ b/packages/cultnet-rs/README.md @@ -136,6 +136,40 @@ honest. The win is narrower and realer: identical payload bytes stop getting decoded into generic sludge and then encoded right back into the same bytes for no reason. +## Reactive Documents + +For local state that should feel owned by the caller, Rust can wrap a registered +CultCache record as a managed reactive document: + +```rust +use std::sync::{Arc, Mutex}; +use cultnet_rs::{CultNetReactiveDocumentOptions, CultNetDocumentRegistry}; + +let cache = Arc::new(Mutex::new(target_cache)); +let note = registry.reactive_document::( + Arc::clone(&cache), + "note:bridge", + CultNetReactiveDocumentOptions::default(), +)?; + +{ + let current = note.current(); + current.lock().unwrap().body = "local prediction".to_string(); +} +``` + +The handle polls the serialized `current` value on the configured debounce +cadence and flushes changed state back through the typed cache. `update(...)`, +`set_current(...)`, `mark_dirty()`, and `flush()` are available when the caller +wants a more explicit Rust shape. + +When a canonical document put arrives while local state is dirty, +`apply_document_put_message(...)` or `apply_raw_document_put_message(...)` +records a `CultNetReactiveDocumentReconciliation`: the canonical value, the +predicted local value, and a delta that can be smoothed by the caller. CultCache +payloads serialize by numeric field slot, so Rust tuple-backed deltas use slot +keys such as `"0"` and `"1"` when field names are not present on the wire. + ## CultMesh Rust Facade Rust is still the low-level substrate runtime, not a clone of the C# game diff --git a/packages/cultnet-rs/src/replication.rs b/packages/cultnet-rs/src/replication.rs index 1597bd26..d02a141f 100644 --- a/packages/cultnet-rs/src/replication.rs +++ b/packages/cultnet-rs/src/replication.rs @@ -9,6 +9,13 @@ use serde::de::DeserializeOwned; use serde_json::Value; use std::collections::BTreeMap; use std::collections::BTreeSet; +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; +use std::thread; +use std::thread::JoinHandle; +use std::time::Duration; use crate::CultNetDocumentMutationContract; use crate::CultNetDocumentRecord; @@ -67,6 +74,56 @@ pub struct CultNetDocumentRegistry { bindings_by_schema_id: BTreeMap, } +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CultNetReactiveDocumentOptions { + pub flush_delay: Duration, + pub detect_local_changes: bool, + pub replace_dirty_current_on_canonical_snapshot: bool, +} + +impl Default for CultNetReactiveDocumentOptions { + fn default() -> Self { + Self { + flush_delay: Duration::from_millis(16), + detect_local_changes: true, + replace_dirty_current_on_canonical_snapshot: false, + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct CultNetReactiveDocumentReconciliation { + pub canonical: T, + pub predicted: T, + pub delta: BTreeMap, + pub version: u64, + pub received_at: String, +} + +struct CultNetReactiveDocumentState { + dirty: bool, + flushing: bool, + flush_queued: bool, + last_clean_payload: Vec, + reconciliation: Option>, + reconciliation_version: u64, + last_error: Option, +} + +pub struct CultNetReactiveDocument +where + T: DatabaseEntry + Serialize + DeserializeOwned, +{ + registry: CultNetDocumentRegistry, + cache: Arc>, + record_key: String, + current: Arc>, + state: Arc>>, + options: CultNetReactiveDocumentOptions, + disposed: Arc, + detect_worker: Option>, +} + impl CultNetDocumentRegistry { pub fn new() -> Self { Self::default() @@ -448,6 +505,18 @@ impl CultNetDocumentRegistry { ) } + pub fn reactive_document( + &self, + cache: Arc>, + record_key: impl Into, + options: CultNetReactiveDocumentOptions, + ) -> Result> + where + T: DatabaseEntry + Serialize + DeserializeOwned, + { + CultNetReactiveDocument::new(self.clone(), cache, record_key, options) + } + fn document_record_from_envelope( &self, envelope: &CultCacheEnvelope, @@ -496,6 +565,443 @@ impl CultNetDocumentRegistry { } } +impl CultNetReactiveDocument +where + T: DatabaseEntry + Serialize + DeserializeOwned, +{ + pub fn new( + registry: CultNetDocumentRegistry, + cache: Arc>, + record_key: impl Into, + options: CultNetReactiveDocumentOptions, + ) -> Result { + let record_key = record_key.into(); + if record_key.trim().is_empty() { + return Err(anyhow!("record_key must be non-empty")); + } + registry.require_binding(T::TYPE)?; + let current = { + let cache = cache + .lock() + .map_err(|_| anyhow!("CultCache mutex poisoned"))?; + cache.get_required::(&record_key)? + }; + let last_clean_payload = serialize_typed(¤t)?; + let current = Arc::new(Mutex::new(current)); + let state = Arc::new(Mutex::new(CultNetReactiveDocumentState { + dirty: false, + flushing: false, + flush_queued: false, + last_clean_payload, + reconciliation: None, + reconciliation_version: 0, + last_error: None, + })); + let disposed = Arc::new(AtomicBool::new(false)); + let detect_worker = if options.detect_local_changes { + Some(start_reactive_detection_worker::( + Arc::clone(&cache), + Arc::clone(¤t), + Arc::clone(&state), + Arc::clone(&disposed), + options.flush_delay, + record_key.clone(), + )) + } else { + None + }; + Ok(Self { + registry, + cache, + record_key, + current, + state, + options, + disposed, + detect_worker, + }) + } + + pub fn current(&self) -> Arc> { + Arc::clone(&self.current) + } + + pub fn record_key(&self) -> &str { + &self.record_key + } + + pub fn is_dirty(&self) -> bool { + self.state.lock().map(|state| state.dirty).unwrap_or(false) + } + + pub fn reconciliation(&self) -> Option> { + self.state + .lock() + .ok() + .and_then(|state| state.reconciliation.clone()) + } + + pub fn last_error(&self) -> Option { + self.state + .lock() + .ok() + .and_then(|state| state.last_error.clone()) + } + + pub fn update(&self, update: impl FnOnce(&mut T)) -> Result { + let predicted = { + let mut current = self + .current + .lock() + .map_err(|_| anyhow!("reactive document mutex poisoned"))?; + update(&mut current); + current.clone() + }; + { + let mut state = self + .state + .lock() + .map_err(|_| anyhow!("reactive document state mutex poisoned"))?; + state.dirty = true; + } + if self.options.flush_delay.is_zero() { + self.flush()?; + } + Ok(predicted) + } + + pub fn set_current(&self, value: T) -> Result { + { + let mut current = self + .current + .lock() + .map_err(|_| anyhow!("reactive document mutex poisoned"))?; + *current = value.clone(); + } + { + let mut state = self + .state + .lock() + .map_err(|_| anyhow!("reactive document state mutex poisoned"))?; + state.dirty = true; + } + if self.options.flush_delay.is_zero() { + self.flush()?; + } + Ok(value) + } + + pub fn mark_dirty(&self) -> Result<()> { + let mut state = self + .state + .lock() + .map_err(|_| anyhow!("reactive document state mutex poisoned"))?; + state.dirty = true; + Ok(()) + } + + pub fn refresh(&self) -> Result { + let canonical = { + let cache = self + .cache + .lock() + .map_err(|_| anyhow!("CultCache mutex poisoned"))?; + cache.get_required::(&self.record_key)? + }; + { + let mut current = self + .current + .lock() + .map_err(|_| anyhow!("reactive document mutex poisoned"))?; + *current = canonical.clone(); + } + { + let mut state = self + .state + .lock() + .map_err(|_| anyhow!("reactive document state mutex poisoned"))?; + state.last_clean_payload = serialize_typed(&canonical)?; + state.dirty = false; + state.flush_queued = false; + state.reconciliation = None; + } + Ok(canonical) + } + + pub fn flush(&self) -> Result<()> { + flush_reactive_document::(&self.cache, &self.current, &self.state, &self.record_key) + } + + pub fn apply_document_put_message(&self, message: &CultNetMessage) -> Result { + let canonical = { + let mut cache = self + .cache + .lock() + .map_err(|_| anyhow!("CultCache mutex poisoned"))?; + self.registry + .apply_document_put_message::(&mut cache, message)? + }; + self.apply_canonical_value(canonical) + } + + pub fn apply_raw_document_put_message(&self, message: &CultNetMessage) -> Result { + let canonical = { + let mut cache = self + .cache + .lock() + .map_err(|_| anyhow!("CultCache mutex poisoned"))?; + self.registry + .apply_raw_document_put_message::(&mut cache, message)? + }; + self.apply_canonical_value(canonical) + } + + pub fn clear_reconciliation(&self) -> Result<()> { + let mut state = self + .state + .lock() + .map_err(|_| anyhow!("reactive document state mutex poisoned"))?; + state.reconciliation = None; + Ok(()) + } + + fn apply_canonical_value(&self, canonical: T) -> Result { + let predicted = self + .current + .lock() + .map_err(|_| anyhow!("reactive document mutex poisoned"))? + .clone(); + let mut state = self + .state + .lock() + .map_err(|_| anyhow!("reactive document state mutex poisoned"))?; + if state.dirty || state.flushing { + let delta = create_reconciliation_delta(&predicted, &canonical)?; + if delta.is_empty() { + state.reconciliation = None; + } else { + state.reconciliation_version += 1; + state.reconciliation = Some(CultNetReactiveDocumentReconciliation { + canonical: canonical.clone(), + predicted, + delta, + version: state.reconciliation_version, + received_at: now_utc_second(), + }); + } + if !self.options.replace_dirty_current_on_canonical_snapshot { + return Ok(canonical); + } + } + drop(state); + { + let mut current = self + .current + .lock() + .map_err(|_| anyhow!("reactive document mutex poisoned"))?; + *current = canonical.clone(); + } + let mut state = self + .state + .lock() + .map_err(|_| anyhow!("reactive document state mutex poisoned"))?; + state.last_clean_payload = serialize_typed(&canonical)?; + state.reconciliation = None; + Ok(canonical) + } +} + +impl Drop for CultNetReactiveDocument +where + T: DatabaseEntry + Serialize + DeserializeOwned, +{ + fn drop(&mut self) { + self.disposed.store(true, Ordering::SeqCst); + let _ = self.detect_worker.take(); + } +} + +fn start_reactive_detection_worker( + cache: Arc>, + current: Arc>, + state: Arc>>, + disposed: Arc, + flush_delay: Duration, + record_key: String, +) -> JoinHandle<()> +where + T: DatabaseEntry + Serialize + DeserializeOwned, +{ + thread::spawn(move || { + let delay = if flush_delay.is_zero() { + Duration::from_millis(1) + } else { + flush_delay + }; + while !disposed.load(Ordering::SeqCst) { + thread::sleep(delay); + match detect_reactive_document_change::(¤t, &state).and_then(|dirty| { + if dirty { + flush_reactive_document::(&cache, ¤t, &state, &record_key)?; + } + Ok(()) + }) { + Ok(()) => {} + Err(error) => { + if let Ok(mut state) = state.lock() { + state.last_error = Some(error.to_string()); + } + } + } + } + }) +} + +fn detect_reactive_document_change( + current: &Arc>, + state: &Arc>>, +) -> Result +where + T: DatabaseEntry + Serialize + DeserializeOwned, +{ + let payload = { + let current = current + .lock() + .map_err(|_| anyhow!("reactive document mutex poisoned"))?; + serialize_typed(&*current)? + }; + let mut state = state + .lock() + .map_err(|_| anyhow!("reactive document state mutex poisoned"))?; + if !state.dirty && !state.flushing && payload != state.last_clean_payload { + state.dirty = true; + } + Ok(state.dirty && !state.flushing) +} + +fn flush_reactive_document( + cache: &Arc>, + current: &Arc>, + state: &Arc>>, + record_key: &str, +) -> Result<()> +where + T: DatabaseEntry + Serialize + DeserializeOwned, +{ + let predicted = { + let mut state_guard = state + .lock() + .map_err(|_| anyhow!("reactive document state mutex poisoned"))?; + if !state_guard.dirty { + drop(state_guard); + if !detect_reactive_document_change::(current, state)? { + return Ok(()); + } + state_guard = state + .lock() + .map_err(|_| anyhow!("reactive document state mutex poisoned"))?; + } + if state_guard.flushing { + state_guard.flush_queued = true; + return Ok(()); + } + state_guard.flushing = true; + state_guard.dirty = false; + current + .lock() + .map_err(|_| anyhow!("reactive document mutex poisoned"))? + .clone() + }; + let payload = serialize_typed(&predicted)?; + { + let mut cache = cache + .lock() + .map_err(|_| anyhow!("CultCache mutex poisoned"))?; + cache.put::(record_key.to_string(), &predicted)?; + } + let should_flush_again = { + let mut state = state + .lock() + .map_err(|_| anyhow!("reactive document state mutex poisoned"))?; + state.flushing = false; + state.last_clean_payload = payload; + state.last_error = None; + state.reconciliation = None; + let changed_after_flush = { + let current = current + .lock() + .map_err(|_| anyhow!("reactive document mutex poisoned"))?; + serialize_typed(&*current)? != state.last_clean_payload + }; + if changed_after_flush { + state.dirty = true; + } + let should_flush_again = state.flush_queued || state.dirty; + state.flush_queued = false; + should_flush_again + }; + if should_flush_again { + flush_reactive_document::(cache, current, state, record_key)?; + } + Ok(()) +} + +fn serialize_typed(value: &T) -> Result> +where + T: Serialize, +{ + Ok(rmp_serde::to_vec(value)?) +} + +fn create_reconciliation_delta(predicted: &T, canonical: &T) -> Result> +where + T: Serialize, +{ + let predicted = serde_json::to_value(predicted)?; + let canonical = serde_json::to_value(canonical)?; + let mut delta = BTreeMap::new(); + match (predicted, canonical) { + (Value::Object(predicted), Value::Object(canonical)) => { + for (key, predicted_value) in predicted { + let canonical_value = canonical.get(&key).cloned().unwrap_or(Value::Null); + if predicted_value == canonical_value { + continue; + } + delta.insert( + key, + numeric_delta(&predicted_value, &canonical_value).unwrap_or(predicted_value), + ); + } + } + (Value::Array(predicted), Value::Array(canonical)) => { + for (index, predicted_value) in predicted.into_iter().enumerate() { + let canonical_value = canonical.get(index).cloned().unwrap_or(Value::Null); + if predicted_value == canonical_value { + continue; + } + delta.insert( + index.to_string(), + numeric_delta(&predicted_value, &canonical_value).unwrap_or(predicted_value), + ); + } + } + (predicted, canonical) if predicted != canonical => { + delta.insert( + "value".to_string(), + numeric_delta(&predicted, &canonical).unwrap_or(predicted), + ); + } + _ => {} + } + Ok(delta) +} + +fn numeric_delta(predicted: &Value, canonical: &Value) -> Option { + let predicted = predicted.as_f64()?; + let canonical = canonical.as_f64()?; + serde_json::Number::from_f64(predicted - canonical).map(Value::Number) +} + fn round_trip_typed(value: &T) -> Result where T: Serialize + DeserializeOwned, diff --git a/packages/cultnet-rs/tests/cultnet.rs b/packages/cultnet-rs/tests/cultnet.rs index 8ff65fa0..e72a93a1 100644 --- a/packages/cultnet-rs/tests/cultnet.rs +++ b/packages/cultnet-rs/tests/cultnet.rs @@ -17,6 +17,7 @@ use cultnet_rs::CultNetDocumentPutOptions; use cultnet_rs::CultNetDocumentRegistry; use cultnet_rs::CultNetMessage; use cultnet_rs::CultNetMutationAuthority; +use cultnet_rs::CultNetReactiveDocumentOptions; use cultnet_rs::CultNetReconnectController; use cultnet_rs::CultNetReconnectPolicyOptions; use cultnet_rs::CultNetRudpPacket; @@ -163,6 +164,30 @@ struct GhostlightAgentStateUiFixture { display_name: String, } +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache( + type = "ghostlight.reactive-note", + schema = "GhostlightReactiveNoteFixture" +)] +struct GhostlightReactiveNoteFixture { + #[cultcache(key = 0)] + body: String, + #[cultcache(key = 1)] + revision: i32, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache( + type = "ghostlight.reactive-note.ui", + schema = "GhostlightReactiveNoteUiFixture" +)] +struct GhostlightReactiveNoteUiFixture { + #[cultcache(key = 0)] + body: String, + #[cultcache(key = 1)] + revision: i32, +} + #[test] fn security_helpers_round_trip_encrypted_strings_and_validate_sessions() -> Result<()> { let server_security = CultNetServerSecurityOptions::development(); @@ -1766,6 +1791,149 @@ fn raw_snapshot_replication_hydrates_same_schema_rust_aliases() -> Result<()> { Ok(()) } +#[test] +fn reactive_document_coalesces_direct_same_schema_alias_member_writes() -> Result<()> { + let temp = tempfile::tempdir()?; + let target_store = temp.path().join("target-reactive-alias.msgpack"); + let mut registry = CultNetDocumentRegistry::new(); + registry.register(CultNetDocumentBinding::for_entry_with_schema_id::< + GhostlightReactiveNoteUiFixture, + >( + "ghostlight.reactive_note.v0".to_string(), + "ghostlight.reactive_note.v0".to_string(), + )); + let cache = Arc::new(Mutex::new(CultCache::new())); + { + let mut cache = cache.lock().expect("cache mutex"); + cache.register_entry_type::()?; + cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&target_store)); + cache.pull_all_backing_stores()?; + cache.put( + "note:reactive", + &GhostlightReactiveNoteUiFixture { + body: "initial".to_string(), + revision: 1, + }, + )?; + } + + let reactive = registry.reactive_document::( + Arc::clone(&cache), + "note:reactive", + CultNetReactiveDocumentOptions { + flush_delay: StdDuration::from_millis(5), + ..CultNetReactiveDocumentOptions::default() + }, + )?; + { + let current = reactive.current(); + let mut current = current.lock().expect("reactive current mutex"); + current.body = "first-local-edit".to_string(); + current.body = "second-local-edit".to_string(); + current.revision = 2; + } + + for _ in 0..30 { + let body = cache + .lock() + .expect("cache mutex") + .get_required::("note:reactive")? + .body; + if body == "second-local-edit" { + break; + } + thread::sleep(StdDuration::from_millis(5)); + } + + let stored = cache + .lock() + .expect("cache mutex") + .get_required::("note:reactive")?; + assert_eq!(stored.body, "second-local-edit"); + assert_eq!(stored.revision, 2); + assert!(!reactive.is_dirty()); + assert!(reactive.last_error().is_none()); + Ok(()) +} + +#[test] +fn reactive_document_tracks_canonical_reconciliation_delta() -> Result<()> { + let temp = tempfile::tempdir()?; + let target_store = temp.path().join("target-reactive-reconcile.msgpack"); + let mut registry = CultNetDocumentRegistry::new(); + registry.register(CultNetDocumentBinding::for_entry_with_schema_id::< + GhostlightReactiveNoteFixture, + >( + "ghostlight.reactive_note.v0".to_string(), + "ghostlight.reactive_note.v0".to_string(), + )); + let cache = Arc::new(Mutex::new(CultCache::new())); + { + let mut cache = cache.lock().expect("cache mutex"); + cache.register_entry_type::()?; + cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&target_store)); + cache.pull_all_backing_stores()?; + cache.put( + "note:reconcile", + &GhostlightReactiveNoteFixture { + body: "initial".to_string(), + revision: 1, + }, + )?; + } + + let reactive = registry.reactive_document::( + Arc::clone(&cache), + "note:reconcile", + CultNetReactiveDocumentOptions { + flush_delay: StdDuration::from_secs(60), + detect_local_changes: false, + ..CultNetReactiveDocumentOptions::default() + }, + )?; + reactive.update(|note| { + note.body = "local-prediction".to_string(); + note.revision = 2; + })?; + let authoritative = registry.create_document_put_message( + "put-authoritative", + "note:reconcile", + &GhostlightReactiveNoteFixture { + body: "authoritative".to_string(), + revision: 7, + }, + CultNetDocumentPutOptions::default(), + )?; + + reactive.apply_document_put_message(&authoritative)?; + + let current = reactive.current(); + let current = current.lock().expect("reactive current mutex").clone(); + assert_eq!(current.body, "local-prediction"); + let reconciliation = reactive + .reconciliation() + .expect("dirty canonical apply records reconciliation"); + assert_eq!(reconciliation.canonical.body, "authoritative"); + assert_eq!(reconciliation.predicted.body, "local-prediction"); + assert_eq!( + reconciliation.delta.get("0"), + Some(&serde_json::json!("local-prediction")) + ); + assert_eq!( + reconciliation.delta.get("1"), + Some(&serde_json::json!(-5.0)) + ); + + reactive.flush()?; + let stored = cache + .lock() + .expect("cache mutex") + .get_required::("note:reconcile")?; + assert_eq!(stored.body, "local-prediction"); + assert!(reactive.reconciliation().is_none()); + Ok(()) +} + #[test] fn client_security_keeps_the_connection_key_visible_without_exposing_cipher_logic() -> Result<()> { let options = CultNetClientSecurityOptions::development();