forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

mergeable_cid_encoding.rs314 lines, 11.7 KiBHistoryRawDownload
1//! Encoding and decoding of mergeable container ids.
2
3#[test]
4#[cfg(feature = "counter")]
5fn mergeable_container_id_roundtrips_parent_key_and_type() {
6 use loro_internal::ContainerType;
7
8 let parent = loro_common::ContainerID::new_root("state", ContainerType::Map);
9 let key = "field\u{1}with/slash:and:semicolon";
10 let cid = loro_common::ContainerID::new_mergeable(&parent, key, ContainerType::Counter);
11
12 assert!(cid.is_mergeable());
13 let (decoded_parent, decoded_key, decoded_type) = cid.parse_mergeable().unwrap();
14 assert_eq!(decoded_parent, parent);
15 assert_eq!(decoded_key, key);
16 assert_eq!(decoded_type, ContainerType::Counter);
17}
18
19#[test]
20fn user_root_names_cannot_use_mergeable_namespace() {
21 assert!(!loro_common::check_root_container_name(
22 loro_common::MERGEABLE_NAMESPACE_PREFIX
23 ));
24}
25
26/// `parse_mergeable` is a pure decoder and must return `None` (not panic, not
27/// silently misinterpret) for every malformed payload. This guards against
28/// future drift in the encoder + decoder pair.
29///
30/// The cid does NOT encode the container kind in its name — kind already lives in
31/// `ContainerID::Root::container_type`. Distinct kinds at the same `(parent, key)` therefore share
32/// the same name string but compare unequal at the `ContainerID` level, which is what callers see.
33#[test]
34#[cfg(feature = "counter")]
35fn parse_mergeable_rejects_malformed_payloads() {
36 use loro_common::{ContainerID, ContainerType};
37
38 // Non-mergeable root: returns None.
39 let plain_root = ContainerID::new_root("ordinary", ContainerType::Map);
40 assert!(plain_root.parse_mergeable().is_none());
41
42 // Mergeable prefix but missing the required key segment.
43 let no_key = ContainerID::Root {
44 name: "🤝:$state".into(),
45 container_type: ContainerType::Counter,
46 };
47 assert!(
48 no_key.parse_mergeable().is_none(),
49 "payload without a key segment must reject"
50 );
51
52 // Mergeable prefix, but empty payload.
53 let truncated = ContainerID::Root {
54 name: "🤝:".into(),
55 container_type: ContainerType::Counter,
56 };
57 assert!(
58 truncated.parse_mergeable().is_none(),
59 "empty payload must reject"
60 );
61
62 // Unknown escapes, raw slash, and dangling backslash must reject.
63 let malformed = ContainerID::Root {
64 name: "🤝:$state>bad\\xescape".into(),
65 container_type: ContainerType::Counter,
66 };
67 assert!(
68 malformed.parse_mergeable().is_none(),
69 "unknown escape in payload must reject"
70 );
71
72 let raw_slash = ContainerID::Root {
73 name: "🤝:$state>raw/slash".into(),
74 container_type: ContainerType::Counter,
75 };
76 assert!(raw_slash.parse_mergeable().is_none());
77
78 let dangling = ContainerID::Root {
79 name: "🤝:$state>dangling\\".into(),
80 container_type: ContainerType::Counter,
81 };
82 assert!(dangling.parse_mergeable().is_none());
83
84 for name in ["🤝:$root\\sname>key", "🤝:$root\\0name>key"] {
85 let invalid_root_name = ContainerID::Root {
86 name: name.into(),
87 container_type: ContainerType::Counter,
88 };
89 assert!(
90 invalid_root_name.parse_mergeable().is_none(),
91 "root base parent must reject decoded slash/NUL: {name:?}"
92 );
93 }
94
95 for name in [
96 "🤝:@Z:0>key",
97 "🤝:@001:0>key",
98 "🤝:@1:00>key",
99 "🤝:@1:-0>key",
100 ] {
101 let non_canonical = ContainerID::Root {
102 name: name.into(),
103 container_type: ContainerType::Counter,
104 };
105 assert!(
106 non_canonical.parse_mergeable().is_none(),
107 "non-canonical base36 payload must reject: {name:?}"
108 );
109 }
110}
111
112/// `LoroDoc::get_map` must reject names in the mergeable namespace at the
113/// call site, not just in `check_root_container_name`. Otherwise user code
114/// could fabricate a Root cid that masquerades as a mergeable child and
115/// confuse the parent-edge walks.
116///
117/// This test runs `check_root_container_name` directly on a variety of
118/// user-supplied strings; the runtime `get_map` / `get_text` / etc. calls
119/// route through this validator (see callers in `crates/loro-internal/src/`).
120/// If the validator is bypassed by a runtime path, that's a separate bug —
121/// but it's not something this test can prove without intentionally writing
122/// `🤝:` keys, which is what we're trying to prevent in the first place.
123#[test]
124fn root_name_validator_rejects_mergeable_namespace_inputs() {
125 use loro_common::{check_root_container_name, MERGEABLE_NAMESPACE_PREFIX};
126
127 // Bare prefix.
128 assert!(!check_root_container_name(MERGEABLE_NAMESPACE_PREFIX));
129 // Prefix + arbitrary payload.
130 assert!(!check_root_container_name("🤝:deadbeef"));
131 assert!(!check_root_container_name("🤝:"));
132 // Prefix-as-substring is OK (not a prefix), validator still allows it.
133 assert!(check_root_container_name("foo🤝:bar"));
134 // Prefix with a leading zero-width space is NOT a prefix match, allowed.
135 assert!(check_root_container_name("\u{200B}🤝:abc"));
136 // Sanity: ordinary user names still pass.
137 assert!(check_root_container_name("state"));
138 assert!(check_root_container_name("ordinary-name_with-symbols"));
139 // Empty is still rejected (pre-existing behavior).
140 assert!(!check_root_container_name(""));
141 // Slash and NUL still rejected (pre-existing behavior).
142 assert!(!check_root_container_name("a/b"));
143 assert!(!check_root_container_name("a\0b"));
144}
145
146/// For each supported container kind, `new_mergeable` produces a deterministic
147/// cid that decodes back to the same `(parent, key, kind)`. Counter is gated
148/// on the feature; the rest are unconditional.
149#[test]
150fn mergeable_cid_roundtrips_for_every_container_kind() {
151 use loro_common::{ContainerID, ContainerType};
152 let parent = ContainerID::new_root("state", ContainerType::Map);
153
154 for kind in ContainerType::ALL_TYPES {
155 let cid = ContainerID::new_mergeable(&parent, "field", kind);
156 assert!(cid.is_mergeable(), "kind {kind:?}: must be mergeable");
157 let again = ContainerID::new_mergeable(&parent, "field", kind);
158 assert_eq!(cid, again, "kind {kind:?}: cid must be deterministic");
159 let (decoded_parent, decoded_key, decoded_kind) = cid
160 .parse_mergeable()
161 .unwrap_or_else(|| panic!("kind {kind:?}: parse_mergeable returned None"));
162 assert_eq!(decoded_parent, parent, "kind {kind:?}: parent roundtrip");
163 assert_eq!(decoded_key, "field", "kind {kind:?}: key roundtrip");
164 assert_eq!(decoded_kind, kind, "kind {kind:?}: kind roundtrip");
165 }
166}
167
168/// Key encoding is escaped path segments, so it must round-trip cleanly for
169/// degenerate inputs: empty, long, delimiters, embedded NUL, and embedded
170/// mergeable prefix substring. Catches off-by-one and ad-hoc string-split
171/// mistakes in any future decoder change.
172#[test]
173fn mergeable_cid_roundtrips_for_degenerate_keys() {
174 use loro_common::{ContainerID, ContainerType};
175 let parent = ContainerID::new_root("state", ContainerType::Map);
176
177 let long_key: String = std::iter::repeat('k').take(2048).collect();
178 let cases: Vec<&str> = vec![
179 "",
180 long_key.as_str(),
181 "with\0nul\0bytes",
182 "embedded 🤝: substring in the middle",
183 "starts_with_🤝:_prefix",
184 "trailing_emoji_🤝:",
185 "ascii/slash/looking",
186 "contains>separator",
187 "contains\\backslash",
188 "mixed>\\/\0chars",
189 ];
190
191 for key in cases {
192 let cid = ContainerID::new_mergeable(&parent, key, ContainerType::Map);
193 assert!(cid.is_mergeable(), "key {key:?}: must be mergeable");
194 let (decoded_parent, decoded_key, decoded_kind) = cid
195 .parse_mergeable()
196 .unwrap_or_else(|| panic!("key {key:?}: parse_mergeable returned None"));
197 assert_eq!(decoded_parent, parent);
198 assert_eq!(decoded_key, key, "key {key:?}: round-trip mismatch");
199 assert_eq!(decoded_kind, ContainerType::Map);
200 }
201}
202
203#[test]
204fn mergeable_cid_uses_flattened_path_payload() {
205 use loro_common::{ContainerID, ContainerType, MERGEABLE_NAMESPACE_PREFIX};
206
207 let parent = ContainerID::new_root("state", ContainerType::Map);
208 let child = ContainerID::new_mergeable(&parent, "note>1", ContainerType::Map);
209 let grandchild = ContainerID::new_mergeable(&child, "body/slash\\nul\0", ContainerType::Text);
210
211 let name = match &grandchild {
212 ContainerID::Root { name, .. } => name.as_str(),
213 _ => panic!("expected Root"),
214 };
215 assert!(
216 name.starts_with(MERGEABLE_NAMESPACE_PREFIX),
217 "mergeable cid must use the reserved namespace"
218 );
219 assert_eq!(
220 name, "🤝:$state>note\\>1>body\\sslash\\\\nul\\0",
221 "nested mergeable ids must extend the flattened path, not embed parent cid bytes"
222 );
223 assert!(
224 !name.contains('/'),
225 "synthetic root names must not contain raw slash"
226 );
227 assert!(
228 !name.contains('\0'),
229 "synthetic root names must not contain raw NUL"
230 );
231
232 let (decoded_parent, decoded_key, decoded_kind) = grandchild.parse_mergeable().unwrap();
233 assert_eq!(decoded_parent, child);
234 assert_eq!(decoded_key, "body/slash\\nul\0");
235 assert_eq!(decoded_kind, ContainerType::Text);
236}
237
238#[test]
239fn mergeable_cid_roundtrips_normal_base_parent() {
240 use loro_common::{ContainerID, ContainerType, ID};
241
242 let parent = ContainerID::new_normal(
243 ID {
244 peer: u64::MAX,
245 counter: i32::MIN,
246 },
247 ContainerType::Map,
248 );
249 let cid = ContainerID::new_mergeable(&parent, "field", ContainerType::List);
250 let name = match &cid {
251 ContainerID::Root { name, .. } => name.as_str(),
252 _ => panic!("expected Root"),
253 };
254 assert!(
255 name.starts_with("🤝:@3w5e11264sgsf:-zik0zk>"),
256 "normal parent ids should use compact base36 encoding; got {name:?}"
257 );
258
259 let (decoded_parent, decoded_key, decoded_kind) = cid.parse_mergeable().unwrap();
260 assert_eq!(decoded_parent, parent);
261 assert_eq!(decoded_key, "field");
262 assert_eq!(decoded_kind, ContainerType::List);
263}
264
265#[test]
266fn mergeable_cid_roundtrips_escaped_root_base_parent() {
267 use loro_common::{ContainerID, ContainerType};
268
269 let parent = ContainerID::new_root("root>\\name", ContainerType::Map);
270 let cid = ContainerID::new_mergeable(&parent, "field", ContainerType::Tree);
271 let name = match &cid {
272 ContainerID::Root { name, .. } => name.as_str(),
273 _ => panic!("expected Root"),
274 };
275 assert_eq!(name, "🤝:$root\\>\\\\name>field");
276
277 let (decoded_parent, decoded_key, decoded_kind) = cid.parse_mergeable().unwrap();
278 assert_eq!(decoded_parent, parent);
279 assert_eq!(decoded_key, "field");
280 assert_eq!(decoded_kind, ContainerType::Tree);
281}
282
283#[test]
284#[should_panic(expected = "mergeable child parent must be a map")]
285fn mergeable_cid_rejects_non_map_parent() {
286 use loro_common::{ContainerID, ContainerType};
287
288 let parent = ContainerID::new_root("content", ContainerType::Text);
289 let _ = ContainerID::new_mergeable(&parent, "field", ContainerType::Map);
290}
291
292#[test]
293fn nested_mergeable_cid_size_grows_linearly() {
294 use loro_common::{ContainerID, ContainerType};
295
296 let mut cid = ContainerID::new_root("state", ContainerType::Map);
297 let mut sizes = Vec::new();
298 for _ in 0..=8 {
299 cid = ContainerID::new_mergeable(&cid, "k", ContainerType::Map);
300 sizes.push(cid.to_bytes().len());
301 }
302
303 for window in sizes.windows(2) {
304 assert_eq!(
305 window[1] - window[0],
306 2,
307 "each additional one-byte key should add only separator + key bytes; sizes={sizes:?}"
308 );
309 }
310 assert!(
311 sizes[8] < 64,
312 "depth 8 should stay compact with flattened encoding; sizes={sizes:?}"
313 );
314}