forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

state.rs2873 lines, 112.2 KiBHistoryRawDownload
1pub mod container_tree;
2
3use crate::sync::{AtomicU64, Mutex, RwLock};
4#[cfg(test)]
5use std::cell::Cell;
6use std::sync::{Arc, Weak};
7use std::{borrow::Cow, io::Write, sync::atomic::Ordering};
8
9use container_store::ContainerStore;
10use dead_containers_cache::DeadContainersCache;
11use enum_as_inner::EnumAsInner;
12use enum_dispatch::enum_dispatch;
13use loro_common::{ContainerID, Lamport, LoroError, LoroResult, TreeID, ID};
14use loro_delta::DeltaItem;
15use rustc_hash::{FxHashMap, FxHashSet};
16use smallvec::SmallVec;
17use tracing::{info_span, instrument, warn};
18
19use crate::{
20 configure::{Configure, DefaultRandom, SecureRandomGenerator},
21 container::{idx::ContainerIdx, richtext::config::StyleConfigMap, tree::tree_op::TreeOp},
22 cursor::{Cursor, PosType},
23 delta::TreeExternalDiff,
24 diff_calc::{DiffCalculator, DiffMode},
25 event::{Diff, EventTriggerKind, Index, InternalContainerDiff, InternalDiff, KeptChange},
26 fx_map,
27 handler::ValueOrHandler,
28 id::PeerID,
29 lock::{LoroLockGroup, LoroMutex},
30 op::{Op, RawOp, RawOpContent},
31 version::{Frontiers, VersionVector},
32 ContainerDiff, ContainerType, DocDiff, InternalString, LoroDocInner, LoroValue, OpLog,
33};
34
35pub(crate) mod analyzer;
36pub(crate) mod container_store;
37#[cfg(feature = "counter")]
38mod counter_state;
39mod dead_containers_cache;
40mod list_state;
41mod map_state;
42mod mergeable;
43mod movable_list_state;
44mod richtext_state;
45mod tree_state;
46mod unknown_state;
47mod value_decode;
48
49pub(crate) use self::movable_list_state::{IndexType, MovableListState};
50pub(crate) use container_store::GcStore;
51pub(crate) use list_state::ListState;
52pub(crate) use map_state::MapState;
53pub(crate) use richtext_state::{redact_dead_style_values, RichtextState};
54pub(crate) use tree_state::FiIfNotConfigured;
55pub(crate) use tree_state::{get_meta_value, FractionalIndexGenResult, NodePosition, TreeState};
56pub use tree_state::{TreeNode, TreeNodeWithChildren, TreeParentId};
57
58use self::{container_store::ContainerWrapper, unknown_state::UnknownState};
59
60#[cfg(feature = "counter")]
61use self::counter_state::CounterState;
62
63use super::{arena::SharedArena, event::InternalDocDiff};
64
65#[cfg(test)]
66thread_local! {
67 static FAIL_NEXT_IMPORT_STATE_APPLY: Cell<bool> = Cell::new(false);
68}
69
70#[cfg(test)]
71pub(crate) fn fail_next_import_state_apply_for_test() {
72 FAIL_NEXT_IMPORT_STATE_APPLY.with(|fail| fail.set(true));
73}
74
75fn visible_container_value_is_empty(kind: ContainerType, value: &LoroValue) -> bool {
76 match kind {
77 ContainerType::Text => value.as_string().is_some_and(|value| value.is_empty()),
78 ContainerType::Map | ContainerType::List | ContainerType::MovableList => {
79 value.is_empty_collection()
80 }
81 ContainerType::Tree => value.as_list().is_some_and(|value| value.is_empty()),
82 #[cfg(feature = "counter")]
83 ContainerType::Counter => false,
84 ContainerType::Unknown(_) => false,
85 }
86}
87
88fn deleted_root_container_value_is_cleared(kind: ContainerType, value: &LoroValue) -> bool {
89 match kind {
90 #[cfg(feature = "counter")]
91 ContainerType::Counter => value.as_double().is_some_and(|value| *value == 0.0),
92 _ => visible_container_value_is_empty(kind, value),
93 }
94}
95
96fn state_decode_error(message: impl Into<Box<str>>) -> LoroError {
97 LoroError::DecodeError(message.into())
98}
99
100fn decode_peer_table(bytes: &mut &[u8], context: &str) -> LoroResult<Vec<PeerID>> {
101 let peer_num = leb128::read::unsigned(bytes)
102 .map_err(|_| state_decode_error(format!("{context}: invalid peer table length")))?;
103 let peer_num = usize::try_from(peer_num)
104 .map_err(|_| state_decode_error(format!("{context}: peer table length overflow")))?;
105 let peer_bytes_len = peer_num
106 .checked_mul(std::mem::size_of::<PeerID>())
107 .ok_or_else(|| state_decode_error(format!("{context}: peer table byte length overflow")))?;
108 if bytes.len() < peer_bytes_len {
109 return Err(state_decode_error(format!(
110 "{context}: truncated peer table"
111 )));
112 }
113
114 let peer_bytes = &bytes[..peer_bytes_len];
115 let peers = peer_bytes
116 .chunks_exact(std::mem::size_of::<PeerID>())
117 .map(|chunk| {
118 let mut buf = [0u8; std::mem::size_of::<PeerID>()];
119 buf.copy_from_slice(chunk);
120 PeerID::from_le_bytes(buf)
121 })
122 .collect();
123 *bytes = &bytes[peer_bytes_len..];
124 Ok(peers)
125}
126
127fn decode_peer_from_table(peers: &[PeerID], peer_idx: usize, context: &str) -> LoroResult<PeerID> {
128 peers
129 .get(peer_idx)
130 .copied()
131 .ok_or_else(|| state_decode_error(format!("{context}: peer index out of range")))
132}
133
134fn read_state_leb_u64(bytes: &mut &[u8], context: &str) -> LoroResult<u64> {
135 leb128::read::unsigned(bytes)
136 .map_err(|_| state_decode_error(format!("{context}: invalid integer")))
137}
138
139fn decode_counter(counter: i32, context: &str) -> LoroResult<i32> {
140 if counter < 0 {
141 return Err(state_decode_error(format!("{context}: negative counter")));
142 }
143
144 Ok(counter)
145}
146
147fn decode_lamport_from_delta(
148 counter: i32,
149 lamport_sub_counter: i32,
150 context: &str,
151) -> LoroResult<Lamport> {
152 decode_counter(counter, context)?;
153 let lamport = counter
154 .checked_add(lamport_sub_counter)
155 .ok_or_else(|| state_decode_error(format!("{context}: lamport overflow")))?;
156 u32::try_from(lamport).map_err(|_| state_decode_error(format!("{context}: negative lamport")))
157}
158
159pub struct DocState {
160 pub(super) peer: Arc<AtomicU64>,
161
162 pub(super) frontiers: Frontiers,
163 // pub(super) states: FxHashMap<ContainerIdx, State>,
164 pub(super) store: ContainerStore,
165 pub(super) arena: SharedArena,
166 pub(crate) config: Configure,
167 // resolve event stuff
168 doc: Weak<LoroDocInner>,
169 // txn related stuff
170 in_txn: bool,
171 changed_idx_in_txn: FxHashSet<ContainerIdx>,
172
173 // diff related stuff
174 event_recorder: EventRecorder,
175
176 dead_containers_cache: DeadContainersCache,
177 alive_containers_cache: Option<AliveContainersCache>,
178 /// Set while recording for a caller that only uses actual changes
179 /// ([`crate::undo::DiffBatch::from_changes`]: revert, undo). Containers that keep their
180 /// state are then not revived at all, which skips building full states nobody reads.
181 record_changes_only: bool,
182 /// Set while a local transaction that may be rolled back runs (`apply_diff`,
183 /// `revert_to`). See [`Self::begin_local_rollback`].
184 local_rollback: Option<LocalRollbackJournal>,
185}
186
187/// What undoing a local transaction's ops by checkout cannot restore exactly,
188/// recorded as the ops are applied. See `context/apply-diff-atomicity.md`.
189struct LocalRollbackJournal {
190 /// The `apply_diff` scope that began it.
191 scope: u64,
192 /// The value of each counter before the transaction's first op on it:
193 /// subtracting the increments again may not give back the same float.
194 #[cfg(feature = "counter")]
195 counters: FxHashMap<ContainerIdx, f64>,
196}
197
198struct AliveContainersCache {
199 frontiers: Frontiers,
200 roots: Vec<ContainerIdx>,
201 indices: Arc<FxHashSet<ContainerIdx>>,
202}
203
204/// Which containers an alive-container walk follows.
205#[derive(Debug, Clone, Copy, PartialEq, Eq)]
206enum AliveWalk {
207 /// Containers reachable through the current value (`get_deep_value` view).
208 Visible,
209 /// `Visible` plus the meta maps of deleted tree nodes and everything they reach.
210 ///
211 /// Shallow/state-only export filters the root state with this set. A tree node deleted
212 /// before the root can still be revived by a retained op: a node that is only dead because
213 /// an ancestor was deleted can be moved out locally, and a peer's `Move` op revives even a
214 /// directly deleted node (the local handler refuses that, and undo/`revert_to` allocate a
215 /// new `TreeID`, but the tree CRDT applies such an op). The revived node keeps its old meta map,
216 /// so that map must stay in the root state for the latest state and every checkout in the
217 /// retained range. Map/list children deleted before the root cannot be re-attached (a
218 /// re-insert creates a new container id) and are still dropped.
219 Retention,
220}
221
222const ALIVE_CONTAINERS_CACHE_MAX_BYTES: usize = 4 * 1024 * 1024;
223
224fn estimated_alive_containers_cache_bytes(
225 roots_capacity: usize,
226 indices: &FxHashSet<ContainerIdx>,
227) -> usize {
228 // Hash-table control bytes and alignment are implementation details. A pointer of overhead per
229 // entry is deliberately conservative, so retaining the cache cannot silently become another
230 // form of full-state materialization on documents with very many small containers.
231 roots_capacity
232 .saturating_mul(std::mem::size_of::<ContainerIdx>())
233 .saturating_add(
234 indices
235 .capacity()
236 .saturating_mul(std::mem::size_of::<ContainerIdx>() + std::mem::size_of::<usize>()),
237 )
238}
239
240impl std::fmt::Debug for DocState {
241 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
242 f.debug_struct("DocState")
243 .field("peer", &self.peer)
244 .finish()
245 }
246}
247
248#[derive(Clone, Copy)]
249pub(crate) struct ContainerCreationContext<'a> {
250 pub configure: &'a Configure,
251 pub peer: PeerID,
252}
253
254pub(crate) struct DiffApplyContext<'a> {
255 pub mode: DiffMode,
256 pub doc: &'a Weak<LoroDocInner>,
257}
258
259pub(crate) trait FastStateSnapshot {
260 fn encode_snapshot_fast<W: Write>(&mut self, w: W);
261 fn decode_value(bytes: &[u8]) -> LoroResult<(LoroValue, &[u8])>;
262 fn decode_snapshot_fast(
263 idx: ContainerIdx,
264 v: (LoroValue, &[u8]),
265 ctx: ContainerCreationContext,
266 ) -> LoroResult<Self>
267 where
268 Self: Sized;
269}
270
271#[derive(Debug, Clone, Default)]
272pub(crate) struct ApplyLocalOpReturn {
273 pub deleted_containers: Vec<ContainerID>,
274}
275
276#[enum_dispatch]
277pub(crate) trait ContainerState {
278 fn container_idx(&self) -> ContainerIdx;
279
280 fn is_state_empty(&self) -> bool;
281
282 #[must_use]
283 fn apply_diff_and_convert(&mut self, diff: InternalDiff, ctx: DiffApplyContext) -> Diff;
284
285 /// Apply a state diff. Returns `Err` when the diff is malformed in a
286 /// way that would corrupt the container (e.g. a `Retain`/`Insert` that
287 /// overruns the current state). The error is propagated up to
288 /// `doc.import` so the caller can observe the failure without the
289 /// doc-state panicking inside a lock.
290 fn apply_diff(&mut self, diff: InternalDiff, ctx: DiffApplyContext) -> LoroResult<()>;
291
292 /// Validate a state diff before it is applied. Implementations should keep
293 /// this check proportional to the diff size and must not mutate container
294 /// state.
295 fn validate_diff(&self, _diff: &InternalDiff) -> LoroResult<()> {
296 Ok(())
297 }
298
299 fn apply_local_op(&mut self, raw_op: &RawOp, op: &Op) -> LoroResult<ApplyLocalOpReturn>;
300 /// Convert a state to a diff, such that an empty state will be transformed into the same as this state when it's applied.
301 fn to_diff(&mut self, doc: &Weak<LoroDocInner>) -> Diff;
302
303 fn get_value(&mut self) -> LoroValue;
304
305 /// Get the index of the child container
306 #[allow(unused)]
307 fn get_child_index(&self, id: &ContainerID) -> Option<Index>;
308
309 #[allow(unused)]
310 fn contains_child(&self, id: &ContainerID) -> bool;
311
312 #[allow(unused)]
313 fn get_child_containers(&self) -> Vec<ContainerID>;
314
315 fn fork(&self, config: &Configure) -> Self;
316}
317
318impl<T: FastStateSnapshot> FastStateSnapshot for Box<T> {
319 fn encode_snapshot_fast<W: Write>(&mut self, w: W) {
320 self.as_mut().encode_snapshot_fast(w)
321 }
322
323 fn decode_value(bytes: &[u8]) -> LoroResult<(LoroValue, &[u8])> {
324 T::decode_value(bytes)
325 }
326
327 fn decode_snapshot_fast(
328 idx: ContainerIdx,
329 v: (LoroValue, &[u8]),
330 ctx: ContainerCreationContext,
331 ) -> LoroResult<Self>
332 where
333 Self: Sized,
334 {
335 T::decode_snapshot_fast(idx, v, ctx).map(|x| Box::new(x))
336 }
337}
338
339impl<T: ContainerState> ContainerState for Box<T> {
340 fn container_idx(&self) -> ContainerIdx {
341 self.as_ref().container_idx()
342 }
343
344 fn is_state_empty(&self) -> bool {
345 self.as_ref().is_state_empty()
346 }
347
348 fn apply_diff_and_convert(&mut self, diff: InternalDiff, ctx: DiffApplyContext) -> Diff {
349 self.as_mut().apply_diff_and_convert(diff, ctx)
350 }
351
352 fn apply_diff(&mut self, diff: InternalDiff, ctx: DiffApplyContext) -> LoroResult<()> {
353 self.as_mut().apply_diff(diff, ctx)
354 }
355
356 fn validate_diff(&self, diff: &InternalDiff) -> LoroResult<()> {
357 self.as_ref().validate_diff(diff)
358 }
359
360 fn apply_local_op(&mut self, raw_op: &RawOp, op: &Op) -> LoroResult<ApplyLocalOpReturn> {
361 self.as_mut().apply_local_op(raw_op, op)
362 }
363
364 #[doc = r" Convert a state to a diff, such that an empty state will be transformed into the same as this state when it's applied."]
365 fn to_diff(&mut self, doc: &Weak<LoroDocInner>) -> Diff {
366 self.as_mut().to_diff(doc)
367 }
368
369 fn get_value(&mut self) -> LoroValue {
370 self.as_mut().get_value()
371 }
372
373 #[doc = r" Get the index of the child container"]
374 #[allow(unused)]
375 fn get_child_index(&self, id: &ContainerID) -> Option<Index> {
376 self.as_ref().get_child_index(id)
377 }
378
379 fn contains_child(&self, id: &ContainerID) -> bool {
380 self.as_ref().contains_child(id)
381 }
382
383 #[allow(unused)]
384 fn get_child_containers(&self) -> Vec<ContainerID> {
385 self.as_ref().get_child_containers()
386 }
387
388 fn fork(&self, config: &Configure) -> Self {
389 Box::new(self.as_ref().fork(config))
390 }
391}
392
393#[allow(clippy::enum_variant_names)]
394#[enum_dispatch(ContainerState)]
395#[derive(EnumAsInner, Debug)]
396pub enum State {
397 ListState(Box<ListState>),
398 MovableListState(Box<MovableListState>),
399 MapState(Box<MapState>),
400 RichtextState(Box<RichtextState>),
401 TreeState(Box<TreeState>),
402 #[cfg(feature = "counter")]
403 CounterState(Box<counter_state::CounterState>),
404 UnknownState(UnknownState),
405}
406
407impl From<ListState> for State {
408 fn from(s: ListState) -> Self {
409 Self::ListState(Box::new(s))
410 }
411}
412
413impl From<RichtextState> for State {
414 fn from(s: RichtextState) -> Self {
415 Self::RichtextState(Box::new(s))
416 }
417}
418
419impl From<MovableListState> for State {
420 fn from(s: MovableListState) -> Self {
421 Self::MovableListState(Box::new(s))
422 }
423}
424
425impl From<MapState> for State {
426 fn from(s: MapState) -> Self {
427 Self::MapState(Box::new(s))
428 }
429}
430
431impl From<TreeState> for State {
432 fn from(s: TreeState) -> Self {
433 Self::TreeState(Box::new(s))
434 }
435}
436
437#[cfg(feature = "counter")]
438impl From<CounterState> for State {
439 fn from(s: CounterState) -> Self {
440 Self::CounterState(Box::new(s))
441 }
442}
443
444impl State {
445 pub fn new_list(idx: ContainerIdx) -> Self {
446 Self::ListState(Box::new(ListState::new(idx)))
447 }
448
449 pub fn new_map(idx: ContainerIdx) -> Self {
450 Self::MapState(Box::new(MapState::new(idx)))
451 }
452
453 pub fn new_richtext(idx: ContainerIdx, config: Arc<RwLock<StyleConfigMap>>) -> Self {
454 Self::RichtextState(Box::new(RichtextState::new(idx, config)))
455 }
456
457 pub fn new_tree(idx: ContainerIdx, peer: PeerID) -> Self {
458 Self::TreeState(Box::new(TreeState::new(idx, peer)))
459 }
460
461 pub fn new_unknown(idx: ContainerIdx) -> Self {
462 Self::UnknownState(UnknownState::new(idx))
463 }
464
465 pub fn encode_snapshot_fast<W: Write>(&mut self, mut w: W) {
466 match self {
467 State::ListState(s) => s.encode_snapshot_fast(&mut w),
468 State::MovableListState(s) => s.encode_snapshot_fast(&mut w),
469 State::MapState(s) => s.encode_snapshot_fast(&mut w),
470 State::RichtextState(s) => s.encode_snapshot_fast(&mut w),
471 State::TreeState(s) => s.encode_snapshot_fast(&mut w),
472 #[cfg(feature = "counter")]
473 State::CounterState(s) => s.encode_snapshot_fast(&mut w),
474 State::UnknownState(s) => s.encode_snapshot_fast(&mut w),
475 }
476 }
477
478 pub fn fork(&self, config: &Configure) -> Self {
479 match self {
480 State::ListState(list_state) => State::ListState(list_state.fork(config)),
481 State::MovableListState(movable_list_state) => {
482 State::MovableListState(movable_list_state.fork(config))
483 }
484 State::MapState(map_state) => State::MapState(map_state.fork(config)),
485 State::RichtextState(richtext_state) => {
486 State::RichtextState(richtext_state.fork(config))
487 }
488 State::TreeState(tree_state) => State::TreeState(tree_state.fork(config)),
489 #[cfg(feature = "counter")]
490 State::CounterState(counter_state) => State::CounterState(counter_state.fork(config)),
491 State::UnknownState(unknown_state) => State::UnknownState(unknown_state.fork(config)),
492 }
493 }
494}
495
496impl DocState {
497 #[inline]
498 pub fn new_arc(
499 doc: Weak<LoroDocInner>,
500 arena: SharedArena,
501 config: Configure,
502 lock_group: &LoroLockGroup,
503 ) -> Arc<LoroMutex<Self>> {
504 let peer = DefaultRandom.next_u64();
505 // TODO: maybe we should switch to certain version in oplog?
506
507 let peer = Arc::new(AtomicU64::new(peer));
508 Arc::new(lock_group.new_lock(
509 Self {
510 store: ContainerStore::new(arena.clone(), config.clone(), peer.clone()),
511 peer,
512 arena,
513 frontiers: Frontiers::default(),
514 doc,
515 config,
516 in_txn: false,
517 changed_idx_in_txn: FxHashSet::default(),
518 event_recorder: Default::default(),
519 dead_containers_cache: Default::default(),
520 alive_containers_cache: None,
521 record_changes_only: false,
522 local_rollback: None,
523 },
524 crate::lock::LockKind::DocState,
525 ))
526 }
527
528 pub fn fork_with_new_peer_id(
529 &mut self,
530 doc: Weak<LoroDocInner>,
531 arena: SharedArena,
532 config: Configure,
533 ) -> Arc<Mutex<Self>> {
534 let peer = Arc::new(AtomicU64::new(DefaultRandom.next_u64()));
535 let store = self.store.fork(arena.clone(), peer.clone(), config.clone());
536 Arc::new(Mutex::new(Self {
537 peer,
538 frontiers: self.frontiers.clone(),
539 store,
540 arena,
541 config,
542 doc,
543 in_txn: false,
544 changed_idx_in_txn: FxHashSet::default(),
545 event_recorder: Default::default(),
546 dead_containers_cache: Default::default(),
547 alive_containers_cache: None,
548 record_changes_only: false,
549 local_rollback: None,
550 }))
551 }
552
553 pub fn start_recording(&mut self) {
554 if self.is_recording() {
555 return;
556 }
557
558 self.event_recorder.recording_diff = true;
559 self.event_recorder.diff_start_version = Some(self.frontiers.clone());
560 }
561
562 #[inline(always)]
563 pub fn stop_and_clear_recording(&mut self) {
564 self.event_recorder = Default::default();
565 }
566
567 #[inline(always)]
568 pub fn is_recording(&self) -> bool {
569 self.event_recorder.recording_diff
570 }
571
572 pub fn refresh_peer_id(&mut self) {
573 self.peer.store(
574 DefaultRandom.next_u64(),
575 std::sync::atomic::Ordering::Relaxed,
576 );
577 }
578
579 /// Take all the diffs that are recorded and convert them to events.
580 pub fn take_events(&mut self) -> Vec<DocDiff> {
581 if !self.is_recording() {
582 return vec![];
583 }
584
585 self.convert_current_batch_diff_into_event();
586 std::mem::take(&mut self.event_recorder.events)
587 }
588
589 /// Record the next diff.
590 /// Caller should call [pre_txn] before calling this.
591 ///
592 /// # Panic
593 ///
594 /// Panic when the diff cannot be merged with the previous diff.
595 /// Caller should call [pre_txn] before calling this to avoid panic.
596 fn record_diff(&mut self, diff: InternalDocDiff) {
597 if !self.event_recorder.recording_diff || diff.diff.is_empty() {
598 return;
599 }
600
601 let Some(last_diff) = self.event_recorder.diffs.last_mut() else {
602 self.event_recorder.diffs.push(diff.into_owned());
603 return;
604 };
605
606 if last_diff.can_merge(&diff) {
607 self.event_recorder.diffs.push(diff.into_owned());
608 return;
609 }
610
611 panic!("should call pre_txn before record_diff")
612 }
613
614 /// This should be called when DocState is going to apply a transaction / a diff.
615 fn pre_txn(&mut self, next_origin: InternalString, next_trigger: EventTriggerKind) {
616 if !self.is_recording() {
617 return;
618 }
619
620 let Some(last_diff) = self.event_recorder.diffs.last() else {
621 return;
622 };
623
624 if last_diff.origin == next_origin && last_diff.by == next_trigger {
625 return;
626 }
627
628 // current diff batch cannot merge with the incoming diff,
629 // need to convert all the current diffs into event
630 self.convert_current_batch_diff_into_event()
631 }
632
633 fn convert_current_batch_diff_into_event(&mut self) {
634 let recorder = &mut self.event_recorder;
635 if recorder.diffs.is_empty() {
636 return;
637 }
638
639 let diffs = std::mem::take(&mut recorder.diffs);
640 let start = recorder.diff_start_version.take().unwrap();
641 recorder.diff_start_version = Some((*diffs.last().unwrap().new_version).to_owned());
642 let event = self.diffs_to_event(diffs, start);
643 self.event_recorder.events.push(event);
644 }
645
646 /// Change the peer id of this doc state.
647 /// It changes the peer id for the future txn on this AppState
648 #[inline]
649 pub fn set_peer_id(&mut self, peer: PeerID) {
650 self.peer.store(peer, std::sync::atomic::Ordering::Relaxed);
651 }
652
653 pub fn peer_id(&self) -> PeerID {
654 self.peer.load(std::sync::atomic::Ordering::Relaxed)
655 }
656
657 /// It's expected that diff only contains [`InternalDiff`]
658 ///
659 /// Returns `Err` if any container state rejects its diff as malformed
660 /// (see `ContainerState::validate_diff`). Validation runs before mutating
661 /// any container state, so a returned error leaves the doc-state view at
662 /// the previous version.
663 #[instrument(skip_all)]
664 pub(crate) fn apply_diff(
665 &mut self,
666 mut diff: InternalDocDiff<'static>,
667 diff_mode: DiffMode,
668 ) -> LoroResult<()> {
669 if self.in_txn {
670 return Err(LoroError::TransactionError(
671 "apply_diff should not be called in a transaction"
672 .to_string()
673 .into_boxed_str(),
674 ));
675 }
676
677 let is_recording = self.is_recording();
678 let Cow::Owned(mut diffs) = std::mem::take(&mut diff.diff) else {
679 unreachable!()
680 };
681 self.validate_diff_batch(&diffs)?;
682 #[cfg(test)]
683 if diff.origin.as_str() == "__loro_fail_import_state_apply" {
684 return Err(LoroError::internal("state apply failpoint"));
685 }
686 #[cfg(test)]
687 if diff.by == EventTriggerKind::Import {
688 let should_fail = FAIL_NEXT_IMPORT_STATE_APPLY.with(|fail| {
689 let should_fail = fail.get();
690 if should_fail {
691 fail.set(false);
692 }
693 should_fail
694 });
695 if should_fail {
696 return Err(LoroError::internal("state apply failpoint"));
697 }
698 }
699 // `diff_mode` here is the DIRECTION mode (`origin_diff_mode` from
700 // `calc_diff_internal`), not the mode the calculators computed with:
701 // Checkout means the transition may go backwards, which can revive any
702 // container. Any checkout also clears it, even a forward one
703 // (`attach`, `checkout_to_latest`): while the state was behind the
704 // oplog, a container created later looked cut at its map or list
705 // parent. Every other forward transition keeps the state at the
706 // oplog's latest version, where only a tree or movable-list move can
707 // revive a container (see `dead_containers_cache.rs`).
708 if diff_mode == DiffMode::Checkout || diff.by == EventTriggerKind::Checkout {
709 self.dead_containers_cache.clear();
710 } else if diffs.iter().any(|d| {
711 matches!(
712 d.idx.get_type(),
713 ContainerType::Tree | ContainerType::MovableList
714 )
715 }) {
716 self.dead_containers_cache.clear_revivable();
717 }
718 self.pre_txn(diff.origin.clone(), diff.by);
719
720 // # Revival
721 //
722 // A Container, if it is deleted from its parent Container, will still exist
723 // in the internal state of Loro; whereas on the user side, a tree structure
724 // is maintained following Events, and at this point, the corresponding state
725 // is considered deleted.
726 //
727 // Sometimes, this "pseudo-dead" Container may be revived (for example, through
728 // backtracking or parallel editing), and the user side should receive an Event
729 // that restores the consistency between the revived Container and the internal
730 // state of Loro. This Event is required to restore the pseudo-dead Container
731 // State to its current state on Loro, and we refer to this process as "revival".
732 //
733 // Revival occurs during the application of the internal diff, and this operation
734 // is necessary when it needs to be converted into an external Event.
735 //
736 // We can utilize the output of the Diff to determine which child nodes should be revived.
737 //
738 // For nodes that are to be revived, we can disregard the Events output by their
739 // round of apply_diff_and_convert, and instead, directly convert their state into
740 // an Event once their application is complete.
741 //
742 // Suppose A is revived and B is A's child, and B also needs to be revived; therefore,
743 // we should process each level alternately.
744
745 self.register_meta_parents_of_created_tree_nodes(&diffs);
746 // We need to ensure diff is processed in order
747 diffs.sort_by_cached_key(|diff| self.arena.get_depth(diff.idx));
748 let mut to_revive_in_next_layer: FxHashSet<ContainerIdx> = FxHashSet::default();
749 let mut to_revive_in_this_layer: FxHashSet<ContainerIdx> = FxHashSet::default();
750 // Revived containers that kept their id and state: a mergeable child re-activated by
751 // a container that is not itself revived, and what such a container holds. Their event
752 // still carries the full state; `KeptChange` records their actual change.
753 let mut kept: FxHashSet<ContainerIdx> = FxHashSet::default();
754 let mut last_depth = 0;
755 let len = diffs.len();
756 for mut diff in std::mem::replace(&mut diffs, Vec::with_capacity(len)) {
757 let Some(depth) = self.arena.get_depth(diff.idx) else {
758 warn!("{:?} is not in arena. It could be a dangling container that was deleted before the shallow start version.", self.arena.idx_to_id(diff.idx));
759 continue;
760 };
761 let this_depth = depth.get();
762 while this_depth > last_depth {
763 // Clear `to_revive` when we are going to process a new level
764 // so that we can process the revival of the next level
765 let to_create = std::mem::take(&mut to_revive_in_this_layer);
766 to_revive_in_this_layer = std::mem::take(&mut to_revive_in_next_layer);
767 for new in to_create {
768 if let Some(d) =
769 self.revive_without_diff(new, &mut to_revive_in_this_layer, &mut kept)
770 {
771 diffs.push(d);
772 }
773 }
774
775 last_depth += 1;
776 }
777
778 let idx = diff.idx;
779 let internal_diff = std::mem::take(&mut diff.diff);
780 match &internal_diff {
781 crate::event::DiffVariant::None => {
782 if is_recording {
783 let state = self.store.get_or_create_mut(diff.idx);
784 let extern_diff = state.to_diff(&self.doc);
785 trigger_on_new_container(
786 &extern_diff,
787 |cid| {
788 to_revive_in_next_layer.insert(cid);
789 },
790 &self.arena,
791 );
792 diff.diff = extern_diff.into();
793 }
794 }
795 crate::event::DiffVariant::Internal(inner_diff) => {
796 self.ensure_containers_created_by_internal_diff(inner_diff);
797 let cid = self.arena.idx_to_id(idx).unwrap();
798 info_span!("apply diff on", container_id = ?cid).in_scope(
799 || -> LoroResult<()> {
800 if self.in_txn {
801 self.changed_idx_in_txn.insert(idx);
802 }
803 let state = self.store.get_or_create_mut(idx);
804 if is_recording {
805 let is_revived =
806 diff.bring_back || to_revive_in_this_layer.contains(&idx);
807 let is_kept = is_revived && kept.contains(&idx);
808 let ctx = DiffApplyContext {
809 mode: diff.diff_mode,
810 doc: &self.doc,
811 };
812 let internal_diff = internal_diff.into_internal().unwrap();
813 // Containers the actual change inserts are new to a doc that
814 // kept this container, so they are revived with full state.
815 let mut inserted: FxHashSet<ContainerIdx> = FxHashSet::default();
816 // process bring_back before apply
817 let external_diff = if is_kept {
818 let change = state.apply_diff_and_convert(internal_diff, ctx);
819 trigger_on_new_container(
820 &change,
821 |cid| {
822 inserted.insert(cid);
823 },
824 &self.arena,
825 );
826 diff.kept = Some(KeptChange::from_diff(change));
827 state.to_diff(&self.doc)
828 } else if is_revived {
829 state.apply_diff(internal_diff, ctx)?;
830 state.to_diff(&self.doc)
831 } else {
832 state.apply_diff_and_convert(internal_diff, ctx)
833 };
834 let arena = &self.arena;
835 let changes_only = self.record_changes_only;
836 trigger_on_new_container(
837 &external_diff,
838 |cid| {
839 if changes_only && !is_revived && is_mergeable(arena, cid) {
840 // It keeps its state; its own diff (if any) is
841 // its change.
842 return;
843 }
844 to_revive_in_next_layer.insert(cid);
845 let keeps_state = if is_revived {
846 is_kept
847 && (!inserted.contains(&cid)
848 || is_mergeable(arena, cid))
849 } else {
850 // A container that keeps its id re-activates a
851 // mergeable child at its deterministic cid.
852 is_mergeable(arena, cid)
853 };
854 if keeps_state {
855 kept.insert(cid);
856 }
857 },
858 arena,
859 );
860 diff.diff = external_diff.into();
861 } else {
862 state.apply_diff(
863 internal_diff.into_internal().unwrap(),
864 DiffApplyContext {
865 mode: diff.diff_mode,
866 doc: &self.doc,
867 },
868 )?;
869 }
870 Ok(())
871 },
872 )?;
873 }
874 crate::event::DiffVariant::External(_) => unreachable!(),
875 }
876
877 to_revive_in_this_layer.remove(&idx);
878 if !diff.diff.is_empty() || matches!(diff.kept, Some(KeptChange::Changed(_))) {
879 diffs.push(diff);
880 }
881 }
882
883 // Revive the last several layers
884 while !to_revive_in_this_layer.is_empty() || !to_revive_in_next_layer.is_empty() {
885 let to_create = std::mem::take(&mut to_revive_in_this_layer);
886 for new in to_create {
887 if let Some(d) =
888 self.revive_without_diff(new, &mut to_revive_in_next_layer, &mut kept)
889 {
890 diffs.push(d);
891 }
892 }
893
894 to_revive_in_this_layer = std::mem::take(&mut to_revive_in_next_layer);
895 }
896
897 diff.diff = diffs.into();
898 self.frontiers = diff.new_version.clone().into_owned();
899
900 if self.is_recording() {
901 self.record_diff(diff)
902 }
903 Ok(())
904 }
905
906 /// Registers the tree as the parent of the meta map of every node a tree diff in this batch
907 /// (re)creates, before the batch is sorted by depth.
908 ///
909 /// Normally the node's `Create` op or the snapshot state registered it already. A node
910 /// deleted before a shallow root and revived by a retained op has neither when the root state
911 /// lacks its meta (blobs from exporters before loro-dev/loro#1119). Without a parent the meta
912 /// has no depth: `ensure_container` panicked with "Parent is not registered", and the meta's
913 /// own diff in the same batch was skipped as a dangling container.
914 fn register_meta_parents_of_created_tree_nodes(&mut self, diffs: &[InternalContainerDiff]) {
915 for diff in diffs {
916 let crate::event::DiffVariant::Internal(InternalDiff::Tree(delta)) = &diff.diff else {
917 continue;
918 };
919 for item in delta.diff.iter() {
920 if matches!(item.action, crate::delta::TreeInternalDiff::Create { .. }) {
921 let meta_idx = self
922 .arena
923 .register_container(&item.target.associated_meta_container());
924 if self.arena.get_registered_parent(meta_idx).is_none() {
925 self.arena.set_parent(meta_idx, Some(diff.idx));
926 }
927 }
928 }
929 }
930 }
931
932 /// Create store entries for every container this diff brings alive.
933 ///
934 /// Full snapshot export no longer walks the alive-container graph to discover containers
935 /// that exist only as references inside another container's value (e.g. an empty child
936 /// created by a remote peer, whose own container has no ops and therefore no diff). Such
937 /// entries must be created when the reference is applied so the next flush persists them.
938 fn ensure_containers_created_by_internal_diff(&mut self, diff: &InternalDiff) {
939 let mut to_ensure: SmallVec<[ContainerID; 2]> = SmallVec::new();
940 match diff {
941 InternalDiff::ListRaw(delta) => {
942 for item in delta.iter() {
943 if let crate::delta::DeltaItem::Insert { insert, .. } = item {
944 match &insert.values {
945 either::Either::Left(values) => {
946 for value in values.as_slice() {
947 if let LoroValue::Container(c) = value {
948 to_ensure.push(c.clone());
949 }
950 }
951 }
952 either::Either::Right(LoroValue::Container(c)) => {
953 to_ensure.push(c.clone())
954 }
955 either::Either::Right(_) => {}
956 }
957 }
958 }
959 }
960 InternalDiff::Map(delta) => {
961 // Mergeable markers are deliberately not materialized here: the parent map's
962 // marker is the single source of truth for an ensured-but-empty mergeable
963 // child, and it resolves lazily via `does_container_exist`/`get_reachable`.
964 for value in delta.updated.values() {
965 let Some(Some(value)) = value.as_ref().map(|v| v.value.as_ref()) else {
966 continue;
967 };
968 if let LoroValue::Container(c) = value {
969 to_ensure.push(c.clone());
970 }
971 }
972 }
973 InternalDiff::Tree(delta) => {
974 for item in delta.diff.iter() {
975 if matches!(item.action, crate::delta::TreeInternalDiff::Create { .. }) {
976 to_ensure.push(item.target.associated_meta_container());
977 }
978 }
979 }
980 InternalDiff::MovableList(delta) => {
981 for elem in delta.elements.values() {
982 if let LoroValue::Container(c) = &elem.value {
983 to_ensure.push(c.clone());
984 }
985 }
986 }
987 InternalDiff::RichtextRaw(_) => {}
988 #[cfg(feature = "counter")]
989 InternalDiff::Counter(_) => {}
990 InternalDiff::Unknown => {}
991 }
992
993 for id in to_ensure {
994 self.ensure_container(&id);
995 }
996 }
997
998 /// Whether a forward import diff has to be recomputed in Checkout mode because a
999 /// movable-list op targets an element this state no longer holds.
1000 /// See [`MovableListState::references_absent_elem`].
1001 pub(crate) fn needs_checkout_diff(&mut self, diffs: &[InternalContainerDiff]) -> bool {
1002 diffs.iter().any(|diff| {
1003 let crate::event::DiffVariant::Internal(InternalDiff::MovableList(delta)) = &diff.diff
1004 else {
1005 return false;
1006 };
1007 match self.store.get_container(diff.idx) {
1008 Some(State::MovableListState(state)) => state.references_absent_elem(delta),
1009 Some(_) => unreachable!("movable list diff for a non movable list container"),
1010 None => delta
1011 .elements
1012 .values()
1013 .any(|elem| elem.pos.is_none() || elem.value_id.is_none()),
1014 }
1015 })
1016 }
1017
1018 fn validate_diff_batch(&mut self, diffs: &[InternalContainerDiff]) -> LoroResult<()> {
1019 for diff in diffs {
1020 let crate::event::DiffVariant::Internal(internal_diff) = &diff.diff else {
1021 continue;
1022 };
1023 if let Some(state) = self.store.get_container(diff.idx) {
1024 state.validate_diff(internal_diff)?;
1025 } else {
1026 let state = create_state_(diff.idx, &self.config, self.peer_id());
1027 state.validate_diff(internal_diff)?;
1028 }
1029 }
1030
1031 Ok(())
1032 }
1033
1034 pub fn apply_local_op(&mut self, raw_op: &RawOp, op: &Op) -> LoroResult<()> {
1035 // set parent first, `MapContainer` will only be created for TreeID that does not contain
1036 self.set_container_parent_by_raw_op(raw_op);
1037 self.ensure_containers_created_by_op(op);
1038 let state = self.store.get_or_create_mut(op.container);
1039 if self.in_txn {
1040 self.changed_idx_in_txn.insert(op.container);
1041 }
1042 #[cfg(feature = "counter")]
1043 if let (Some(journal), State::CounterState(counter)) = (&mut self.local_rollback, &*state) {
1044 journal
1045 .counters
1046 .entry(op.container)
1047 .or_insert_with(|| counter.value());
1048 }
1049 // A local move can take a node out of a deleted subtree. Movable-list
1050 // elements cannot be revived locally: a deleted one has no index.
1051 if let RawOpContent::Tree(tree_op) = &raw_op.content {
1052 if matches!(**tree_op, TreeOp::Move { .. }) {
1053 self.dead_containers_cache.clear_revivable();
1054 }
1055 }
1056 state.apply_local_op(raw_op, op)?;
1057 Ok(())
1058 }
1059
1060 /// Start recording what [`Self::finish_local_rollback`] needs to undo the
1061 /// local ops applied from now on: the containers that get new state and the
1062 /// counters' values.
1063 ///
1064 /// `scope` identifies the caller. A journal of another scope is replaced: two
1065 /// scopes never share a transaction, so that scope's transaction was
1066 /// committed by another thread and cannot be rolled back anyway.
1067 pub(crate) fn begin_local_rollback(&mut self, scope: u64) {
1068 self.store.begin_created_journal();
1069 self.local_rollback = Some(LocalRollbackJournal {
1070 scope,
1071 #[cfg(feature = "counter")]
1072 counters: Default::default(),
1073 });
1074 }
1075
1076 /// Stop recording for `scope`, keeping the ops.
1077 pub(crate) fn end_local_rollback(&mut self, scope: u64) {
1078 if self
1079 .local_rollback
1080 .as_ref()
1081 .is_some_and(|j| j.scope == scope)
1082 {
1083 self.store.take_created_journal();
1084 self.local_rollback = None;
1085 }
1086 }
1087
1088 /// Takes the event recorder out, so that a state change the caller discards
1089 /// is not recorded; put it back with [`Self::restore_event_recorder`].
1090 pub(crate) fn take_event_recorder(&mut self) -> EventRecorder {
1091 std::mem::take(&mut self.event_recorder)
1092 }
1093
1094 pub(crate) fn restore_event_recorder(&mut self, recorder: EventRecorder) {
1095 self.event_recorder = recorder;
1096 }
1097
1098 /// Finish rolling back the local ops applied since
1099 /// [`Self::begin_local_rollback`], after the caller undid them by checking
1100 /// the state out at the version before them. `peer` and `start_counter` are
1101 /// the id of the first op. Restores what the checkout cannot:
1102 ///
1103 /// - containers that got state since (new or never loaded before) lose it,
1104 /// so the store is the same as before, including which roots show up;
1105 /// - counters get their exact old values;
1106 /// - containers the ops created lose their parent link, since the next ops
1107 /// reuse their ids (`SharedArena::forget_parents_of_discarded_ops`);
1108 /// - the liveness caches, which may hold answers for the state in between.
1109 pub(crate) fn finish_local_rollback(
1110 &mut self,
1111 scope: u64,
1112 peer: PeerID,
1113 start_counter: crate::id::Counter,
1114 ) {
1115 let created = self.store.take_created_journal();
1116 let journal = self.local_rollback.take();
1117 assert!(
1118 journal.as_ref().is_some_and(|j| j.scope == scope),
1119 "the journal of a rolled back apply_diff was replaced"
1120 );
1121 #[cfg(feature = "counter")]
1122 if let Some(journal) = journal {
1123 for (idx, value) in journal.counters {
1124 if let Some(State::CounterState(counter)) = self.store.get_container_mut(idx) {
1125 counter.set_value(value);
1126 }
1127 }
1128 }
1129 #[cfg(not(feature = "counter"))]
1130 let _ = journal;
1131 self.store.remove_created(&created);
1132 self.arena
1133 .forget_parents_of_discarded_ops(peer, start_counter);
1134 self.dead_containers_cache.clear();
1135 self.alive_containers_cache = None;
1136 }
1137
1138 pub(crate) fn start_txn(&mut self, origin: InternalString, trigger: EventTriggerKind) {
1139 self.pre_txn(origin, trigger);
1140 self.in_txn = true;
1141 }
1142
1143 pub(crate) fn abort_txn(&mut self) {
1144 self.in_txn = false;
1145 }
1146
1147 /// Undo [`Self::abort_txn`] for a transaction that goes on
1148 /// (`LoroDoc::rollback_apply_diff_scope`).
1149 pub(crate) fn resume_txn(&mut self) {
1150 self.in_txn = true;
1151 }
1152
1153 pub fn iter_and_decode_all(&mut self) -> impl Iterator<Item = &mut State> {
1154 self.store.iter_and_decode_all()
1155 }
1156
1157 pub(crate) fn iter_all_containers_mut(
1158 &mut self,
1159 ) -> impl Iterator<Item = (ContainerIdx, &mut ContainerWrapper)> {
1160 self.store.iter_all_containers()
1161 }
1162
1163 pub fn does_container_exist(&mut self, id: &ContainerID) -> bool {
1164 // A container may exist even if not yet registered in the arena.
1165 // Check arena first, then fall back to KV presence in the store.
1166 let is_mergeable = id.is_mergeable();
1167 if id.is_root() && !is_mergeable {
1168 return true;
1169 }
1170
1171 let registered = if is_mergeable {
1172 None
1173 } else {
1174 self.arena.id_to_idx(id)
1175 };
1176 if let Some(idx) = registered {
1177 if self.arena.get_depth(idx).is_some() {
1178 return true;
1179 }
1180 }
1181
1182 if self.store.contains_id(id) {
1183 return true;
1184 }
1185
1186 // Decided by the first lookup: another thread (e.g. creating a handler) may register
1187 // the container in between, without its parent.
1188 if !is_mergeable && registered.is_none() {
1189 // A document loaded from a snapshot parses its changes lazily, so a container that
1190 // an op created may not be registered yet.
1191 if let Some(idx) = self.arena.find_created_container(id) {
1192 if self.arena.get_depth(idx).is_some() {
1193 return true;
1194 }
1195 }
1196 }
1197
1198 // An ensured-but-empty mergeable child has no ops or KV state of its own yet;
1199 // the parent map's binary child ref is the source of truth for its existence.
1200 is_mergeable && self.get_reachable(id)
1201 }
1202
1203 pub(crate) fn commit_txn(&mut self, new_frontiers: Frontiers, diff: Option<InternalDocDiff>) {
1204 self.in_txn = false;
1205 self.frontiers = new_frontiers;
1206 if let Some(diff) = diff {
1207 if self.is_recording() {
1208 self.record_diff(diff);
1209 }
1210 }
1211 }
1212
1213 /// Ensure the container is created and will be encoded in the next `encode` call
1214 #[inline]
1215 pub(crate) fn ensure_container(&mut self, id: &ContainerID) {
1216 self.store.ensure_container(id);
1217 }
1218
1219 /// Ensure all alive containers are created in DocState and will be encoded in the next
1220 /// `encode` call, and return the alive set.
1221 ///
1222 /// Only shallow snapshot export needs this now (its `retain_keys` filter requires the alive
1223 /// set). The set is a *retention* set: it also contains the meta maps (and what they reach)
1224 /// of deleted tree nodes, because a later op can revive such a node with its old meta. See
1225 /// [`AliveWalk::Retention`]. Full snapshot export relies on the write-time invariant maintained by
1226 /// `ensure_containers_created_by_op` / `ensure_containers_created_by_internal_diff` instead
1227 /// of walking the graph.
1228 ///
1229 /// Returns arena indices rather than IDs so callers do not have to hold a second set of
1230 /// cloned container IDs; callers that need IDs map them through the arena.
1231 pub(crate) fn ensure_all_alive_containers(
1232 &mut self,
1233 ) -> LoroResult<Arc<FxHashSet<ContainerIdx>>> {
1234 let roots = self.existing_retention_roots();
1235 if !self.in_txn {
1236 if let Some(cache) = &self.alive_containers_cache {
1237 if cache.frontiers == self.frontiers && cache.roots == roots {
1238 return Ok(cache.indices.clone());
1239 }
1240 }
1241 }
1242 // Do not hold the previous version's set while constructing its replacement.
1243 self.alive_containers_cache = None;
1244
1245 let indices = Arc::new(
1246 self.get_all_alive_container_indices_from_roots(&roots, AliveWalk::Retention)?,
1247 );
1248 for idx in indices.iter() {
1249 let id = self.arena.get_container_id(*idx).unwrap();
1250 if !self.store.contains_id(&id) {
1251 self.store.ensure_container(&id);
1252 }
1253 }
1254
1255 if !self.in_txn {
1256 // The walk can discover and ensure an empty mergeable child, which registers another
1257 // retention root without advancing the document version. Store the post-walk roots so
1258 // the next unchanged export can use the cache immediately.
1259 let roots = self.existing_retention_roots();
1260 if estimated_alive_containers_cache_bytes(roots.capacity(), &indices)
1261 <= ALIVE_CONTAINERS_CACHE_MAX_BYTES
1262 {
1263 self.alive_containers_cache = Some(AliveContainersCache {
1264 frontiers: self.frontiers.clone(),
1265 roots,
1266 indices: indices.clone(),
1267 });
1268 }
1269 }
1270
1271 Ok(indices)
1272 }
1273
1274 pub(crate) fn get_value_by_idx(&mut self, container_idx: ContainerIdx) -> LoroValue {
1275 self.store
1276 .get_value(container_idx)
1277 .unwrap_or_else(|| container_idx.get_type().default_value())
1278 }
1279
1280 pub(crate) fn get_map_value_by_key(
1281 &mut self,
1282 container_idx: ContainerIdx,
1283 key: &str,
1284 ) -> Option<LoroValue> {
1285 self.store.map_get(container_idx, key)
1286 }
1287
1288 pub(crate) fn get_map_len(&mut self, container_idx: ContainerIdx) -> usize {
1289 self.store.map_len(container_idx)
1290 }
1291
1292 pub(crate) fn get_map_keys(&mut self, container_idx: ContainerIdx) -> Vec<InternalString> {
1293 self.store.map_keys(container_idx)
1294 }
1295
1296 pub(crate) fn get_map_entries(
1297 &mut self,
1298 container_idx: ContainerIdx,
1299 ) -> Vec<(InternalString, LoroValue)> {
1300 self.store.map_entries(container_idx)
1301 }
1302
1303 pub(crate) fn get_list_value_at(
1304 &mut self,
1305 container_idx: ContainerIdx,
1306 index: usize,
1307 ) -> Option<LoroValue> {
1308 self.store.list_get(container_idx, index)
1309 }
1310
1311 pub(crate) fn get_list_len(&mut self, container_idx: ContainerIdx) -> usize {
1312 self.store.list_len(container_idx)
1313 }
1314
1315 pub(crate) fn get_list_values(&mut self, container_idx: ContainerIdx) -> Vec<LoroValue> {
1316 self.store.list_values(container_idx)
1317 }
1318
1319 pub(crate) fn get_text_unicode_len(&mut self, container_idx: ContainerIdx) -> usize {
1320 self.store.text_unicode_len(container_idx).unwrap_or(0)
1321 }
1322
1323 pub(crate) fn get_text_utf16_len(&mut self, container_idx: ContainerIdx) -> usize {
1324 self.store.text_utf16_len(container_idx).unwrap_or(0)
1325 }
1326
1327 pub(crate) fn get_text_utf8_len(&mut self, container_idx: ContainerIdx) -> usize {
1328 self.store.text_utf8_len(container_idx).unwrap_or(0)
1329 }
1330
1331 pub(crate) fn has_decoded_container_state(&mut self, container_idx: ContainerIdx) -> bool {
1332 self.store.has_decoded_state(container_idx)
1333 }
1334
1335 /// Length of a text container in the given `pos_type`, taking a single
1336 /// `DocState` lock and a single container-store lookup.
1337 ///
1338 /// The per-`pos_type` store helpers already branch on decoded-vs-lazy
1339 /// internally, and their lazy branch reads the cheap length metadata
1340 /// without materializing the full richtext state — preserving the
1341 /// lazy-snapshot memory behavior. Callers previously took two separate
1342 /// locks (one to check decoded-ness, one to query), which showed up as a
1343 /// per-op regression on the text editing hot path. Only `Entity` length has
1344 /// no store helper and falls back to the state path.
1345 pub(crate) fn get_text_len(&mut self, container_idx: ContainerIdx, pos_type: PosType) -> usize {
1346 match pos_type {
1347 PosType::Unicode => self.get_text_unicode_len(container_idx),
1348 PosType::Utf16 => self.get_text_utf16_len(container_idx),
1349 PosType::Event if cfg!(feature = "wasm") => self.get_text_utf16_len(container_idx),
1350 PosType::Event => self.get_text_unicode_len(container_idx),
1351 PosType::Bytes => self.get_text_utf8_len(container_idx),
1352 PosType::Entity => self.with_state_mut(container_idx, |state| {
1353 state.as_richtext_state_mut().unwrap().len(PosType::Entity)
1354 }),
1355 }
1356 }
1357
1358 /// Set the state of the container with the given container idx.
1359 /// This is only used for decode.
1360 ///
1361 /// # Panic
1362 ///
1363 /// If the state is not empty.
1364 pub(super) fn init_with_states_and_version(
1365 &mut self,
1366 frontiers: Frontiers,
1367 oplog: &OpLog,
1368 unknown_containers: Vec<ContainerIdx>,
1369 need_to_register_parent: bool,
1370 origin: InternalString,
1371 ) -> LoroResult<()> {
1372 self.pre_txn(Default::default(), EventTriggerKind::Import);
1373 if need_to_register_parent {
1374 for state in self.store.iter_and_decode_all() {
1375 let idx = state.container_idx();
1376 let s = state;
1377 for child_id in s.get_child_containers() {
1378 let child_idx = self.arena.register_container(&child_id);
1379 self.arena.set_parent(child_idx, Some(idx));
1380 }
1381 }
1382 }
1383
1384 if !unknown_containers.is_empty() {
1385 let mut diff_calc = DiffCalculator::new(false);
1386 let stack_vv;
1387 let vv = if oplog.frontiers() == &frontiers {
1388 oplog.vv()
1389 } else {
1390 stack_vv = oplog.dag().frontiers_to_vv(&frontiers);
1391 stack_vv.as_ref().unwrap()
1392 };
1393
1394 let (unknown_diffs, _diff_mode) = diff_calc.calc_diff_internal(
1395 oplog,
1396 &Default::default(),
1397 &Default::default(),
1398 vv,
1399 &frontiers,
1400 Some(&|idx| !idx.is_unknown() && unknown_containers.contains(&idx)),
1401 );
1402 self.apply_diff(
1403 InternalDocDiff {
1404 origin: origin.clone(),
1405 by: EventTriggerKind::Import,
1406 diff: unknown_diffs.into(),
1407 new_version: Cow::Owned(frontiers.clone()),
1408 },
1409 DiffMode::Checkout,
1410 )?;
1411 }
1412
1413 if self.is_recording() {
1414 let diff: Vec<_> = self
1415 .store
1416 .iter_all_containers()
1417 .map(|(idx, state)| InternalContainerDiff {
1418 idx,
1419 bring_back: false,
1420 diff: state
1421 .get_state_mut(
1422 idx,
1423 ContainerCreationContext {
1424 configure: &self.config,
1425 peer: self.peer.load(Ordering::Relaxed),
1426 },
1427 )
1428 .to_diff(&self.doc)
1429 .into(),
1430 diff_mode: DiffMode::Checkout,
1431 kept: None,
1432 })
1433 .collect();
1434
1435 self.record_diff(InternalDocDiff {
1436 origin,
1437 by: EventTriggerKind::Import,
1438 diff: diff.into(),
1439 new_version: Cow::Borrowed(&frontiers),
1440 });
1441 }
1442
1443 self.frontiers = frontiers;
1444 Ok(())
1445 }
1446
1447 #[inline(always)]
1448 #[allow(unused)]
1449 pub(crate) fn with_state<F, R>(&mut self, idx: ContainerIdx, f: F) -> R
1450 where
1451 F: FnOnce(&State) -> R,
1452 {
1453 let depth = self.arena.get_depth(idx).unwrap().get() as usize;
1454 let state = self.store.get_or_create_imm(idx);
1455 f(state)
1456 }
1457
1458 #[inline(always)]
1459 pub(crate) fn with_state_mut<F, R>(&mut self, idx: ContainerIdx, f: F) -> R
1460 where
1461 F: FnOnce(&mut State) -> R,
1462 {
1463 let state = self.store.get_or_create_mut(idx);
1464 f(state)
1465 }
1466
1467 pub(crate) fn set_record_changes_only(&mut self, on: bool) {
1468 self.record_changes_only = on;
1469 }
1470
1471 /// The container's current state as a full-state diff, the shape revival events use.
1472 pub(crate) fn container_full_diff(&mut self, idx: ContainerIdx) -> Diff {
1473 let doc = self.doc.clone();
1474 self.store.get_or_create_mut(idx).to_diff(&doc)
1475 }
1476
1477 pub(crate) fn is_container_state_empty(&mut self, idx: ContainerIdx) -> bool {
1478 self.store.get_or_create_mut(idx).is_state_empty()
1479 }
1480
1481 /// Revives a container that has no diff of its own in this batch: its event is its full
1482 /// state. Children it holds are queued into `to_revive`; if it kept its state, they did too.
1483 fn revive_without_diff(
1484 &mut self,
1485 idx: ContainerIdx,
1486 to_revive: &mut FxHashSet<ContainerIdx>,
1487 kept: &mut FxHashSet<ContainerIdx>,
1488 ) -> Option<InternalContainerDiff> {
1489 let state = self.store.get_or_create_mut(idx);
1490 if state.is_state_empty() {
1491 return None;
1492 }
1493
1494 let is_kept = kept.contains(&idx);
1495 let external_diff = state.to_diff(&self.doc);
1496 trigger_on_new_container(
1497 &external_diff,
1498 |cid| {
1499 to_revive.insert(cid);
1500 if is_kept {
1501 kept.insert(cid);
1502 }
1503 },
1504 &self.arena,
1505 );
1506
1507 Some(InternalContainerDiff {
1508 idx,
1509 bring_back: true,
1510 diff: external_diff.into(),
1511 diff_mode: DiffMode::Checkout,
1512 kept: is_kept.then_some(KeptChange::Unchanged),
1513 })
1514 }
1515
1516 pub(super) fn is_in_txn(&self) -> bool {
1517 self.in_txn
1518 }
1519
1520 pub fn can_import_snapshot(&self) -> bool {
1521 !self.in_txn && self.arena.can_import_snapshot() && self.store.can_import_snapshot()
1522 }
1523
1524 pub(crate) fn reset_to_empty_for_failed_snapshot_import(&mut self) {
1525 let was_recording = self.is_recording();
1526 self.frontiers = Frontiers::default();
1527 self.store =
1528 ContainerStore::new(self.arena.clone(), self.config.clone(), self.peer.clone());
1529 self.in_txn = false;
1530 self.changed_idx_in_txn.clear();
1531 self.event_recorder = Default::default();
1532 if was_recording {
1533 self.start_recording();
1534 }
1535 self.dead_containers_cache = Default::default();
1536 self.alive_containers_cache = None;
1537 }
1538
1539 pub fn get_value(&mut self) -> LoroValue {
1540 let roots = self.preferred_root_containers();
1541 let ans: loro_common::LoroMapValue = roots
1542 .into_iter()
1543 .map(|idx| {
1544 let id = self.arena.idx_to_id(idx).unwrap();
1545 let ContainerID::Root {
1546 name,
1547 container_type: _,
1548 } = &id
1549 else {
1550 unreachable!()
1551 };
1552 (name.to_string(), LoroValue::Container(id))
1553 })
1554 .collect();
1555 LoroValue::Map(ans)
1556 }
1557
1558 pub fn get_deep_value(&mut self) -> LoroValue {
1559 let roots = self.preferred_root_containers();
1560 let mut ans = FxHashMap::with_capacity_and_hasher(roots.len(), Default::default());
1561 let binding = self.config.deleted_root_containers.clone();
1562 let deleted_root_container = binding.lock();
1563 let should_hide_empty_root_container = self
1564 .config
1565 .hide_empty_root_containers
1566 .load(Ordering::Relaxed);
1567 for root_idx in roots {
1568 let id = self.arena.idx_to_id(root_idx).unwrap();
1569 match &id {
1570 loro_common::ContainerID::Root { name, .. } => {
1571 let v = self.get_container_deep_value(root_idx);
1572 if should_hide_empty_root_container
1573 && visible_container_value_is_empty(root_idx.get_type(), &v)
1574 {
1575 continue;
1576 }
1577
1578 if deleted_root_container.contains(&id)
1579 && deleted_root_container_value_is_cleared(root_idx.get_type(), &v)
1580 {
1581 continue;
1582 }
1583
1584 ans.insert(name.to_string(), v);
1585 }
1586 loro_common::ContainerID::Normal { .. } => {
1587 unreachable!()
1588 }
1589 }
1590 }
1591
1592 LoroValue::Map(ans.into())
1593 }
1594
1595 pub fn get_deep_value_with_id(&mut self) -> LoroValue {
1596 let roots = self.preferred_root_containers();
1597 let mut ans = FxHashMap::with_capacity_and_hasher(roots.len(), Default::default());
1598 for root_idx in roots {
1599 let id = self.arena.idx_to_id(root_idx).unwrap();
1600 match id.clone() {
1601 loro_common::ContainerID::Root { name, .. } => {
1602 ans.insert(
1603 name.to_string(),
1604 self.get_container_deep_value_with_id(root_idx, Some(id)),
1605 );
1606 }
1607 loro_common::ContainerID::Normal { .. } => {
1608 unreachable!()
1609 }
1610 }
1611 }
1612
1613 LoroValue::Map(ans.into())
1614 }
1615
1616 pub(crate) fn preferred_root_containers(&mut self) -> Vec<ContainerIdx> {
1617 let flag = self.store.load_root_containers();
1618 // Mergeable cids live in a private namespace and are logically children of a regular
1619 // Map — they must not appear here. `top_level_root_containers` already excludes them,
1620 // so this loop is O(top_level_roots) regardless of the number of mergeable cids.
1621 let roots = self.arena.top_level_root_containers(flag);
1622 let mut selected = FxHashMap::default();
1623 let mut names = Vec::new();
1624
1625 for idx in roots {
1626 let Some(id) = self.arena.idx_to_id(idx) else {
1627 continue;
1628 };
1629 if !self.store.contains_id(&id) {
1630 continue;
1631 }
1632 let Some(name) = self.root_container_name(idx) else {
1633 continue;
1634 };
1635 let is_empty = self.root_container_is_empty(idx);
1636 match selected.entry(name.clone()) {
1637 std::collections::hash_map::Entry::Vacant(entry) => {
1638 names.push(name);
1639 entry.insert((idx, is_empty));
1640 }
1641 std::collections::hash_map::Entry::Occupied(mut entry) => {
1642 let (_, selected_is_empty) = entry.get();
1643 // Keep the previous last-root-wins behavior, except an empty
1644 // root should not hide a non-empty root with the same name.
1645 if *selected_is_empty || !is_empty {
1646 entry.insert((idx, is_empty));
1647 }
1648 }
1649 }
1650 }
1651
1652 names
1653 .into_iter()
1654 .filter_map(|name| selected.remove(&name).map(|(idx, _)| idx))
1655 .collect()
1656 }
1657
1658 pub(crate) fn preferred_root_container_idx_by_key(
1659 &mut self,
1660 root_index: &InternalString,
1661 ) -> Option<ContainerIdx> {
1662 let flag = self.store.load_root_containers();
1663 // Same reasoning as `preferred_root_containers`: only top-level roots are eligible.
1664 let roots = self.arena.top_level_root_containers(flag);
1665 let mut selected = None;
1666
1667 for idx in roots {
1668 let Some(id) = self.arena.idx_to_id(idx) else {
1669 continue;
1670 };
1671 if !self.store.contains_id(&id) {
1672 continue;
1673 }
1674 let Some(name) = self.root_container_name(idx) else {
1675 continue;
1676 };
1677 if &name != root_index {
1678 continue;
1679 }
1680
1681 let is_empty = self.root_container_is_empty(idx);
1682 match selected {
1683 None => selected = Some((idx, is_empty)),
1684 Some((_, selected_is_empty)) => {
1685 if selected_is_empty || !is_empty {
1686 selected = Some((idx, is_empty));
1687 }
1688 }
1689 }
1690 }
1691
1692 selected.map(|(idx, _)| idx)
1693 }
1694
1695 fn root_container_name(&self, idx: ContainerIdx) -> Option<InternalString> {
1696 match self.arena.idx_to_id(idx)? {
1697 ContainerID::Root { name, .. } => Some(name),
1698 ContainerID::Normal { .. } => None,
1699 }
1700 }
1701
1702 fn root_container_is_empty(&mut self, idx: ContainerIdx) -> bool {
1703 let value = self
1704 .store
1705 .get_value_ephemeral(idx)
1706 .unwrap_or_else(|| idx.get_type().default_value());
1707 visible_container_value_is_empty(idx.get_type(), &value)
1708 }
1709
1710 pub fn get_all_container_value_flat(&mut self) -> LoroValue {
1711 let mut map = FxHashMap::default();
1712 self.store.iter_and_decode_all().for_each(|c| {
1713 let value = c.get_value();
1714 let cid = self.arena.idx_to_id(c.container_idx()).unwrap().to_string();
1715 map.insert(cid, value);
1716 });
1717
1718 LoroValue::Map(map.into())
1719 }
1720
1721 pub(crate) fn get_container_deep_value_with_id(
1722 &mut self,
1723 container: ContainerIdx,
1724 id: Option<ContainerID>,
1725 ) -> LoroValue {
1726 let id = id.unwrap_or_else(|| self.arena.idx_to_id(container).unwrap());
1727 let Some(value) = self.store.get_value_ephemeral(container) else {
1728 return container.get_type().default_value();
1729 };
1730 // The `cid` is the container id's Display string, the same form that the
1731 // JS `container.id` getter returns (e.g. `cid:root-map:Map`,
1732 // `cid:92@2311024965712536503:Map`).
1733 let cid_str = LoroValue::String(id.to_string().into());
1734 match value {
1735 LoroValue::Container(_) => unreachable!(),
1736 LoroValue::List(mut list) => {
1737 if container.get_type() == ContainerType::Tree {
1738 get_meta_value(list.make_mut(), self);
1739 } else {
1740 if list.iter().all(|x| !x.is_container()) {
1741 return LoroValue::Map(
1742 (fx_map!(
1743 "cid".into() => cid_str,
1744 "value".into() => LoroValue::List(list)
1745 ))
1746 .into(),
1747 );
1748 }
1749
1750 let list_mut = list.make_mut();
1751 for item in list_mut.iter_mut() {
1752 if item.is_container() {
1753 let container = item.as_container().unwrap();
1754 let container_idx = self.arena.register_container(container);
1755 let value = self.get_container_deep_value_with_id(
1756 container_idx,
1757 Some(container.clone()),
1758 );
1759 *item = value;
1760 }
1761 }
1762 }
1763 LoroValue::Map(
1764 (fx_map!(
1765 "cid".into() => cid_str,
1766 "value".into() => LoroValue::List(list)
1767 ))
1768 .into(),
1769 )
1770 }
1771 LoroValue::Map(mut map) => {
1772 // A map's mergeable children are encoded as compact binary markers in the map's
1773 // own value table (loro-dev/loro#759), so they are already present in `map` here.
1774 // Derive the active children straight from that value — re-fetching the
1775 // `MapState` would force the snapshot-backed container to decode and break the
1776 // lazy-value invariant for roots.
1777 let mergeable_children = self.mergeable_children_from_value(&id, &map);
1778
1779 let map_mut = map.make_mut();
1780 for (_key, value) in map_mut.iter_mut() {
1781 if value.is_container() {
1782 let container = value.as_container().unwrap();
1783 let container_idx = self.arena.register_container(container);
1784 let new_value = self.get_container_deep_value_with_id(
1785 container_idx,
1786 Some(container.clone()),
1787 );
1788 *value = new_value;
1789 }
1790 }
1791 // Replace each marker with the nested deep value of its resolved child, keyed
1792 // under the same logical key.
1793 for (key, cid) in mergeable_children {
1794 let child_idx = self.arena.register_container(&cid);
1795 let new_value = self.get_container_deep_value_with_id(child_idx, Some(cid));
1796 map_mut.insert(key.to_string(), new_value);
1797 }
1798
1799 LoroValue::Map(
1800 (fx_map!(
1801 "cid".into() => cid_str,
1802 "value".into() => LoroValue::Map(map)
1803 ))
1804 .into(),
1805 )
1806 }
1807 _ => LoroValue::Map(
1808 (fx_map!(
1809 "cid".into() => cid_str,
1810 "value".into() => value
1811 ))
1812 .into(),
1813 ),
1814 }
1815 }
1816
1817 pub fn get_container_deep_value(&mut self, container: ContainerIdx) -> LoroValue {
1818 let Some(value) = self.store.get_value_ephemeral(container) else {
1819 return container.get_type().default_value();
1820 };
1821 match value {
1822 LoroValue::Container(_) => unreachable!(),
1823 LoroValue::List(mut list) => {
1824 if container.get_type() == ContainerType::Tree {
1825 // Each tree node has an associated map container to represent
1826 // the metadata of this node. When the user get the deep value,
1827 // we need to add a field named `meta` to the tree node,
1828 // whose value is deep value of map container.
1829 get_meta_value(list.make_mut(), self);
1830 } else {
1831 if list.iter().all(|x| !x.is_container()) {
1832 return LoroValue::List(list);
1833 }
1834
1835 let list_mut = list.make_mut();
1836 for item in list_mut.iter_mut() {
1837 if item.is_container() {
1838 let container = item.as_container().unwrap();
1839 let container_idx = self.arena.register_container(container);
1840 let value = self.get_container_deep_value(container_idx);
1841 *item = value;
1842 }
1843 }
1844 }
1845 LoroValue::List(list)
1846 }
1847 LoroValue::Map(mut map) => {
1848 // A map's mergeable children are encoded as compact binary markers in the map's
1849 // own value table (loro-dev/loro#759), so they are already present in `map` here.
1850 // Derive the active children straight from that value — re-fetching the
1851 // `MapState` would force the snapshot-backed container to decode and break the
1852 // lazy-value invariant for roots.
1853 let mergeable_children = self
1854 .arena
1855 .idx_to_id(container)
1856 .map(|parent_id| self.mergeable_children_from_value(&parent_id, &map))
1857 .unwrap_or_default();
1858
1859 if mergeable_children.is_empty() && map.iter().all(|x| !x.1.is_container()) {
1860 return LoroValue::Map(map);
1861 }
1862
1863 let map_mut = map.make_mut();
1864 for (_key, value) in map_mut.iter_mut() {
1865 if value.is_container() {
1866 let container = value.as_container().unwrap();
1867 let container_idx = self.arena.register_container(container);
1868 let new_value = self.get_container_deep_value(container_idx);
1869 *value = new_value;
1870 }
1871 }
1872 // Replace each marker with the nested deep value of its resolved child, keyed
1873 // under the same logical key.
1874 for (key, cid) in mergeable_children {
1875 let child_idx = self.arena.register_container(&cid);
1876 let new_value = self.get_container_deep_value(child_idx);
1877 map_mut.insert(key.to_string(), new_value);
1878 }
1879 LoroValue::Map(map)
1880 }
1881 _ => value,
1882 }
1883 }
1884
1885 /// Get the deep value of a list/movable-list container's elements in the range
1886 /// `[start, end)`.
1887 ///
1888 /// `start`/`end` are clamped to the list length; an empty or inverted range
1889 /// returns an empty list. Container items inside the range are replaced by
1890 /// their deep value: when `with_id` is true they become `{ cid, value }` nodes
1891 /// (via [`Self::get_container_deep_value_with_id`]), otherwise their plain deep
1892 /// value (via [`Self::get_container_deep_value`]).
1893 pub(crate) fn get_list_range_deep_value(
1894 &mut self,
1895 container: ContainerIdx,
1896 start: usize,
1897 end: usize,
1898 with_id: bool,
1899 ) -> LoroValue {
1900 let Some(value) = self.store.get_value_ephemeral(container) else {
1901 return container.get_type().default_value();
1902 };
1903 let LoroValue::List(list) = value else {
1904 return container.get_type().default_value();
1905 };
1906
1907 let len = list.len();
1908 let start = start.min(len);
1909 let end = end.min(len);
1910 if start >= end {
1911 return LoroValue::List(Default::default());
1912 }
1913
1914 let mut ans = Vec::with_capacity(end - start);
1915 for item in list.iter().skip(start).take(end - start) {
1916 if item.is_container() {
1917 let cid = item.as_container().unwrap();
1918 let container_idx = self.arena.register_container(cid);
1919 let value = if with_id {
1920 self.get_container_deep_value_with_id(container_idx, Some(cid.clone()))
1921 } else {
1922 self.get_container_deep_value(container_idx)
1923 };
1924 ans.push(value);
1925 } else {
1926 ans.push(item.clone());
1927 }
1928 }
1929
1930 LoroValue::List(ans.into())
1931 }
1932
1933 pub(crate) fn get_all_alive_containers(&mut self) -> LoroResult<FxHashSet<ContainerID>> {
1934 Ok(self
1935 .get_all_alive_container_indices()?
1936 .into_iter()
1937 .map(|idx| self.arena.get_container_id(idx).unwrap())
1938 .collect())
1939 }
1940
1941 fn get_all_alive_container_indices(&mut self) -> LoroResult<FxHashSet<ContainerIdx>> {
1942 let roots = self.existing_retention_roots();
1943 self.get_all_alive_container_indices_from_roots(&roots, AliveWalk::Visible)
1944 }
1945
1946 /// Root containers that currently have a store entry. Uses a root-only
1947 /// key scan (`load_roots`), so lazily imported docs stay lazy.
1948 pub(crate) fn existing_retention_roots(&mut self) -> Vec<ContainerIdx> {
1949 let flag = self.store.load_root_containers();
1950 self.arena
1951 .root_containers(flag)
1952 .into_iter()
1953 .filter(|idx| {
1954 let id = self.arena.get_container_id(*idx).unwrap();
1955 self.store.contains_id(&id)
1956 })
1957 .collect()
1958 }
1959
1960 fn get_all_alive_container_indices_from_roots(
1961 &mut self,
1962 roots: &[ContainerIdx],
1963 walk: AliveWalk,
1964 ) -> LoroResult<FxHashSet<ContainerIdx>> {
1965 let mut ans = FxHashSet::default();
1966 let mut to_visit = Vec::new();
1967 for &idx in roots {
1968 let id = self.arena.get_container_id(idx).unwrap();
1969 let expected_parent = id
1970 .parse_mergeable()
1971 .map(|(parent_id, _, _)| self.arena.register_container(&parent_id));
1972 to_visit.push((idx, expected_parent));
1973 }
1974
1975 while let Some((idx, expected_parent)) = to_visit.pop() {
1976 if !ans.insert(idx) {
1977 // The same child may be referenced by multiple parents. Even though its value was
1978 // already traversed, every additional edge still has to agree with the encoded and
1979 // registered parent.
1980 self.validate_alive_parent(idx, expected_parent)?;
1981 continue;
1982 }
1983 self.get_alive_children_of(idx, expected_parent, walk, &mut to_visit)?;
1984 }
1985
1986 Ok(ans)
1987 }
1988
1989 /// Keys of stored normal containers, created at or before `root_vv`, that the retention
1990 /// walk ([`AliveWalk::Retention`] from every stored root) may not reach. A fast filter: an
1991 /// empty result means filtering by the walk would remove nothing; otherwise the full walk
1992 /// must decide, and only keys in both sets may be removed.
1993 ///
1994 /// Every stored container's parent is read from its encoded header, and only containers
1995 /// that are the header parent of another stored container are decoded to list their
1996 /// children; leaf containers (a big text, childless maps, tree metas) are never decoded.
1997 /// A container counts as reached only through its header parent, so a header that lies
1998 /// about the parent makes the container a candidate, and the full walk then rejects the
1999 /// inconsistency instead of dropping the container. A child referenced by a container
2000 /// other than its header parent is rejected here directly.
2001 ///
2002 /// Two kinds of entries are never candidates:
2003 /// - Containers created after `root_vv`. A root state written with an overlay keeps an
2004 /// empty entry for them, which nothing at the root references yet.
2005 /// - Stored children of a reached container of an unknown (newer) type. Its value decodes
2006 /// to `Null`, so neither this filter nor the full walk can list its children; they are
2007 /// kept. An unknown type claimed only by a header parent that is not stored, or an
2008 /// unreferenced unknown entry, gets no such protection.
2009 pub(crate) fn unreached_stored_containers(
2010 &mut self,
2011 root_vv: &VersionVector,
2012 ) -> LoroResult<Vec<bytes::Bytes>> {
2013 let entries = self.store.get_kv_clone().scan_all_entries();
2014 // Stored normal containers: id -> (key, header parent).
2015 let mut stored: FxHashMap<ContainerID, (bytes::Bytes, Option<ContainerID>)> =
2016 FxHashMap::default();
2017 let mut stored_roots = Vec::new();
2018 let mut has_stored_children: FxHashSet<ContainerID> = FxHashSet::default();
2019 // Header children of unknown-type parents, whose references cannot be decoded.
2020 let mut unknown_children: FxHashMap<ContainerID, Vec<ContainerID>> = FxHashMap::default();
2021 for (key, value) in entries {
2022 let id = ContainerID::try_from_bytes(&key)?;
2023 let (peer, counter) = match &id {
2024 ContainerID::Root { .. } => {
2025 stored_roots.push(id);
2026 continue;
2027 }
2028 ContainerID::Normal { peer, counter, .. } => (*peer, *counter),
2029 };
2030 if !root_vv.includes_id(ID::new(peer, counter)) {
2031 continue;
2032 }
2033 let parent = ContainerWrapper::try_decode_parent(&value)?;
2034 if let Some(parent) = &parent {
2035 if parent.is_unknown() {
2036 unknown_children
2037 .entry(parent.clone())
2038 .or_default()
2039 .push(id.clone());
2040 }
2041 has_stored_children.insert(parent.clone());
2042 }
2043 stored.insert(id, (key, parent));
2044 }
2045
2046 // Roots are always retained; only those parenting a stored container need a visit.
2047 let mut to_visit: Vec<ContainerID> = stored_roots
2048 .into_iter()
2049 .filter(|id| has_stored_children.contains(id))
2050 .collect();
2051 let mut retained: FxHashSet<ContainerID> = FxHashSet::default();
2052 while let Some(parent_id) = to_visit.pop() {
2053 let children = if parent_id.is_unknown() {
2054 unknown_children.remove(&parent_id).unwrap_or_default()
2055 } else {
2056 self.retained_child_refs(&parent_id)?
2057 };
2058 for child_id in children {
2059 let Some((_, header_parent)) = stored.get(&child_id) else {
2060 // A root (always retained), a container created after the root, or an
2061 // unstored, hence empty, child.
2062 continue;
2063 };
2064 if header_parent.as_ref() != Some(&parent_id) {
2065 return Err(LoroError::DecodeError(
2066 format!(
2067 "container {child_id:?} is referenced by {parent_id:?}, but its snapshot state encodes parent {header_parent:?}"
2068 )
2069 .into_boxed_str(),
2070 ));
2071 }
2072 if has_stored_children.contains(&child_id) && !retained.contains(&child_id) {
2073 to_visit.push(child_id.clone());
2074 }
2075 retained.insert(child_id);
2076 }
2077 }
2078
2079 Ok(stored
2080 .into_iter()
2081 .filter(|(id, _)| !retained.contains(id))
2082 .map(|(_, (key, _))| key)
2083 .collect())
2084 }
2085
2086 /// Normal-container children the retention walk follows from `id`: every node meta of a
2087 /// tree (deleted nodes included, see [`AliveWalk::Retention`]) and the container values of
2088 /// a map or list. Mergeable children are root containers, which are always retained, so
2089 /// their markers are not resolved. Unlike `get_alive_children_of`, children are not
2090 /// registered in the arena.
2091 fn retained_child_refs(&mut self, id: &ContainerID) -> LoroResult<Vec<ContainerID>> {
2092 let idx = self.arena.register_container(id);
2093 if idx.get_type() == ContainerType::Tree {
2094 return Ok(self
2095 .store
2096 .try_get_parent_and_tree_meta_ids_ephemeral(idx)?
2097 .map(|(_, ids)| ids)
2098 .unwrap_or_default());
2099 }
2100
2101 let Some((_, value)) = self.store.try_get_parent_and_value_ephemeral(idx)? else {
2102 return Ok(Vec::new());
2103 };
2104 let containers = |values: &mut dyn Iterator<Item = &LoroValue>| {
2105 values
2106 .filter_map(|v| v.as_container().cloned())
2107 .collect::<Vec<_>>()
2108 };
2109 Ok(match &value {
2110 LoroValue::Map(map) => containers(&mut map.values()),
2111 LoroValue::List(list) => containers(&mut list.iter()),
2112 _ => Vec::new(),
2113 })
2114 }
2115
2116 fn validate_alive_parent(
2117 &mut self,
2118 child_idx: ContainerIdx,
2119 expected_parent: Option<ContainerIdx>,
2120 ) -> LoroResult<()> {
2121 let encoded_parent = self.store.get_parent_ephemeral(child_idx)?;
2122 self.validate_alive_parent_with_encoded(child_idx, expected_parent, encoded_parent)
2123 }
2124
2125 fn validate_alive_parent_with_encoded(
2126 &mut self,
2127 child_idx: ContainerIdx,
2128 expected_parent: Option<ContainerIdx>,
2129 encoded_parent: Option<Option<ContainerID>>,
2130 ) -> LoroResult<()> {
2131 let child_id = self.arena.get_container_id(child_idx).unwrap();
2132 let expected_parent_id = expected_parent.and_then(|idx| self.arena.get_container_id(idx));
2133 if let Some(encoded_parent) = encoded_parent {
2134 if encoded_parent != expected_parent_id {
2135 return Err(LoroError::DecodeError(
2136 format!(
2137 "container {child_id:?} expects parent {expected_parent_id:?}, but its snapshot state encodes parent {encoded_parent:?}"
2138 )
2139 .into_boxed_str(),
2140 ));
2141 }
2142 }
2143
2144 match self.arena.get_registered_parent(child_idx) {
2145 Some(registered_parent) if registered_parent == expected_parent => {}
2146 Some(registered_parent) => {
2147 let registered_parent =
2148 registered_parent.and_then(|idx| self.arena.get_container_id(idx));
2149 return Err(LoroError::DecodeError(
2150 format!(
2151 "container {child_id:?} expects parent {expected_parent_id:?}, but its registered parent is {registered_parent:?}"
2152 )
2153 .into_boxed_str(),
2154 ));
2155 }
2156 None => self.arena.set_parent(child_idx, expected_parent),
2157 }
2158
2159 Ok(())
2160 }
2161
2162 fn register_alive_child(
2163 &mut self,
2164 parent_idx: ContainerIdx,
2165 child_id: &ContainerID,
2166 ans: &mut Vec<(ContainerIdx, Option<ContainerIdx>)>,
2167 ) {
2168 let child_idx = self.arena.register_container(child_id);
2169 ans.push((child_idx, Some(parent_idx)));
2170 }
2171
2172 fn get_alive_children_of(
2173 &mut self,
2174 idx: ContainerIdx,
2175 expected_parent: Option<ContainerIdx>,
2176 walk: AliveWalk,
2177 ans: &mut Vec<(ContainerIdx, Option<ContainerIdx>)>,
2178 ) -> LoroResult<()> {
2179 if walk == AliveWalk::Retention && idx.get_type() == ContainerType::Tree {
2180 let Some((encoded_parent, meta_ids)) =
2181 self.store.try_get_parent_and_tree_meta_ids_ephemeral(idx)?
2182 else {
2183 self.validate_alive_parent_with_encoded(idx, expected_parent, None)?;
2184 return Ok(());
2185 };
2186 self.validate_alive_parent_with_encoded(idx, expected_parent, Some(encoded_parent))?;
2187 for id in meta_ids.iter() {
2188 self.register_alive_child(idx, id, ans);
2189 }
2190 return Ok(());
2191 }
2192
2193 let Some((encoded_parent, value)) = self.store.try_get_parent_and_value_ephemeral(idx)?
2194 else {
2195 self.validate_alive_parent_with_encoded(idx, expected_parent, None)?;
2196 return Ok(());
2197 };
2198 self.validate_alive_parent_with_encoded(idx, expected_parent, Some(encoded_parent))?;
2199
2200 match value {
2201 LoroValue::Container(_) => unreachable!(),
2202 LoroValue::List(list) => {
2203 if idx.get_type() == ContainerType::Tree {
2204 // Each tree node has an associated map container to represent
2205 // the metadata of this node. When the user get the deep value,
2206 // we need to add a field named `meta` to the tree node,
2207 // whose value is deep value of map container.
2208 let mut list = list.unwrap();
2209 while let Some(node) = list.pop() {
2210 let map = node.as_map().unwrap();
2211 let meta = map.get("meta").unwrap();
2212 let id = meta.as_container().unwrap();
2213 self.register_alive_child(idx, id, ans);
2214 let children = map.get("children").unwrap();
2215 let children = children.as_list().unwrap();
2216 for child in children.iter() {
2217 list.push(child.clone());
2218 }
2219 }
2220 } else {
2221 for item in list.iter() {
2222 if let LoroValue::Container(id) = item {
2223 self.register_alive_child(idx, id, ans);
2224 }
2225 }
2226 }
2227 }
2228 LoroValue::Map(map) => {
2229 for (_key, value) in map.iter() {
2230 if let LoroValue::Container(id) = value {
2231 self.register_alive_child(idx, id, ans);
2232 }
2233 }
2234 // Mergeable children are resolved from compact binary markers stored in this
2235 // map's own value table (loro-dev/loro#759): the active child at each key is the
2236 // deterministic cid for whichever marker the map's regular LWW resolved to.
2237 // Derive them from the value we already fetched lazily above — re-reading the
2238 // decoded `MapState` would force a snapshot-backed map to materialize its full
2239 // state. Pull them in so alive-container walks (notably shallow snapshot export)
2240 // include mergeable cids and don't filter their KV out by `retain_keys`.
2241 let mergeable_cids: Vec<ContainerID> = self
2242 .arena
2243 .idx_to_id(idx)
2244 .map(|parent_id| {
2245 self.mergeable_children_from_value(&parent_id, &map)
2246 .into_iter()
2247 .map(|(_key, cid)| cid)
2248 .collect()
2249 })
2250 .unwrap_or_default();
2251 for cid in mergeable_cids {
2252 self.register_alive_child(idx, &cid, ans);
2253 }
2254 }
2255 _ => {}
2256 }
2257
2258 Ok(())
2259 }
2260
2261 // Because we need to calculate path based on [DocState], so we cannot extract
2262 // the event recorder to a separate module.
2263 fn diffs_to_event(&mut self, diffs: Vec<InternalDocDiff<'_>>, from: Frontiers) -> DocDiff {
2264 if diffs.is_empty() {
2265 panic!("diffs is empty");
2266 }
2267
2268 let triggered_by = diffs[0].by;
2269 debug_assert!(diffs.iter().all(|x| x.by == triggered_by));
2270 let mut containers = FxHashMap::default();
2271 let to = (*diffs.last().unwrap().new_version).to_owned();
2272 let origin = diffs[0].origin.clone();
2273 for diff in diffs {
2274 #[allow(clippy::unnecessary_to_owned)]
2275 for container_diff in diff.diff.into_owned() {
2276 let Some((last_container_diff, last_kept, _)) =
2277 containers.get_mut(&container_diff.idx)
2278 else {
2279 if let Some(path) = self.get_path(container_diff.idx) {
2280 containers.insert(
2281 container_diff.idx,
2282 (container_diff.diff, container_diff.kept, path),
2283 );
2284 } else {
2285 // if we cannot find the path to the container, the container must be overwritten afterwards.
2286 // So we can ignore the diff from it.
2287 let _container_id = self
2288 .arena
2289 .idx_to_id(container_diff.idx)
2290 .map(|x| x.to_string())
2291 .unwrap_or_else(|| "unknown".to_string());
2292 #[cfg(feature = "logging")]
2293 loro_common::warn!(
2294 "⚠️ WARNING: ignore event because cannot find its path {:#?} container id:{}",
2295 &container_diff,
2296 _container_id
2297 );
2298 }
2299
2300 continue;
2301 };
2302 // Compose in place. Cloning the accumulated diff here made a
2303 // batch of N same-container fragments O(N^2) (each compose
2304 // cloned the growing accumulator), which is hit whenever a
2305 // subscriber is attached and many edits land on one container
2306 // in a single event batch.
2307 let prev = std::mem::take(last_container_diff);
2308 if last_kept.is_some() || container_diff.kept.is_some() {
2309 // Track the actual change next to the full-state revival.
2310 let as_change = |kept: Option<KeptChange>, diff: &crate::event::DiffVariant| {
2311 kept.unwrap_or_else(|| {
2312 KeptChange::from_diff(diff.clone().into_external().unwrap())
2313 })
2314 };
2315 let prev_change = as_change(last_kept.take(), &prev);
2316 let next_change = as_change(container_diff.kept.clone(), &container_diff.diff);
2317 *last_kept = Some(prev_change.then(next_change));
2318 }
2319 *last_container_diff = if container_diff.kept.is_some() {
2320 // A full-state revival supersedes what the container showed before.
2321 container_diff.diff
2322 } else {
2323 prev.compose(container_diff.diff).unwrap()
2324 };
2325 }
2326 }
2327 let mut diff: Vec<_> = containers
2328 .into_iter()
2329 .map(|(container, (diff, kept, path))| {
2330 let idx = container;
2331 let id = self.arena.get_container_id(idx).unwrap();
2332 let is_unknown = id.is_unknown();
2333
2334 ContainerDiff {
2335 id,
2336 idx,
2337 diff: diff.into_external().unwrap(),
2338 is_unknown,
2339 path,
2340 kept,
2341 }
2342 })
2343 .collect();
2344
2345 // Sort by path length, so caller can apply the diff from the root to the leaf.
2346 // Otherwise, the caller may use a wrong path to apply the diff.
2347
2348 diff.sort_by_key(|x| {
2349 (
2350 x.path.len(),
2351 match &x.id {
2352 ContainerID::Root { .. } => 0,
2353 ContainerID::Normal { counter, .. } => *counter + 1,
2354 },
2355 )
2356 });
2357 DocDiff {
2358 from,
2359 to,
2360 origin,
2361 by: triggered_by,
2362 diff,
2363 }
2364 }
2365
2366 pub(crate) fn get_reachable(&mut self, id: &ContainerID) -> bool {
2367 if id.is_root() && !id.is_mergeable() {
2368 return true;
2369 }
2370
2371 // If not registered yet, check KV presence for ordinary containers, then register lazily.
2372 // Mergeable children can be active through a parent marker before they have their
2373 // own KV state, so their reachability must be resolved by the logical edge walk below.
2374 if self.arena.id_to_idx(id).is_none() {
2375 if !id.is_mergeable() && !self.does_container_exist(id) {
2376 return false;
2377 }
2378 self.arena.register_container(id);
2379 }
2380
2381 let mut idx = self.arena.id_to_idx(id).unwrap();
2382 loop {
2383 let id = self.arena.idx_to_id(idx).unwrap();
2384 if let Some(parent_idx) = self.arena.get_parent(idx) {
2385 if !self.contains_logical_child(parent_idx, &id) {
2386 return false;
2387 }
2388 idx = parent_idx;
2389 } else {
2390 if id.is_root() && !id.is_mergeable() {
2391 return true;
2392 }
2393
2394 return false;
2395 }
2396 }
2397 }
2398
2399 // the container may be override, so it may return None
2400 pub(super) fn get_path(&mut self, idx: ContainerIdx) -> Option<Vec<(ContainerID, Index)>> {
2401 let mut ans = Vec::new();
2402 let mut idx = idx;
2403 loop {
2404 let id = self.arena.idx_to_id(idx).unwrap();
2405 if let Some(parent_idx) = self.arena.get_parent(idx) {
2406 let Some(prop) = self.get_logical_child_index(parent_idx, &id) else {
2407 tracing::warn!("Missing in parent's children");
2408 return None;
2409 };
2410 ans.push((id, prop));
2411 idx = parent_idx;
2412 } else {
2413 // this container may be deleted
2414 if id.is_mergeable() {
2415 tracing::info!(id = %id, "Missing parent - mergeable container is inactive");
2416 return None;
2417 }
2418 let Ok(prop) = id.clone().into_root() else {
2419 let id = format!("{}", &id);
2420 tracing::info!(?id, "Missing parent - container is deleted");
2421 return None;
2422 };
2423 ans.push((id, Index::Key(prop.0)));
2424 break;
2425 }
2426 }
2427
2428 ans.reverse();
2429
2430 Some(ans)
2431 }
2432
2433 pub(crate) fn check_before_decode_snapshot(&self) -> LoroResult<()> {
2434 if self.is_in_txn() {
2435 return Err(LoroError::DecodeError(
2436 "State is in txn".to_string().into_boxed_str(),
2437 ));
2438 }
2439
2440 if !self.can_import_snapshot() {
2441 return Err(LoroError::DecodeError(
2442 "State is not empty, cannot import snapshot directly"
2443 .to_string()
2444 .into_boxed_str(),
2445 ));
2446 }
2447
2448 Ok(())
2449 }
2450
2451 /// Check whether two [DocState]s are the same. Panic if not.
2452 ///
2453 /// Compared to check equality on `get_deep_value`, this function also checks the equality on richtext
2454 /// styles and states that are not reachable from the root.
2455 ///
2456 /// This is only used for test.
2457 pub(crate) fn check_is_the_same(&mut self, other: &mut Self) {
2458 fn get_entries_for_state(
2459 arena: &SharedArena,
2460 state: &mut State,
2461 ) -> Option<(ContainerID, (ContainerIdx, LoroValue))> {
2462 if state.is_state_empty() {
2463 return None;
2464 }
2465
2466 let id = arena.idx_to_id(state.container_idx()).unwrap();
2467 let value = match state {
2468 State::RichtextState(s) => s.get_richtext_value(),
2469 _ => state.get_value(),
2470 };
2471 if match &value {
2472 LoroValue::List(l) => l.is_empty(),
2473 LoroValue::Map(m) => m.is_empty(),
2474 _ => false,
2475 } {
2476 return None;
2477 }
2478 #[cfg(feature = "counter")]
2479 if id.container_type() == ContainerType::Counter {
2480 if let LoroValue::Double(c) = value {
2481 if c.abs() < f64::EPSILON {
2482 return None;
2483 }
2484 }
2485 }
2486
2487 Some((id, (state.container_idx(), value)))
2488 }
2489
2490 let self_id_to_states: FxHashMap<ContainerID, (ContainerIdx, LoroValue)> = self
2491 .store
2492 .iter_and_decode_all()
2493 .filter_map(|state: &mut State| {
2494 let arena = &self.arena;
2495 get_entries_for_state(arena, state)
2496 })
2497 .collect();
2498 let mut other_id_to_states: FxHashMap<ContainerID, (ContainerIdx, LoroValue)> = other
2499 .store
2500 .iter_and_decode_all()
2501 .filter_map(|state: &mut State| {
2502 let arena = &other.arena;
2503 get_entries_for_state(arena, state)
2504 })
2505 .collect();
2506 for (id, (idx, this_value)) in self_id_to_states {
2507 let (_, other_value) = match other_id_to_states.remove(&id) {
2508 Some(x) => x,
2509 None => {
2510 panic!(
2511 "id: {:?}, path: {:?} is missing, value={:?}",
2512 id,
2513 self.get_path(idx),
2514 &this_value
2515 );
2516 }
2517 };
2518
2519 pretty_assertions::assert_eq!(
2520 this_value,
2521 other_value,
2522 "[self!=other] id: {:?}, path: {:?}",
2523 id,
2524 self.get_path(idx)
2525 );
2526 }
2527
2528 if !other_id_to_states.is_empty() {
2529 panic!("other has more states {:#?}", &other_id_to_states);
2530 }
2531 }
2532
2533 pub fn create_state(&self, idx: ContainerIdx) -> State {
2534 let config = &self.config;
2535 let peer = self.peer.load(std::sync::atomic::Ordering::Relaxed);
2536 create_state_(idx, config, peer)
2537 }
2538
2539 pub fn create_unknown_state(&self, idx: ContainerIdx) -> State {
2540 State::UnknownState(UnknownState::new(idx))
2541 }
2542
2543 pub fn get_relative_position(&mut self, pos: &Cursor, use_event_index: bool) -> Option<usize> {
2544 let idx = self.arena.register_container(&pos.container);
2545 let state = self.store.get_container_mut(idx)?;
2546 if let Some(id) = pos.id {
2547 match state {
2548 State::ListState(s) => s.get_index_of_id(id),
2549 State::RichtextState(s) => s.get_text_index_of_id(id, use_event_index),
2550 State::MovableListState(s) => s.get_index_of_id(id),
2551 State::MapState(_) | State::TreeState(_) | State::UnknownState(_) => unreachable!(),
2552 #[cfg(feature = "counter")]
2553 State::CounterState(_) => unreachable!(),
2554 }
2555 } else {
2556 if matches!(pos.side, crate::cursor::Side::Left) {
2557 return Some(0);
2558 }
2559
2560 match state {
2561 State::ListState(s) => Some(s.len()),
2562 State::RichtextState(s) => Some(if use_event_index {
2563 s.len_event()
2564 } else {
2565 s.len_unicode()
2566 }),
2567 State::MovableListState(s) => Some(s.len()),
2568 State::MapState(_) | State::TreeState(_) | State::UnknownState(_) => unreachable!(),
2569 #[cfg(feature = "counter")]
2570 State::CounterState(_) => unreachable!(),
2571 }
2572 }
2573 }
2574
2575 pub fn get_value_by_path(&mut self, path: &[Index]) -> Option<LoroValue> {
2576 if path.is_empty() {
2577 return None;
2578 }
2579
2580 enum CurContainer {
2581 Container(ContainerIdx),
2582 TreeNode {
2583 tree: ContainerIdx,
2584 node: Option<TreeID>,
2585 },
2586 }
2587
2588 let mut state_idx = {
2589 let root_index = path[0].as_key()?;
2590 CurContainer::Container(self.preferred_root_container_idx_by_key(root_index)?)
2591 };
2592
2593 if path.len() == 1 {
2594 if let CurContainer::Container(c) = state_idx {
2595 let cid = self.arena.idx_to_id(c)?;
2596 return Some(LoroValue::Container(cid));
2597 }
2598 }
2599
2600 let mut i = 1;
2601 while i < path.len() - 1 {
2602 let index = &path[i];
2603 match state_idx {
2604 CurContainer::Container(idx) => {
2605 let parent_id = self.arena.idx_to_id(idx);
2606 let parent_state = self.store.get_container_mut(idx)?;
2607 match parent_state {
2608 State::ListState(l) => {
2609 let Some(LoroValue::Container(c)) = l.get(*index.as_seq()?) else {
2610 return None;
2611 };
2612 state_idx = CurContainer::Container(self.arena.register_container(c));
2613 }
2614 State::MovableListState(l) => {
2615 let Some(LoroValue::Container(c)) =
2616 l.get(*index.as_seq()?, IndexType::ForUser)
2617 else {
2618 return None;
2619 };
2620 state_idx = CurContainer::Container(self.arena.register_container(c));
2621 }
2622 State::MapState(m) => {
2623 let key = index.as_key()?;
2624 let value = m.get(key)?;
2625 let c = match value {
2626 LoroValue::Container(c) => c.clone(),
2627 value => {
2628 let parent_id = parent_id?;
2629 let kind = loro_common::parse_mergeable_marker(
2630 &parent_id, key, value,
2631 )?;
2632 ContainerID::new_mergeable(&parent_id, key, kind)
2633 }
2634 };
2635 state_idx = CurContainer::Container(self.arena.register_container(&c));
2636 }
2637 State::RichtextState(_) => return None,
2638 State::TreeState(_) => {
2639 state_idx = CurContainer::TreeNode {
2640 tree: idx,
2641 node: None,
2642 };
2643 continue;
2644 }
2645 #[cfg(feature = "counter")]
2646 State::CounterState(_) => return None,
2647 // Unknown containers are opaque to this version; the
2648 // path simply has no match below them.
2649 State::UnknownState(_) => return None,
2650 }
2651 }
2652 CurContainer::TreeNode { tree, node } => match index {
2653 Index::Key(internal_string) => {
2654 let node = node?;
2655 let idx = self
2656 .arena
2657 .register_container(&node.associated_meta_container());
2658 let map = self.store.get_container(idx)?;
2659 let Some(LoroValue::Container(c)) =
2660 map.as_map_state().unwrap().get(internal_string)
2661 else {
2662 return None;
2663 };
2664
2665 state_idx = CurContainer::Container(self.arena.register_container(c));
2666 }
2667 Index::Seq(i) => {
2668 let tree_state =
2669 self.store.get_container_mut(tree)?.as_tree_state().unwrap();
2670 let parent: TreeParentId = if let Some(node) = node {
2671 node.into()
2672 } else {
2673 TreeParentId::Root
2674 };
2675 let child = tree_state.get_children(&parent)?.nth(*i)?;
2676 state_idx = CurContainer::TreeNode {
2677 tree,
2678 node: Some(child),
2679 };
2680 }
2681 Index::Node(tree_id) => {
2682 let tree_state =
2683 self.store.get_container_mut(tree)?.as_tree_state().unwrap();
2684 if tree_state.parent(tree_id).is_some() {
2685 state_idx = CurContainer::TreeNode {
2686 tree,
2687 node: Some(*tree_id),
2688 }
2689 } else {
2690 return None;
2691 }
2692 }
2693 },
2694 }
2695 i += 1;
2696 }
2697
2698 let parent_idx = match state_idx {
2699 CurContainer::Container(container_idx) => container_idx,
2700 CurContainer::TreeNode { tree, node } => {
2701 if let Some(node) = node {
2702 self.arena
2703 .register_container(&node.associated_meta_container())
2704 } else {
2705 tree
2706 }
2707 }
2708 };
2709
2710 let index = path.last().unwrap();
2711 let parent_id = self.arena.idx_to_id(parent_idx);
2712 let parent_state = self.store.get_or_create_mut(parent_idx);
2713 let value: LoroValue = match parent_state {
2714 State::ListState(l) => l.get(*index.as_seq()?).cloned()?,
2715 State::MovableListState(l) => l.get(*index.as_seq()?, IndexType::ForUser).cloned()?,
2716 State::MapState(m) => {
2717 if let Some(key) = index.as_key() {
2718 let value = m.get(key).cloned()?;
2719 if let Some(parent_id) = &parent_id {
2720 if let Some(kind) =
2721 loro_common::parse_mergeable_marker(parent_id, key, &value)
2722 {
2723 let cid = ContainerID::new_mergeable(parent_id, key, kind);
2724 LoroValue::Container(cid)
2725 } else {
2726 value
2727 }
2728 } else {
2729 value
2730 }
2731 } else if let CurContainer::TreeNode { tree, node } = state_idx {
2732 match index {
2733 Index::Seq(index) => {
2734 let tree_state =
2735 self.store.get_container_mut(tree)?.as_tree_state().unwrap();
2736 let parent: TreeParentId = if let Some(node) = node {
2737 node.into()
2738 } else {
2739 TreeParentId::Root
2740 };
2741 let child = tree_state.get_children(&parent)?.nth(*index)?;
2742 child.associated_meta_container().into()
2743 }
2744 Index::Node(id) => id.associated_meta_container().into(),
2745 _ => return None,
2746 }
2747 } else {
2748 return None;
2749 }
2750 }
2751 State::RichtextState(s) => {
2752 let s = s.to_string_mut();
2753 s.chars()
2754 .nth(*index.as_seq()?)
2755 .map(|c| c.to_string().into())?
2756 }
2757 State::TreeState(_) => {
2758 let id = index.as_node()?;
2759 let cid = id.associated_meta_container();
2760 cid.into()
2761 }
2762 #[cfg(feature = "counter")]
2763 // Leaf containers have no addressable children; the path has no match.
2764 State::CounterState(_) => return None,
2765 State::UnknownState(_) => return None,
2766 };
2767
2768 Some(value)
2769 }
2770
2771 pub(crate) fn shallow_root_store(&self) -> Option<&Arc<GcStore>> {
2772 self.store.shallow_root_store()
2773 }
2774}
2775
2776fn create_state_(idx: ContainerIdx, config: &Configure, peer: u64) -> State {
2777 match idx.get_type() {
2778 ContainerType::Map => State::MapState(Box::new(MapState::new(idx))),
2779 ContainerType::List => State::ListState(Box::new(ListState::new(idx))),
2780 ContainerType::Text => State::RichtextState(Box::new(RichtextState::new(
2781 idx,
2782 config.text_style_config.clone(),
2783 ))),
2784 ContainerType::Tree => State::TreeState(Box::new(TreeState::new(idx, peer))),
2785 ContainerType::MovableList => State::MovableListState(Box::new(MovableListState::new(idx))),
2786 #[cfg(feature = "counter")]
2787 ContainerType::Counter => {
2788 State::CounterState(Box::new(counter_state::CounterState::new(idx)))
2789 }
2790 ContainerType::Unknown(_) => State::UnknownState(UnknownState::new(idx)),
2791 }
2792}
2793
2794fn is_mergeable(arena: &SharedArena, idx: ContainerIdx) -> bool {
2795 arena.idx_to_id(idx).is_some_and(|id| id.is_mergeable())
2796}
2797
2798fn trigger_on_new_container(
2799 state_diff: &Diff,
2800 mut listener: impl FnMut(ContainerIdx),
2801 arena: &SharedArena,
2802) {
2803 match state_diff {
2804 Diff::List(list) => {
2805 for delta in list.iter() {
2806 if let DeltaItem::Replace {
2807 value,
2808 attr,
2809 delete: _,
2810 } = delta
2811 {
2812 if attr.from_move {
2813 continue;
2814 }
2815
2816 for v in value.iter() {
2817 if let ValueOrHandler::Handler(h) = v {
2818 let idx = h.container_idx();
2819 listener(idx);
2820 }
2821 }
2822 }
2823 }
2824 }
2825 Diff::Map(map) => {
2826 for (_, v) in map.updated.iter() {
2827 if let Some(ValueOrHandler::Handler(h)) = &v.value {
2828 let idx = h.container_idx();
2829 listener(idx);
2830 }
2831 }
2832 }
2833 Diff::Tree(tree) => {
2834 for item in tree.iter() {
2835 if matches!(item.action, TreeExternalDiff::Create { .. }) {
2836 let id = item.target.associated_meta_container();
2837 // Ensure registration instead of assuming it's already in arena
2838 listener(arena.register_container(&id));
2839 }
2840 }
2841 }
2842 _ => {}
2843 };
2844}
2845
2846#[derive(Default, Clone)]
2847pub(crate) struct EventRecorder {
2848 recording_diff: bool,
2849 // A batch of diffs will be converted to a event when
2850 // they cannot be merged with the next diff.
2851 diffs: Vec<InternalDocDiff<'static>>,
2852 events: Vec<DocDiff>,
2853 diff_start_version: Option<Frontiers>,
2854}
2855
2856impl EventRecorder {
2857 #[allow(unused)]
2858 pub fn new() -> Self {
2859 Self::default()
2860 }
2861}
2862
2863#[test]
2864fn test_size() {
2865 println!("Size of State = {}", std::mem::size_of::<State>());
2866 println!("Size of MapState = {}", std::mem::size_of::<MapState>());
2867 println!("Size of ListState = {}", std::mem::size_of::<ListState>());
2868 println!(
2869 "Size of TextState = {}",
2870 std::mem::size_of::<RichtextState>()
2871 );
2872 println!("Size of TreeState = {}", std::mem::size_of::<TreeState>());
2873}