forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

unknown_parent.rs102 lines, 3.9 KiBHistoryRawDownload
1//! A snapshot from a newer Loro may store a child whose parent has a container
2//! type unknown to this version. `parent()` used to hit `unreachable!()`.
3
4use bytes::Bytes;
5use loro_common::{ContainerID, ContainerType};
6use loro_internal::{
7 handler::Handler, loro::ExportMode, HandlerTrait, ListHandler, LoroDoc, ToJson,
8};
9use loro_kv_store::{mem_store::MemKvConfig, MemKvStore};
10
11const UNKNOWN: ContainerType = ContainerType::Unknown(9);
12
13/// Header of a stored container: kind, depth, parent. See
14/// `ContainerWrapper::encode`.
15fn header(kind: ContainerType, depth: u64, parent: &Option<ContainerID>) -> Vec<u8> {
16 let mut out = vec![kind.to_u8()];
17 leb128::write::unsigned(&mut out, depth).unwrap();
18 postcard::to_io(parent, &mut out).unwrap();
19 out
20}
21
22/// Rewrites the stored header of `child` so its parent is the root container
23/// `parent`, which is added with an empty (unknown) state.
24fn reparent_in_kv(section: &[u8], child: &ContainerID, parent: &ContainerID) -> Vec<u8> {
25 let mut kv = MemKvStore::new(MemKvConfig::default());
26 kv.import_all(Bytes::copy_from_slice(section)).unwrap();
27 let key = child.to_bytes();
28 let Some(value) = kv.get(&key) else {
29 return section.to_vec();
30 };
31 let kind = ContainerType::try_from_u8(value[0]).unwrap();
32 let mut reader = &value[1..];
33 let depth = leb128::read::unsigned(&mut reader).unwrap();
34 let (_, payload) = postcard::take_from_bytes::<Option<ContainerID>>(reader).unwrap();
35 let mut new_value = header(kind, depth, &Some(parent.clone()));
36 new_value.extend_from_slice(payload);
37 kv.set(&key, new_value.into());
38 kv.set(
39 &parent.to_bytes(),
40 header(parent.container_type(), 1, &None).into(),
41 );
42 kv.export_all().to_vec()
43}
44
45/// Rewrites every container state section of a snapshot.
46fn forge_snapshot(bytes: &[u8], child: &ContainerID, parent: &ContainerID) -> Vec<u8> {
47 // magic (4) + checksum (16) + encode mode (2), then the body
48 let (head, mut body) = bytes.split_at(22);
49 let mut sections = Vec::new();
50 for _ in 0..3 {
51 let len = u32::from_le_bytes(body[..4].try_into().unwrap()) as usize;
52 sections.push(&body[4..4 + len]);
53 body = &body[4 + len..];
54 }
55 assert!(body.is_empty());
56
57 let mut out = head.to_vec();
58 for (i, section) in sections.into_iter().enumerate() {
59 // The oplog, and a state section of length 1 (a marker), stay as is
60 let section = if i == 0 || section.len() <= 1 {
61 section.to_vec()
62 } else {
63 reparent_in_kv(section, child, parent)
64 };
65 out.extend_from_slice(&(section.len() as u32).to_le_bytes());
66 out.extend_from_slice(&section);
67 }
68 let checksum = xxhash_rust::xxh32::xxh32(&out[20..], u32::from_le_bytes(*b"LORO"));
69 out[16..20].copy_from_slice(&checksum.to_le_bytes());
70 out
71}
72
73#[test]
74fn parent_of_a_child_of_an_unknown_container() {
75 let doc = LoroDoc::new_auto_commit();
76 doc.set_peer_id(1).unwrap();
77 let list = doc
78 .get_map("m")
79 .insert_container("x", ListHandler::new_detached())
80 .unwrap();
81 list.push(loro_common::LoroValue::from(1)).unwrap();
82 doc.commit_then_renew();
83 let child = list.id();
84
85 // The creating op is not in a shallow snapshot at the latest version, so
86 // the stored header decides the parent
87 let bytes = doc
88 .export(ExportMode::shallow_snapshot(&doc.oplog_frontiers()))
89 .unwrap();
90 let parent = ContainerID::new_root("future", UNKNOWN);
91 let forged = forge_snapshot(&bytes, &child, &parent);
92 assert_ne!(forged, bytes);
93
94 let doc = LoroDoc::new_auto_commit();
95 doc.import(&forged).unwrap();
96 let list = doc.get_list(child);
97 let Some(Handler::Unknown(p)) = list.parent() else {
98 panic!("expected an unknown parent, got {:?}", list.parent());
99 };
100 assert_eq!(p.id(), parent);
101 assert_eq!(list.get_value().to_json_value(), serde_json::json!([1]));
102}