forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

arena.rs1037 lines, 40.9 KiBHistoryRawDownload
1mod str_arena;
2use self::str_arena::{StrArena, StrArenaCheckpoint};
3use crate::sync::{Mutex, MutexGuard, RwLock, RwLockWriteGuard};
4use crate::{
5 change::Lamport,
6 container::{
7 idx::ContainerIdx,
8 list::list_op::{InnerListOp, ListOp},
9 map::MapSet,
10 ContainerID,
11 },
12 id::Counter,
13 op::{InnerContent, ListSlice, Op, RawOp, RawOpContent, ValueSlice},
14};
15use append_only_bytes::BytesSlice;
16use loro_common::{PeerID, ID};
17use rustc_hash::FxHashMap;
18use std::fmt;
19use std::{
20 num::NonZeroU16,
21 ops::{Range, RangeBounds},
22 sync::Arc,
23};
24
25pub(crate) struct LoadAllFlag;
26type ParentResolver = dyn Fn(ContainerID) -> Option<ContainerID> + Send + Sync + 'static;
27/// Loads the change holding the op with the given ID, if the op log has it. Parsing a change
28/// registers the parent link of every container its ops create, and a normal container's ID is
29/// the ID of the op that created it. It answers [`CreatorOp::Corrupt`] if the op log has the
30/// change but cannot parse it. See `context/arena-parent-links.md`.
31type CreatorResolver = dyn Fn(&SharedArena, ID) -> CreatorOp + Send + Sync + 'static;
32
33/// What the op log's history knows about an op ID, answered by the [`CreatorResolver`].
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub(crate) enum CreatorOp {
36 /// The change holding the op is parsed, so the parent of every container the op creates
37 /// is registered.
38 Loaded,
39 /// The history has no op with this ID: it was not received or committed yet, or it is
40 /// before the shallow root.
41 Absent,
42 /// A change block holds the op but cannot be decoded or parsed, so nothing is known about
43 /// the containers it creates. The op log records the block and reports it from the next
44 /// fallible entry point (import, export, checkout); the lookup itself answers like
45 /// `Absent` instead of panicking under the state lock.
46 Corrupt,
47}
48
49#[derive(Default)]
50struct ArenaContainers {
51 container_idx_to_id: Vec<ContainerID>,
52 /// Cached container depth. `None` means unknown or waiting on an unknown parent depth.
53 /// Use `get_depth()` for authoritative reads; direct access is only a cache fast path.
54 depth: Vec<Option<NonZeroU16>>,
55 container_id_to_idx: FxHashMap<ContainerID, ContainerIdx>,
56 /// The parent of each container.
57 parents: FxHashMap<ContainerIdx, Option<ContainerIdx>>,
58 /// All retention roots: top-level user roots **and** mergeable cids. Used by
59 /// alive-container / shallow-snapshot retention walks that must see both.
60 root_c_idx: Vec<ContainerIdx>,
61 /// Subset of `root_c_idx` containing only top-level (non-mergeable) roots. This is the
62 /// list user-facing APIs enumerate (`preferred_root_containers`, `get_value`,
63 /// `get_deep_value`, jsonpath, ...). Keeping it pre-filtered means those paths do
64 /// not pay a per-mergeable `is_mergeable()` parse on every call.
65 top_level_root_c_idx: Vec<ContainerIdx>,
66 /// Optional resolver used when querying parent for a container that has not been registered yet.
67 /// If set, `get_parent` will try this resolver to lazily fetch and register the parent.
68 ///
69 /// Locking: the resolver may read the state KV store. Code that loads from KV must snapshot
70 /// KV data and release the KV lock before taking the arena lock.
71 parent_resolver: Option<Arc<ParentResolver>>,
72 /// Set by the op log. Used after `parent_resolver` when a container's parent is still
73 /// unknown, e.g. the meta of a tree node that was never alive in a document loaded from a
74 /// snapshot, whose change blocks are parsed lazily.
75 ///
76 /// Locking: it takes the change store's locks and parses changes, which registers
77 /// containers in this arena, so it must be called without holding the arena lock. It runs
78 /// without the op log lock; see `ChangeStore::creator_resolver`.
79 creator_resolver: Option<Arc<CreatorResolver>>,
80}
81
82#[derive(Default)]
83struct InnerSharedArena {
84 // Container metadata is a single consistency domain. Keep it under one
85 // mutex so container id/index/parent/depth updates cannot acquire locks in
86 // inconsistent orders.
87 containers: RwLock<ArenaContainers>,
88 str: Arc<Mutex<StrArena>>,
89}
90
91impl fmt::Debug for InnerSharedArena {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 f.debug_struct("InnerSharedArena")
94 .field("containers", &"<Mutex<_>>")
95 .field("str", &"<Arc<Mutex<_>>>")
96 .finish()
97 }
98}
99
100/// This is shared between [OpLog] and [AppState].
101///
102#[derive(Debug, Clone)]
103pub struct SharedArena {
104 inner: Arc<InnerSharedArena>,
105}
106
107pub(crate) struct SharedArenaRollback {
108 container_len: usize,
109 str: StrArenaCheckpoint,
110}
111
112/// How far the arena reached when something that refers into it was built, e.g. a parsed
113/// change block: it can only refer to containers and text allocated before.
114#[derive(Debug, Clone, Copy, Default)]
115pub(crate) struct ArenaExtent {
116 containers: usize,
117 str_bytes: usize,
118}
119
120impl SharedArenaRollback {
121 /// Whether rolling back to this checkpoint keeps everything within `extent`.
122 pub(crate) fn keeps(&self, extent: ArenaExtent) -> bool {
123 extent.containers <= self.container_len && extent.str_bytes <= self.str.bytes_len()
124 }
125}
126
127#[derive(Debug)]
128pub struct StrAllocResult {
129 /// unicode start
130 pub start: usize,
131 /// unicode end
132 pub end: usize,
133}
134
135impl ArenaContainers {
136 /// Add a freshly-registered cid to the retention-root tracking vectors.
137 ///
138 /// Centralizes the `root_c_idx ⊇ top_level_root_c_idx` invariant: `root_c_idx` is the set of
139 /// retention roots (top-level user roots **and** mergeable cids) that seed the alive-walk for
140 /// shallow snapshot; `top_level_root_c_idx` is the user-visible subset enumerated by
141 /// `preferred_root_containers` etc. Every push to either vector should go through this method,
142 /// so the invariant is maintained by construction rather than by remembering to push to two
143 /// vectors at every call site.
144 fn push_root(&mut self, idx: ContainerIdx, is_mergeable: bool) {
145 self.root_c_idx.push(idx);
146 if !is_mergeable {
147 self.top_level_root_c_idx.push(idx);
148 }
149 }
150
151 fn register_container(&mut self, id: &ContainerID) -> ContainerIdx {
152 if let Some(&idx) = self.container_id_to_idx.get(id) {
153 return idx;
154 }
155
156 let idx = self.container_idx_to_id.len();
157 self.container_idx_to_id.push(id.clone());
158 let idx = ContainerIdx::from_index_and_type(idx as u32, id.container_type());
159 self.container_id_to_idx.insert(id.clone(), idx);
160 // Resolve the cid's kind once. `is_mergeable` is non-trivial for mergeable names,
161 // so we avoid calling it twice on the same id.
162 let mergeable_parts = if id.is_root() {
163 id.parse_mergeable()
164 } else {
165 None
166 };
167 match (id.is_root(), mergeable_parts) {
168 (true, None) => {
169 self.push_root(idx, false);
170 self.parents.insert(idx, None);
171 self.depth.push(NonZeroU16::new(1));
172 }
173 (true, Some((parent_id, _key, _kind))) => {
174 // Mergeable Roots are retention roots AND logical children. Push to `root_c_idx`
175 // so shallow snapshot's `retain_keys` does not GC the loser of a concurrent-kind
176 // conflict (whose state is reachable only by its deterministic cid, not through
177 // the parent marker); then `set_parent` for path/event resolution. They are
178 // deliberately absent from `top_level_root_c_idx` so user-facing root
179 // enumeration does not have to filter them out.
180 self.push_root(idx, true);
181 self.depth.push(None);
182 let parent_idx = self.register_container(&parent_id);
183 self.set_parent(idx, Some(parent_idx));
184 }
185 (false, _) => {
186 self.depth.push(None);
187 }
188 }
189 idx
190 }
191
192 fn set_parent(&mut self, child: ContainerIdx, parent: Option<ContainerIdx>) {
193 self.parents.insert(child, parent);
194
195 match parent {
196 Some(p) => {
197 // Keep parent linking side-effect free. Calling `get_depth()` here may invoke the
198 // lazy parent resolver, which can acquire the state KV lock. Import/load paths may
199 // be assembling parent edges from KV snapshots, so resolving depth here would make
200 // arena -> KV and KV -> arena lock orders coexist.
201 if let Some(d) = self.depth[p.to_index() as usize] {
202 self.depth[child.to_index() as usize] = NonZeroU16::new(d.get() + 1);
203 } else {
204 self.depth[child.to_index() as usize] = None;
205 }
206 }
207 None => {
208 self.depth[child.to_index() as usize] = NonZeroU16::new(1);
209 }
210 }
211 }
212
213 fn get_depth(&mut self, target: ContainerIdx) -> Option<NonZeroU16> {
214 if let Some(d) = self.depth[target.to_index() as usize] {
215 return Some(d);
216 }
217
218 let parent: Option<ContainerIdx> = if let Some(p) = self.parents.get(&target) {
219 *p
220 } else {
221 let id = self
222 .container_idx_to_id
223 .get(target.to_index() as usize)
224 .unwrap()
225 .clone();
226 if id.is_root() && !id.is_mergeable() {
227 None
228 } else {
229 // Mergeable Roots get registered via the main `register_container` path, which
230 // already wires their parent edge — they should never reach here with a missing
231 // `parents` entry. But for ordinary children whose parent isn't in the arena
232 // yet, fall back to the resolver.
233 let resolver = self.parent_resolver.clone()?;
234 let parent_id = resolver(id)?;
235 // Route through `register_container` so a freshly-discovered parent (especially
236 // a mergeable cid) lands in `root_c_idx`, gets its own parent edge wired up,
237 // and has `parents` initialized — instead of being half-registered with just
238 // `idx_to_id` / `id_to_idx` / `depth` and silently missing from retention walks.
239 let parent_idx =
240 if let Some(idx) = self.container_id_to_idx.get(&parent_id).copied() {
241 // Already in the arena. For a top-level root that was hand-registered
242 // somewhere else without a `parents` entry, ensure it has one.
243 if parent_id.is_root() && !parent_id.is_mergeable() {
244 self.parents.entry(idx).or_insert(None);
245 if self.depth[idx.to_index() as usize].is_none() {
246 self.depth[idx.to_index() as usize] = NonZeroU16::new(1);
247 }
248 }
249 idx
250 } else {
251 self.register_container(&parent_id)
252 };
253
254 Some(parent_idx)
255 }
256 };
257
258 let d = match parent {
259 Some(p) => NonZeroU16::new(self.get_depth(p)?.get() + 1),
260 None => NonZeroU16::new(1),
261 };
262 self.depth[target.to_index() as usize] = d;
263 d
264 }
265
266 fn container_id(&self, idx: ContainerIdx) -> Option<ContainerID> {
267 self.container_idx_to_id
268 .get(idx.to_index() as usize)
269 .cloned()
270 }
271}
272
273pub(crate) struct ArenaGuards<'a> {
274 containers: RwLockWriteGuard<'a, ArenaContainers>,
275}
276
277impl ArenaGuards<'_> {
278 pub fn register_container(&mut self, id: &ContainerID) -> ContainerIdx {
279 self.containers.register_container(id)
280 }
281
282 pub fn set_parent(&mut self, child: ContainerIdx, parent: Option<ContainerIdx>) {
283 self.containers.set_parent(child, parent);
284 }
285}
286
287impl SharedArena {
288 #[allow(clippy::new_without_default)]
289 pub fn new() -> Self {
290 Self {
291 inner: Arc::new(InnerSharedArena::default()),
292 }
293 }
294
295 pub fn fork(&self) -> Self {
296 Self {
297 inner: Arc::new(InnerSharedArena {
298 containers: RwLock::new({
299 let containers = self.inner.containers.read();
300 ArenaContainers {
301 container_idx_to_id: containers.container_idx_to_id.clone(),
302 depth: containers.depth.clone(),
303 container_id_to_idx: containers.container_id_to_idx.clone(),
304 parents: containers.parents.clone(),
305 root_c_idx: containers.root_c_idx.clone(),
306 top_level_root_c_idx: containers.top_level_root_c_idx.clone(),
307 parent_resolver: containers.parent_resolver.clone(),
308 // It reads the source document's op log.
309 creator_resolver: None,
310 }
311 }),
312 str: self.inner.str.clone(),
313 }),
314 }
315 }
316
317 /// See [`ArenaExtent`].
318 pub(crate) fn extent(&self) -> ArenaExtent {
319 ArenaExtent {
320 containers: self.inner.containers.read().container_idx_to_id.len(),
321 str_bytes: self.inner.str.lock().bytes_len(),
322 }
323 }
324
325 pub(crate) fn checkpoint_for_rollback(&self) -> SharedArenaRollback {
326 let containers = self.inner.containers.read();
327 let container_len = containers.container_idx_to_id.len();
328 drop(containers);
329 let str = self.inner.str.lock().checkpoint();
330 SharedArenaRollback { container_len, str }
331 }
332
333 /// Call it through the op log's change store (`ChangeStore::rollback_arena` and friends),
334 /// which does it under the lock the creator resolver parses under and drops the parsed
335 /// changes that may refer to what this removes. See `context/arena-parent-links.md`.
336 ///
337 /// Container indices are never freed: a container registered since the checkpoint keeps
338 /// its index. `DocState` (store entries, caches) and handlers on other threads may hold
339 /// it, and a new container that reused it would inherit their state (loro-dev/loro#1164).
340 /// What the failed import may have told the arena about those containers is dropped: the
341 /// parent links of normal containers registered since the checkpoint, and links to them.
342 /// The resolvers find the links again from the kept history or the state. Roots keep their
343 /// links, which their IDs determine. Text is truncated; only parsed changes refer to it. See `context/failed-import-arena-indices.md`.
344 pub(crate) fn rollback(&self, checkpoint: SharedArenaRollback) {
345 {
346 let mut guard = self.inner.containers.write();
347 let containers = &mut *guard;
348 let container_len = checkpoint.container_len;
349 if containers.container_idx_to_id.len() > container_len {
350 let ids = &containers.container_idx_to_id;
351 containers.parents.retain(|child, parent| {
352 let child_is_new = (child.to_index() as usize) >= container_len;
353 let parent_is_new =
354 parent.is_some_and(|p| (p.to_index() as usize) >= container_len);
355 !((child_is_new || parent_is_new) && ids[child.to_index() as usize].is_normal())
356 });
357 // A cached depth may have been computed through a dropped link, also for the
358 // descendants of a container registered before the checkpoint. Roots and
359 // links that are kept give the same depth again.
360 containers.depth.fill(None);
361 }
362 }
363
364 self.inner.str.lock().rollback(checkpoint.str);
365 }
366
367 pub(crate) fn with_guards(&self, f: impl FnOnce(&mut ArenaGuards)) {
368 let mut guards = self.get_arena_guards();
369 f(&mut guards);
370 }
371
372 fn get_arena_guards(&self) -> ArenaGuards<'_> {
373 ArenaGuards {
374 containers: self.inner.containers.write(),
375 }
376 }
377
378 pub fn register_container(&self, id: &ContainerID) -> ContainerIdx {
379 self.inner.containers.write().register_container(id)
380 }
381
382 pub fn get_container_id(&self, idx: ContainerIdx) -> Option<ContainerID> {
383 self.inner.containers.read().container_id(idx)
384 }
385
386 /// Fast map from `ContainerID` to `ContainerIdx` for containers already registered
387 /// in the arena.
388 ///
389 /// Important: This is not an existence check. Absence here does not imply that a
390 /// container does not exist, since registration can be lazy and containers may
391 /// be persisted only in the state KV store until first use.
392 ///
393 /// For existence-aware lookup that consults persisted state and performs lazy
394 /// registration, prefer `DocState::resolve_idx`.
395 pub fn id_to_idx(&self, id: &ContainerID) -> Option<ContainerIdx> {
396 self.inner
397 .containers
398 .read()
399 .container_id_to_idx
400 .get(id)
401 .copied()
402 }
403
404 #[inline]
405 pub fn idx_to_id(&self, id: ContainerIdx) -> Option<ContainerID> {
406 self.inner.containers.read().container_id(id)
407 }
408
409 #[inline]
410 pub fn with_idx_to_id<R>(&self, f: impl FnOnce(&Vec<ContainerID>) -> R) -> R {
411 let containers = self.inner.containers.read();
412 f(&containers.container_idx_to_id)
413 }
414
415 pub fn alloc_str(&self, str: &str) -> StrAllocResult {
416 let mut text_lock = self.inner.str.lock();
417 _alloc_str(&mut text_lock, str)
418 }
419
420 /// return slice and unicode index
421 pub fn alloc_str_with_slice(&self, str: &str) -> (BytesSlice, StrAllocResult) {
422 let mut text_lock = self.inner.str.lock();
423 _alloc_str_with_slice(&mut text_lock, str)
424 }
425
426 /// alloc str without extra info
427 pub fn alloc_str_fast(&self, bytes: &[u8]) {
428 let mut text_lock = self.inner.str.lock();
429 text_lock.alloc(std::str::from_utf8(bytes).unwrap());
430 }
431
432 /// Bytes held by the string arena; it only ever grows.
433 #[cfg(test)]
434 pub(crate) fn str_len_bytes(&self) -> usize {
435 self.inner.str.lock().len_bytes()
436 }
437
438 #[inline]
439 pub fn utf16_len(&self) -> usize {
440 self.inner.str.lock().len_utf16()
441 }
442
443 #[inline]
444 pub fn set_parent(&self, child: ContainerIdx, parent: Option<ContainerIdx>) {
445 self.inner.containers.write().set_parent(child, parent);
446 }
447
448 /// Forget the parent links of the normal containers whose creating op is `peer`'s op at
449 /// `start_counter` or later, after such ops were discarded (a rolled back local
450 /// transaction). The next op at that id may create the container under another parent,
451 /// and until then the container has no parent, so it reads as deleted without being
452 /// cached as deleted. The registrations stay: other code may hold their indices. The
453 /// caller removes their state. See `context/apply-diff-atomicity.md`.
454 pub(crate) fn forget_parents_of_discarded_ops(&self, peer: PeerID, start_counter: Counter) {
455 let mut containers = self.inner.containers.write();
456 let discarded: Vec<ContainerIdx> = containers
457 .container_idx_to_id
458 .iter()
459 .enumerate()
460 .filter(|(_, id)| {
461 matches!(id, ContainerID::Normal { peer: p, counter, .. }
462 if *p == peer && *counter >= start_counter)
463 })
464 .map(|(i, id)| ContainerIdx::from_index_and_type(i as u32, id.container_type()))
465 .collect();
466 for idx in discarded {
467 containers.parents.remove(&idx);
468 containers.depth[idx.to_index() as usize] = None;
469 }
470 }
471
472 pub fn log_hierarchy(&self) {
473 if cfg!(debug_assertions) {
474 let containers = self.inner.containers.read();
475 for (c, p) in containers.parents.iter() {
476 tracing::info!(
477 "container {:?} {:?} {:?}",
478 c,
479 containers.container_id(*c),
480 p.and_then(|x| containers.container_id(x))
481 );
482 }
483 }
484 }
485
486 pub fn log_all_containers(&self) {
487 let containers = self.inner.containers.read();
488 containers.container_id_to_idx.iter().for_each(|(id, idx)| {
489 tracing::info!("container {:?} {:?}", id, idx);
490 });
491 containers
492 .container_idx_to_id
493 .iter()
494 .enumerate()
495 .for_each(|(i, id)| {
496 tracing::info!("container {} {:?}", i, id);
497 });
498 }
499
500 /// The parent of `child`, or `None` for a top-level root.
501 ///
502 /// Also `None` for a normal container that no op in the history creates (an ID from the
503 /// user that is not a container, an op not received yet, or a container that is not in
504 /// the state of a shallow document and whose creating op was trimmed): no path leads to
505 /// it, so it is treated like a container whose parent no longer holds it. A history that
506 /// has the op but cannot parse it panics instead (see [`CreatorResolver`]).
507 pub fn get_parent(&self, child: ContainerIdx) -> Option<ContainerIdx> {
508 match self.resolve_parent(child) {
509 Some(parent) => parent,
510 None => {
511 assert!(
512 self.inner.containers.read().creator_resolver.is_some(),
513 "InternalError: Parent is not registered"
514 );
515 None
516 }
517 }
518 }
519
520 /// Finds and registers `child`'s parent edge: the registered edge, else the state KV
521 /// (`parent_resolver`), else the change that created it (`creator_resolver`).
522 ///
523 /// Returns `Some(parent)` when the edge is known (`parent` is `None` for a top-level root)
524 /// and `None` when no source knows the container.
525 fn resolve_parent(&self, child: ContainerIdx) -> Option<Option<ContainerIdx>> {
526 let (child_id, resolver, creator_resolver) = {
527 let containers = self.inner.containers.read();
528 let child_id = containers.container_id(child).unwrap();
529 if child_id.is_root() && !child_id.is_mergeable() {
530 // TODO: PERF: we can speed this up by use a special bit in ContainerIdx to indicate
531 // whether the target is a root container
532 return Some(None);
533 }
534
535 // Try fast path first
536 if let Some(p) = containers.parents.get(&child).copied() {
537 return Some(p);
538 }
539
540 // Fallback: try to resolve parent lazily via the resolvers if provided.
541 (
542 child_id,
543 containers.parent_resolver.clone(),
544 containers.creator_resolver.clone(),
545 )
546 };
547 if let Some(resolver) = resolver {
548 if let Some(parent_id) = resolver(child_id.clone()) {
549 let parent_idx = self.register_container(&parent_id);
550 self.set_parent(child, Some(parent_idx));
551 return Some(Some(parent_idx));
552 }
553 }
554
555 if let (Some(resolver), ContainerID::Normal { peer, counter, .. }) =
556 (creator_resolver, &child_id)
557 {
558 return match resolver(self, ID::new(*peer, *counter)) {
559 // Registered unless the op does not create this container.
560 CreatorOp::Loaded => self.get_registered_parent(child),
561 CreatorOp::Absent | CreatorOp::Corrupt => None,
562 };
563 }
564
565 None
566 }
567
568 /// The index of a normal container that is not registered yet but that an op in the
569 /// history creates. Loading that op's change registers the container and its parent.
570 pub(crate) fn find_created_container(&self, id: &ContainerID) -> Option<ContainerIdx> {
571 if let Some(idx) = self.id_to_idx(id) {
572 return Some(idx);
573 }
574 let ContainerID::Normal { peer, counter, .. } = id else {
575 return None;
576 };
577 let resolver = self.inner.containers.read().creator_resolver.clone()?;
578 match resolver(self, ID::new(*peer, *counter)) {
579 CreatorOp::Loaded => self.id_to_idx(id),
580 CreatorOp::Absent | CreatorOp::Corrupt => None,
581 }
582 }
583
584 /// Return the parent edge already stored in the arena without invoking the lazy resolver.
585 ///
586 /// The outer `Option` distinguishes an unregistered edge from a registered root edge.
587 pub(crate) fn get_registered_parent(
588 &self,
589 child: ContainerIdx,
590 ) -> Option<Option<ContainerIdx>> {
591 self.inner.containers.read().parents.get(&child).copied()
592 }
593
594 /// Call `f` on each ancestor of `container`, including `container` itself.
595 ///
596 /// f(ContainerIdx, is_first)
597 pub fn with_ancestors(&self, container: ContainerIdx, mut f: impl FnMut(ContainerIdx, bool)) {
598 let mut container = Some(container);
599 let mut is_first = true;
600 while let Some(c) = container {
601 f(c, is_first);
602 is_first = false;
603 container = self.get_parent(c)
604 }
605 }
606
607 #[inline]
608 pub fn slice_by_unicode(&self, range: impl RangeBounds<usize>) -> BytesSlice {
609 self.inner.str.lock().slice_by_unicode(range)
610 }
611
612 #[inline]
613 pub fn slice_by_utf8(&self, range: impl RangeBounds<usize>) -> BytesSlice {
614 self.inner.str.lock().slice_bytes(range)
615 }
616
617 #[inline]
618 pub fn slice_str_by_unicode_range(&self, range: Range<usize>) -> String {
619 let mut s = self.inner.str.lock();
620 let s: &mut StrArena = &mut s;
621 let mut ans = String::with_capacity(range.len());
622 ans.push_str(s.slice_str_by_unicode(range));
623 ans
624 }
625
626 #[inline]
627 pub fn with_text_slice(&self, range: Range<usize>, mut f: impl FnMut(&str)) {
628 f(self.inner.str.lock().slice_str_by_unicode(range))
629 }
630
631 pub fn convert_single_op(
632 &self,
633 container: &ContainerID,
634 peer: PeerID,
635 counter: Counter,
636 lamport: Lamport,
637 content: RawOpContent,
638 ) -> Op {
639 let container = self.register_container(container);
640 self.inner_convert_op(content, peer, counter, lamport, container)
641 }
642
643 pub fn can_import_snapshot(&self) -> bool {
644 self.inner.str.lock().is_empty()
645 }
646
647 fn inner_convert_op(
648 &self,
649 content: RawOpContent<'_>,
650 _peer: PeerID,
651 counter: i32,
652 _lamport: Lamport,
653 container: ContainerIdx,
654 ) -> Op {
655 match content {
656 crate::op::RawOpContent::Map(MapSet { key, value }) => Op {
657 counter,
658 container,
659 content: crate::op::InnerContent::Map(MapSet { key, value }),
660 },
661 crate::op::RawOpContent::List(list) => match list {
662 ListOp::Insert { slice, pos } => match slice {
663 ListSlice::RawData(values) => Op {
664 counter,
665 container,
666 content: crate::op::InnerContent::List(InnerListOp::Insert {
667 slice: ValueSlice::new(values.into_owned()),
668 pos,
669 }),
670 },
671 ListSlice::RawStr { str, unicode_len } => {
672 let (slice, _) = self.alloc_str_with_slice(&str);
673 Op {
674 counter,
675 container,
676 content: crate::op::InnerContent::List(InnerListOp::InsertText {
677 slice,
678 unicode_len: unicode_len as u32,
679 pos: pos as u32,
680 }),
681 }
682 }
683 },
684 ListOp::Delete(span) => Op {
685 counter,
686 container,
687 content: crate::op::InnerContent::List(InnerListOp::Delete(span)),
688 },
689 ListOp::StyleStart {
690 start,
691 end,
692 info,
693 key,
694 value,
695 } => Op {
696 counter,
697 container,
698 content: InnerContent::List(InnerListOp::StyleStart {
699 start,
700 end,
701 key,
702 info,
703 value,
704 }),
705 },
706 ListOp::StyleEnd => Op {
707 counter,
708 container,
709 content: InnerContent::List(InnerListOp::StyleEnd),
710 },
711 ListOp::Move {
712 from,
713 to,
714 elem_id: from_id,
715 } => Op {
716 counter,
717 container,
718 content: InnerContent::List(InnerListOp::Move {
719 from,
720 to,
721 elem_id: from_id,
722 }),
723 },
724 ListOp::Set { elem_id, value } => Op {
725 counter,
726 container,
727 content: InnerContent::List(InnerListOp::Set { elem_id, value }),
728 },
729 },
730 crate::op::RawOpContent::Tree(tree) => Op {
731 counter,
732 container,
733 content: crate::op::InnerContent::Tree(tree.clone()),
734 },
735 #[cfg(feature = "counter")]
736 crate::op::RawOpContent::Counter(c) => Op {
737 counter,
738 container,
739 content: crate::op::InnerContent::Future(crate::op::FutureInnerContent::Counter(c)),
740 },
741 crate::op::RawOpContent::Unknown { prop, value } => Op {
742 counter,
743 container,
744 content: crate::op::InnerContent::Future(crate::op::FutureInnerContent::Unknown {
745 prop,
746 value: Box::new(value),
747 }),
748 },
749 }
750 }
751
752 #[inline]
753 pub fn convert_raw_op(&self, op: &RawOp) -> Op {
754 self.inner_convert_op(
755 op.content.clone(),
756 op.id.peer,
757 op.id.counter,
758 op.lamport,
759 op.container,
760 )
761 }
762
763 #[inline]
764 pub fn export_containers(&self) -> Vec<ContainerID> {
765 self.inner.containers.read().container_idx_to_id.clone()
766 }
767
768 pub fn export_parents(&self) -> Vec<Option<ContainerIdx>> {
769 let containers = self.inner.containers.read();
770 containers
771 .container_idx_to_id
772 .iter()
773 .enumerate()
774 .map(|(x, id)| {
775 let idx = ContainerIdx::from_index_and_type(x as u32, id.container_type());
776 let parent_idx = containers.parents.get(&idx)?;
777 *parent_idx
778 })
779 .collect()
780 }
781
782 /// Returns all the possible root containers of the docs
783 ///
784 /// We need to load all the cached kv in DocState before we can ensure all root contains are covered.
785 /// So we need the flag type here.
786 ///
787 /// This includes mergeable cids (which are also retention roots). Callers that only want
788 /// user-visible top-level roots should use [`Self::top_level_root_containers`].
789 #[inline]
790 pub(crate) fn root_containers(&self, _f: LoadAllFlag) -> Vec<ContainerIdx> {
791 self.inner.containers.read().root_c_idx.clone()
792 }
793
794 /// Returns only the user-visible top-level root containers (excludes mergeable cids).
795 ///
796 /// Used by `preferred_root_containers`, `get_value` / `get_deep_value`, jsonpath, etc. —
797 /// any path that enumerates the doc's top-level roots. Pre-filtering at registration time
798 /// keeps these calls O(top_level_roots) instead of O(top_level_roots + mergeable_cids).
799 #[inline]
800 pub(crate) fn top_level_root_containers(&self, _f: LoadAllFlag) -> Vec<ContainerIdx> {
801 self.inner.containers.read().top_level_root_c_idx.clone()
802 }
803
804 // TODO: this can return a u16 directly now, since the depths are always valid
805 pub(crate) fn get_depth(&self, container: ContainerIdx) -> Option<NonZeroU16> {
806 if let Some(d) = self.inner.containers.read().depth[container.to_index() as usize] {
807 return Some(d);
808 }
809
810 // `ArenaContainers::get_depth` runs under the arena lock, where the creator resolver
811 // cannot run, so resolve the missing parent links first.
812 let mut c = container;
813 // Every step goes one level up, and no valid chain is deeper than `u16::MAX`.
814 let mut steps = 0usize;
815 loop {
816 steps += 1;
817 assert!(
818 steps <= u16::MAX as usize + 1,
819 "InternalError: the parent links of {:?} form a cycle",
820 self.idx_to_id(container)
821 );
822 {
823 let containers = self.inner.containers.read();
824 if containers.depth[c.to_index() as usize].is_some() {
825 break;
826 }
827 match containers.parents.get(&c).copied() {
828 Some(Some(p)) => {
829 c = p;
830 continue;
831 }
832 Some(None) => break,
833 None => {}
834 }
835 }
836 match self.resolve_parent(c) {
837 Some(Some(p)) => c = p,
838 _ => break,
839 }
840 }
841 self.inner.containers.write().get_depth(container)
842 }
843}
844
845fn _alloc_str_with_slice(
846 text_lock: &mut MutexGuard<'_, StrArena>,
847 str: &str,
848) -> (BytesSlice, StrAllocResult) {
849 let start = text_lock.len_bytes();
850 let ans = _alloc_str(text_lock, str);
851 (text_lock.slice_bytes(start..), ans)
852}
853
854fn _alloc_str(text_lock: &mut MutexGuard<'_, StrArena>, str: &str) -> StrAllocResult {
855 let start = text_lock.len_unicode();
856 text_lock.alloc(str);
857 StrAllocResult {
858 start,
859 end: text_lock.len_unicode(),
860 }
861}
862
863fn _slice_str(range: Range<usize>, s: &mut StrArena) -> String {
864 let mut ans = String::with_capacity(range.len());
865 ans.push_str(s.slice_str_by_unicode(range));
866 ans
867}
868
869impl SharedArena {
870 /// Register or clear a resolver to lazily determine a container's parent when missing.
871 ///
872 /// - The resolver receives the child `ContainerIdx` and returns an optional `ContainerID` of its parent.
873 /// - If the resolver returns `Some`, `SharedArena` will register the parent in the arena and link it.
874 /// - If the resolver is `None` or returns `None`, `get_parent` will panic for non-root containers as before.
875 pub fn set_parent_resolver<F>(&self, resolver: Option<F>)
876 where
877 F: Fn(ContainerID) -> Option<ContainerID> + Send + Sync + 'static,
878 {
879 self.inner.containers.write().parent_resolver =
880 resolver.map(|f| Arc::new(f) as Arc<ParentResolver>);
881 }
882
883 /// Register the op log's [`CreatorResolver`]. See `creator_resolver` in `ArenaContainers`.
884 pub(crate) fn set_creator_resolver<F>(&self, resolver: F)
885 where
886 F: Fn(&SharedArena, ID) -> CreatorOp + Send + Sync + 'static,
887 {
888 self.inner.containers.write().creator_resolver = Some(Arc::new(resolver));
889 }
890}
891
892#[cfg(test)]
893mod tests {
894 use super::*;
895 use loro_common::ContainerType;
896 use std::sync::{
897 atomic::{AtomicBool, Ordering},
898 Arc,
899 };
900
901 /// When a non-mergeable child is registered, then later asks for its depth and the parent
902 /// resolver yields a mergeable cid, the mergeable parent must be registered through the
903 /// retention-root path (push to `root_c_idx`, recursively link its own parent) — exactly the
904 /// same way the main `register_container` path would handle a freshly-encountered mergeable
905 /// cid. Without this, shallow snapshot's alive-walk would silently GC the mergeable parent's
906 /// state.
907 #[test]
908 fn get_depth_resolver_registers_mergeable_parent_as_retention_root() {
909 let arena = SharedArena::new();
910
911 let top_root = ContainerID::new_root("state", ContainerType::Map);
912 let mergeable_parent = ContainerID::new_mergeable(&top_root, "profile", ContainerType::Map);
913 let child = ContainerID::new_normal(loro_common::ID::new(1, 0), ContainerType::List);
914
915 let mergeable_parent_for_resolver = mergeable_parent.clone();
916 let child_for_resolver = child.clone();
917 arena.set_parent_resolver(Some(move |q: ContainerID| {
918 if q == child_for_resolver {
919 Some(mergeable_parent_for_resolver.clone())
920 } else {
921 None
922 }
923 }));
924
925 let child_idx = arena.register_container(&child);
926 let _ = arena.get_depth(child_idx);
927
928 let flag = LoadAllFlag;
929 let mergeable_idx = arena
930 .id_to_idx(&mergeable_parent)
931 .expect("resolver should have registered the mergeable parent");
932 assert!(
933 arena.root_containers(flag).contains(&mergeable_idx),
934 "mergeable parent discovered via resolver must be a retention root"
935 );
936
937 let flag = LoadAllFlag;
938 assert!(
939 !arena
940 .top_level_root_containers(flag)
941 .contains(&mergeable_idx),
942 "mergeable parent must not appear in user-facing top-level enumeration"
943 );
944
945 let flag = LoadAllFlag;
946 let top_root_idx = arena
947 .id_to_idx(&top_root)
948 .expect("mergeable parent's own grandparent must also be registered");
949 assert!(
950 arena
951 .top_level_root_containers(flag)
952 .contains(&top_root_idx),
953 "the mergeable parent's grandparent (a top-level root) must be in the top-level list"
954 );
955 }
956
957 /// The creator resolver parses changes, which registers containers in the arena, so
958 /// `get_parent` and `get_depth` must call it without holding the arena lock.
959 #[test]
960 fn creator_resolver_runs_outside_the_arena_lock() {
961 let arena = SharedArena::new();
962 let root = ContainerID::new_root("tree", ContainerType::Tree);
963 let meta = ContainerID::new_normal(ID::new(1, 3), ContainerType::Map);
964 let meta_for_resolver = meta.clone();
965 arena.set_creator_resolver(move |arena: &SharedArena, id: ID| {
966 assert_eq!(id, ID::new(1, 3));
967 // What parsing the change does: register the container and its parent.
968 let parent = arena.register_container(&root);
969 let child = arena.register_container(&meta_for_resolver);
970 arena.set_parent(child, Some(parent));
971 CreatorOp::Loaded
972 });
973
974 let meta_idx = arena.register_container(&meta);
975 assert_eq!(arena.get_depth(meta_idx).map(|d| d.get()), Some(2));
976 let root_idx = arena.id_to_idx(&ContainerID::new_root("tree", ContainerType::Tree));
977 assert_eq!(arena.get_parent(meta_idx), root_idx);
978 }
979
980 #[test]
981 fn a_container_that_no_op_creates_has_no_parent() {
982 for answer in [CreatorOp::Loaded, CreatorOp::Absent, CreatorOp::Corrupt] {
983 // `Loaded`: the op exists but creates something else.
984 let arena = SharedArena::new();
985 arena.set_creator_resolver(move |_: &SharedArena, _: ID| answer);
986 let id = ContainerID::new_normal(ID::new(1, 3), ContainerType::Map);
987 let idx = arena.register_container(&id);
988 assert_eq!(arena.get_parent(idx), None);
989 assert_eq!(arena.get_depth(idx), None);
990 let missing = ContainerID::new_normal(ID::new(1, 4), ContainerType::Text);
991 assert_eq!(arena.find_created_container(&missing), None);
992 }
993 }
994
995 #[test]
996 #[should_panic(expected = "form a cycle")]
997 fn a_parent_cycle_fails_fast() {
998 let arena = SharedArena::new();
999 let a =
1000 arena.register_container(&ContainerID::new_normal(ID::new(1, 0), ContainerType::Map));
1001 let b =
1002 arena.register_container(&ContainerID::new_normal(ID::new(1, 1), ContainerType::Map));
1003 arena.set_parent(a, Some(b));
1004 arena.set_parent(b, Some(a));
1005 arena.get_depth(a);
1006 }
1007
1008 /// Without an op log to ask, an unknown parent is still an internal error.
1009 #[test]
1010 #[should_panic(expected = "Parent is not registered")]
1011 fn unknown_parent_without_a_creator_resolver_panics() {
1012 let arena = SharedArena::new();
1013 let idx =
1014 arena.register_container(&ContainerID::new_normal(ID::new(1, 3), ContainerType::Map));
1015 arena.get_parent(idx);
1016 }
1017
1018 #[test]
1019 fn set_parent_does_not_resolve_missing_parent_depth() {
1020 let arena = SharedArena::new();
1021 let parent = ContainerID::new_normal(loro_common::ID::new(1, 0), ContainerType::Map);
1022 let child = ContainerID::new_mergeable(&parent, "field", ContainerType::Text);
1023 let resolver_called = Arc::new(AtomicBool::new(false));
1024 let called = resolver_called.clone();
1025 arena.set_parent_resolver(Some(move |_| {
1026 called.store(true, Ordering::SeqCst);
1027 None
1028 }));
1029
1030 arena.register_container(&child);
1031
1032 assert!(
1033 !resolver_called.load(Ordering::SeqCst),
1034 "registering a mergeable child must not invoke the lazy parent resolver"
1035 );
1036 }
1037}