Add Rust reactive document sync

This commit is contained in:
Meta Vens 2026-06-28 00:31:35 +01:00
commit 60f782faa7
3 changed files with 708 additions and 0 deletions

View file

@ -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::<UiNote>(
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

View file

@ -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<String, CultNetDocumentBinding>,
}
#[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<T> {
pub canonical: T,
pub predicted: T,
pub delta: BTreeMap<String, Value>,
pub version: u64,
pub received_at: String,
}
struct CultNetReactiveDocumentState<T> {
dirty: bool,
flushing: bool,
flush_queued: bool,
last_clean_payload: Vec<u8>,
reconciliation: Option<CultNetReactiveDocumentReconciliation<T>>,
reconciliation_version: u64,
last_error: Option<String>,
}
pub struct CultNetReactiveDocument<T>
where
T: DatabaseEntry + Serialize + DeserializeOwned,
{
registry: CultNetDocumentRegistry,
cache: Arc<Mutex<CultCache>>,
record_key: String,
current: Arc<Mutex<T>>,
state: Arc<Mutex<CultNetReactiveDocumentState<T>>>,
options: CultNetReactiveDocumentOptions,
disposed: Arc<AtomicBool>,
detect_worker: Option<JoinHandle<()>>,
}
impl CultNetDocumentRegistry {
pub fn new() -> Self {
Self::default()
@ -448,6 +505,18 @@ impl CultNetDocumentRegistry {
)
}
pub fn reactive_document<T>(
&self,
cache: Arc<Mutex<CultCache>>,
record_key: impl Into<String>,
options: CultNetReactiveDocumentOptions,
) -> Result<CultNetReactiveDocument<T>>
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<T> CultNetReactiveDocument<T>
where
T: DatabaseEntry + Serialize + DeserializeOwned,
{
pub fn new(
registry: CultNetDocumentRegistry,
cache: Arc<Mutex<CultCache>>,
record_key: impl Into<String>,
options: CultNetReactiveDocumentOptions,
) -> Result<Self> {
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::<T>(&record_key)?
};
let last_clean_payload = serialize_typed(&current)?;
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::<T>(
Arc::clone(&cache),
Arc::clone(&current),
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<Mutex<T>> {
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<CultNetReactiveDocumentReconciliation<T>> {
self.state
.lock()
.ok()
.and_then(|state| state.reconciliation.clone())
}
pub fn last_error(&self) -> Option<String> {
self.state
.lock()
.ok()
.and_then(|state| state.last_error.clone())
}
pub fn update(&self, update: impl FnOnce(&mut T)) -> Result<T> {
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<T> {
{
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<T> {
let canonical = {
let cache = self
.cache
.lock()
.map_err(|_| anyhow!("CultCache mutex poisoned"))?;
cache.get_required::<T>(&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::<T>(&self.cache, &self.current, &self.state, &self.record_key)
}
pub fn apply_document_put_message(&self, message: &CultNetMessage) -> Result<T> {
let canonical = {
let mut cache = self
.cache
.lock()
.map_err(|_| anyhow!("CultCache mutex poisoned"))?;
self.registry
.apply_document_put_message::<T>(&mut cache, message)?
};
self.apply_canonical_value(canonical)
}
pub fn apply_raw_document_put_message(&self, message: &CultNetMessage) -> Result<T> {
let canonical = {
let mut cache = self
.cache
.lock()
.map_err(|_| anyhow!("CultCache mutex poisoned"))?;
self.registry
.apply_raw_document_put_message::<T>(&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<T> {
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<T> Drop for CultNetReactiveDocument<T>
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<T>(
cache: Arc<Mutex<CultCache>>,
current: Arc<Mutex<T>>,
state: Arc<Mutex<CultNetReactiveDocumentState<T>>>,
disposed: Arc<AtomicBool>,
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>(&current, &state).and_then(|dirty| {
if dirty {
flush_reactive_document::<T>(&cache, &current, &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<T>(
current: &Arc<Mutex<T>>,
state: &Arc<Mutex<CultNetReactiveDocumentState<T>>>,
) -> Result<bool>
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<T>(
cache: &Arc<Mutex<CultCache>>,
current: &Arc<Mutex<T>>,
state: &Arc<Mutex<CultNetReactiveDocumentState<T>>>,
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::<T>(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::<T>(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::<T>(cache, current, state, record_key)?;
}
Ok(())
}
fn serialize_typed<T>(value: &T) -> Result<Vec<u8>>
where
T: Serialize,
{
Ok(rmp_serde::to_vec(value)?)
}
fn create_reconciliation_delta<T>(predicted: &T, canonical: &T) -> Result<BTreeMap<String, Value>>
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<Value> {
let predicted = predicted.as_f64()?;
let canonical = canonical.as_f64()?;
serde_json::Number::from_f64(predicted - canonical).map(Value::Number)
}
fn round_trip_typed<T>(value: &T) -> Result<T>
where
T: Serialize + DeserializeOwned,

View file

@ -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::<GhostlightReactiveNoteUiFixture>()?;
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::<GhostlightReactiveNoteUiFixture>(
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::<GhostlightReactiveNoteUiFixture>("note:reactive")?
.body;
if body == "second-local-edit" {
break;
}
thread::sleep(StdDuration::from_millis(5));
}
let stored = cache
.lock()
.expect("cache mutex")
.get_required::<GhostlightReactiveNoteUiFixture>("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::<GhostlightReactiveNoteFixture>()?;
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::<GhostlightReactiveNoteFixture>(
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::<GhostlightReactiveNoteFixture>("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();