diff --git a/brokkr-daemon/Cargo.toml b/brokkr-daemon/Cargo.toml index 5839b77..58bbccf 100644 --- a/brokkr-daemon/Cargo.toml +++ b/brokkr-daemon/Cargo.toml @@ -6,7 +6,7 @@ publish = false [dependencies] anyhow = "1" -cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c2a9a6e526390808ef195759056fda0b9a55d8a3", package = "cultcache-rs" } +cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "baf4ecf78fae634fafef956d3b85420162c074bb", package = "cultcache-rs" } rmp-serde = "1.3" serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/brokkr-daemon/src/main.rs b/brokkr-daemon/src/main.rs index be9fbc0..557389b 100644 --- a/brokkr-daemon/src/main.rs +++ b/brokkr-daemon/src/main.rs @@ -1390,7 +1390,7 @@ impl MirrorStore { fn documents(&mut self) -> Result> { let mut documents = Vec::new(); for envelope in self.store.pull_all()? { - let value = decode_payload(&envelope).with_context(|| { + let value = cultcache_rs::decode_payload::(&envelope.payload).with_context(|| { format!("failed to decode {} at {}", envelope.r#type, envelope.key) })?; documents.push(CacheDocument { @@ -1409,25 +1409,11 @@ impl MirrorStore { payload, stored_at: chrono_like_now(), schema_id: Some(schema.to_string()), - }) + })?; + Ok(()) } } -fn decode_payload(envelope: &CultCacheEnvelope) -> Result { - let mut cursor = io::Cursor::new(envelope.payload.as_slice()); - let value: Value = rmp_serde::decode::from_read(&mut cursor) - .with_context(|| format!("payload is not a MessagePack value for {}", envelope.key))?; - let trailing = envelope.payload.len() as u64 - cursor.position(); - if trailing != 0 { - return Err(anyhow!( - "payload for {} is not exactly one MessagePack value: {} trailing byte(s)", - envelope.key, - trailing - )); - } - Ok(value) -} - fn parse_object_binding(value: &Value) -> Option { Some(ObjectBinding { binding_id: field_string(value, 1, "bindingId")?, @@ -3323,42 +3309,94 @@ mod tests { Ok(()) } - #[test] - fn decode_payload_refuses_trailing_bytes() -> Result<()> { - let mut payload = rmp_serde::to_vec(&json!({"a": 1}))?; - let clean = CultCacheEnvelope { - key: "k/clean".to_string(), - r#type: "t".to_string(), - payload: payload.clone(), - stored_at: String::new(), - schema_id: None, - }; - assert_eq!(decode_payload(&clean)?, json!({"a": 1})); - - payload.push(0xc0); - let dirty = CultCacheEnvelope { - key: "k/dirty".to_string(), + fn raw_envelope(key: &str, payload: Vec) -> CultCacheEnvelope { + CultCacheEnvelope { + key: key.to_string(), + r#type: "brokkr.sync.receipt.v0".to_string(), payload, - ..clean - }; - let message = format!("{:#}", decode_payload(&dirty).unwrap_err()); + stored_at: chrono_like_now(), + schema_id: Some("brokkr.sync.receipt.v0".to_string()), + } + } + + #[test] + fn store_read_refuses_trailing_bytes() -> Result<()> { + let temp = tempfile::tempdir()?; + let path = temp.path().join("store.ccmp"); + let mut raw = SingleFileMessagePackBackingStore::new(&path); + let clean = rmp_serde::to_vec(&json!({"a": 1}))?; + raw.push(&raw_envelope("k/clean", clean.clone()))?; + let documents = MirrorStore::open(&path)?.documents()?; + assert_eq!(documents.len(), 1); + assert_eq!(documents[0].value, json!({"a": 1})); + + let mut dirty = clean; + dirty.push(0xc0); + raw.push(&raw_envelope("k/dirty", dirty))?; + let message = format!("{:#}", MirrorStore::open(&path)?.documents().unwrap_err()); assert!(message.contains("k/dirty"), "{message}"); - assert!(message.contains("1 trailing byte"), "{message}"); - assert!(!message.contains("c0"), "{message}"); + assert!(!message.to_lowercase().contains("c0"), "{message}"); Ok(()) } #[test] - fn decode_payload_refuses_json_payload() -> Result<()> { + fn store_read_refuses_json_payload() -> Result<()> { + let temp = tempfile::tempdir()?; + let path = temp.path().join("store.ccmp"); let receipt = json!({"schema": "brokkr.sync.receipt.v0", "status": "ok"}); - let envelope = CultCacheEnvelope { - key: "sync/receipts/json".to_string(), - r#type: "brokkr.sync.receipt.v0".to_string(), - payload: serde_json::to_vec(&receipt)?, - stored_at: String::new(), - schema_id: None, - }; - assert!(decode_payload(&envelope).is_err()); + SingleFileMessagePackBackingStore::new(&path) + .push(&raw_envelope("sync/receipts/json", serde_json::to_vec(&receipt)?))?; + let message = format!("{:#}", MirrorStore::open(&path)?.documents().unwrap_err()); + assert!(message.contains("sync/receipts/json"), "{message}"); + Ok(()) + } + + #[test] + fn sync_once_writes_unity_active_state_to_blender_visibility_command() -> Result<()> { + let temp = tempfile::tempdir()?; + let unity_path = temp.path().join("unity.ccmp"); + let blender_path = temp.path().join("blender.ccmp"); + seed_component_property_stores(&unity_path, &blender_path, "active-state")?; + + let report = run_sync_once(&SyncArgs { + unity_cache: unity_path, + blender_cache: blender_path.clone(), + dry_run: false, + })?; + + assert_eq!(report.blender_commands_written, 1, "{report:#?}"); + let command = MirrorStore::open(&blender_path)? + .documents()? + .into_iter() + .find(|document| document.key.starts_with("blender/commands/")) + .expect("Brokkr should emit a Blender visibility command"); + assert_eq!(command.value["action"], "setObjectVisibility"); + assert_eq!(command.value["targetObjectName"], "Cube"); + assert_eq!(command.value["visible"], true); + Ok(()) + } + + #[test] + fn dry_run_counts_active_state_command_but_writes_none() -> Result<()> { + let temp = tempfile::tempdir()?; + let unity_path = temp.path().join("unity.ccmp"); + let blender_path = temp.path().join("blender.ccmp"); + seed_component_property_stores(&unity_path, &blender_path, "active-state")?; + + let report = run_sync_once(&SyncArgs { + unity_cache: unity_path, + blender_cache: blender_path.clone(), + dry_run: true, + })?; + + assert_eq!(report.blender_commands_written, 1, "{report:#?}"); + assert!( + MirrorStore::open(&blender_path)? + .documents()? + .iter() + .all(|document| !document.key.starts_with("blender/commands/")), + "a dry run must not write a command intent" + ); Ok(()) } @@ -3387,7 +3425,7 @@ mod tests { "receipt payload should be a MessagePack map, led by {lead:#04x}" ); assert!(serde_json::from_slice::(&receipt.payload).is_err()); - assert!(decode_payload(receipt)?.is_object()); + assert!(cultcache_rs::decode_payload::(&receipt.payload)?.is_object()); } Ok(()) } diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 1279f97..677f03d 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -1101,11 +1101,24 @@ def bridge_documents(cultcache: Any) -> dict[str, Any]: def convert_store(source: str, destination: str, cultlib_py_src: str = "") -> int: - """Write the records of an older (JSON payload) bridge store to a new MessagePack file and return the count. - The destination must not exist and the source is never written: stop every writer, convert, then swap the files.""" + """Write the records of a bridge store to a new MessagePack file and return the count converted. + JSON payloads (the old default) are converted; MessagePack payloads, such as records the new daemon already + appended to the old store, are carried through. The destination must not exist and the source is never written: + stop every writer, convert, then swap the files.""" _cultmesh, cultcache = _load_cultmesh(cultlib_py_src) + json_codec, msgpack_codec = cultcache.JSON_PAYLOAD_CODEC, cultcache.MESSAGEPACK_PAYLOAD_CODEC + + def decode_either(payload: bytes) -> Any: + # A JSON object or array never starts like a MessagePack map or array, so a payload JSON refuses is MessagePack. + try: + return json_codec.decode(payload) + except Exception: + return msgpack_codec.decode(payload) + + either = cultcache.PayloadCodec("JSON or MessagePack", json_codec.encode, decode_either) return cultcache.convert( - cultcache.SingleFileMessagePackBackingStore(source), destination, bridge_documents(cultcache).values()) + cultcache.SingleFileMessagePackBackingStore(source), destination, bridge_documents(cultcache).values(), + source_codec=either) def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]: diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 842f886..3b3a93d 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -26,7 +26,7 @@ convert, check the new file opens, then swap it in for the original: py -3 -c "import sys; sys.path.insert(0, r'/surfaces/blender/brokkr_bridge'); import blender_target as t; print(t.convert_store(r'/blender-editor.ccmp', r'/blender-editor.mp.ccmp'))" ``` -The command prints the record count and leaves the source unwritten. +The command prints the record count and leaves the source unwritten. Records a new daemon already appended (MessagePack) are carried into the new file. The default node cache is: diff --git a/surfaces/blender/tests/test_store_convert.py b/surfaces/blender/tests/test_store_convert.py index 48fc8da..17d6506 100644 --- a/surfaces/blender/tests/test_store_convert.py +++ b/surfaces/blender/tests/test_store_convert.py @@ -76,6 +76,26 @@ class ConvertStoreTests(unittest.TestCase): decoded = msgpack.unpackb(envelope.payload, raw=False) # raises ExtraData on a trailing byte self.assertIsInstance(decoded, dict, envelope.key) + def test_mixed_store_converts_json_and_carries_messagepack(self): + import msgpack + # What the new daemon appends to an old store before the operator converts it. + appended = {"schema": bt.SYNC_RECEIPT_SCHEMA, "receiptId": "r2", "status": "ok"} + self.cultcache.SingleFileMessagePackBackingStore(self.source).push(self.cultcache.CultCacheEnvelope( + key="sync/receipts/r2", type=bt.SYNC_RECEIPT_SCHEMA, payload=msgpack.packb(appended), + stored_at="2026-11-27T01:00:00Z", schema_id=bt.SYNC_RECEIPT_SCHEMA)) + before = sha256(self.source) + destination = self.dir / "mixed.mp.ccmp" + self.assertEqual(bt.convert_store(str(self.source), str(destination), PACKAGES), len(self.records) + 1) + self.assertEqual(sha256(self.source), before) + node = self.cultmesh.CultMesh.start_node(str(destination), runtime_id="brokkr-test-mixed") + for document in bt.bridge_documents(self.cultcache).values(): + node.database.register_document(document) + node.database.pull() + snapshot = node.database.snapshot() + self.assertEqual(snapshot[bt.SYNC_RECEIPT_SCHEMA]["sync/receipts/r2"], appended) + for (schema, key), value in self.records.items(): + self.assertEqual(snapshot[schema][key], value, (schema, key)) + def test_convert_store_writes_only_a_new_file(self): destination = self.dir / "new.ccmp" bt.convert_store(str(self.source), str(destination), PACKAGES)