Tree

Struct Tree 

Source
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>

Source

pub fn new() -> Self

create a new Tree instance

Source

pub fn rm_child(&mut self, child_id: &ID)

helper for removing a triple based on child_id

Source

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?
examples/demo.rs (line 354)
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}
Source

pub fn add_node(&mut self, child_id: ID, tt: TreeNode<ID, TM>)

adds a node to the tree

Source

pub fn find(&self, child_id: &ID) -> Option<&TreeNode<ID, TM>>

returns matching node, or None.

Examples found in repository?
examples/demo.rs (line 197)
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}
Source

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?
examples/demo.rs (line 430)
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}
Source

pub fn walk<F>(&self, parent_id: &ID, f: F)
where F: FnMut(&Self, &ID, usize),

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?
examples/demo.rs (lines 195-203)
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}
Source

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.
Source

pub fn num_nodes(&self) -> usize

Total number of nodes (triples) in the tree

Trait Implementations§

Source§

impl<ID: Clone + TreeId, TM: Clone + TreeMeta> Clone for Tree<ID, TM>

Source§

fn clone(&self) -> Tree<ID, TM>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<ID: Debug + TreeId, TM: Debug + TreeMeta> Debug for Tree<ID, TM>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<ID: Default + TreeId, TM: Default + TreeMeta> Default for Tree<ID, TM>

Source§

fn default() -> Tree<ID, TM>

Returns the “default value” for a type. Read more
Source§

impl<'de, ID, TM> Deserialize<'de> for Tree<ID, TM>
where ID: Deserialize<'de> + TreeId, TM: Deserialize<'de> + TreeMeta,

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<ID: TreeId + Debug, TM: TreeMeta + Debug> Display for Tree<ID, TM>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
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.

Source§

type Item = (ID, TreeNode<ID, TM>)

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<ID, TreeNode<ID, TM>>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<ID: PartialEq + TreeId, TM: PartialEq + TreeMeta> PartialEq for Tree<ID, TM>

Source§

fn eq(&self, other: &Tree<ID, TM>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<ID, TM> Serialize for Tree<ID, TM>
where ID: Serialize + TreeId, TM: Serialize + TreeMeta,

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<ID: Eq + TreeId, TM: Eq + TreeMeta> Eq for Tree<ID, TM>

Source§

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>

§

impl<ID, TM> Send for Tree<ID, TM>
where ID: Send, TM: Send,

§

impl<ID, TM> Sync for Tree<ID, TM>
where ID: Sync, TM: Sync,

§

impl<ID, TM> Unpin for Tree<ID, TM>
where ID: Unpin, TM: Unpin,

§

impl<ID, TM> UnwindSafe for Tree<ID, TM>
where ID: UnwindSafe, TM: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<TM> TreeMeta for TM
where TM: Clone,