project_note
Clone
https://git.tahinli.com/Tahinli/project_note.git
0 watching·0 forks·Rust·3.6 MiB·c49f5e7·Tahinli·1 month ago·2 commits
| 1 | use either::Either; |
| 2 | use enum_as_inner::EnumAsInner; |
| 3 | use fractional_index::FractionalIndex; |
| 4 | use itertools::Itertools; |
| 5 | use loro_common::{ |
| 6 | ContainerID, IdFull, IdLp, LoroError, LoroResult, LoroTreeError, LoroValue, PeerID, TreeID, |
| 7 | DELETED_TREE_ROOT, ID, |
| 8 | }; |
| 9 | use rand::SeedableRng; |
| 10 | use rustc_hash::{FxHashMap, FxHashSet}; |
| 11 | use serde::Serialize; |
| 12 | use std::collections::VecDeque; |
| 13 | use std::fmt::Debug; |
| 14 | use std::ops::{Deref, DerefMut}; |
| 15 | use std::sync::Weak; |
| 16 | |
| 17 | use super::{ApplyLocalOpReturn, ContainerState, DiffApplyContext}; |
| 18 | use crate::configure::Configure; |
| 19 | use crate::container::idx::ContainerIdx; |
| 20 | use crate::delta::{TreeDiff, TreeDiffItem, TreeExternalDiff}; |
| 21 | use crate::diff_calc::DiffMode; |
| 22 | use crate::event::InternalDiff; |
| 23 | use crate::op::Op; |
| 24 | use crate::{ |
| 25 | container::tree::tree_op::TreeOp, |
| 26 | delta::TreeInternalDiff, |
| 27 | event::{Diff, Index}, |
| 28 | op::RawOp, |
| 29 | }; |
| 30 | use crate::{DocState, LoroDocInner}; |
| 31 | |
| 32 | #[derive(Clone, Debug, EnumAsInner)] |
| 33 | pub enum TreeFractionalIndexConfigInner { |
| 34 | GenerateFractionalIndex { |
| 35 | jitter: u8, |
| 36 | rng: Box<rand::rngs::StdRng>, |
| 37 | }, |
| 38 | MoveDisabled, |
| 39 | } |
| 40 | |
| 41 | /// The state of movable tree. |
| 42 | /// |
| 43 | /// using flat representation |
| 44 | #[derive(Debug, Clone)] |
| 45 | pub struct TreeState { |
| 46 | idx: ContainerIdx, |
| 47 | trees: FxHashMap<TreeID, TreeStateNode>, |
| 48 | children: TreeChildrenCache, |
| 49 | fractional_index_config: TreeFractionalIndexConfigInner, |
| 50 | peer_id: PeerID, |
| 51 | } |
| 52 | |
| 53 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 54 | pub(crate) struct TreeStateNode { |
| 55 | pub parent: TreeParentId, |
| 56 | pub position: Option<FractionalIndex>, |
| 57 | pub last_move_op: IdFull, |
| 58 | } |
| 59 | |
| 60 | #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] |
| 61 | pub(crate) struct NodePosition { |
| 62 | pub(crate) position: FractionalIndex, |
| 63 | // different nodes created by a peer may have the same position |
| 64 | // when we merge updates that cause cycles. |
| 65 | // for example [::fuzz::test::test_tree::same_peer_have_same_position()] |
| 66 | pub(crate) idlp: IdLp, |
| 67 | } |
| 68 | |
| 69 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, EnumAsInner, Serialize)] |
| 70 | pub enum TreeParentId { |
| 71 | Node(TreeID), |
| 72 | Root, |
| 73 | Deleted, |
| 74 | // We use `Unexist` as the old parent of a new node created |
| 75 | // so we can infer the retreat internal diff is `Uncreate` |
| 76 | Unexist, |
| 77 | } |
| 78 | |
| 79 | impl From<Option<TreeID>> for TreeParentId { |
| 80 | fn from(id: Option<TreeID>) -> Self { |
| 81 | match id { |
| 82 | Some(id) => { |
| 83 | if TreeID::is_deleted_root(&id) { |
| 84 | TreeParentId::Deleted |
| 85 | } else { |
| 86 | TreeParentId::Node(id) |
| 87 | } |
| 88 | } |
| 89 | None => TreeParentId::Root, |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | impl From<TreeID> for TreeParentId { |
| 95 | fn from(id: TreeID) -> Self { |
| 96 | if TreeID::is_deleted_root(&id) { |
| 97 | TreeParentId::Deleted |
| 98 | } else { |
| 99 | TreeParentId::Node(id) |
| 100 | } |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | impl From<&TreeID> for TreeParentId { |
| 105 | fn from(id: &TreeID) -> Self { |
| 106 | if TreeID::is_deleted_root(id) { |
| 107 | TreeParentId::Deleted |
| 108 | } else { |
| 109 | TreeParentId::Node(*id) |
| 110 | } |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | impl TreeParentId { |
| 115 | pub fn tree_id(&self) -> Option<TreeID> { |
| 116 | match self { |
| 117 | TreeParentId::Node(id) => Some(*id), |
| 118 | TreeParentId::Root => None, |
| 119 | TreeParentId::Deleted => Some(DELETED_TREE_ROOT), |
| 120 | TreeParentId::Unexist => unreachable!(), |
| 121 | } |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | #[derive(Debug, Clone)] |
| 126 | enum NodeChildren { |
| 127 | Vec(Vec<(NodePosition, TreeID)>), |
| 128 | BTree(btree::ChildTree), |
| 129 | } |
| 130 | |
| 131 | impl Default for NodeChildren { |
| 132 | fn default() -> Self { |
| 133 | NodeChildren::Vec(vec![]) |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | impl NodeChildren { |
| 138 | const MAX_SIZE_FOR_ARRAY: usize = 16; |
| 139 | fn get_index_by_child_id(&self, target: &TreeID) -> Option<usize> { |
| 140 | match self { |
| 141 | NodeChildren::Vec(v) => v.iter().position(|(_, id)| id == target), |
| 142 | NodeChildren::BTree(btree) => btree.id_to_index(target), |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | fn get_last_insert_index_by_position( |
| 147 | &self, |
| 148 | node_position: &NodePosition, |
| 149 | ) -> Result<usize, usize> { |
| 150 | match self { |
| 151 | NodeChildren::Vec(v) => v.binary_search_by_key(&node_position, |x| &x.0), |
| 152 | NodeChildren::BTree(btree) => btree.get_index_by_node_position(node_position), |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | fn get_node_position_at(&self, pos: usize) -> Option<&NodePosition> { |
| 157 | match self { |
| 158 | NodeChildren::Vec(v) => v.get(pos).map(|x| &x.0), |
| 159 | NodeChildren::BTree(btree) => btree.get_elem_at(pos).map(|x| x.pos.as_ref()), |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | fn get_elem_at(&self, pos: usize) -> Option<(&NodePosition, &TreeID)> { |
| 164 | match self { |
| 165 | NodeChildren::Vec(v) => v.get(pos).map(|x| (&x.0, &x.1)), |
| 166 | NodeChildren::BTree(btree) => btree.get_elem_at(pos).map(|x| (x.pos.as_ref(), &x.id)), |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | fn generate_fi_at(&self, pos: usize, target: &TreeID) -> FractionalIndexGenResult { |
| 171 | let mut reset_ids = vec![]; |
| 172 | let mut left = None; |
| 173 | let mut next_right = None; |
| 174 | { |
| 175 | let mut right = None; |
| 176 | let children_num = self.len(); |
| 177 | if children_num == 0 { |
| 178 | return FractionalIndexGenResult::Ok(FractionalIndex::default()); |
| 179 | } |
| 180 | |
| 181 | if pos > 0 { |
| 182 | left = self.get_node_position_at(pos - 1); |
| 183 | } |
| 184 | if pos < children_num { |
| 185 | right = self.get_elem_at(pos); |
| 186 | } |
| 187 | |
| 188 | let left_fi = left.map(|x| &x.position); |
| 189 | // if left and right have the same fractional indexes, we need to scan further to |
| 190 | // find all the ids that need to be reset |
| 191 | if let Some(left_fi) = left_fi { |
| 192 | if Some(left_fi) == right.map(|x| &x.0.position) { |
| 193 | // TODO: the min length between left and right |
| 194 | reset_ids.push(*right.unwrap().1); |
| 195 | for i in (pos + 1)..children_num { |
| 196 | let this_position = |
| 197 | self.get_node_position_at(i).map(|x| &x.position).unwrap(); |
| 198 | if this_position == left_fi { |
| 199 | reset_ids.push(*self.get_elem_at(i).unwrap().1); |
| 200 | } else { |
| 201 | next_right = Some(this_position.clone()); |
| 202 | break; |
| 203 | } |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | if reset_ids.is_empty() { |
| 209 | return FractionalIndexGenResult::Ok( |
| 210 | FractionalIndex::new(left.map(|x| &x.position), right.map(|x| &x.0.position)) |
| 211 | .unwrap(), |
| 212 | ); |
| 213 | } |
| 214 | } |
| 215 | let positions = FractionalIndex::generate_n_evenly( |
| 216 | left.map(|x| &x.position), |
| 217 | next_right.as_ref(), |
| 218 | reset_ids.len() + 1, |
| 219 | ) |
| 220 | .unwrap(); |
| 221 | FractionalIndexGenResult::Rearrange( |
| 222 | Some(*target) |
| 223 | .into_iter() |
| 224 | .chain(reset_ids) |
| 225 | .zip(positions) |
| 226 | .collect(), |
| 227 | ) |
| 228 | } |
| 229 | |
| 230 | fn get_id_at(&self, pos: usize) -> Option<TreeID> { |
| 231 | match self { |
| 232 | NodeChildren::Vec(v) => v.get(pos).map(|x| x.1), |
| 233 | NodeChildren::BTree(btree) => btree.get_elem_at(pos).map(|x| x.id), |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | fn delete_child(&mut self, target: &TreeID) { |
| 238 | match self { |
| 239 | NodeChildren::Vec(v) => { |
| 240 | v.retain(|(_, id)| id != target); |
| 241 | } |
| 242 | NodeChildren::BTree(v) => { |
| 243 | v.delete_child(target); |
| 244 | } |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | fn upgrade(&mut self) { |
| 249 | match self { |
| 250 | NodeChildren::Vec(v) => { |
| 251 | let mut btree = btree::ChildTree::new(); |
| 252 | for (pos, id) in v.drain(..) { |
| 253 | btree.insert_child(pos, id); |
| 254 | } |
| 255 | |
| 256 | *self = NodeChildren::BTree(btree); |
| 257 | } |
| 258 | NodeChildren::BTree(_) => unreachable!(), |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | fn insert_child(&mut self, pos: NodePosition, id: TreeID) { |
| 263 | match self { |
| 264 | NodeChildren::Vec(v) => { |
| 265 | if v.len() >= Self::MAX_SIZE_FOR_ARRAY { |
| 266 | self.upgrade(); |
| 267 | return self.insert_child(pos, id); |
| 268 | } |
| 269 | |
| 270 | let r = v.binary_search_by(|(target, _)| target.cmp(&pos)); |
| 271 | match r { |
| 272 | Ok(_) => unreachable!(), |
| 273 | Err(i) => { |
| 274 | v.insert(i, (pos, id)); |
| 275 | } |
| 276 | } |
| 277 | } |
| 278 | NodeChildren::BTree(v) => { |
| 279 | v.insert_child(pos, id); |
| 280 | } |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | fn push_child_in_order(&mut self, pos: NodePosition, id: TreeID) { |
| 285 | match self { |
| 286 | NodeChildren::Vec(v) => { |
| 287 | if v.len() >= Self::MAX_SIZE_FOR_ARRAY { |
| 288 | self.upgrade(); |
| 289 | return self.push_child_in_order(pos, id); |
| 290 | } |
| 291 | |
| 292 | if let Some(last) = v.last() { |
| 293 | assert!(last.0 < pos); |
| 294 | } |
| 295 | v.push((pos, id)); |
| 296 | } |
| 297 | NodeChildren::BTree(v) => { |
| 298 | v.push_child_in_order(pos, id); |
| 299 | } |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | fn len(&self) -> usize { |
| 304 | match self { |
| 305 | NodeChildren::Vec(v) => v.len(), |
| 306 | NodeChildren::BTree(v) => v.len(), |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | fn has_child(&self, node_position: &NodePosition) -> bool { |
| 311 | match self { |
| 312 | NodeChildren::Vec(v) => v |
| 313 | .binary_search_by(|(target, _)| target.cmp(node_position)) |
| 314 | .is_ok(), |
| 315 | NodeChildren::BTree(v) => v.has_child(node_position), |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | fn iter(&self) -> impl Iterator<Item = (&NodePosition, &TreeID)> { |
| 320 | match self { |
| 321 | NodeChildren::Vec(v) => Either::Left(v.iter().map(|x| (&x.0, &x.1))), |
| 322 | NodeChildren::BTree(t) => Either::Right(t.iter()), |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | #[derive(Clone, Default)] |
| 328 | struct TreeChildrenCache(FxHashMap<TreeParentId, NodeChildren>); |
| 329 | |
| 330 | mod btree { |
| 331 | use std::{cmp::Ordering, ops::Range, sync::Arc}; |
| 332 | |
| 333 | use generic_btree::{ |
| 334 | rle::{CanRemove, HasLength, Mergeable, Sliceable, TryInsert}, |
| 335 | BTree, BTreeTrait, Cursor, FindResult, LeafIndex, LengthFinder, Query, UseLengthFinder, |
| 336 | }; |
| 337 | use loro_common::TreeID; |
| 338 | use rustc_hash::FxHashMap; |
| 339 | |
| 340 | use super::NodePosition; |
| 341 | |
| 342 | struct ChildTreeTrait; |
| 343 | #[derive(Debug, Clone)] |
| 344 | pub(super) struct ChildTree { |
| 345 | tree: BTree<ChildTreeTrait>, |
| 346 | id_to_leaf_index: FxHashMap<TreeID, LeafIndex>, |
| 347 | } |
| 348 | |
| 349 | impl ChildTree { |
| 350 | pub(super) fn new() -> Self { |
| 351 | Self { |
| 352 | tree: BTree::new(), |
| 353 | id_to_leaf_index: FxHashMap::default(), |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | pub(super) fn insert_child(&mut self, pos: NodePosition, id: TreeID) { |
| 358 | let (c, _) = self.tree.insert::<KeyQuery>( |
| 359 | &pos, |
| 360 | Elem { |
| 361 | pos: Arc::new(pos.clone()), |
| 362 | id, |
| 363 | }, |
| 364 | ); |
| 365 | |
| 366 | self.id_to_leaf_index.insert(id, c.leaf); |
| 367 | } |
| 368 | |
| 369 | pub(super) fn push_child_in_order(&mut self, pos: NodePosition, id: TreeID) { |
| 370 | let c = self.tree.push(Elem { |
| 371 | pos: Arc::new(pos.clone()), |
| 372 | id, |
| 373 | }); |
| 374 | self.id_to_leaf_index.insert(id, c.leaf); |
| 375 | } |
| 376 | |
| 377 | pub(super) fn delete_child(&mut self, id: &TreeID) { |
| 378 | if let Some(leaf) = self.id_to_leaf_index.remove(id) { |
| 379 | self.tree.remove_leaf(Cursor { leaf, offset: 0 }); |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | pub(super) fn has_child(&self, pos: &NodePosition) -> bool { |
| 384 | match self.tree.query::<KeyQuery>(pos) { |
| 385 | Some(r) => r.found, |
| 386 | None => false, |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | pub(super) fn iter(&self) -> impl Iterator<Item = (&NodePosition, &TreeID)> { |
| 391 | self.tree.iter().map(|x| (&*x.pos, &x.id)) |
| 392 | } |
| 393 | |
| 394 | pub(super) fn len(&self) -> usize { |
| 395 | self.tree.root_cache().len |
| 396 | } |
| 397 | |
| 398 | pub(super) fn get_elem_at(&self, pos: usize) -> Option<&Elem> { |
| 399 | let result = self.tree.query::<LengthFinder>(&pos)?; |
| 400 | if !result.found { |
| 401 | return None; |
| 402 | } |
| 403 | self.tree.get_elem(result.leaf()) |
| 404 | } |
| 405 | |
| 406 | pub(super) fn id_to_index(&self, id: &TreeID) -> Option<usize> { |
| 407 | let leaf_index = self.id_to_leaf_index.get(id)?; |
| 408 | let mut ans = 0; |
| 409 | self.tree.visit_previous_caches( |
| 410 | Cursor { |
| 411 | leaf: *leaf_index, |
| 412 | offset: 0, |
| 413 | }, |
| 414 | |prev| match prev { |
| 415 | generic_btree::PreviousCache::NodeCache(c) => { |
| 416 | ans += c.len; |
| 417 | } |
| 418 | generic_btree::PreviousCache::PrevSiblingElem(_) => { |
| 419 | ans += 1; |
| 420 | } |
| 421 | generic_btree::PreviousCache::ThisElemAndOffset { .. } => {} |
| 422 | }, |
| 423 | ); |
| 424 | |
| 425 | Some(ans) |
| 426 | } |
| 427 | |
| 428 | pub(super) fn get_index_by_node_position( |
| 429 | &self, |
| 430 | node_position: &NodePosition, |
| 431 | ) -> Result<usize, usize> { |
| 432 | let Some(res) = self.tree.query::<KeyQuery>(node_position) else { |
| 433 | return Ok(0); |
| 434 | }; |
| 435 | let mut ans = 0; |
| 436 | self.tree |
| 437 | .visit_previous_caches(res.cursor, |prev| match prev { |
| 438 | generic_btree::PreviousCache::NodeCache(c) => { |
| 439 | ans += c.len; |
| 440 | } |
| 441 | generic_btree::PreviousCache::PrevSiblingElem(_) => { |
| 442 | ans += 1; |
| 443 | } |
| 444 | generic_btree::PreviousCache::ThisElemAndOffset { elem: _, offset } => { |
| 445 | ans += offset; |
| 446 | } |
| 447 | }); |
| 448 | if res.found { |
| 449 | Ok(ans) |
| 450 | } else { |
| 451 | Err(ans) |
| 452 | } |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | #[derive(Clone, Debug)] |
| 457 | pub(super) struct Elem { |
| 458 | pub(super) pos: Arc<NodePosition>, |
| 459 | pub(super) id: TreeID, |
| 460 | } |
| 461 | |
| 462 | impl Mergeable for Elem { |
| 463 | fn can_merge(&self, _rhs: &Self) -> bool { |
| 464 | false |
| 465 | } |
| 466 | |
| 467 | fn merge_right(&mut self, _rhs: &Self) { |
| 468 | unreachable!() |
| 469 | } |
| 470 | |
| 471 | fn merge_left(&mut self, _left: &Self) { |
| 472 | unreachable!() |
| 473 | } |
| 474 | } |
| 475 | |
| 476 | impl HasLength for Elem { |
| 477 | fn rle_len(&self) -> usize { |
| 478 | 1 |
| 479 | } |
| 480 | } |
| 481 | |
| 482 | impl Sliceable for Elem { |
| 483 | fn _slice(&self, range: std::ops::Range<usize>) -> Self { |
| 484 | assert!(range.len() == 1); |
| 485 | self.clone() |
| 486 | } |
| 487 | } |
| 488 | |
| 489 | impl CanRemove for Elem { |
| 490 | fn can_remove(&self) -> bool { |
| 491 | false |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | impl TryInsert for Elem { |
| 496 | fn try_insert(&mut self, _pos: usize, elem: Self) -> Result<(), Self> |
| 497 | where |
| 498 | Self: Sized, |
| 499 | { |
| 500 | Err(elem) |
| 501 | } |
| 502 | } |
| 503 | |
| 504 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 505 | struct Cache { |
| 506 | range: Option<Range<Arc<NodePosition>>>, |
| 507 | len: usize, |
| 508 | } |
| 509 | |
| 510 | impl BTreeTrait for ChildTreeTrait { |
| 511 | type Elem = Elem; |
| 512 | type Cache = Cache; |
| 513 | type CacheDiff = (); |
| 514 | const USE_DIFF: bool = false; |
| 515 | |
| 516 | fn calc_cache_internal( |
| 517 | cache: &mut Self::Cache, |
| 518 | caches: &[generic_btree::Child<Self>], |
| 519 | ) -> Self::CacheDiff { |
| 520 | if caches.is_empty() { |
| 521 | *cache = Default::default(); |
| 522 | return; |
| 523 | } |
| 524 | |
| 525 | *cache = Cache { |
| 526 | range: Some( |
| 527 | caches[0].cache.range.as_ref().unwrap().start.clone() |
| 528 | ..caches |
| 529 | .last() |
| 530 | .unwrap() |
| 531 | .cache |
| 532 | .range |
| 533 | .as_ref() |
| 534 | .unwrap() |
| 535 | .end |
| 536 | .clone(), |
| 537 | ), |
| 538 | len: caches.iter().map(|x| x.cache.len).sum(), |
| 539 | }; |
| 540 | } |
| 541 | |
| 542 | fn apply_cache_diff(_cache: &mut Self::Cache, _diff: &Self::CacheDiff) { |
| 543 | unreachable!() |
| 544 | } |
| 545 | |
| 546 | fn merge_cache_diff(_diff1: &mut Self::CacheDiff, _diff2: &Self::CacheDiff) {} |
| 547 | |
| 548 | fn get_elem_cache(elem: &Self::Elem) -> Self::Cache { |
| 549 | Cache { |
| 550 | range: Some(elem.pos.clone()..elem.pos.clone()), |
| 551 | len: 1, |
| 552 | } |
| 553 | } |
| 554 | |
| 555 | fn new_cache_to_diff(_cache: &Self::Cache) -> Self::CacheDiff {} |
| 556 | |
| 557 | fn sub_cache(_cache_lhs: &Self::Cache, _cache_rhs: &Self::Cache) -> Self::CacheDiff {} |
| 558 | } |
| 559 | |
| 560 | struct KeyQuery; |
| 561 | |
| 562 | impl Query<ChildTreeTrait> for KeyQuery { |
| 563 | type QueryArg = NodePosition; |
| 564 | |
| 565 | #[inline(always)] |
| 566 | fn init(_target: &Self::QueryArg) -> Self { |
| 567 | KeyQuery |
| 568 | } |
| 569 | |
| 570 | #[inline] |
| 571 | fn find_node( |
| 572 | &mut self, |
| 573 | target: &Self::QueryArg, |
| 574 | caches: &[generic_btree::Child<ChildTreeTrait>], |
| 575 | ) -> FindResult { |
| 576 | let result = caches.binary_search_by(|x| { |
| 577 | let range = x.cache.range.as_ref().unwrap(); |
| 578 | if target < &range.start { |
| 579 | core::cmp::Ordering::Greater |
| 580 | } else if target > &range.end { |
| 581 | core::cmp::Ordering::Less |
| 582 | } else { |
| 583 | core::cmp::Ordering::Equal |
| 584 | } |
| 585 | }); |
| 586 | |
| 587 | match result { |
| 588 | Ok(i) => FindResult::new_found(i, 0), |
| 589 | Err(i) => FindResult::new_missing( |
| 590 | i.min(caches.len() - 1), |
| 591 | if i == caches.len() { 1 } else { 0 }, |
| 592 | ), |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | #[inline(always)] |
| 597 | fn confirm_elem( |
| 598 | &mut self, |
| 599 | q: &Self::QueryArg, |
| 600 | elem: &<ChildTreeTrait as BTreeTrait>::Elem, |
| 601 | ) -> (usize, bool) { |
| 602 | match q.cmp(&elem.pos) { |
| 603 | Ordering::Less => (0, false), |
| 604 | Ordering::Equal => (0, true), |
| 605 | Ordering::Greater => (1, false), |
| 606 | } |
| 607 | } |
| 608 | } |
| 609 | |
| 610 | impl UseLengthFinder<ChildTreeTrait> for ChildTreeTrait { |
| 611 | fn get_len(cache: &<ChildTreeTrait as BTreeTrait>::Cache) -> usize { |
| 612 | cache.len |
| 613 | } |
| 614 | } |
| 615 | } |
| 616 | |
| 617 | impl Debug for TreeChildrenCache { |
| 618 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 619 | writeln!(f, "TreeChildrenCache {{")?; |
| 620 | for (parent, children) in self.0.iter() { |
| 621 | writeln!(f, " {:?}:{{", parent)?; |
| 622 | for (position, id) in children.iter() { |
| 623 | writeln!(f, " {:?} -> {:?}", position, id)?; |
| 624 | } |
| 625 | writeln!(f, " }}")?; |
| 626 | } |
| 627 | writeln!(f, "}}") |
| 628 | } |
| 629 | } |
| 630 | |
| 631 | impl Deref for TreeChildrenCache { |
| 632 | type Target = FxHashMap<TreeParentId, NodeChildren>; |
| 633 | |
| 634 | fn deref(&self) -> &Self::Target { |
| 635 | &self.0 |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | impl DerefMut for TreeChildrenCache { |
| 640 | fn deref_mut(&mut self) -> &mut Self::Target { |
| 641 | &mut self.0 |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | impl NodePosition { |
| 646 | fn new(position: FractionalIndex, idlp: IdLp) -> Self { |
| 647 | Self { position, idlp } |
| 648 | } |
| 649 | } |
| 650 | |
| 651 | pub(crate) enum FiIfNotConfigured { |
| 652 | UseJitterZero, |
| 653 | #[allow(unused)] |
| 654 | Throw, |
| 655 | #[allow(unused)] |
| 656 | Zero, |
| 657 | } |
| 658 | |
| 659 | impl TreeState { |
| 660 | pub fn new(idx: ContainerIdx, peer_id: PeerID) -> Self { |
| 661 | Self { |
| 662 | idx, |
| 663 | trees: FxHashMap::default(), |
| 664 | children: Default::default(), |
| 665 | fractional_index_config: TreeFractionalIndexConfigInner::GenerateFractionalIndex { |
| 666 | jitter: 0, |
| 667 | rng: Box::new(rand::rngs::StdRng::seed_from_u64(0)), |
| 668 | }, |
| 669 | peer_id, |
| 670 | } |
| 671 | } |
| 672 | |
| 673 | pub fn mov( |
| 674 | &mut self, |
| 675 | target: TreeID, |
| 676 | parent: TreeParentId, |
| 677 | id: IdFull, |
| 678 | position: Option<FractionalIndex>, |
| 679 | with_check: bool, |
| 680 | ) -> Result<(), LoroError> { |
| 681 | if with_check { |
| 682 | if let TreeParentId::Node(parent) = parent { |
| 683 | if !self.trees.contains_key(&parent) { |
| 684 | return Err(LoroTreeError::TreeNodeParentNotFound(parent).into()); |
| 685 | } |
| 686 | } |
| 687 | if self.is_ancestor_of(&target, &parent) { |
| 688 | return Err(LoroTreeError::CyclicMoveError.into()); |
| 689 | } |
| 690 | } |
| 691 | if let Some(old_parent) = self.trees.get(&target).map(|x| x.parent) { |
| 692 | // remove old position |
| 693 | self.try_delete_position_cache(&old_parent, &target); |
| 694 | } |
| 695 | |
| 696 | let entry = self.children.entry(parent).or_default(); |
| 697 | let node_position = NodePosition::new(position.clone().unwrap_or_default(), id.idlp()); |
| 698 | debug_assert!(!entry.has_child(&node_position)); |
| 699 | entry.insert_child(node_position, target); |
| 700 | |
| 701 | self.trees.insert( |
| 702 | target, |
| 703 | TreeStateNode { |
| 704 | parent, |
| 705 | position, |
| 706 | last_move_op: id, |
| 707 | }, |
| 708 | ); |
| 709 | |
| 710 | Ok(()) |
| 711 | } |
| 712 | |
| 713 | fn _init_push_tree_node_in_order( |
| 714 | &mut self, |
| 715 | target: TreeID, |
| 716 | parent: TreeParentId, |
| 717 | last_move_op: IdFull, |
| 718 | position: Option<FractionalIndex>, |
| 719 | ) -> Result<(), LoroError> { |
| 720 | debug_assert!(!self.trees.contains_key(&target)); |
| 721 | let entry = self.children.entry(parent).or_default(); |
| 722 | let node_position = |
| 723 | NodePosition::new(position.clone().unwrap_or_default(), last_move_op.idlp()); |
| 724 | debug_assert!(!entry.has_child(&node_position)); |
| 725 | entry.push_child_in_order(node_position, target); |
| 726 | self.trees.insert( |
| 727 | target, |
| 728 | TreeStateNode { |
| 729 | parent, |
| 730 | position, |
| 731 | last_move_op, |
| 732 | }, |
| 733 | ); |
| 734 | |
| 735 | Ok(()) |
| 736 | } |
| 737 | |
| 738 | #[inline(never)] |
| 739 | fn is_ancestor_of(&self, maybe_ancestor: &TreeID, node_id: &TreeParentId) -> bool { |
| 740 | if !self.trees.contains_key(maybe_ancestor) { |
| 741 | return false; |
| 742 | } |
| 743 | let mut node = *node_id; |
| 744 | let mut remaining = self.trees.len(); |
| 745 | loop { |
| 746 | match node { |
| 747 | TreeParentId::Node(id) => { |
| 748 | assert!(remaining > 0, "tree parent cycle"); |
| 749 | remaining -= 1; |
| 750 | if &id == maybe_ancestor { |
| 751 | return true; |
| 752 | } |
| 753 | let parent = self.trees.get(&id).unwrap().parent; |
| 754 | assert_ne!(parent, node, "is_ancestor_of loop"); |
| 755 | node = parent; |
| 756 | } |
| 757 | TreeParentId::Deleted | TreeParentId::Root => return false, |
| 758 | TreeParentId::Unexist => unreachable!(), |
| 759 | } |
| 760 | } |
| 761 | } |
| 762 | |
| 763 | /// Get the parent of the node, if the node does not exist, return None |
| 764 | pub fn parent(&self, target: &TreeID) -> Option<TreeParentId> { |
| 765 | self.trees.get(target).map(|x| x.parent) |
| 766 | } |
| 767 | |
| 768 | /// If the node is unexist, return None. If the node is deleted, return true. |
| 769 | pub(crate) fn is_node_deleted(&self, target: &TreeID) -> Option<bool> { |
| 770 | let mut node = *target; |
| 771 | let mut remaining = self.trees.len(); |
| 772 | loop { |
| 773 | let parent = self.trees.get(&node)?.parent; |
| 774 | assert!(remaining > 0, "tree parent cycle"); |
| 775 | remaining -= 1; |
| 776 | match parent { |
| 777 | TreeParentId::Deleted => return Some(true), |
| 778 | TreeParentId::Root => return Some(false), |
| 779 | TreeParentId::Node(parent) => node = parent, |
| 780 | TreeParentId::Unexist => unreachable!(), |
| 781 | } |
| 782 | } |
| 783 | } |
| 784 | |
| 785 | pub(crate) fn is_node_unexist(&self, target: &TreeID) -> bool { |
| 786 | !self.trees.contains_key(target) |
| 787 | } |
| 788 | |
| 789 | // Get all flat tree nodes, excluding deleted nodes. |
| 790 | pub(crate) fn tree_nodes(&self) -> Vec<TreeNode> { |
| 791 | self.get_all_tree_nodes_under(TreeParentId::Root) |
| 792 | } |
| 793 | |
| 794 | // Get all flat deleted nodes: directly deleted ones (parent `Deleted`) and their descendants. |
| 795 | pub(crate) fn deleted_tree_nodes(&self) -> Vec<TreeNode> { |
| 796 | self.get_all_tree_nodes_under(TreeParentId::Deleted) |
| 797 | } |
| 798 | |
| 799 | // Get all flat tree nodes under the parent |
| 800 | pub(crate) fn get_all_tree_nodes_under(&self, root: TreeParentId) -> Vec<TreeNode> { |
| 801 | let mut ans = vec![]; |
| 802 | let children = self.children.get(&root); |
| 803 | let mut q = children |
| 804 | .map(|x| VecDeque::from_iter(x.iter().enumerate().zip(std::iter::repeat(root)))) |
| 805 | .unwrap_or_default(); |
| 806 | |
| 807 | while let Some(((index, (position, &target)), parent)) = q.pop_front() { |
| 808 | ans.push(TreeNode { |
| 809 | id: target, |
| 810 | parent, |
| 811 | fractional_index: position.position.clone(), |
| 812 | index, |
| 813 | last_move_op: self.trees.get(&target).map(|x| x.last_move_op).unwrap(), |
| 814 | }); |
| 815 | if let Some(children) = self.children.get(&TreeParentId::Node(target)) { |
| 816 | q.extend( |
| 817 | children |
| 818 | .iter() |
| 819 | .enumerate() |
| 820 | .map(|(index, (position, this_target))| { |
| 821 | ((index, (position, this_target)), TreeParentId::Node(target)) |
| 822 | }), |
| 823 | ); |
| 824 | } |
| 825 | } |
| 826 | ans |
| 827 | } |
| 828 | |
| 829 | pub(crate) fn get_all_hierarchy_nodes_under( |
| 830 | &self, |
| 831 | root: TreeParentId, |
| 832 | ) -> Vec<TreeNodeWithChildren> { |
| 833 | let mut ans = vec![]; |
| 834 | let mut pending = vec![(root, &mut ans)]; |
| 835 | while let Some((parent, output)) = pending.pop() { |
| 836 | if let Some(children) = self.children.get(&parent) { |
| 837 | output.extend(children.iter().enumerate().map(|(index, (position, &id))| { |
| 838 | TreeNodeWithChildren { |
| 839 | id, |
| 840 | parent, |
| 841 | fractional_index: position.position.clone(), |
| 842 | index, |
| 843 | children: Vec::new(), |
| 844 | } |
| 845 | })); |
| 846 | for node in output.iter_mut().rev() { |
| 847 | pending.push((TreeParentId::Node(node.id), &mut node.children)); |
| 848 | } |
| 849 | } |
| 850 | } |
| 851 | ans |
| 852 | } |
| 853 | |
| 854 | fn bfs_all_alive_nodes_for_fast_snapshot(&self) -> Vec<TreeNode> { |
| 855 | let mut ans = vec![]; |
| 856 | self._bfs_all_nodes(TreeParentId::Root, &mut ans); |
| 857 | ans |
| 858 | } |
| 859 | |
| 860 | fn bfs_all_deleted_nodes_for_fast_snapshot(&self) -> Vec<TreeNode> { |
| 861 | let mut ans = vec![]; |
| 862 | self._bfs_all_nodes(TreeParentId::Deleted, &mut ans); |
| 863 | ans |
| 864 | } |
| 865 | |
| 866 | fn _bfs_all_nodes(&self, root: TreeParentId, ans: &mut Vec<TreeNode>) { |
| 867 | let mut pending = vec![root]; |
| 868 | while let Some(parent) = pending.pop() { |
| 869 | let Some(children) = self.children.get(&parent) else { |
| 870 | continue; |
| 871 | }; |
| 872 | for (index, (position, target)) in children.iter().enumerate() { |
| 873 | ans.push(TreeNode { |
| 874 | id: *target, |
| 875 | parent, |
| 876 | fractional_index: position.position.clone(), |
| 877 | index, |
| 878 | last_move_op: self.trees.get(target).map(|x| x.last_move_op).unwrap(), |
| 879 | }); |
| 880 | } |
| 881 | |
| 882 | // Preserve the snapshot's existing order: siblings first, followed |
| 883 | // by each sibling's subtree in sibling order. |
| 884 | let start = pending.len(); |
| 885 | pending.extend(children.iter().map(|(_, id)| TreeParentId::Node(*id))); |
| 886 | pending[start..].reverse(); |
| 887 | } |
| 888 | } |
| 889 | |
| 890 | pub fn nodes(&self) -> Vec<TreeID> { |
| 891 | self.trees.keys().copied().collect::<Vec<_>>() |
| 892 | } |
| 893 | |
| 894 | #[cfg(feature = "test_utils")] |
| 895 | pub fn max_counter(&self) -> i32 { |
| 896 | self.trees |
| 897 | .keys() |
| 898 | .filter(|&k| !self.is_node_deleted(k).unwrap()) |
| 899 | .map(|k| k.counter) |
| 900 | .max() |
| 901 | .unwrap_or(0) |
| 902 | } |
| 903 | |
| 904 | pub fn get_children<'a>( |
| 905 | &'a self, |
| 906 | parent: &TreeParentId, |
| 907 | ) -> Option<impl Iterator<Item = TreeID> + 'a> { |
| 908 | self.children.get(parent).map(|x| x.iter().map(|x| *x.1)) |
| 909 | } |
| 910 | |
| 911 | pub fn children_num(&self, parent: &TreeParentId) -> Option<usize> { |
| 912 | self.children.get(parent).map(|x| x.len()) |
| 913 | } |
| 914 | |
| 915 | /// Determine whether the target is the child of the node |
| 916 | /// |
| 917 | /// O(1) |
| 918 | pub fn is_parent(&self, target: &TreeID, parent: &TreeParentId) -> bool { |
| 919 | self.trees.get(target).is_some_and(|x| x.parent == *parent) |
| 920 | } |
| 921 | |
| 922 | /// Delete the position cache of the node |
| 923 | pub(crate) fn try_delete_position_cache(&mut self, parent: &TreeParentId, target: &TreeID) { |
| 924 | if let Some(x) = self.children.get_mut(parent) { |
| 925 | x.delete_child(target); |
| 926 | } |
| 927 | } |
| 928 | |
| 929 | pub(crate) fn generate_position_at( |
| 930 | &mut self, |
| 931 | target: &TreeID, |
| 932 | parent: &TreeParentId, |
| 933 | index: usize, |
| 934 | cfg: FiIfNotConfigured, |
| 935 | ) -> FractionalIndexGenResult { |
| 936 | match &mut self.fractional_index_config { |
| 937 | TreeFractionalIndexConfigInner::GenerateFractionalIndex { jitter, rng } => { |
| 938 | if *jitter == 0 { |
| 939 | self.children |
| 940 | .entry(*parent) |
| 941 | .or_default() |
| 942 | .generate_fi_at(index, target) |
| 943 | } else { |
| 944 | self.children |
| 945 | .entry(*parent) |
| 946 | .or_default() |
| 947 | .generate_fi_at_jitter(index, target, rng.as_mut(), *jitter) |
| 948 | } |
| 949 | } |
| 950 | TreeFractionalIndexConfigInner::MoveDisabled => match cfg { |
| 951 | FiIfNotConfigured::Throw => FractionalIndexGenResult::NotConfigured, |
| 952 | FiIfNotConfigured::UseJitterZero => self |
| 953 | .children |
| 954 | .entry(*parent) |
| 955 | .or_default() |
| 956 | .generate_fi_at(index, target), |
| 957 | FiIfNotConfigured::Zero => FractionalIndexGenResult::Ok(FractionalIndex::default()), |
| 958 | }, |
| 959 | } |
| 960 | } |
| 961 | |
| 962 | pub(crate) fn is_fractional_index_enabled(&self) -> bool { |
| 963 | !matches!( |
| 964 | self.fractional_index_config, |
| 965 | TreeFractionalIndexConfigInner::MoveDisabled |
| 966 | ) |
| 967 | } |
| 968 | |
| 969 | pub(crate) fn enable_generate_fractional_index(&mut self, jitter: u8) { |
| 970 | if let TreeFractionalIndexConfigInner::GenerateFractionalIndex { |
| 971 | jitter: old_jitter, .. |
| 972 | } = &mut self.fractional_index_config |
| 973 | { |
| 974 | *old_jitter = jitter; |
| 975 | return; |
| 976 | } |
| 977 | self.fractional_index_config = TreeFractionalIndexConfigInner::GenerateFractionalIndex { |
| 978 | jitter, |
| 979 | rng: Box::new(rand::rngs::StdRng::seed_from_u64(self.peer_id)), |
| 980 | }; |
| 981 | } |
| 982 | |
| 983 | pub(crate) fn disable_generate_fractional_index(&mut self) { |
| 984 | self.fractional_index_config = TreeFractionalIndexConfigInner::MoveDisabled; |
| 985 | } |
| 986 | |
| 987 | pub(crate) fn get_position(&self, target: &TreeID) -> Option<FractionalIndex> { |
| 988 | self.trees.get(target).and_then(|x| x.position.clone()) |
| 989 | } |
| 990 | |
| 991 | pub(crate) fn get_index_by_tree_id(&self, target: &TreeID) -> Option<usize> { |
| 992 | let parent = self.parent(target)?; |
| 993 | (!parent.is_deleted()) |
| 994 | .then(|| { |
| 995 | self.children |
| 996 | .get(&parent) |
| 997 | .and_then(|x| x.get_index_by_child_id(target)) |
| 998 | }) |
| 999 | .flatten() |
| 1000 | } |
| 1001 | |
| 1002 | pub(crate) fn get_index_by_position( |
| 1003 | &self, |
| 1004 | parent: &TreeParentId, |
| 1005 | node_position: &NodePosition, |
| 1006 | ) -> Option<usize> { |
| 1007 | self.children.get(parent).map(|c| { |
| 1008 | match c.get_last_insert_index_by_position(node_position) { |
| 1009 | Ok(i) => i, |
| 1010 | Err(i) => i, |
| 1011 | } |
| 1012 | }) |
| 1013 | } |
| 1014 | |
| 1015 | pub(crate) fn get_id_by_index(&self, parent: &TreeParentId, index: usize) -> Option<TreeID> { |
| 1016 | (!parent.is_deleted()) |
| 1017 | .then(|| self.children.get(parent).and_then(|x| x.get_id_at(index))) |
| 1018 | .flatten() |
| 1019 | } |
| 1020 | |
| 1021 | /// Check the consistency between `self.trees` and `self.children` |
| 1022 | /// |
| 1023 | /// It's used for debug and test |
| 1024 | #[allow(unused)] |
| 1025 | pub(crate) fn check_tree_integrity(&self) { |
| 1026 | let mut parent_children_map: FxHashMap<TreeParentId, FxHashSet<TreeID>> = |
| 1027 | FxHashMap::default(); |
| 1028 | for (id, node) in self.trees.iter() { |
| 1029 | let parent = node.parent; |
| 1030 | parent_children_map.entry(parent).or_default().insert(*id); |
| 1031 | } |
| 1032 | |
| 1033 | for (parent, children) in parent_children_map.iter() { |
| 1034 | let cached_children = self.get_children(parent).expect("parent not found"); |
| 1035 | let cached_children = cached_children.collect::<FxHashSet<_>>(); |
| 1036 | if &cached_children != children { |
| 1037 | panic!( |
| 1038 | "tree integrity broken: children set of node {:?} is not consistent", |
| 1039 | parent |
| 1040 | ); |
| 1041 | } |
| 1042 | } |
| 1043 | } |
| 1044 | |
| 1045 | pub fn is_empty(&self) -> bool { |
| 1046 | match self.children.get(&TreeParentId::Root) { |
| 1047 | Some(c) => c.len() == 0, |
| 1048 | None => true, |
| 1049 | } |
| 1050 | } |
| 1051 | |
| 1052 | pub fn get_last_move_id(&self, id: &TreeID) -> Option<ID> { |
| 1053 | self.trees.get(id).map(|x| x.last_move_op.id()) |
| 1054 | } |
| 1055 | } |
| 1056 | |
| 1057 | pub(crate) enum FractionalIndexGenResult { |
| 1058 | Ok(FractionalIndex), |
| 1059 | Rearrange(Vec<(TreeID, FractionalIndex)>), |
| 1060 | NotConfigured, |
| 1061 | } |
| 1062 | |
| 1063 | impl TreeState { |
| 1064 | /// Applies a raw `Create` or `Move` op (`Linear` and `ImportGreaterUpdates` |
| 1065 | /// modes) and pushes the events that turn the alive tree before it into |
| 1066 | /// the alive tree after it: |
| 1067 | /// |
| 1068 | /// - alive before and after: `Move`, unless nothing visible changed (e.g. a |
| 1069 | /// `Create` op for a child that the revival of its parent already |
| 1070 | /// brought back where it is); |
| 1071 | /// - alive before only: `Delete`, which covers the subtree; |
| 1072 | /// - alive after only: `Create` for the node and for every node below it, |
| 1073 | /// because a node that leaves a deleted subtree brings its subtree back; |
| 1074 | /// - neither: nothing. |
| 1075 | /// |
| 1076 | /// With `with_check`, an op that would create a cycle is skipped, as in |
| 1077 | /// `apply_diff`. |
| 1078 | fn apply_raw_move_and_convert( |
| 1079 | &mut self, |
| 1080 | target: TreeID, |
| 1081 | parent: TreeParentId, |
| 1082 | last_move_op: IdFull, |
| 1083 | position: &FractionalIndex, |
| 1084 | with_check: bool, |
| 1085 | ans: &mut Vec<TreeDiffItem>, |
| 1086 | ) { |
| 1087 | let old = self |
| 1088 | .trees |
| 1089 | .get(&target) |
| 1090 | .map(|node| (node.parent, node.position.as_ref() == Some(position))); |
| 1091 | let old_index = match &old { |
| 1092 | Some(_) if !self.is_node_deleted(&target).unwrap() => { |
| 1093 | Some(self.get_index_by_tree_id(&target).unwrap()) |
| 1094 | } |
| 1095 | _ => None, |
| 1096 | }; |
| 1097 | let result = self.mov( |
| 1098 | target, |
| 1099 | parent, |
| 1100 | last_move_op, |
| 1101 | Some(position.clone()), |
| 1102 | with_check, |
| 1103 | ); |
| 1104 | if with_check { |
| 1105 | if result.is_err() { |
| 1106 | return; |
| 1107 | } |
| 1108 | } else { |
| 1109 | result.unwrap(); |
| 1110 | } |
| 1111 | |
| 1112 | let alive = !self.is_node_deleted(&target).unwrap(); |
| 1113 | match (old, old_index) { |
| 1114 | (Some((old_parent, same_position)), Some(old_index)) => { |
| 1115 | if !alive { |
| 1116 | ans.push(TreeDiffItem { |
| 1117 | target, |
| 1118 | action: TreeExternalDiff::Delete { |
| 1119 | old_parent, |
| 1120 | old_index, |
| 1121 | }, |
| 1122 | }); |
| 1123 | return; |
| 1124 | } |
| 1125 | let index = self.get_index_by_tree_id(&target).unwrap(); |
| 1126 | if old_parent == parent && old_index == index && same_position { |
| 1127 | return; |
| 1128 | } |
| 1129 | ans.push(TreeDiffItem { |
| 1130 | target, |
| 1131 | action: TreeExternalDiff::Move { |
| 1132 | parent, |
| 1133 | index, |
| 1134 | position: position.clone(), |
| 1135 | old_parent, |
| 1136 | old_index, |
| 1137 | }, |
| 1138 | }); |
| 1139 | } |
| 1140 | (old, _) => { |
| 1141 | if !alive { |
| 1142 | return; |
| 1143 | } |
| 1144 | ans.push(TreeDiffItem { |
| 1145 | target, |
| 1146 | action: TreeExternalDiff::Create { |
| 1147 | parent, |
| 1148 | index: self.get_index_by_tree_id(&target).unwrap(), |
| 1149 | position: position.clone(), |
| 1150 | }, |
| 1151 | }); |
| 1152 | // A node that did not exist has no children yet. |
| 1153 | if old.is_some() { |
| 1154 | self.push_subtree_creation(target, ans); |
| 1155 | } |
| 1156 | } |
| 1157 | } |
| 1158 | } |
| 1159 | |
| 1160 | /// Pushes a `Create` for every node below `root`: parents before their |
| 1161 | /// children and siblings in order, so each `index` is valid when the |
| 1162 | /// events are applied in sequence. |
| 1163 | fn push_subtree_creation(&self, root: TreeID, ans: &mut Vec<TreeDiffItem>) { |
| 1164 | let mut stack = vec![root]; |
| 1165 | while let Some(node) = stack.pop() { |
| 1166 | let parent = TreeParentId::Node(node); |
| 1167 | let Some(children) = self.children.get(&parent) else { |
| 1168 | continue; |
| 1169 | }; |
| 1170 | for (index, (position, &child)) in children.iter().enumerate() { |
| 1171 | ans.push(TreeDiffItem { |
| 1172 | target: child, |
| 1173 | action: TreeExternalDiff::Create { |
| 1174 | parent, |
| 1175 | index, |
| 1176 | position: position.position.clone(), |
| 1177 | }, |
| 1178 | }); |
| 1179 | stack.push(child); |
| 1180 | } |
| 1181 | } |
| 1182 | } |
| 1183 | } |
| 1184 | |
| 1185 | impl ContainerState for TreeState { |
| 1186 | fn container_idx(&self) -> crate::container::idx::ContainerIdx { |
| 1187 | self.idx |
| 1188 | } |
| 1189 | |
| 1190 | fn is_state_empty(&self) -> bool { |
| 1191 | self.nodes().is_empty() |
| 1192 | } |
| 1193 | |
| 1194 | // How we apply the diff is coupled with the [DiffMode] we used to calculate the diff. |
| 1195 | // So be careful when you modify this function. |
| 1196 | fn apply_diff_and_convert( |
| 1197 | &mut self, |
| 1198 | diff: crate::event::InternalDiff, |
| 1199 | ctx: DiffApplyContext, |
| 1200 | ) -> Diff { |
| 1201 | let need_check = !matches!(ctx.mode, DiffMode::Checkout | DiffMode::Linear); |
| 1202 | // In `Checkout` mode the items come from `TreeDiffCalculator`, which |
| 1203 | // has already classified them against its cache and follows every |
| 1204 | // `Create` with the node's subtree. In `Linear` and |
| 1205 | // `ImportGreaterUpdates` modes they are the raw ops, so the events are |
| 1206 | // derived from the state. See `context/tree-events.md`. |
| 1207 | let raw_ops = !matches!(ctx.mode, DiffMode::Checkout); |
| 1208 | let mut ans = vec![]; |
| 1209 | if let InternalDiff::Tree(tree) = &diff { |
| 1210 | // assert never cause cycle move |
| 1211 | for diff in tree.diff.iter() { |
| 1212 | let last_move_op = diff.last_effective_move_op_id; |
| 1213 | let target = diff.target; |
| 1214 | // create associated metadata container |
| 1215 | match &diff.action { |
| 1216 | TreeInternalDiff::Create { parent, position } |
| 1217 | | TreeInternalDiff::Move { parent, position } |
| 1218 | if raw_ops => |
| 1219 | { |
| 1220 | self.apply_raw_move_and_convert( |
| 1221 | target, |
| 1222 | *parent, |
| 1223 | last_move_op, |
| 1224 | position, |
| 1225 | need_check, |
| 1226 | &mut ans, |
| 1227 | ); |
| 1228 | } |
| 1229 | TreeInternalDiff::Create { parent, position } => { |
| 1230 | self.mov(target, *parent, last_move_op, Some(position.clone()), false) |
| 1231 | .unwrap(); |
| 1232 | |
| 1233 | if let TreeParentId::Node(p) = parent { |
| 1234 | // reuse diff cache, at this time,it's "move in deleted" |
| 1235 | if self.is_node_deleted(p).unwrap() { |
| 1236 | continue; |
| 1237 | } |
| 1238 | } |
| 1239 | |
| 1240 | let index = self.get_index_by_tree_id(&target).unwrap(); |
| 1241 | ans.push(TreeDiffItem { |
| 1242 | target, |
| 1243 | action: TreeExternalDiff::Create { |
| 1244 | parent: *parent, |
| 1245 | index, |
| 1246 | position: position.clone(), |
| 1247 | }, |
| 1248 | }); |
| 1249 | } |
| 1250 | TreeInternalDiff::Move { parent, position } => { |
| 1251 | let old_parent = self.trees.get(&target).unwrap().parent; |
| 1252 | // If this is some, the node is still alive at the moment |
| 1253 | let old_index = self.get_index_by_tree_id(&target); |
| 1254 | let was_alive = !self.is_node_deleted(&target).unwrap(); |
| 1255 | self.mov(target, *parent, last_move_op, Some(position.clone()), false) |
| 1256 | .unwrap(); |
| 1257 | |
| 1258 | if let TreeParentId::Node(p) = parent { |
| 1259 | // reuse diff cache, at this time,it's "move in deleted" |
| 1260 | if self.is_node_deleted(p).unwrap() { |
| 1261 | continue; |
| 1262 | } |
| 1263 | } |
| 1264 | |
| 1265 | let index = self.get_index_by_tree_id(&target).unwrap(); |
| 1266 | match was_alive { |
| 1267 | true => { |
| 1268 | ans.push(TreeDiffItem { |
| 1269 | target, |
| 1270 | action: TreeExternalDiff::Move { |
| 1271 | parent: *parent, |
| 1272 | index, |
| 1273 | position: position.clone(), |
| 1274 | old_parent, |
| 1275 | old_index: old_index.unwrap(), |
| 1276 | }, |
| 1277 | }); |
| 1278 | } |
| 1279 | false => { |
| 1280 | ans.push(TreeDiffItem { |
| 1281 | target, |
| 1282 | action: TreeExternalDiff::Create { |
| 1283 | parent: *parent, |
| 1284 | index, |
| 1285 | position: position.clone(), |
| 1286 | }, |
| 1287 | }); |
| 1288 | } |
| 1289 | } |
| 1290 | } |
| 1291 | TreeInternalDiff::Delete { parent, position } => { |
| 1292 | let mut send_event = true; |
| 1293 | if self.is_node_deleted(&target).unwrap() { |
| 1294 | send_event = false; |
| 1295 | } |
| 1296 | if send_event { |
| 1297 | ans.push(TreeDiffItem { |
| 1298 | target, |
| 1299 | action: TreeExternalDiff::Delete { |
| 1300 | old_parent: self.trees.get(&target).unwrap().parent, |
| 1301 | old_index: self.get_index_by_tree_id(&target).unwrap(), |
| 1302 | }, |
| 1303 | }); |
| 1304 | } |
| 1305 | self.mov(target, *parent, last_move_op, position.clone(), false) |
| 1306 | .unwrap(); |
| 1307 | } |
| 1308 | TreeInternalDiff::MoveInDelete { parent, position } => { |
| 1309 | self.mov(target, *parent, last_move_op, position.clone(), false) |
| 1310 | .unwrap(); |
| 1311 | } |
| 1312 | TreeInternalDiff::UnCreate => { |
| 1313 | // maybe the node created and moved to the parent deleted |
| 1314 | if !self.is_node_deleted(&target).unwrap() { |
| 1315 | ans.push(TreeDiffItem { |
| 1316 | target, |
| 1317 | action: TreeExternalDiff::Delete { |
| 1318 | old_parent: self.trees.get(&target).unwrap().parent, |
| 1319 | old_index: self.get_index_by_tree_id(&target).unwrap(), |
| 1320 | }, |
| 1321 | }); |
| 1322 | } |
| 1323 | // delete it from state |
| 1324 | let node = self.trees.remove(&target); |
| 1325 | if let Some(node) = node { |
| 1326 | if !node.parent.is_deleted() { |
| 1327 | self.children |
| 1328 | .get_mut(&node.parent) |
| 1329 | .unwrap() |
| 1330 | .delete_child(&target); |
| 1331 | } |
| 1332 | } |
| 1333 | continue; |
| 1334 | } |
| 1335 | }; |
| 1336 | } |
| 1337 | } |
| 1338 | |
| 1339 | // self.check_tree_integrity(); |
| 1340 | Diff::Tree(TreeDiff { diff: ans }) |
| 1341 | } |
| 1342 | |
| 1343 | // How we apply the diff is coupled with the [DiffMode] we used to calculate the diff. |
| 1344 | // So be careful when you modify this function. |
| 1345 | fn apply_diff(&mut self, diff: InternalDiff, ctx: DiffApplyContext) -> LoroResult<()> { |
| 1346 | if let InternalDiff::Tree(tree) = &diff { |
| 1347 | let need_check = !matches!(ctx.mode, DiffMode::Checkout | DiffMode::Linear); |
| 1348 | // assert never cause cycle move |
| 1349 | for diff in tree.diff.iter() { |
| 1350 | let last_move_op = diff.last_effective_move_op_id; |
| 1351 | let target = diff.target; |
| 1352 | // create associated metadata container |
| 1353 | match &diff.action { |
| 1354 | TreeInternalDiff::Create { parent, position } |
| 1355 | | TreeInternalDiff::Move { |
| 1356 | parent, position, .. |
| 1357 | } => { |
| 1358 | if need_check { |
| 1359 | self.mov(target, *parent, last_move_op, Some(position.clone()), true) |
| 1360 | .unwrap_or_default(); |
| 1361 | } else { |
| 1362 | self.mov(target, *parent, last_move_op, Some(position.clone()), false)?; |
| 1363 | } |
| 1364 | } |
| 1365 | TreeInternalDiff::Delete { parent, position } => { |
| 1366 | self.mov(target, *parent, last_move_op, position.clone(), false)?; |
| 1367 | } |
| 1368 | TreeInternalDiff::MoveInDelete { parent, position } => { |
| 1369 | self.mov(target, *parent, last_move_op, position.clone(), false)?; |
| 1370 | } |
| 1371 | TreeInternalDiff::UnCreate => { |
| 1372 | // delete it from state |
| 1373 | let parent = self.trees.remove(&target); |
| 1374 | if let Some(parent) = parent { |
| 1375 | if !parent.parent.is_deleted() { |
| 1376 | self.children |
| 1377 | .get_mut(&parent.parent) |
| 1378 | .unwrap() |
| 1379 | .delete_child(&target); |
| 1380 | } |
| 1381 | } |
| 1382 | continue; |
| 1383 | } |
| 1384 | }; |
| 1385 | } |
| 1386 | } |
| 1387 | // self.check_tree_integrity(); |
| 1388 | Ok(()) |
| 1389 | } |
| 1390 | |
| 1391 | fn apply_local_op(&mut self, raw_op: &RawOp, _op: &Op) -> LoroResult<ApplyLocalOpReturn> { |
| 1392 | let mut deleted_containers = vec![]; |
| 1393 | match &raw_op.content { |
| 1394 | crate::op::RawOpContent::Tree(tree) => match &**tree { |
| 1395 | TreeOp::Create { |
| 1396 | target, |
| 1397 | parent, |
| 1398 | position, |
| 1399 | } |
| 1400 | | TreeOp::Move { |
| 1401 | target, |
| 1402 | parent, |
| 1403 | position, |
| 1404 | } => { |
| 1405 | let parent = TreeParentId::from(*parent); |
| 1406 | self.mov( |
| 1407 | *target, |
| 1408 | parent, |
| 1409 | raw_op.id_full(), |
| 1410 | Some(position.clone()), |
| 1411 | true, |
| 1412 | )?; |
| 1413 | } |
| 1414 | TreeOp::Delete { target } => { |
| 1415 | let parent = TreeParentId::Deleted; |
| 1416 | deleted_containers.push(ContainerID::new_normal( |
| 1417 | target.id(), |
| 1418 | loro_common::ContainerType::Map, |
| 1419 | )); |
| 1420 | self.mov(*target, parent, raw_op.id_full(), None, true)?; |
| 1421 | } |
| 1422 | }, |
| 1423 | _ => unreachable!(), |
| 1424 | } |
| 1425 | // self.check_tree_integrity(); |
| 1426 | Ok(ApplyLocalOpReturn { deleted_containers }) |
| 1427 | } |
| 1428 | |
| 1429 | fn to_diff(&mut self, _doc: &Weak<LoroDocInner>) -> Diff { |
| 1430 | let mut diffs = vec![]; |
| 1431 | let Some(roots) = self.children.get(&TreeParentId::Root) else { |
| 1432 | return Diff::Tree(TreeDiff { diff: vec![] }); |
| 1433 | }; |
| 1434 | |
| 1435 | let mut q = VecDeque::from_iter(roots.iter()); |
| 1436 | let mut index = 0; |
| 1437 | let mut parent = TreeParentId::Root; |
| 1438 | while let Some((position, node)) = q.pop_front() { |
| 1439 | let node_parent = self.trees.get(node).unwrap().parent; |
| 1440 | if node_parent != parent { |
| 1441 | index = 0; |
| 1442 | parent = node_parent; |
| 1443 | } |
| 1444 | let diff = TreeDiffItem { |
| 1445 | target: *node, |
| 1446 | action: TreeExternalDiff::Create { |
| 1447 | parent: node_parent, |
| 1448 | index, |
| 1449 | position: position.position.clone(), |
| 1450 | }, |
| 1451 | }; |
| 1452 | index += 1; |
| 1453 | diffs.push(diff); |
| 1454 | if let Some(children) = self.children.get(&TreeParentId::Node(*node)) { |
| 1455 | // TODO: Refactor: you can include the index and parent in the q |
| 1456 | // The code will be more robust and easy to understand |
| 1457 | q.extend(children.iter()); |
| 1458 | } |
| 1459 | } |
| 1460 | |
| 1461 | Diff::Tree(TreeDiff { diff: diffs }) |
| 1462 | } |
| 1463 | |
| 1464 | fn get_value(&mut self) -> LoroValue { |
| 1465 | self.get_all_hierarchy_nodes_under(TreeParentId::Root) |
| 1466 | .into_iter() |
| 1467 | .map(|x| x.into_value()) |
| 1468 | .collect::<Vec<_>>() |
| 1469 | .into() |
| 1470 | } |
| 1471 | |
| 1472 | /// Get the index of the child container |
| 1473 | fn get_child_index(&self, id: &ContainerID) -> Option<Index> { |
| 1474 | let id = id.as_normal().unwrap(); |
| 1475 | let tree_id = TreeID { |
| 1476 | peer: *id.0, |
| 1477 | counter: *id.1, |
| 1478 | }; |
| 1479 | if !self.trees.contains_key(&tree_id) || self.is_node_deleted(&tree_id).unwrap() { |
| 1480 | None |
| 1481 | } else { |
| 1482 | Some(Index::Node(tree_id)) |
| 1483 | } |
| 1484 | } |
| 1485 | |
| 1486 | fn contains_child(&self, id: &ContainerID) -> bool { |
| 1487 | let id = id.as_normal().unwrap(); |
| 1488 | let tree_id = TreeID { |
| 1489 | peer: *id.0, |
| 1490 | counter: *id.1, |
| 1491 | }; |
| 1492 | self.trees.contains_key(&tree_id) && !self.is_node_deleted(&tree_id).unwrap() |
| 1493 | } |
| 1494 | |
| 1495 | fn get_child_containers(&self) -> Vec<ContainerID> { |
| 1496 | self.trees |
| 1497 | .keys() |
| 1498 | .map(|n| n.associated_meta_container()) |
| 1499 | .collect_vec() |
| 1500 | } |
| 1501 | |
| 1502 | fn fork(&self, _config: &Configure) -> Self { |
| 1503 | self.clone() |
| 1504 | } |
| 1505 | } |
| 1506 | |
| 1507 | // convert map container to LoroValue |
| 1508 | #[allow(clippy::ptr_arg)] |
| 1509 | pub(crate) fn get_meta_value(nodes: &mut Vec<LoroValue>, state: &mut DocState) { |
| 1510 | let mut pending = nodes.iter_mut().rev().collect::<Vec<_>>(); |
| 1511 | while let Some(node) = pending.pop() { |
| 1512 | let map = node.as_map_mut().unwrap().make_mut(); |
| 1513 | let meta = map.get_mut("meta").unwrap(); |
| 1514 | let id = meta.as_container().unwrap(); |
| 1515 | *meta = state.get_container_deep_value(state.arena.register_container(id)); |
| 1516 | let children = map.get_mut("children").unwrap().as_list_mut().unwrap(); |
| 1517 | pending.extend(children.make_mut().iter_mut().rev()); |
| 1518 | } |
| 1519 | } |
| 1520 | |
| 1521 | #[derive(Debug, Clone)] |
| 1522 | pub struct TreeNode { |
| 1523 | pub id: TreeID, |
| 1524 | pub parent: TreeParentId, |
| 1525 | pub fractional_index: FractionalIndex, |
| 1526 | pub index: usize, |
| 1527 | pub last_move_op: IdFull, |
| 1528 | } |
| 1529 | |
| 1530 | #[derive(Debug, Clone)] |
| 1531 | pub struct TreeNodeWithChildren { |
| 1532 | pub id: TreeID, |
| 1533 | pub parent: TreeParentId, |
| 1534 | pub fractional_index: FractionalIndex, |
| 1535 | pub index: usize, |
| 1536 | pub children: Vec<TreeNodeWithChildren>, |
| 1537 | } |
| 1538 | |
| 1539 | impl TreeNodeWithChildren { |
| 1540 | fn into_value(self) -> LoroValue { |
| 1541 | // Finish a node only after its children, without using the call stack. |
| 1542 | let mut pending = vec![(self, None)]; |
| 1543 | let mut values = Vec::new(); |
| 1544 | while let Some((mut node, child_count)) = pending.pop() { |
| 1545 | if let Some(child_count) = child_count { |
| 1546 | let children = values.split_off(values.len() - child_count); |
| 1547 | values.push(node.into_value_with_children(children)); |
| 1548 | } else { |
| 1549 | let children = std::mem::take(&mut node.children); |
| 1550 | pending.push((node, Some(children.len()))); |
| 1551 | pending.extend(children.into_iter().rev().map(|node| (node, None))); |
| 1552 | } |
| 1553 | } |
| 1554 | values.pop().unwrap() |
| 1555 | } |
| 1556 | |
| 1557 | fn into_value_with_children(self, children: Vec<LoroValue>) -> LoroValue { |
| 1558 | let mut t = FxHashMap::default(); |
| 1559 | t.insert("id".to_string(), self.id.to_string().into()); |
| 1560 | let p = self |
| 1561 | .parent |
| 1562 | .tree_id() |
| 1563 | .map(|p| p.to_string().into()) |
| 1564 | .unwrap_or(LoroValue::Null); |
| 1565 | t.insert("parent".to_string(), p); |
| 1566 | t.insert( |
| 1567 | "meta".to_string(), |
| 1568 | self.id.associated_meta_container().into(), |
| 1569 | ); |
| 1570 | t.insert("index".to_string(), (self.index as i64).into()); |
| 1571 | t.insert( |
| 1572 | "fractional_index".to_string(), |
| 1573 | self.fractional_index.to_string().into(), |
| 1574 | ); |
| 1575 | t.insert("children".to_string(), children.into()); |
| 1576 | t.into() |
| 1577 | } |
| 1578 | } |
| 1579 | |
| 1580 | impl Drop for TreeNodeWithChildren { |
| 1581 | fn drop(&mut self) { |
| 1582 | let mut pending = std::mem::take(&mut self.children); |
| 1583 | while let Some(mut node) = pending.pop() { |
| 1584 | pending.append(&mut node.children); |
| 1585 | } |
| 1586 | } |
| 1587 | } |
| 1588 | |
| 1589 | #[cfg(test)] |
| 1590 | mod traversal_tests { |
| 1591 | use super::*; |
| 1592 | use loro_common::ContainerType; |
| 1593 | |
| 1594 | fn cyclic_parents() -> TreeState { |
| 1595 | let idx = ContainerIdx::from_index_and_type(0, ContainerType::Tree); |
| 1596 | let mut tree = TreeState::new(idx, 1); |
| 1597 | for counter in 0..3 { |
| 1598 | tree._init_push_tree_node_in_order( |
| 1599 | TreeID::new(1, counter), |
| 1600 | TreeParentId::Root, |
| 1601 | IdFull::new(1, counter, counter as u32), |
| 1602 | Some(FractionalIndex::default()), |
| 1603 | ) |
| 1604 | .unwrap(); |
| 1605 | } |
| 1606 | tree.trees.get_mut(&TreeID::new(1, 0)).unwrap().parent = TreeID::new(1, 1).into(); |
| 1607 | tree.trees.get_mut(&TreeID::new(1, 1)).unwrap().parent = TreeID::new(1, 0).into(); |
| 1608 | tree |
| 1609 | } |
| 1610 | |
| 1611 | #[test] |
| 1612 | #[should_panic(expected = "tree parent cycle")] |
| 1613 | fn ancestor_walk_fails_fast_on_an_internal_cycle() { |
| 1614 | cyclic_parents().is_ancestor_of(&TreeID::new(1, 2), &TreeID::new(1, 0).into()); |
| 1615 | } |
| 1616 | |
| 1617 | #[test] |
| 1618 | #[should_panic(expected = "tree parent cycle")] |
| 1619 | fn deletion_walk_fails_fast_on_an_internal_cycle() { |
| 1620 | cyclic_parents().is_node_deleted(&TreeID::new(1, 0)); |
| 1621 | } |
| 1622 | |
| 1623 | #[test] |
| 1624 | fn iterative_walks_keep_hierarchy_and_snapshot_order() { |
| 1625 | let idx = ContainerIdx::from_index_and_type(0, ContainerType::Tree); |
| 1626 | let mut tree = TreeState::new(idx, 1); |
| 1627 | // Two roots, with a branching subtree under each root. |
| 1628 | for (counter, parent) in [ |
| 1629 | (0, None), |
| 1630 | (1, None), |
| 1631 | (2, Some(0)), |
| 1632 | (3, Some(0)), |
| 1633 | (4, Some(2)), |
| 1634 | (5, Some(1)), |
| 1635 | ] { |
| 1636 | tree._init_push_tree_node_in_order( |
| 1637 | TreeID::new(1, counter), |
| 1638 | parent.map(|counter| TreeID::new(1, counter)).into(), |
| 1639 | IdFull::new(1, counter, counter as u32), |
| 1640 | Some(FractionalIndex::default()), |
| 1641 | ) |
| 1642 | .unwrap(); |
| 1643 | } |
| 1644 | let hierarchy = tree.get_all_hierarchy_nodes_under(TreeParentId::Root); |
| 1645 | let mut pending = hierarchy.iter().rev().collect::<Vec<_>>(); |
| 1646 | let mut preorder = Vec::new(); |
| 1647 | while let Some(node) = pending.pop() { |
| 1648 | assert_eq!(tree.parent(&node.id), Some(node.parent)); |
| 1649 | assert_eq!(tree.get_index_by_tree_id(&node.id), Some(node.index)); |
| 1650 | assert_eq!( |
| 1651 | tree.get_position(&node.id), |
| 1652 | Some(node.fractional_index.clone()) |
| 1653 | ); |
| 1654 | preorder.push(node.id.counter); |
| 1655 | pending.extend(node.children.iter().rev()); |
| 1656 | } |
| 1657 | assert_eq!(preorder, vec![0, 2, 4, 3, 1, 5]); |
| 1658 | let snapshot_order = tree.bfs_all_alive_nodes_for_fast_snapshot(); |
| 1659 | assert_eq!( |
| 1660 | snapshot_order |
| 1661 | .iter() |
| 1662 | .map(|node| node.id.counter) |
| 1663 | .collect::<Vec<_>>(), |
| 1664 | vec![0, 1, 2, 3, 4, 5] |
| 1665 | ); |
| 1666 | let root = TreeID::new(1, 0); |
| 1667 | tree.mov( |
| 1668 | root, |
| 1669 | TreeParentId::Deleted, |
| 1670 | IdFull::new(1, 6, 6), |
| 1671 | None, |
| 1672 | true, |
| 1673 | ) |
| 1674 | .unwrap(); |
| 1675 | assert_eq!( |
| 1676 | tree.bfs_all_deleted_nodes_for_fast_snapshot() |
| 1677 | .iter() |
| 1678 | .map(|node| node.id.counter) |
| 1679 | .collect::<Vec<_>>(), |
| 1680 | vec![0, 2, 3, 4] |
| 1681 | ); |
| 1682 | } |
| 1683 | |
| 1684 | #[test] |
| 1685 | fn deep_hierarchy_can_be_dropped_on_a_small_stack() { |
| 1686 | std::thread::Builder::new() |
| 1687 | .stack_size(1 << 20) |
| 1688 | .spawn(|| { |
| 1689 | let idx = ContainerIdx::from_index_and_type(0, ContainerType::Tree); |
| 1690 | let mut tree = TreeState::new(idx, 1); |
| 1691 | for counter in 0..4_000 { |
| 1692 | let parent = (counter > 0).then(|| TreeID::new(1, counter - 1)); |
| 1693 | tree._init_push_tree_node_in_order( |
| 1694 | TreeID::new(1, counter), |
| 1695 | parent.into(), |
| 1696 | IdFull::new(1, counter, counter as u32), |
| 1697 | Some(FractionalIndex::default()), |
| 1698 | ) |
| 1699 | .unwrap(); |
| 1700 | } |
| 1701 | let hierarchy = tree.get_all_hierarchy_nodes_under(TreeParentId::Root); |
| 1702 | let mut nodes = &hierarchy; |
| 1703 | let mut depth = 0; |
| 1704 | while let Some(node) = nodes.first() { |
| 1705 | depth += 1; |
| 1706 | nodes = &node.children; |
| 1707 | } |
| 1708 | assert_eq!(depth, 4_000); |
| 1709 | drop(hierarchy); |
| 1710 | }) |
| 1711 | .unwrap() |
| 1712 | .join() |
| 1713 | .unwrap(); |
| 1714 | } |
| 1715 | } |
| 1716 | |
| 1717 | mod jitter { |
| 1718 | use super::{FractionalIndexGenResult, NodeChildren}; |
| 1719 | use fractional_index::FractionalIndex; |
| 1720 | use loro_common::TreeID; |
| 1721 | use rand::Rng; |
| 1722 | |
| 1723 | impl NodeChildren { |
| 1724 | pub(super) fn generate_fi_at_jitter( |
| 1725 | &self, |
| 1726 | pos: usize, |
| 1727 | target: &TreeID, |
| 1728 | rng: &mut impl Rng, |
| 1729 | jitter: u8, |
| 1730 | ) -> FractionalIndexGenResult { |
| 1731 | let mut reset_ids = vec![]; |
| 1732 | let mut left = None; |
| 1733 | let mut next_right = None; |
| 1734 | { |
| 1735 | let mut right = None; |
| 1736 | let children_num = self.len(); |
| 1737 | if children_num == 0 { |
| 1738 | return FractionalIndexGenResult::Ok(FractionalIndex::jitter_default( |
| 1739 | rng, jitter, |
| 1740 | )); |
| 1741 | } |
| 1742 | |
| 1743 | if pos > 0 { |
| 1744 | left = self.get_node_position_at(pos - 1); |
| 1745 | } |
| 1746 | if pos < children_num { |
| 1747 | right = self.get_elem_at(pos); |
| 1748 | } |
| 1749 | |
| 1750 | let left_fi = left.map(|x| &x.position); |
| 1751 | // if left and right have the same fractional indexes, we need to scan further to |
| 1752 | // find all the ids that need to be reset |
| 1753 | if let Some(left_fi) = left_fi { |
| 1754 | if Some(left_fi) == right.map(|x| &x.0.position) { |
| 1755 | // TODO: the min length between left and right |
| 1756 | reset_ids.push(*right.unwrap().1); |
| 1757 | for i in (pos + 1)..children_num { |
| 1758 | let this_position = &self.get_node_position_at(i).unwrap().position; |
| 1759 | if this_position == left_fi { |
| 1760 | reset_ids.push(*self.get_elem_at(i).unwrap().1); |
| 1761 | } else { |
| 1762 | next_right = Some(this_position.clone()); |
| 1763 | break; |
| 1764 | } |
| 1765 | } |
| 1766 | } |
| 1767 | } |
| 1768 | |
| 1769 | if reset_ids.is_empty() { |
| 1770 | return FractionalIndexGenResult::Ok( |
| 1771 | FractionalIndex::new_jitter( |
| 1772 | left.map(|x| &x.position), |
| 1773 | right.map(|x| &x.0.position), |
| 1774 | rng, |
| 1775 | jitter, |
| 1776 | ) |
| 1777 | .unwrap(), |
| 1778 | ); |
| 1779 | } |
| 1780 | } |
| 1781 | let positions = FractionalIndex::generate_n_evenly_jitter( |
| 1782 | left.map(|x| &x.position), |
| 1783 | next_right.as_ref(), |
| 1784 | reset_ids.len() + 1, |
| 1785 | rng, |
| 1786 | jitter, |
| 1787 | ) |
| 1788 | .unwrap(); |
| 1789 | FractionalIndexGenResult::Rearrange( |
| 1790 | Some(*target) |
| 1791 | .into_iter() |
| 1792 | .chain(reset_ids) |
| 1793 | .zip(positions) |
| 1794 | .collect(), |
| 1795 | ) |
| 1796 | } |
| 1797 | } |
| 1798 | } |
| 1799 | |
| 1800 | mod snapshot { |
| 1801 | use std::{borrow::Cow, collections::BTreeSet}; |
| 1802 | |
| 1803 | use fractional_index::FractionalIndex; |
| 1804 | use loro_common::{IdFull, PeerID, TreeID}; |
| 1805 | use rustc_hash::{FxHashMap, FxHashSet}; |
| 1806 | |
| 1807 | use serde_columnar::columnar; |
| 1808 | |
| 1809 | use crate::{ |
| 1810 | encoding::{arena::PositionArena, value_register::ValueRegister}, |
| 1811 | state::{ |
| 1812 | decode_counter, decode_lamport_from_delta, decode_peer_from_table, decode_peer_table, |
| 1813 | state_decode_error, FastStateSnapshot, |
| 1814 | }, |
| 1815 | }; |
| 1816 | |
| 1817 | use super::{NodePosition, TreeNode, TreeParentId, TreeState}; |
| 1818 | #[columnar(vec, ser, de, iterable)] |
| 1819 | #[derive(Debug, Clone)] |
| 1820 | struct EncodedTreeNodeId { |
| 1821 | #[columnar(strategy = "DeltaRle")] |
| 1822 | peer_idx: usize, |
| 1823 | #[columnar(strategy = "DeltaRle")] |
| 1824 | counter: i32, |
| 1825 | } |
| 1826 | |
| 1827 | #[columnar(vec, ser, de, iterable)] |
| 1828 | #[derive(Debug, Clone)] |
| 1829 | struct EncodedTreeNode { |
| 1830 | /// If this field is 0, it means none, its parent is root |
| 1831 | /// If this field is 1, its parent is the deleted root |
| 1832 | #[columnar(strategy = "DeltaRle")] |
| 1833 | parent_idx_plus_two: usize, |
| 1834 | #[columnar(strategy = "DeltaRle")] |
| 1835 | last_set_peer_idx: usize, |
| 1836 | #[columnar(strategy = "DeltaRle")] |
| 1837 | last_set_counter: i32, |
| 1838 | #[columnar(strategy = "DeltaRle")] |
| 1839 | last_set_lamport_sub_counter: i32, |
| 1840 | fractional_index_idx: usize, |
| 1841 | } |
| 1842 | |
| 1843 | #[columnar(ser, de)] |
| 1844 | struct EncodedTree<'a> { |
| 1845 | #[columnar(class = "vec", iter = "EncodedTreeNodeId")] |
| 1846 | node_ids: Vec<EncodedTreeNodeId>, |
| 1847 | #[columnar(class = "vec", iter = "EncodedTreeNode")] |
| 1848 | nodes: Vec<EncodedTreeNode>, |
| 1849 | #[columnar(borrow)] |
| 1850 | fractional_indexes: Cow<'a, [u8]>, |
| 1851 | #[columnar(borrow)] |
| 1852 | reserved_has_effect_bool_rle: Cow<'a, [u8]>, |
| 1853 | } |
| 1854 | |
| 1855 | fn encode( |
| 1856 | state: &TreeState, |
| 1857 | input: Vec<TreeNode>, |
| 1858 | deleted_nodes: Vec<TreeNode>, |
| 1859 | ) -> (ValueRegister<PeerID>, EncodedTree<'_>) { |
| 1860 | let mut peers: ValueRegister<PeerID> = ValueRegister::new(); |
| 1861 | let mut position_set = BTreeSet::default(); |
| 1862 | let mut nodes = Vec::with_capacity(input.len()); |
| 1863 | let mut node_ids = Vec::with_capacity(input.len()); |
| 1864 | let mut position_register = ValueRegister::new(); |
| 1865 | let mut id_to_idx = FxHashMap::default(); |
| 1866 | for node in input.iter().chain(deleted_nodes.iter()) { |
| 1867 | position_set.insert(node.fractional_index.clone()); |
| 1868 | let idx = node_ids.len(); |
| 1869 | node_ids.push(EncodedTreeNodeId { |
| 1870 | peer_idx: peers.register(&node.id.peer), |
| 1871 | counter: node.id.counter, |
| 1872 | }); |
| 1873 | id_to_idx.insert(node.id, idx); |
| 1874 | } |
| 1875 | |
| 1876 | for p in position_set { |
| 1877 | position_register.register(&p); |
| 1878 | } |
| 1879 | |
| 1880 | for node in input { |
| 1881 | let n = state.trees.get(&node.id).unwrap(); |
| 1882 | let last_set_id = n.last_move_op; |
| 1883 | nodes.push(EncodedTreeNode { |
| 1884 | parent_idx_plus_two: match node.parent { |
| 1885 | TreeParentId::Deleted => 1, |
| 1886 | TreeParentId::Root => 0, |
| 1887 | TreeParentId::Node(id) => id_to_idx.get(&id).unwrap() + 2, |
| 1888 | TreeParentId::Unexist => unreachable!(), |
| 1889 | }, |
| 1890 | last_set_peer_idx: peers.register(&last_set_id.peer), |
| 1891 | last_set_counter: last_set_id.counter, |
| 1892 | last_set_lamport_sub_counter: last_set_id.lamport as i32 - last_set_id.counter, |
| 1893 | fractional_index_idx: position_register.register(&node.fractional_index), |
| 1894 | }) |
| 1895 | } |
| 1896 | |
| 1897 | for node in deleted_nodes { |
| 1898 | let n = state.trees.get(&node.id).unwrap(); |
| 1899 | let last_set_id = n.last_move_op; |
| 1900 | nodes.push(EncodedTreeNode { |
| 1901 | parent_idx_plus_two: match node.parent { |
| 1902 | TreeParentId::Deleted => 1, |
| 1903 | TreeParentId::Root => 0, |
| 1904 | TreeParentId::Node(id) => id_to_idx.get(&id).unwrap() + 2, |
| 1905 | TreeParentId::Unexist => unreachable!(), |
| 1906 | }, |
| 1907 | last_set_peer_idx: peers.register(&last_set_id.peer), |
| 1908 | last_set_counter: last_set_id.counter, |
| 1909 | last_set_lamport_sub_counter: last_set_id.lamport as i32 - last_set_id.counter, |
| 1910 | fractional_index_idx: position_register.register(&node.fractional_index), |
| 1911 | }) |
| 1912 | } |
| 1913 | |
| 1914 | let position_vec = position_register.unwrap_vec(); |
| 1915 | let positions = PositionArena::from_positions(position_vec.iter().map(|p| p.as_bytes())); |
| 1916 | ( |
| 1917 | peers, |
| 1918 | EncodedTree { |
| 1919 | node_ids, |
| 1920 | nodes, |
| 1921 | fractional_indexes: positions.encode().into(), |
| 1922 | reserved_has_effect_bool_rle: vec![].into(), |
| 1923 | }, |
| 1924 | ) |
| 1925 | } |
| 1926 | |
| 1927 | struct DecodedTreeNode { |
| 1928 | id: TreeID, |
| 1929 | parent: TreeParentId, |
| 1930 | last_move_op: IdFull, |
| 1931 | node_position: NodePosition, |
| 1932 | } |
| 1933 | |
| 1934 | /// Returns whether every parent's children appear in strictly increasing |
| 1935 | /// [`NodePosition`] order. Two siblings with the same position and idlp cannot |
| 1936 | /// be produced by any valid history, so they are rejected. |
| 1937 | fn siblings_in_order(nodes: &[DecodedTreeNode]) -> loro_common::LoroResult<bool> { |
| 1938 | let mut last_child: FxHashMap<TreeParentId, &NodePosition> = FxHashMap::default(); |
| 1939 | let mut in_order = true; |
| 1940 | for node in nodes { |
| 1941 | if let Some(prev) = last_child.insert(node.parent, &node.node_position) { |
| 1942 | match prev.cmp(&node.node_position) { |
| 1943 | std::cmp::Ordering::Less => {} |
| 1944 | std::cmp::Ordering::Equal => { |
| 1945 | return Err(state_decode_error( |
| 1946 | "Decode tree state failed: duplicate sibling position", |
| 1947 | )); |
| 1948 | } |
| 1949 | std::cmp::Ordering::Greater => in_order = false, |
| 1950 | } |
| 1951 | } |
| 1952 | } |
| 1953 | Ok(in_order) |
| 1954 | } |
| 1955 | |
| 1956 | impl FastStateSnapshot for TreeState { |
| 1957 | /// Encodes the TreeState into a compact binary format for efficient serialization. |
| 1958 | /// |
| 1959 | /// The encoding schema: |
| 1960 | /// 1. Encodes all nodes using a breadth-first search traversal, ensuring a consistent order. |
| 1961 | /// 2. Uses a ValueRegister to deduplicate and index PeerIDs and TreeIDs, reducing redundancy. |
| 1962 | /// - PeerIDs are stored once and referenced by index. |
| 1963 | /// - TreeIDs are decomposed into peer index and counter for compact representation. |
| 1964 | /// 3. Encodes fractional indexes using a PositionArena for space efficiency |
| 1965 | /// 4. Utilizes delta encoding and run-length encoding for further size reduction: |
| 1966 | /// - Delta encoding stores differences between consecutive values. |
| 1967 | /// - Run-length encoding compresses sequences of repeated values. |
| 1968 | /// 5. Stores parent relationships using indices, with special values for root and deleted nodes. |
| 1969 | /// 6. Encodes last move operation details (peer_idx, counter[Delta], lamport clock[Delta]) for each node. |
| 1970 | fn encode_snapshot_fast<W: std::io::prelude::Write>(&mut self, mut w: W) { |
| 1971 | let all_alive_nodes = self.bfs_all_alive_nodes_for_fast_snapshot(); |
| 1972 | let all_deleted_nodes = self.bfs_all_deleted_nodes_for_fast_snapshot(); |
| 1973 | let (peers, encoded) = encode(self, all_alive_nodes, all_deleted_nodes); |
| 1974 | let peers = peers.unwrap_vec(); |
| 1975 | leb128::write::unsigned(&mut w, peers.len() as u64).unwrap(); |
| 1976 | for peer in peers { |
| 1977 | w.write_all(&peer.to_le_bytes()).unwrap(); |
| 1978 | } |
| 1979 | |
| 1980 | let vec = serde_columnar::to_vec(&encoded).unwrap(); |
| 1981 | w.write_all(&vec).unwrap(); |
| 1982 | } |
| 1983 | |
| 1984 | fn decode_value(_: &[u8]) -> loro_common::LoroResult<(loro_common::LoroValue, &[u8])> { |
| 1985 | unreachable!() |
| 1986 | } |
| 1987 | |
| 1988 | fn decode_snapshot_fast( |
| 1989 | idx: crate::container::idx::ContainerIdx, |
| 1990 | (_, mut bytes): (loro_common::LoroValue, &[u8]), |
| 1991 | ctx: crate::state::ContainerCreationContext, |
| 1992 | ) -> loro_common::LoroResult<Self> |
| 1993 | where |
| 1994 | Self: Sized, |
| 1995 | { |
| 1996 | let peers = decode_peer_table(&mut bytes, "Decode tree state failed")?; |
| 1997 | |
| 1998 | let mut tree = TreeState::new(idx, ctx.peer); |
| 1999 | let encoded: EncodedTree = serde_columnar::from_bytes(bytes).map_err(|err| { |
| 2000 | state_decode_error(format!("Decode tree state failed: invalid metadata: {err}")) |
| 2001 | })?; |
| 2002 | let fractional_indexes = |
| 2003 | PositionArena::decode(&encoded.fractional_indexes)?.try_parse_to_positions()?; |
| 2004 | if encoded.node_ids.len() != encoded.nodes.len() { |
| 2005 | return Err(state_decode_error( |
| 2006 | "Decode tree state failed: node id/node length mismatch", |
| 2007 | )); |
| 2008 | } |
| 2009 | let node_ids = encoded |
| 2010 | .node_ids |
| 2011 | .iter() |
| 2012 | .map(|x| { |
| 2013 | Ok(TreeID::new( |
| 2014 | decode_peer_from_table(&peers, x.peer_idx, "Decode tree state failed")?, |
| 2015 | decode_counter(x.counter, "Decode tree state failed")?, |
| 2016 | )) |
| 2017 | }) |
| 2018 | .collect::<loro_common::LoroResult<Vec<_>>>()?; |
| 2019 | let mut decoded = Vec::with_capacity(node_ids.len()); |
| 2020 | let mut seen_ids = |
| 2021 | FxHashSet::with_capacity_and_hasher(node_ids.len(), Default::default()); |
| 2022 | for (node_id, node) in node_ids.iter().zip(encoded.nodes) { |
| 2023 | if !seen_ids.insert(*node_id) { |
| 2024 | return Err(state_decode_error( |
| 2025 | "Decode tree state failed: duplicate node id", |
| 2026 | )); |
| 2027 | } |
| 2028 | let parent = match node.parent_idx_plus_two { |
| 2029 | 0 => TreeParentId::Root, |
| 2030 | 1 => TreeParentId::Deleted, |
| 2031 | n => { |
| 2032 | let id = *node_ids.get(n - 2).ok_or_else(|| { |
| 2033 | state_decode_error( |
| 2034 | "Decode tree state failed: parent index out of range", |
| 2035 | ) |
| 2036 | })?; |
| 2037 | TreeParentId::from(Some(id)) |
| 2038 | } |
| 2039 | }; |
| 2040 | let last_move_op = IdFull::new( |
| 2041 | decode_peer_from_table( |
| 2042 | &peers, |
| 2043 | node.last_set_peer_idx, |
| 2044 | "Decode tree state failed", |
| 2045 | )?, |
| 2046 | node.last_set_counter, |
| 2047 | decode_lamport_from_delta( |
| 2048 | node.last_set_counter, |
| 2049 | node.last_set_lamport_sub_counter, |
| 2050 | "Decode tree state failed", |
| 2051 | )?, |
| 2052 | ); |
| 2053 | let position = FractionalIndex::from_bytes( |
| 2054 | fractional_indexes |
| 2055 | .get(node.fractional_index_idx) |
| 2056 | .ok_or_else(|| { |
| 2057 | state_decode_error( |
| 2058 | "Decode tree state failed: fractional index out of range", |
| 2059 | ) |
| 2060 | })? |
| 2061 | .clone(), |
| 2062 | ); |
| 2063 | decoded.push(DecodedTreeNode { |
| 2064 | id: *node_id, |
| 2065 | parent, |
| 2066 | last_move_op, |
| 2067 | node_position: NodePosition::new(position, last_move_op.idlp()), |
| 2068 | }); |
| 2069 | } |
| 2070 | |
| 2071 | // Sibling order is fully determined by each node's (fractional index, idlp), |
| 2072 | // so the encoded order carries no information. Rust always writes siblings in |
| 2073 | // that order, but other encoders (loro.js <= 0.2.0, loro-dev/loro#1088) may |
| 2074 | // not; sort instead of tripping `push_child_in_order` on the first read. |
| 2075 | if !siblings_in_order(&decoded)? { |
| 2076 | decoded.sort_by(|a, b| a.node_position.cmp(&b.node_position)); |
| 2077 | // Out-of-order duplicates only become adjacent after sorting. |
| 2078 | let sorted = siblings_in_order(&decoded)?; |
| 2079 | debug_assert!(sorted); |
| 2080 | } |
| 2081 | |
| 2082 | for node in decoded { |
| 2083 | let DecodedTreeNode { |
| 2084 | id, |
| 2085 | parent, |
| 2086 | last_move_op, |
| 2087 | node_position, |
| 2088 | } = node; |
| 2089 | // PERF: we don't need to mov the deleted node, instead we can cache them |
| 2090 | tree._init_push_tree_node_in_order( |
| 2091 | id, |
| 2092 | parent, |
| 2093 | last_move_op, |
| 2094 | Some(node_position.position), |
| 2095 | ) |
| 2096 | .map_err(|err| { |
| 2097 | state_decode_error(format!("Decode tree state failed: invalid node: {err}")) |
| 2098 | })?; |
| 2099 | } |
| 2100 | Ok(tree) |
| 2101 | } |
| 2102 | } |
| 2103 | |
| 2104 | #[cfg(test)] |
| 2105 | mod tests { |
| 2106 | use loro_common::{ContainerType, LoroValue}; |
| 2107 | |
| 2108 | use crate::{container::idx::ContainerIdx, state::ContainerCreationContext}; |
| 2109 | |
| 2110 | use super::*; |
| 2111 | |
| 2112 | #[test] |
| 2113 | fn tree_fast_snapshot_rejects_corrupt_state_metadata() { |
| 2114 | let idx = ContainerIdx::from_index_and_type(0, ContainerType::Tree); |
| 2115 | let configure = Default::default(); |
| 2116 | let ctx = ContainerCreationContext { |
| 2117 | configure: &configure, |
| 2118 | peer: 0, |
| 2119 | }; |
| 2120 | |
| 2121 | assert!(TreeState::decode_snapshot_fast(idx, (LoroValue::Null, &[1]), ctx).is_err()); |
| 2122 | } |
| 2123 | |
| 2124 | #[test] |
| 2125 | fn tree_fast_snapshot_rejects_negative_node_counter() { |
| 2126 | let idx = ContainerIdx::from_index_and_type(0, ContainerType::Tree); |
| 2127 | let configure = Default::default(); |
| 2128 | let ctx = ContainerCreationContext { |
| 2129 | configure: &configure, |
| 2130 | peer: 0, |
| 2131 | }; |
| 2132 | |
| 2133 | let position = fractional_index::FractionalIndex::default(); |
| 2134 | let positions = PositionArena::from_positions([position.as_bytes()]); |
| 2135 | let encoded = EncodedTree { |
| 2136 | node_ids: vec![EncodedTreeNodeId { |
| 2137 | peer_idx: 0, |
| 2138 | counter: -1, |
| 2139 | }], |
| 2140 | nodes: vec![EncodedTreeNode { |
| 2141 | parent_idx_plus_two: 0, |
| 2142 | last_set_peer_idx: 0, |
| 2143 | last_set_counter: 0, |
| 2144 | last_set_lamport_sub_counter: 0, |
| 2145 | fractional_index_idx: 0, |
| 2146 | }], |
| 2147 | fractional_indexes: positions.encode().into(), |
| 2148 | reserved_has_effect_bool_rle: vec![].into(), |
| 2149 | }; |
| 2150 | |
| 2151 | let mut bytes = Vec::new(); |
| 2152 | leb128::write::unsigned(&mut bytes, 1).unwrap(); |
| 2153 | bytes.extend_from_slice(&1_u64.to_le_bytes()); |
| 2154 | bytes.extend_from_slice(&serde_columnar::to_vec(&encoded).unwrap()); |
| 2155 | |
| 2156 | assert!(TreeState::decode_snapshot_fast(idx, (LoroValue::Null, &bytes), ctx).is_err()); |
| 2157 | } |
| 2158 | |
| 2159 | /// Encodes `(counter, parent_idx_plus_two, last_set_counter, position_idx)` nodes of |
| 2160 | /// peer 1, with lamport == counter for every last-set op. |
| 2161 | fn encode_nodes( |
| 2162 | nodes: &[(i32, usize, i32, usize)], |
| 2163 | positions: &[FractionalIndex], |
| 2164 | ) -> Vec<u8> { |
| 2165 | let arena = PositionArena::from_positions(positions.iter().map(|p| p.as_bytes())); |
| 2166 | let encoded = EncodedTree { |
| 2167 | node_ids: nodes |
| 2168 | .iter() |
| 2169 | .map(|&(counter, ..)| EncodedTreeNodeId { |
| 2170 | peer_idx: 0, |
| 2171 | counter, |
| 2172 | }) |
| 2173 | .collect(), |
| 2174 | nodes: nodes |
| 2175 | .iter() |
| 2176 | .map( |
| 2177 | |&(_, parent_idx_plus_two, last_set_counter, fractional_index_idx)| { |
| 2178 | EncodedTreeNode { |
| 2179 | parent_idx_plus_two, |
| 2180 | last_set_peer_idx: 0, |
| 2181 | last_set_counter, |
| 2182 | last_set_lamport_sub_counter: 0, |
| 2183 | fractional_index_idx, |
| 2184 | } |
| 2185 | }, |
| 2186 | ) |
| 2187 | .collect(), |
| 2188 | fractional_indexes: arena.encode().into(), |
| 2189 | reserved_has_effect_bool_rle: vec![].into(), |
| 2190 | }; |
| 2191 | let mut bytes = Vec::new(); |
| 2192 | leb128::write::unsigned(&mut bytes, 1).unwrap(); |
| 2193 | bytes.extend_from_slice(&1_u64.to_le_bytes()); |
| 2194 | bytes.extend_from_slice(&serde_columnar::to_vec(&encoded).unwrap()); |
| 2195 | bytes |
| 2196 | } |
| 2197 | |
| 2198 | fn decode(bytes: &[u8]) -> loro_common::LoroResult<TreeState> { |
| 2199 | let idx = ContainerIdx::from_index_and_type(0, ContainerType::Tree); |
| 2200 | let configure = Default::default(); |
| 2201 | let ctx = ContainerCreationContext { |
| 2202 | configure: &configure, |
| 2203 | peer: 0, |
| 2204 | }; |
| 2205 | TreeState::decode_snapshot_fast(idx, (LoroValue::Null, bytes), ctx) |
| 2206 | } |
| 2207 | |
| 2208 | fn children_of(tree: &TreeState, parent: TreeParentId) -> Vec<i32> { |
| 2209 | tree.get_children(&parent) |
| 2210 | .unwrap() |
| 2211 | .map(|id| id.counter) |
| 2212 | .collect() |
| 2213 | } |
| 2214 | |
| 2215 | /// loro-dev/loro#1088: loro.js <= 0.2.0 wrote siblings in creation order. |
| 2216 | #[test] |
| 2217 | fn tree_fast_snapshot_sorts_unordered_siblings() { |
| 2218 | // Cover both the Vec and the BTree representation of `NodeChildren`. |
| 2219 | for n in [3, super::super::NodeChildren::MAX_SIZE_FOR_ARRAY as i32 + 5] { |
| 2220 | let positions = FractionalIndex::generate_n_evenly(None, None, n as usize).unwrap(); |
| 2221 | // Root node 0 has children 1..=n. Child i takes the (n - i)th position, so |
| 2222 | // the encoded order is exactly the reverse of the sibling order. Node n + 1 |
| 2223 | // is a child of node 1, and the deleted node n + 2 is encoded between alive |
| 2224 | // nodes instead of after them. |
| 2225 | let mut nodes = vec![(0, 0, 0, 0)]; |
| 2226 | nodes.push((n + 2, 1, n + 2, 0)); |
| 2227 | for i in 1..=n { |
| 2228 | nodes.push((i, 2, i, (n - i) as usize)); |
| 2229 | } |
| 2230 | nodes.push((n + 1, 4, n + 1, 0)); |
| 2231 | let tree = decode(&encode_nodes(&nodes, &positions)).unwrap(); |
| 2232 | |
| 2233 | assert_eq!(children_of(&tree, TreeParentId::Root), vec![0]); |
| 2234 | let root = TreeID::new(1, 0); |
| 2235 | assert_eq!( |
| 2236 | children_of(&tree, TreeParentId::Node(root)), |
| 2237 | (1..=n).rev().collect::<Vec<_>>() |
| 2238 | ); |
| 2239 | assert_eq!( |
| 2240 | children_of(&tree, TreeParentId::Node(TreeID::new(1, 1))), |
| 2241 | vec![n + 1] |
| 2242 | ); |
| 2243 | assert_eq!(children_of(&tree, TreeParentId::Deleted), vec![n + 2]); |
| 2244 | assert_eq!(tree.is_node_deleted(&TreeID::new(1, n + 2)), Some(true)); |
| 2245 | } |
| 2246 | } |
| 2247 | |
| 2248 | #[test] |
| 2249 | fn tree_fast_snapshot_orders_same_position_siblings_by_idlp() { |
| 2250 | let positions = vec![FractionalIndex::default()]; |
| 2251 | // Same fractional index: lamport (== last-set counter here) breaks the tie. |
| 2252 | let nodes = [(0, 0, 0, 0), (1, 2, 5, 0), (2, 2, 3, 0), (3, 2, 4, 0)]; |
| 2253 | let tree = decode(&encode_nodes(&nodes, &positions)).unwrap(); |
| 2254 | assert_eq!( |
| 2255 | children_of(&tree, TreeParentId::Node(TreeID::new(1, 0))), |
| 2256 | vec![2, 3, 1] |
| 2257 | ); |
| 2258 | } |
| 2259 | |
| 2260 | #[test] |
| 2261 | fn tree_fast_snapshot_rejects_duplicate_nodes_and_sibling_positions() { |
| 2262 | let positions = FractionalIndex::generate_n_evenly(None, None, 2).unwrap(); |
| 2263 | // The same node id twice. |
| 2264 | let duplicate_id = [(0, 0, 0, 0), (0, 0, 1, 1)]; |
| 2265 | assert!(decode(&encode_nodes(&duplicate_id, &positions)).is_err()); |
| 2266 | // Two siblings with the same position and last-set idlp, adjacent in the input. |
| 2267 | let adjacent = [(0, 0, 0, 0), (1, 0, 0, 0)]; |
| 2268 | assert!(decode(&encode_nodes(&adjacent, &positions)).is_err()); |
| 2269 | // ... and only adjacent once the out-of-order input is sorted. |
| 2270 | let unordered = [(0, 0, 0, 1), (1, 0, 3, 0), (2, 0, 0, 1)]; |
| 2271 | assert!(decode(&encode_nodes(&unordered, &positions)).is_err()); |
| 2272 | } |
| 2273 | } |
| 2274 | } |