forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

parent.rs151 lines, 6.1 KiBHistoryRawDownload
1//! This file contains the methods to maintain the parent-child relationship in Loro.
2//! The child-parent relationship is established when the child container is created.
3//! It won't be changed. So the depth of a container is fixed.
4//!
5//!
6
7use loro_common::{ContainerID, LoroValue};
8use smallvec::SmallVec;
9
10use crate::{
11 arena::SharedArena,
12 change::Change,
13 container::{list::list_op::ListOp, map::MapSet},
14 op::{ListSlice, Op, RawOp, RawOpContent},
15 DocState, OpLog,
16};
17
18impl OpLog {
19 /// Establish the link between the child container and the parent container.
20 /// This relationship will never be broken.
21 /// It's used at the entry of creating new ops to ensure all the valid containers
22 /// in Loro are properly linked.
23 pub(super) fn register_container_and_parent_link(&self, change: &Change) {
24 let arena = &self.arena;
25 register_container_and_parent_link(arena, change);
26 }
27}
28
29pub(super) fn register_container_and_parent_link(arena: &SharedArena, change: &Change) {
30 for op in change.ops.iter() {
31 op.content.visit_created_children(&mut |c| {
32 let idx = arena.register_container(c);
33 arena.set_parent(idx, Some(op.container));
34 });
35 }
36}
37
38/// A transaction registers the parent of every container its ops create when it applies them
39/// ([`DocState::set_container_parent_by_raw_op`]), before the change is committed. Until then
40/// the op log cannot tell the parent, so a container a local op path forgot to link reads as
41/// deleted instead of failing (see `SharedArena::get_parent`). Check it on commit.
42#[cfg(debug_assertions)]
43pub(super) fn assert_local_parent_links_registered(arena: &SharedArena, change: &Change) {
44 for op in change.ops.iter() {
45 op.content.visit_created_children(&mut |c| {
46 let parent = arena
47 .id_to_idx(c)
48 .and_then(|idx| arena.get_registered_parent(idx));
49 assert_eq!(
50 parent,
51 Some(Some(op.container)),
52 "InternalError: local op {} created {c} without registering its parent",
53 loro_common::ID::new(change.id.peer, op.counter)
54 );
55 });
56 }
57}
58
59impl DocState {
60 /// This is used in txn to short cut the process of applying an op to the state.
61 /// So the op here has not been registered on the oplog yet.
62 pub(super) fn set_container_parent_by_raw_op(&self, raw_op: &RawOp) {
63 let container = raw_op.container;
64 match &raw_op.content {
65 RawOpContent::List(op) => {
66 if let ListOp::Insert {
67 slice: ListSlice::RawData(list),
68 ..
69 } = op
70 {
71 let list = match list {
72 std::borrow::Cow::Borrowed(list) => list.iter(),
73 std::borrow::Cow::Owned(list) => list.iter(),
74 };
75 for value in list {
76 if let LoroValue::Container(c) = value {
77 let idx = self.arena.register_container(c);
78 self.arena.set_parent(idx, Some(container));
79 }
80 }
81 }
82 if let ListOp::Set {
83 elem_id: _,
84 value: LoroValue::Container(c),
85 } = op
86 {
87 let idx = self.arena.register_container(c);
88 self.arena.set_parent(idx, Some(container));
89 }
90 }
91 RawOpContent::Map(MapSet { key: _, value }) => {
92 if let Some(LoroValue::Container(c)) = value {
93 let idx = self.arena.register_container(c);
94 self.arena.set_parent(idx, Some(container));
95 }
96 }
97 RawOpContent::Tree(tree) => {
98 let target = tree.target();
99 // create associated metadata container
100 // TODO: maybe we could create map container only when setting metadata
101 let container_id = target.associated_meta_container();
102 let child_idx = self.arena.register_container(&container_id);
103 self.arena.set_parent(child_idx, Some(container));
104 }
105 #[cfg(feature = "counter")]
106 RawOpContent::Counter(_) => {}
107 RawOpContent::Unknown { .. } => {}
108 }
109 }
110
111 /// Create store entries for the containers this local op brings alive.
112 ///
113 /// Full snapshot export no longer walks the alive-container graph, so "every referenced
114 /// container has a store entry" must hold by construction: an empty child inserted via
115 /// `insert_container` would otherwise only exist inside its parent's value and be skipped
116 /// by `flush`.
117 ///
118 /// Mergeable markers are deliberately NOT handled here: an ensured-but-empty mergeable
119 /// child has no independent existence — the parent map's marker is its single source of
120 /// truth, and materializing a store entry for it would keep `has_container` true after the
121 /// marker is removed (see `loro_get_container_for_deleted_mergeable_children`).
122 pub(super) fn ensure_containers_created_by_op(&mut self, op: &Op) {
123 let mut to_ensure: SmallVec<[ContainerID; 2]> = SmallVec::new();
124 op.content
125 .visit_created_children(&mut |c| to_ensure.push(c.clone()));
126
127 for id in to_ensure {
128 self.ensure_container(&id);
129 }
130 }
131}
132
133#[cfg(test)]
134mod test {
135 use loro_common::ID;
136
137 use crate::{arena::SharedArena, LoroDoc, TreeParentId};
138
139 #[test]
140 #[cfg(debug_assertions)]
141 #[should_panic(expected = "without registering its parent")]
142 fn a_local_op_must_link_the_containers_it_creates() {
143 let doc = LoroDoc::new_auto_commit();
144 doc.set_peer_id(1).unwrap();
145 doc.get_tree("tree").create(TreeParentId::Root).unwrap();
146 doc.commit_then_renew();
147 let change = doc.oplog().lock().get_change_at(ID::new(1, 0)).unwrap();
148 // An arena that the transaction did not register the node's meta in.
149 super::assert_local_parent_links_registered(&SharedArena::new(), &change);
150 }
151}