pub struct Tree<ID: TreeId, TM: TreeMeta> { /* private fields */ }Expand description
Implements Tree, a set of triples representing current tree structure.
Normally this Tree struct should not be instantiated directly.
Instead instantiate State (lower-level) or TreeReplica (higher-level)
and invoke operations on them.
§From the paper[1]:
We can represent the tree as a set of (parent, meta, child) triples, denoted in Isabelle/HOL as (’n × ’m × ’n) set. When we have (p, m, c) ∈ tree, that means c is a child of p in the tree, with associated metadata m. Given a tree, we can construct a new tree’ in which the child c is moved to a new parent p, with associated metadata m, as follows:
tree’ = {(p’, m’, c’) ∈ tree. c’ != c} ∪ {(p, m, c)}
§That is, we remove any existing parent-child relationship for c from the set tree, and then add {(p, m, c)} to represent the new parent-child relationship.
[1] https://martin.kleppmann.com/papers/move-op.pdf
Implementations§
Source§impl<ID: TreeId, TM: TreeMeta> Tree<ID, TM>
impl<ID: TreeId, TM: TreeMeta> Tree<ID, TM>
Sourcepub fn rm_subtree(&mut self, parent_id: &ID, include_parent: bool)
pub fn rm_subtree(&mut self, parent_id: &ID, include_parent: bool)
removes a subtree. useful for emptying trash. not used by crdt algo.
Examples found in repository?
278fn demo_move_to_trash() {
279 // pass true flag to enable causally stable threshold tracking
280 let mut r1: TreeReplica<TypeId, TypeMeta, TypeActor> = TreeReplica::new(new_id());
281 let mut r2: TreeReplica<TypeId, TypeMeta, TypeActor> = TreeReplica::new(new_id());
282
283 let ids: HashMap<&str, TypeId> = [
284 ("forest", new_id()),
285 ("trash", new_id()),
286 ("root", new_id()),
287 ("home", new_id()),
288 ("bob", new_id()),
289 ("project", new_id()),
290 ]
291 .iter()
292 .cloned()
293 .collect();
294
295 // Generate initial tree state.
296 //
297 // - forest
298 // - trash
299 // - root
300 // - home
301 // - bob
302 // - project
303 let mut ops = vec![
304 (ids["forest"], "root", ids["root"]),
305 (ids["forest"], "trash", ids["trash"]),
306 (ids["root"], "home", ids["home"]),
307 (ids["home"], "bob", ids["bob"]),
308 (ids["bob"], "project", ids["project"]),
309 ];
310
311 // add some nodes under project
312 mktree_ops(&mut ops, &mut r1, ids["project"], 2, 3);
313 let opmoves = r1.opmoves(ops);
314 r1.apply_ops_byref(&opmoves);
315 r2.apply_ops_byref(&opmoves);
316
317 println!("Initial tree");
318 print_tree(r1.tree(), &ids["forest"]);
319
320 // move project to trash
321 let ops = vec![r1.opmove(ids["trash"], "project", ids["project"])];
322 r1.apply_ops_byref(&ops);
323 r2.apply_ops_byref(&ops);
324
325 println!("\nAfter project moved to trash (deleted) on both replicas");
326 print_tree(r1.tree(), &ids["forest"]);
327
328 // Initially, trashed nodes must be retained because a concurrent move
329 // operation may move them back out of the trash.
330 //
331 // Once the operation that moved a node to the trash is causally
332 // stable, we know that no future operations will refer to this node,
333 // and so the trashed node and its descendants can be discarded.
334 //
335 // note: change r1.opmoves() to r2.opmoves() above to
336 // make the causally stable threshold less than the trash operation
337 // timestamp, which will cause this test to fail, ie hit the
338 // "trash should not be emptied" condition.
339 let result = r2.causally_stable_threshold();
340 match result {
341 Some(cst) if cst < ops[0].timestamp() => {
342 println!(
343 "\ncausally stable threshold:\n{:#?}\n\ntrash operation:\n{:#?}",
344 cst,
345 ops[0].timestamp()
346 );
347 panic!("!error: causally stable threshold is less than trash operation timestamp");
348 }
349 None => panic!("!error: causally stable threshold not found"),
350 _ => {}
351 }
352
353 // empty trash
354 r1.tree_mut().rm_subtree(&ids["trash"], false);
355 println!("\nDelete op is now causally stable, so we can empty trash:");
356 print_tree(r1.tree(), &ids["forest"]);
357}Sourcepub fn find(&self, child_id: &ID) -> Option<&TreeNode<ID, TM>>
pub fn find(&self, child_id: &ID) -> Option<&TreeNode<ID, TM>>
returns matching node, or None.
Examples found in repository?
180fn demo_walk_deep_tree() {
181 let mut r1: TreeReplica<TypeId, TypeMeta, TypeActor> = TreeReplica::new(new_id());
182
183 let ids: HashMap<&str, TypeId> = [("root", new_id())].iter().cloned().collect();
184
185 // Generate initial tree state.
186 println!("generating ops...");
187 let mut ops = vec![(0, "root", ids["root"])];
188 mktree_ops(&mut ops, &mut r1, ids["root"], 2, 6); // <-- max 6 levels deep.
189
190 println!("applying ops...");
191 let ops_len = ops.len();
192 r1.apply_ops_byref(&r1.opmoves(ops));
193
194 println!("walking tree...");
195 r1.tree().walk(&ids["root"], |tree, node_id, depth| {
196 if true {
197 let meta = match tree.find(node_id) {
198 Some(tn) => format!("{:?}", tn.metadata()),
199 None => format!("{:?}", node_id),
200 };
201 println!("{:indent$}{}", "", meta, indent = depth);
202 }
203 });
204
205 println!("\nnodes in tree: {}", ops_len);
206}
207
208/// Demonstrates log truncation
209///
210/// This requires that causally stable threshold tracking is enabled in `TreeReplica`
211fn demo_truncate_log() {
212 let mut replicas: Vec<TreeReplica<TypeId, TypeMeta, TypeActor>> = Vec::new();
213 let num_replicas = 5;
214
215 // start some replicas.
216 for _i in 0..num_replicas {
217 // pass true flag to enable causally stable threshold tracking
218 let r: TreeReplica<TypeId, TypeMeta, TypeActor> = TreeReplica::new(new_id());
219 replicas.push(r);
220 }
221
222 let root_id = new_id();
223
224 // Generate initial tree state.
225 let mut opmoves = vec![replicas[0].opmove(0, "root", root_id)];
226
227 println!("generating move operations...");
228
229 // generate some initial ops from all replicas.
230 for r in replicas.iter_mut() {
231 let finaldepth = rand::thread_rng().gen_range(3, 6);
232 let mut ops = vec![];
233 mktree_ops(&mut ops, r, root_id, 2, finaldepth);
234 opmoves.extend(r.opmoves(ops));
235 }
236
237 // apply all ops to all replicas
238 println!(
239 "applying {} operations to all {} replicas...\n",
240 opmoves.len(),
241 replicas.len()
242 );
243 apply_ops_to_replicas(&mut replicas, &opmoves);
244
245 #[derive(Debug)]
246 #[allow(dead_code)]
247 struct Stat {
248 pub replica: TypeActor,
249 pub ops_before_truncate: usize,
250 pub ops_after_truncate: usize,
251 }
252
253 let mut stats: Vec<Stat> = Vec::new();
254 for r in replicas.iter_mut() {
255 println!("truncating log of replica {}...", r.id());
256 println!(
257 "causally stable threshold: {:?}\n",
258 r.causally_stable_threshold()
259 );
260 let ops_b4 = r.state().log().len();
261 r.truncate_log();
262 let ops_after = r.state().log().len();
263 stats.push(Stat {
264 replica: *r.id(),
265 ops_before_truncate: ops_b4,
266 ops_after_truncate: ops_after,
267 });
268 }
269
270 println!("-- Stats -- ");
271 println!("\n{:#?}", stats);
272}
273
274/// Demonstrates moving items to a Trash node outside the nominal root and then
275/// emptying the trash after the log is truncated.
276///
277/// This requires that causally stable threshold tracking is enabled in `TreeReplica`
278fn demo_move_to_trash() {
279 // pass true flag to enable causally stable threshold tracking
280 let mut r1: TreeReplica<TypeId, TypeMeta, TypeActor> = TreeReplica::new(new_id());
281 let mut r2: TreeReplica<TypeId, TypeMeta, TypeActor> = TreeReplica::new(new_id());
282
283 let ids: HashMap<&str, TypeId> = [
284 ("forest", new_id()),
285 ("trash", new_id()),
286 ("root", new_id()),
287 ("home", new_id()),
288 ("bob", new_id()),
289 ("project", new_id()),
290 ]
291 .iter()
292 .cloned()
293 .collect();
294
295 // Generate initial tree state.
296 //
297 // - forest
298 // - trash
299 // - root
300 // - home
301 // - bob
302 // - project
303 let mut ops = vec![
304 (ids["forest"], "root", ids["root"]),
305 (ids["forest"], "trash", ids["trash"]),
306 (ids["root"], "home", ids["home"]),
307 (ids["home"], "bob", ids["bob"]),
308 (ids["bob"], "project", ids["project"]),
309 ];
310
311 // add some nodes under project
312 mktree_ops(&mut ops, &mut r1, ids["project"], 2, 3);
313 let opmoves = r1.opmoves(ops);
314 r1.apply_ops_byref(&opmoves);
315 r2.apply_ops_byref(&opmoves);
316
317 println!("Initial tree");
318 print_tree(r1.tree(), &ids["forest"]);
319
320 // move project to trash
321 let ops = vec![r1.opmove(ids["trash"], "project", ids["project"])];
322 r1.apply_ops_byref(&ops);
323 r2.apply_ops_byref(&ops);
324
325 println!("\nAfter project moved to trash (deleted) on both replicas");
326 print_tree(r1.tree(), &ids["forest"]);
327
328 // Initially, trashed nodes must be retained because a concurrent move
329 // operation may move them back out of the trash.
330 //
331 // Once the operation that moved a node to the trash is causally
332 // stable, we know that no future operations will refer to this node,
333 // and so the trashed node and its descendants can be discarded.
334 //
335 // note: change r1.opmoves() to r2.opmoves() above to
336 // make the causally stable threshold less than the trash operation
337 // timestamp, which will cause this test to fail, ie hit the
338 // "trash should not be emptied" condition.
339 let result = r2.causally_stable_threshold();
340 match result {
341 Some(cst) if cst < ops[0].timestamp() => {
342 println!(
343 "\ncausally stable threshold:\n{:#?}\n\ntrash operation:\n{:#?}",
344 cst,
345 ops[0].timestamp()
346 );
347 panic!("!error: causally stable threshold is less than trash operation timestamp");
348 }
349 None => panic!("!error: causally stable threshold not found"),
350 _ => {}
351 }
352
353 // empty trash
354 r1.tree_mut().rm_subtree(&ids["trash"], false);
355 println!("\nDelete op is now causally stable, so we can empty trash:");
356 print_tree(r1.tree(), &ids["forest"]);
357}
358
359fn print_help() {
360 let buf = "
361Usage: tree <demo>
362
363<demo> can be any of:
364 demo_concurrent_moves
365 demo_concurrent_moves_cycle
366 demo_truncate_log
367 demo_walk_deep_tree
368 demo_move_to_trash
369
370";
371 println!("{}", buf);
372}
373
374// Returns op tuples representing a depth-first tree,
375// with 2 children for each parent.
376fn mktree_ops(
377 ops: &mut Vec<(TypeId, TypeMeta, TypeActor)>,
378 r: &mut TreeReplica<TypeId, TypeMeta, TypeActor>,
379 parent_id: u64,
380 depth: usize,
381 max_depth: usize,
382) {
383 if depth > max_depth {
384 return;
385 }
386
387 for i in 0..2 {
388 let name = if i == 0 { "a" } else { "b" };
389 let child_id = new_id();
390 ops.push((parent_id, name, child_id));
391 mktree_ops(ops, r, child_id, depth + 1, max_depth);
392 }
393}
394
395// applies each operation in ops to each replica in replicas.
396fn apply_ops_to_replicas<ID, TM, A>(
397 replicas: &mut [TreeReplica<ID, TM, A>],
398 ops: &[OpMove<ID, TM, A>],
399) where
400 ID: TreeId,
401 A: Actor + std::fmt::Debug,
402 TM: TreeMeta,
403{
404 for r in replicas.iter_mut() {
405 r.apply_ops_byref(ops);
406 }
407}
408
409// note: in practice a UUID (at least 128 bits should be used)
410fn new_id() -> TypeId {
411 rand::random::<TypeId>()
412}
413
414// print a treenode, recursively
415fn print_treenode<ID, TM>(tree: &Tree<ID, TM>, node_id: &ID, depth: usize, with_id: bool)
416where
417 ID: TreeId + std::fmt::Debug,
418 TM: TreeMeta + std::fmt::Debug,
419{
420 let result = tree.find(node_id);
421 let meta = match result {
422 Some(tn) => format!("{:?}", tn.metadata()),
423 None if depth == 0 => "forest".to_string(),
424 None => {
425 panic!("tree node {:?} not found", node_id);
426 }
427 };
428 println!("{:indent$}{}", "", meta, indent = depth * 2);
429
430 for c in tree.children(node_id) {
431 print_treenode(tree, &c, depth + 1, with_id);
432 }
433}Sourcepub fn children(&self, parent_id: &ID) -> Vec<ID>
pub fn children(&self, parent_id: &ID) -> Vec<ID>
returns children (IDs) of a given parent node. useful for walking tree. not used by crdt algo.
Examples found in repository?
415fn print_treenode<ID, TM>(tree: &Tree<ID, TM>, node_id: &ID, depth: usize, with_id: bool)
416where
417 ID: TreeId + std::fmt::Debug,
418 TM: TreeMeta + std::fmt::Debug,
419{
420 let result = tree.find(node_id);
421 let meta = match result {
422 Some(tn) => format!("{:?}", tn.metadata()),
423 None if depth == 0 => "forest".to_string(),
424 None => {
425 panic!("tree node {:?} not found", node_id);
426 }
427 };
428 println!("{:indent$}{}", "", meta, indent = depth * 2);
429
430 for c in tree.children(node_id) {
431 print_treenode(tree, &c, depth + 1, with_id);
432 }
433}Sourcepub fn walk<F>(&self, parent_id: &ID, f: F)
pub fn walk<F>(&self, parent_id: &ID, f: F)
walks tree and calls FnMut f for each node. not used by crdt algo.
walk uses a non-recursive algorithm, so calling it on a deep tree will not cause stack overflow.
Examples found in repository?
180fn demo_walk_deep_tree() {
181 let mut r1: TreeReplica<TypeId, TypeMeta, TypeActor> = TreeReplica::new(new_id());
182
183 let ids: HashMap<&str, TypeId> = [("root", new_id())].iter().cloned().collect();
184
185 // Generate initial tree state.
186 println!("generating ops...");
187 let mut ops = vec![(0, "root", ids["root"])];
188 mktree_ops(&mut ops, &mut r1, ids["root"], 2, 6); // <-- max 6 levels deep.
189
190 println!("applying ops...");
191 let ops_len = ops.len();
192 r1.apply_ops_byref(&r1.opmoves(ops));
193
194 println!("walking tree...");
195 r1.tree().walk(&ids["root"], |tree, node_id, depth| {
196 if true {
197 let meta = match tree.find(node_id) {
198 Some(tn) => format!("{:?}", tn.metadata()),
199 None => format!("{:?}", node_id),
200 };
201 println!("{:indent$}{}", "", meta, indent = depth);
202 }
203 });
204
205 println!("\nnodes in tree: {}", ops_len);
206}Sourcepub fn is_ancestor(&self, child_id: &ID, ancestor_id: &ID) -> bool
pub fn is_ancestor(&self, child_id: &ID, ancestor_id: &ID) -> bool
returns true if ancestor_id is an ancestor of child_id in tree.
parent | child
--------------
1 2
1 3
3 5
2 6
6 8
1
2 3
6 5
8
is 2 ancestor of 8? yes.
is 2 ancestor of 5? no.Trait Implementations§
Source§impl<'de, ID, TM> Deserialize<'de> for Tree<ID, TM>
impl<'de, ID, TM> Deserialize<'de> for Tree<ID, TM>
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Source§impl<ID: TreeId, TM: TreeMeta> IntoIterator for Tree<ID, TM>
Implement IntoIterator for Tree. This is useful for
walking all Nodes in tree without knowing a starting point.
impl<ID: TreeId, TM: TreeMeta> IntoIterator for Tree<ID, TM>
Implement IntoIterator for Tree. This is useful for
walking all Nodes in tree without knowing a starting point.
impl<ID: Eq + TreeId, TM: Eq + TreeMeta> Eq for Tree<ID, TM>
impl<ID: TreeId, TM: TreeMeta> StructuralPartialEq for Tree<ID, TM>
Auto Trait Implementations§
impl<ID, TM> Freeze for Tree<ID, TM>
impl<ID, TM> RefUnwindSafe for Tree<ID, TM>where
ID: RefUnwindSafe,
TM: RefUnwindSafe,
impl<ID, TM> Send for Tree<ID, TM>
impl<ID, TM> Sync for Tree<ID, TM>
impl<ID, TM> Unpin for Tree<ID, TM>
impl<ID, TM> UnwindSafe for Tree<ID, TM>where
ID: UnwindSafe,
TM: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more