forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

txn.rs1221 lines, 43.1 KiBHistoryRawDownload
1use std::{
2 borrow::Cow,
3 mem::take,
4 sync::{Arc, Weak},
5};
6
7use enum_as_inner::EnumAsInner;
8use generic_btree::rle::{HasLength as RleHasLength, Mergeable as GBSliceable};
9use loro_common::{ContainerType, IdLp, IdSpan, LoroResult};
10use loro_delta::{array_vec::ArrayVec, DeltaRopeBuilder};
11use rle::{HasLength, Mergable, RleVec, Sliceable};
12use rustc_hash::FxHashMap;
13use smallvec::SmallVec;
14
15use crate::utils::subscription::DeferredPanic;
16use crate::{
17 change::{Change, Lamport, Timestamp},
18 container::{
19 idx::ContainerIdx,
20 list::list_op::{DeleteSpan, InnerListOp},
21 richtext::Style,
22 IntoContainerId,
23 },
24 delta::{ResolvedMapDelta, ResolvedMapValue, StyleMeta, StyleMetaItem, TreeDiff, TreeDiffItem},
25 encoding::export_fast_updates_in_range,
26 event::{Diff, ListDeltaMeta, TextDiff},
27 handler::{Handler, ValueOrHandler},
28 id::{Counter, PeerID, ID},
29 lock::{LoroMutex, LoroMutexGuard},
30 loro::CommitOptions,
31 op::{InnerContent, Op, RawOp, RawOpContent},
32 pre_commit::{ChangeModifier, PreCommitCallbackPayload},
33 span::HasIdSpan,
34 version::Frontiers,
35 ChangeMeta, InternalString, LoroDoc, LoroDocInner, LoroError, LoroValue,
36};
37
38use super::{
39 arena::SharedArena,
40 event::{InternalContainerDiff, InternalDocDiff},
41 handler::{ListHandler, MapHandler, TextHandler, TreeHandler},
42 oplog::OpLog,
43 state::DocState,
44};
45
46impl crate::LoroDoc {
47 /// Create a new transaction.
48 /// Every ops created inside one transaction will be packed into a single
49 /// [Change].
50 ///
51 /// There can only be one active transaction at a time for a [LoroDoc].
52 #[inline(always)]
53 pub fn txn(&self) -> Result<Transaction, LoroError> {
54 self.txn_with_origin("")
55 }
56
57 /// Create a new transaction with specified origin.
58 ///
59 /// The origin will be propagated to the events.
60 /// There can only be one active transaction at a time for a [LoroDoc].
61 pub fn txn_with_origin(&self, origin: &str) -> Result<Transaction, LoroError> {
62 if !self.can_edit() {
63 return Err(LoroError::TransactionError(
64 String::from("LoroDoc is in readonly detached mode. To make it writable in detached mode, call `set_detached_editing(true)`.").into_boxed_str(),
65 ));
66 }
67
68 let mut txn = Transaction::new_with_origin(self.inner.clone(), origin.into())?;
69
70 let obs = self.observer.clone();
71 let local_update_subs_weak = self.local_update_subs.downgrade();
72 txn.set_on_commit(Box::new(move |state, oplog, id_span| {
73 let mut state = state.lock();
74 let events = state.take_events();
75 drop(state);
76 // A panicking subscriber must not drop the other events, nor the
77 // local update of this commit, which apps send to their peers.
78 let mut panic = DeferredPanic::default();
79 for event in events {
80 panic.run(|| obs.emit(event));
81 }
82
83 if id_span.atom_len() != 0 {
84 if let Some(local_update_subs) = local_update_subs_weak.upgrade() {
85 if !local_update_subs.inner().is_empty() {
86 let bytes = { export_fast_updates_in_range(&oplog.lock(), &[id_span]) };
87 panic.run(|| local_update_subs.emit(&(), bytes));
88 }
89 }
90 }
91 panic.resume();
92 }));
93
94 Ok(txn)
95 }
96
97 pub fn start_auto_commit(&self) {
98 self.auto_commit
99 .store(true, std::sync::atomic::Ordering::Release);
100 let mut self_txn = self.txn.lock();
101 if self_txn.is_some() || !self.can_edit() {
102 return;
103 }
104
105 let txn = self
106 .txn()
107 .expect("auto-commit should be able to create a transaction");
108 self_txn.replace(txn);
109 }
110
111 #[inline]
112 pub fn renew_txn_if_auto_commit(&self, options: Option<CommitOptions>) {
113 if self.auto_commit.load(std::sync::atomic::Ordering::Acquire) && self.can_edit() {
114 let mut self_txn = self.txn.lock();
115 if self_txn.is_some() {
116 return;
117 }
118
119 let mut txn = self
120 .txn()
121 .expect("auto-commit should be able to renew a transaction");
122 if let Some(options) = options {
123 txn.set_options(options);
124 }
125 self_txn.replace(txn);
126 }
127 }
128
129 #[inline]
130 pub(crate) fn _renew_txn_if_auto_commit_with_guard(
131 &self,
132 options: Option<CommitOptions>,
133 mut guard: LoroMutexGuard<Option<Transaction>>,
134 ) {
135 if self.auto_commit.load(std::sync::atomic::Ordering::Acquire) && self.can_edit() {
136 if guard.is_some() {
137 return;
138 }
139
140 let mut txn = self
141 .txn()
142 .expect("auto-commit should be able to renew a transaction");
143 if let Some(options) = options {
144 txn.set_options(options);
145 }
146 guard.replace(txn);
147 }
148 }
149}
150
151pub(crate) type OnCommitFn =
152 Box<dyn FnOnce(&Arc<LoroMutex<DocState>>, &Arc<LoroMutex<OpLog>>, IdSpan) + Sync + Send>;
153
154pub struct Transaction {
155 peer: PeerID,
156 origin: InternalString,
157 start_counter: Counter,
158 next_counter: Counter,
159 start_lamport: Lamport,
160 next_lamport: Lamport,
161 doc: Weak<LoroDocInner>,
162 frontiers: Frontiers,
163 local_ops: RleVec<[Op; 1]>, // TODO: use a more efficient data structure
164 event_hints: FxHashMap<ContainerIdx, Vec<EventHint>>,
165 pub(super) arena: SharedArena,
166 finished: bool,
167 on_commit: Option<OnCommitFn>,
168 timestamp: Option<Timestamp>,
169 msg: Option<Arc<str>>,
170 latest_timestamp: Timestamp,
171 pub(super) is_peer_first_appearance: bool,
172 /// The DAG's frontiers when the txn began, before its first op.
173 dag_frontiers_at_start: Frontiers,
174 /// Set while `LoroDoc::apply_diff` or `revert_to` runs a batch in this txn,
175 /// which is rolled back if the batch fails (context/apply-diff-atomicity.md).
176 rollback_scope: Option<RollbackScope>,
177}
178
179/// See [`Transaction::begin_rollback_scope`].
180#[derive(Debug)]
181struct RollbackScope {
182 id: u64,
183 thread: usize,
184 /// Another thread applied an op in this txn while the batch ran.
185 foreign_ops: bool,
186 /// The txn's next counter and lamport when the batch began.
187 counter: Counter,
188 lamport: Lamport,
189 is_peer_first_appearance: bool,
190 /// For each container the batch gave an event hint to: how many hints it
191 /// had before, and the last one, which the batch's first hint may have been
192 /// merged into.
193 event_hints: FxHashMap<ContainerIdx, (usize, Option<EventHint>)>,
194}
195
196/// Identifies the current thread for [`RollbackScope`]: the address of a
197/// thread local is unique among the live threads.
198fn current_thread_mark() -> usize {
199 thread_local!(static MARK: u8 = const { 0 });
200 MARK.with(|m| m as *const u8 as usize)
201}
202
203/// What [`Transaction::roll_back_scope`] took out of a txn.
204pub(crate) struct RolledBackBatch {
205 pub(crate) peer: PeerID,
206 /// The txn's first op, its lamport, and the version it was applied on.
207 pub(crate) txn_start_counter: Counter,
208 pub(crate) txn_start_lamport: Lamport,
209 pub(crate) deps: Frontiers,
210 /// The DAG's frontiers before the txn's first op.
211 pub(crate) dag_frontiers_at_start: Frontiers,
212 /// The batch's ops are `batch_start..batch_end`; the txn keeps the ops before.
213 pub(crate) batch_start: Counter,
214 pub(crate) batch_end: Counter,
215 /// Every op of the txn, including the batch's.
216 pub(crate) ops: RleVec<[Op; 1]>,
217 pub(crate) timestamp: Timestamp,
218}
219
220impl std::fmt::Debug for Transaction {
221 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222 f.debug_struct("Transaction")
223 .field("peer", &self.peer)
224 .field("origin", &self.origin)
225 .field("start_counter", &self.start_counter)
226 .field("next_counter", &self.next_counter)
227 .field("start_lamport", &self.start_lamport)
228 .field("next_lamport", &self.next_lamport)
229 .field("frontiers", &self.frontiers)
230 .field("local_ops", &self.local_ops)
231 .field("event_hints", &self.event_hints)
232 .field("arena", &self.arena)
233 .field("finished", &self.finished)
234 .field("on_commit", &self.on_commit.is_some())
235 .field("timestamp", &self.timestamp)
236 .finish()
237 }
238}
239
240/// We can infer local events directly from the local behavior. This enum is used to
241/// record them, so that we can avoid recalculate them when we commit the transaction.
242///
243/// For example, when we insert a text in wasm, users use the utf16 index to send the
244/// command. However, internally loro will convert it to unicode index. But the users
245/// still need events that are in utf16 index. To avoid the round trip, we record the
246/// events here.
247#[derive(Debug, Clone, EnumAsInner)]
248pub(super) enum EventHint {
249 Mark {
250 start: u32,
251 end: u32,
252 style: Style,
253 },
254 InsertText {
255 /// pos is a Unicode index. If wasm, it's a UTF-16 index.
256 pos: u32,
257 event_len: u32,
258 unicode_len: u32,
259 styles: StyleMeta,
260 },
261 /// pos is a Unicode index. If wasm, it's a UTF-16 index.
262 DeleteText {
263 span: DeleteSpan,
264 unicode_len: usize,
265 },
266 InsertList {
267 len: u32,
268 pos: usize,
269 },
270 SetList {
271 index: usize,
272 value: LoroValue,
273 },
274 Move {
275 value: LoroValue,
276 from: u32,
277 to: u32,
278 },
279 DeleteList(DeleteSpan),
280 Map {
281 key: InternalString,
282 value: Option<LoroValue>,
283 },
284 // use vec because we could bring back some node that has children
285 Tree(SmallVec<[TreeDiffItem; 1]>),
286 MarkEnd,
287 #[cfg(feature = "counter")]
288 Counter(f64),
289}
290
291impl generic_btree::rle::HasLength for EventHint {
292 fn rle_len(&self) -> usize {
293 match self {
294 EventHint::Mark { .. } => 1,
295 EventHint::InsertText {
296 unicode_len: len, ..
297 } => *len as usize,
298 EventHint::DeleteText { unicode_len, .. } => *unicode_len,
299 EventHint::InsertList { len, .. } => *len as usize,
300 EventHint::DeleteList(d) => d.len(),
301 EventHint::Map { .. } => 1,
302 EventHint::Tree(_) => 1,
303 EventHint::MarkEnd => 1,
304 EventHint::Move { .. } => 1,
305 EventHint::SetList { .. } => 1,
306 #[cfg(feature = "counter")]
307 EventHint::Counter(_) => 1,
308 }
309 }
310}
311
312impl generic_btree::rle::Mergeable for EventHint {
313 fn can_merge(&self, rhs: &Self) -> bool {
314 match (self, rhs) {
315 (
316 EventHint::InsertText {
317 pos,
318 unicode_len: _,
319 event_len,
320 styles,
321 },
322 EventHint::InsertText {
323 pos: r_pos,
324 styles: r_styles,
325 ..
326 },
327 ) => *pos + *event_len == *r_pos && styles == r_styles,
328 (EventHint::InsertList { pos, len }, EventHint::InsertList { pos: pos_right, .. }) => {
329 pos + *len as usize == *pos_right
330 }
331 // We don't merge delete text because it's hard to infer the correct pos to split:
332 // `range` param is in unicode range, but the delete text event is in UTF-16 range.
333 // Without the original text, it's impossible to convert the range.
334 (EventHint::DeleteText { span, .. }, EventHint::DeleteText { span: r, .. }) => {
335 span.is_mergable(r, &())
336 }
337 (EventHint::DeleteList(l), EventHint::DeleteList(r)) => l.is_mergable(r, &()),
338 _ => false,
339 }
340 }
341
342 fn merge_right(&mut self, rhs: &Self) {
343 match (self, rhs) {
344 (
345 EventHint::InsertText {
346 event_len,
347 unicode_len: len,
348 ..
349 },
350 EventHint::InsertText {
351 event_len: r_event_len,
352 unicode_len: r_len,
353 ..
354 },
355 ) => {
356 *len += *r_len;
357 *event_len += *r_event_len;
358 }
359 (
360 EventHint::InsertList { len, pos: _ },
361 EventHint::InsertList { len: r_len, pos: _ },
362 ) => *len += *r_len,
363 (EventHint::DeleteList(l), EventHint::DeleteList(r)) => l.merge(r, &()),
364 (
365 EventHint::DeleteText { span, unicode_len },
366 EventHint::DeleteText {
367 span: r_span,
368 unicode_len: r_len,
369 },
370 ) => {
371 *unicode_len += *r_len;
372 span.merge(r_span, &());
373 }
374 _ => unreachable!(),
375 }
376 }
377
378 fn merge_left(&mut self, _: &Self) {
379 unreachable!()
380 }
381}
382
383impl Transaction {
384 #[inline]
385 pub fn new(doc: Arc<LoroDocInner>) -> LoroResult<Self> {
386 Self::new_with_origin(doc.clone(), "".into())
387 }
388
389 pub fn new_with_origin(doc: Arc<LoroDocInner>, origin: InternalString) -> LoroResult<Self> {
390 let oplog_lock = doc.oplog.lock();
391 let mut state_lock = doc.state.lock();
392 if state_lock.is_in_txn() {
393 return Err(LoroError::DuplicatedTransactionError);
394 }
395
396 state_lock.start_txn(origin, crate::event::EventTriggerKind::Local);
397 let arena = state_lock.arena.clone();
398 let frontiers = state_lock.frontiers.clone();
399 let peer = state_lock.peer.load(std::sync::atomic::Ordering::Relaxed);
400 let next_counter = oplog_lock.next_id(peer).counter;
401 let next_lamport = oplog_lock.dag.frontiers_to_next_lamport(&frontiers);
402 let dag_frontiers_at_start = oplog_lock.dag.frontiers().clone();
403 let latest_timestamp = oplog_lock.get_greatest_timestamp(&frontiers);
404 if let Err(err) =
405 oplog_lock.check_change_greater_than_last_peer_id(peer, next_counter, &frontiers)
406 {
407 state_lock.abort_txn();
408 return Err(err);
409 }
410 drop(state_lock);
411 drop(oplog_lock);
412 Ok(Self {
413 peer,
414 doc: Arc::downgrade(&doc),
415 arena,
416 frontiers,
417 timestamp: None,
418 next_counter,
419 next_lamport,
420 origin: Default::default(),
421 start_counter: next_counter,
422 start_lamport: next_lamport,
423 event_hints: Default::default(),
424 local_ops: RleVec::new(),
425 finished: false,
426 on_commit: None,
427 msg: None,
428 latest_timestamp,
429 is_peer_first_appearance: false,
430 dag_frontiers_at_start,
431 rollback_scope: None,
432 })
433 }
434
435 pub fn set_origin(&mut self, origin: InternalString) {
436 self.origin = origin;
437 }
438
439 pub fn set_timestamp(&mut self, time: Timestamp) {
440 self.timestamp = Some(time);
441 }
442
443 pub fn set_msg(&mut self, msg: Option<Arc<str>>) {
444 self.msg = msg;
445 }
446
447 pub fn local_ops(&self) -> &RleVec<[Op; 1]> {
448 &self.local_ops
449 }
450
451 pub fn peer(&self) -> &PeerID {
452 &self.peer
453 }
454
455 pub fn timestamp(&self) -> &Option<Timestamp> {
456 &self.timestamp
457 }
458
459 pub fn frontiers(&self) -> &Frontiers {
460 &self.frontiers
461 }
462 pub fn msg(&self) -> &Option<Arc<str>> {
463 &self.msg
464 }
465
466 pub fn lamport(&self) -> &Lamport {
467 &self.start_lamport
468 }
469
470 pub(crate) fn set_on_commit(&mut self, f: OnCommitFn) {
471 self.on_commit = Some(f);
472 }
473
474 pub(crate) fn take_on_commit(&mut self) -> Option<OnCommitFn> {
475 self.on_commit.take()
476 }
477
478 pub fn commit(mut self) -> Result<Option<CommitOptions>, LoroError> {
479 let mut panic = DeferredPanic::default();
480 let ans = self._commit(&mut panic);
481 panic.resume();
482 ans
483 }
484
485 /// [`Self::commit`] for a caller that holds the doc's txn lock: a panic of a
486 /// pre-commit callback is put in `panic`, to be raised after the lock is
487 /// released.
488 pub(crate) fn commit_deferring_panic(
489 mut self,
490 panic: &mut DeferredPanic,
491 ) -> Result<Option<CommitOptions>, LoroError> {
492 self._commit(panic)
493 }
494
495 /// A pre-commit callback that panics is user code panicking in the middle
496 /// of a commit: the change is already applied to the state and the op log
497 /// holds it as uncommitted. The commit is finished as if the callback had
498 /// returned, and its panic is put in `panic` to be raised once no doc lock
499 /// is held.
500 #[tracing::instrument(level = "debug", skip(self, panic))]
501 fn _commit(&mut self, panic: &mut DeferredPanic) -> Result<Option<CommitOptions>, LoroError> {
502 if self.finished {
503 return Ok(None);
504 }
505
506 let Some(doc) = self.doc.upgrade() else {
507 return Ok(None);
508 };
509 self.finished = true;
510 if self.local_ops.is_empty() {
511 let mut state = doc.state.lock();
512 state.abort_txn();
513 return Ok(Some(self.take_options()));
514 }
515
516 let ops = std::mem::take(&mut self.local_ops);
517 let deps = take(&mut self.frontiers);
518 let change = Change {
519 lamport: self.start_lamport,
520 ops,
521 deps,
522 id: ID::new(self.peer, self.start_counter),
523 timestamp: self.latest_timestamp.max(
524 self.timestamp
525 .unwrap_or_else(|| doc.oplog.lock().get_timestamp_for_next_txn()),
526 ),
527 commit_msg: take(&mut self.msg),
528 };
529
530 let change_meta = ChangeMeta::from_change(&change);
531 {
532 // add change to uncommit field of oplog
533 let mut oplog = doc.oplog.lock();
534 oplog.set_uncommitted_change(change);
535 }
536
537 let modifier = ChangeModifier::default();
538 panic.run(|| {
539 doc.pre_commit_subs.emit(
540 &(),
541 PreCommitCallbackPayload {
542 change_meta,
543 origin: self.origin.to_string(),
544 modifier: modifier.clone(),
545 },
546 )
547 });
548
549 let mut oplog = doc.oplog.lock();
550 let mut state = doc.state.lock();
551
552 let Some(mut change) = oplog.uncommitted_change.take() else {
553 state.abort_txn();
554 drop(state);
555 drop(oplog);
556 return Err(LoroError::internal(
557 "missing uncommitted change while committing transaction",
558 ));
559 };
560 modifier.modify_change(&mut change);
561 let diff = if state.is_recording() {
562 Some(change_to_diff(
563 &change,
564 doc.clone(),
565 std::mem::take(&mut self.event_hints),
566 ))
567 } else {
568 None
569 };
570
571 let last_id = change.id_last();
572 if let Err(err) = oplog.import_local_change(change) {
573 state.abort_txn();
574 drop(state);
575 drop(oplog);
576 return Err(err);
577 }
578
579 state.commit_txn(
580 Frontiers::from_id(last_id),
581 diff.map(|arr| InternalDocDiff {
582 by: crate::event::EventTriggerKind::Local,
583 origin: self.origin.clone(),
584 diff: Cow::Owned(
585 arr.into_iter()
586 .map(|x| InternalContainerDiff {
587 idx: x.idx,
588 bring_back: false,
589 diff: (x.diff.into()),
590 diff_mode: crate::diff_calc::DiffMode::Linear,
591 kept: None,
592 })
593 .collect(),
594 ),
595 new_version: Cow::Borrowed(oplog.frontiers()),
596 }),
597 );
598 drop(state);
599 drop(oplog);
600 if let Some(on_commit) = self.on_commit.take() {
601 assert!(!doc.txn.is_locked());
602 on_commit(&doc.state.clone(), &doc.oplog.clone(), self.id_span());
603 }
604 Ok(None)
605 }
606
607 /// Mark the start of a batch that `LoroDoc` rolls back if it fails
608 /// ([`Self::roll_back_scope`]). The txn may already hold ops; they are kept.
609 pub(crate) fn begin_rollback_scope(&mut self, id: u64) {
610 debug_assert!(self.rollback_scope.is_none());
611 self.rollback_scope = Some(RollbackScope {
612 id,
613 thread: current_thread_mark(),
614 foreign_ops: false,
615 counter: self.next_counter,
616 lamport: self.next_lamport,
617 is_peer_first_appearance: self.is_peer_first_appearance,
618 event_hints: FxHashMap::default(),
619 });
620 }
621
622 pub(crate) fn has_rollback_scope(&self) -> bool {
623 self.rollback_scope.is_some()
624 }
625
626 pub(crate) fn end_rollback_scope(&mut self, id: u64) {
627 if self.rollback_scope.as_ref().is_some_and(|s| s.id == id) {
628 self.rollback_scope = None;
629 }
630 }
631
632 /// Whether this is the txn scope `id` began in and every op in it came from
633 /// the thread that began it.
634 pub(crate) fn rollback_scope_is_intact(&self, id: u64) -> bool {
635 self.rollback_scope
636 .as_ref()
637 .is_some_and(|s| s.id == id && !s.foreign_ops)
638 }
639
640 /// Take the ops of scope `id` (which must be intact) out of the txn: it
641 /// keeps its ops from before the scope, and its counters and event hints are
642 /// as they were then. The ops stay applied to the state and the DAG's
643 /// version; the caller undoes them.
644 pub(crate) fn roll_back_scope(&mut self, id: u64) -> RolledBackBatch {
645 assert!(self.rollback_scope_is_intact(id));
646 let scope = self.rollback_scope.take().unwrap();
647 let ops = take(&mut self.local_ops);
648 for op in ops.iter() {
649 let end = op.counter + op.atom_len() as Counter;
650 if end <= scope.counter {
651 self.local_ops.push(op.clone());
652 } else if op.counter < scope.counter {
653 self.local_ops
654 .push(op.slice(0, (scope.counter - op.counter) as usize));
655 }
656 }
657 for (container, (len, last)) in scope.event_hints {
658 if len == 0 {
659 self.event_hints.remove(&container);
660 continue;
661 }
662 let hints = self.event_hints.get_mut(&container).unwrap();
663 hints.truncate(len);
664 *hints.last_mut().unwrap() = last.unwrap();
665 }
666 let batch_end = self.next_counter;
667 self.next_counter = scope.counter;
668 self.next_lamport = scope.lamport;
669 self.is_peer_first_appearance = scope.is_peer_first_appearance;
670 RolledBackBatch {
671 peer: self.peer,
672 txn_start_counter: self.start_counter,
673 txn_start_lamport: self.start_lamport,
674 deps: self.frontiers.clone(),
675 dag_frontiers_at_start: self.dag_frontiers_at_start.clone(),
676 batch_start: scope.counter,
677 batch_end,
678 ops,
679 timestamp: self.latest_timestamp,
680 }
681 }
682
683 fn take_options(&self) -> CommitOptions {
684 let mut options = CommitOptions::new();
685 if !self.origin.is_empty() {
686 options = options.origin(self.origin.as_str());
687 }
688 if let Some(msg) = self.msg.as_ref() {
689 options = options.commit_msg(msg);
690 }
691 if let Some(timestamp) = self.timestamp {
692 options = options.timestamp(timestamp);
693 }
694 options
695 }
696
697 pub(super) fn apply_local_op(
698 &mut self,
699 container: ContainerIdx,
700 content: RawOpContent,
701 event: EventHint,
702 // check whether context and txn are referring to the same state context
703 doc: &LoroDoc,
704 ) -> LoroResult<()> {
705 // A transaction must be applied to the document it was created for.
706 // `insert_with_txn`/`delete_with_txn` are public API, so this guards
707 // against misuse (passing one doc's txn to another doc's handler), which
708 // would otherwise stamp the target doc's state/oplog with the wrong
709 // peer+counter. Compare doc identity via the `Weak` pointer (no atomic
710 // upgrade) on the hot path; only upgrade to fill in the error on the
711 // rare mismatch.
712 if self.doc.as_ptr() != Arc::as_ptr(&doc.inner) {
713 let found = doc
714 .state
715 .lock()
716 .peer
717 .load(std::sync::atomic::Ordering::Relaxed);
718 let expected = self
719 .doc
720 .upgrade()
721 .map(|d| {
722 d.state
723 .lock()
724 .peer
725 .load(std::sync::atomic::Ordering::Relaxed)
726 })
727 .unwrap_or(found);
728 return Err(LoroError::UnmatchedContext { expected, found });
729 }
730
731 if let Some(scope) = &mut self.rollback_scope {
732 if scope.thread != current_thread_mark() {
733 scope.foreign_ops = true;
734 }
735 }
736
737 let len = content.content_len();
738 assert!(len > 0);
739 let raw_op = RawOp {
740 id: ID {
741 peer: self.peer,
742 counter: self.next_counter,
743 },
744 lamport: self.next_lamport,
745 container,
746 content,
747 };
748
749 let mut oplog = doc.oplog.lock();
750 let mut state = doc.state.lock();
751 if state.is_deleted(container) {
752 return Err(LoroError::ContainerDeleted {
753 container: Box::new(state.arena.idx_to_id(container).unwrap()),
754 });
755 }
756
757 let op = self.arena.convert_raw_op(&raw_op);
758 state.apply_local_op(&raw_op, &op)?;
759 {
760 if !self.is_peer_first_appearance && !oplog.dag.latest_vv_contains_peer(self.peer) {
761 self.is_peer_first_appearance = true;
762 }
763 // update version info
764 let dep_id = Frontiers::from_id(ID::new(self.peer, self.next_counter - 1));
765 let start_id = ID::new(self.peer, self.next_counter);
766 self.next_counter += len as Counter;
767 oplog.dag.update_version_on_new_local_op(
768 if self.local_ops.is_empty() {
769 &self.frontiers
770 } else {
771 &dep_id
772 },
773 start_id,
774 self.next_lamport,
775 len,
776 );
777 // Local ops are always visible; bump the cached count incrementally
778 // instead of recomputing it from the version vectors every op.
779 oplog.inc_visible_op_count(len);
780 self.next_lamport += len as Lamport;
781 // set frontiers to the last op id
782 let last_id = start_id.inc(len as Counter - 1);
783 state.frontiers = Frontiers::from_id(last_id);
784 };
785 drop(state);
786 drop(oplog);
787 debug_assert_eq!(
788 event.rle_len(),
789 op.atom_len(),
790 "event:{:#?} \nop:{:#?}",
791 &event,
792 &op
793 );
794
795 let container_hints = self.event_hints.entry(container).or_default();
796 if let Some(scope) = &mut self.rollback_scope {
797 scope
798 .event_hints
799 .entry(container)
800 .or_insert_with(|| (container_hints.len(), container_hints.last().cloned()));
801 }
802
803 match container_hints.last_mut() {
804 Some(last) if last.can_merge(&event) => {
805 last.merge_right(&event);
806 }
807 _ => {
808 container_hints.push(event);
809 }
810 }
811 self.local_ops.push(op);
812 Ok(())
813 }
814
815 /// id can be a str, ContainerID, or ContainerIdRaw.
816 /// if it's str it will use Root container, which will not be None
817 pub fn get_text<I: IntoContainerId>(&self, id: I) -> TextHandler {
818 let id = id.into_container_id(&self.arena, ContainerType::Text);
819 Handler::new_attached(id, LoroDoc::from_inner(self.doc.upgrade().unwrap()))
820 .into_text()
821 .unwrap()
822 }
823
824 /// id can be a str, ContainerID, or ContainerIdRaw.
825 /// if it's str it will use Root container, which will not be None
826 pub fn get_list<I: IntoContainerId>(&self, id: I) -> ListHandler {
827 let id = id.into_container_id(&self.arena, ContainerType::List);
828 Handler::new_attached(id, LoroDoc::from_inner(self.doc.upgrade().unwrap()))
829 .into_list()
830 .unwrap()
831 }
832
833 /// id can be a str, ContainerID, or ContainerIdRaw.
834 /// if it's str it will use Root container, which will not be None
835 pub fn get_map<I: IntoContainerId>(&self, id: I) -> MapHandler {
836 let id = id.into_container_id(&self.arena, ContainerType::Map);
837 Handler::new_attached(id, LoroDoc::from_inner(self.doc.upgrade().unwrap()))
838 .into_map()
839 .unwrap()
840 }
841
842 /// id can be a str, ContainerID, or ContainerIdRaw.
843 /// if it's str it will use Root container, which will not be None
844 pub fn get_tree<I: IntoContainerId>(&self, id: I) -> TreeHandler {
845 let id = id.into_container_id(&self.arena, ContainerType::Tree);
846 Handler::new_attached(id, LoroDoc::from_inner(self.doc.upgrade().unwrap()))
847 .into_tree()
848 .unwrap()
849 }
850 pub fn next_id(&self) -> ID {
851 ID {
852 peer: self.peer,
853 counter: self.next_counter,
854 }
855 }
856
857 #[inline]
858 pub fn id_span(&self) -> IdSpan {
859 IdSpan::new(self.peer, self.start_counter, self.next_counter)
860 }
861
862 pub fn next_idlp(&self) -> IdLp {
863 IdLp {
864 peer: self.peer,
865 lamport: self.next_lamport,
866 }
867 }
868
869 pub fn is_empty(&self) -> bool {
870 self.local_ops.is_empty()
871 }
872
873 pub(crate) fn len(&self) -> usize {
874 (self.next_counter - self.start_counter) as usize
875 }
876
877 pub(crate) fn set_options(&mut self, options: CommitOptions) {
878 self.origin = options.origin.unwrap_or_default();
879 self.msg = options.commit_msg;
880 self.timestamp = options.timestamp;
881 }
882
883 pub(crate) fn set_default_options(&mut self, default_options: crate::loro::CommitOptions) {
884 if self.origin.is_empty() {
885 self.origin = default_options.origin.unwrap_or_default();
886 }
887 if self.msg.is_none() {
888 self.msg = default_options.commit_msg;
889 }
890 if self.timestamp.is_none() {
891 self.timestamp = default_options.timestamp;
892 }
893 }
894}
895
896impl Drop for Transaction {
897 #[tracing::instrument(level = "debug", skip(self))]
898 fn drop(&mut self) {
899 if !self.finished {
900 // TODO: should we abort here or commit here?
901 // what if commit fails?
902 let mut panic = DeferredPanic::default();
903 let ans = self._commit(&mut panic);
904 // Raising it while already unwinding would abort the process.
905 if !std::thread::panicking() {
906 panic.resume();
907 }
908 ans.unwrap();
909 }
910 }
911}
912
913#[derive(Debug, Clone)]
914pub(crate) struct TxnContainerDiff {
915 pub(crate) idx: ContainerIdx,
916 pub(crate) diff: Diff,
917}
918
919// PERF: could be compacter
920fn change_to_diff(
921 change: &Change,
922 doc: Arc<LoroDocInner>,
923 event_hints: FxHashMap<ContainerIdx, Vec<EventHint>>,
924) -> Vec<TxnContainerDiff> {
925 let mut ans: Vec<TxnContainerDiff> = Vec::with_capacity(change.ops.len());
926 let peer = change.id.peer;
927 let mut lamport = change.lamport;
928
929 // Group ops by container first to match our new structure
930 let mut ops_by_container: FxHashMap<ContainerIdx, Vec<Op>> = FxHashMap::default();
931 for op in change.ops.iter() {
932 ops_by_container
933 .entry(op.container)
934 .or_default()
935 .push(op.clone());
936 }
937
938 // Process each container's hints and ops together
939 for (container_idx, hints) in event_hints {
940 let Some(container_ops) = ops_by_container.get_mut(&container_idx) else {
941 continue;
942 };
943
944 let mut op_index = 0;
945 let mut hint_iter = hints.into_iter();
946 let mut current_hint = hint_iter.next();
947
948 while op_index < container_ops.len() {
949 let Some(hint) = current_hint.take() else {
950 unreachable!("Missing hint for op");
951 };
952
953 // Collect the ops that belong to this hint. Ops and hints merge by
954 // different rules (text delete hints use UTF-16 spans in WASM), so a
955 // hint can cover several ops and an op can cover several hints.
956 let mut ops_for_hint: SmallVec<[Op; 1]> = SmallVec::new();
957 let mut total_len = 0;
958 while total_len < hint.rle_len() {
959 let Some(op) = container_ops.get_mut(op_index) else {
960 unreachable!("Op/hint length mismatch: {hint:?}");
961 };
962 let op_len = op.atom_len();
963 let needed = hint.rle_len() - total_len;
964 if op_len > needed {
965 ops_for_hint.push(op.slice(0, needed));
966 *op = op.slice(needed, op_len);
967 total_len += needed;
968 } else {
969 total_len += op_len;
970 ops_for_hint.push(op.clone());
971 op_index += 1;
972 }
973 }
974
975 debug_assert!(
976 ops_for_hint.iter().all(|op| op_matches_hint(op, &hint)),
977 "Op/hint kind mismatch: {hint:?} {ops_for_hint:?}"
978 );
979
980 // Move to next hint
981 current_hint = hint_iter.next();
982
983 // Generate diff based on hint type
984 match hint {
985 EventHint::Mark { start, end, style } => {
986 let mut meta = StyleMeta::default();
987 meta.insert(
988 style.key.clone(),
989 StyleMetaItem {
990 lamport,
991 peer: change.id.peer,
992 value: style.data,
993 },
994 );
995 let diff = DeltaRopeBuilder::new()
996 .retain(start as usize, Default::default())
997 .retain(
998 (end - start) as usize,
999 meta.to_option_map().unwrap_or_default().into(),
1000 )
1001 .build();
1002 ans.push(TxnContainerDiff {
1003 idx: container_idx,
1004 diff: Diff::Text(diff),
1005 });
1006 }
1007 EventHint::InsertText { styles, pos, .. } => {
1008 let mut delta: TextDiff = DeltaRopeBuilder::new()
1009 .retain(pos as usize, Default::default())
1010 .build();
1011 for op in ops_for_hint.iter() {
1012 let InnerListOp::InsertText { slice, .. } = op.content.as_list().unwrap()
1013 else {
1014 unreachable!()
1015 };
1016
1017 delta.push_insert(
1018 slice.clone().into(),
1019 styles.to_option_map().unwrap_or_default().into(),
1020 );
1021 }
1022 ans.push(TxnContainerDiff {
1023 idx: container_idx,
1024 diff: Diff::Text(delta),
1025 })
1026 }
1027 EventHint::DeleteText {
1028 span,
1029 unicode_len: _,
1030 // we don't need to iter over ops here, because we already
1031 // know what the events should be
1032 } => ans.push(TxnContainerDiff {
1033 idx: container_idx,
1034 diff: Diff::Text(
1035 DeltaRopeBuilder::new()
1036 .retain(span.start() as usize, Default::default())
1037 .delete(span.len())
1038 .build(),
1039 ),
1040 }),
1041 EventHint::InsertList { pos, .. } => {
1042 // We should use pos from event hint because index in op may
1043 // be using op index for the MovableList
1044 let mut index = pos;
1045 for op in ops_for_hint.iter() {
1046 let (range, _) = op.content.as_list().unwrap().as_insert().unwrap();
1047 let values = range
1048 .as_slice()
1049 .iter()
1050 .map(|v| ValueOrHandler::from_value(v.clone(), &doc));
1051 let len = values.len();
1052 ans.push(TxnContainerDiff {
1053 idx: container_idx,
1054 diff: Diff::List(
1055 DeltaRopeBuilder::new()
1056 .retain(index, Default::default())
1057 .insert_many(values, Default::default())
1058 .build(),
1059 ),
1060 });
1061 index += len;
1062 }
1063 }
1064 EventHint::DeleteList(s) => {
1065 ans.push(TxnContainerDiff {
1066 idx: container_idx,
1067 diff: Diff::List(
1068 DeltaRopeBuilder::new()
1069 .retain(s.start() as usize, Default::default())
1070 .delete(s.len())
1071 .build(),
1072 ),
1073 });
1074 }
1075 EventHint::Map { key, value } => {
1076 // Mirror `MapState::apply_diff_and_convert`: a marker write surfaces to
1077 // subscribers as the deterministic Container, not the raw binary value.
1078 let parent_id = doc.arena.idx_to_id(container_idx);
1079 let value = value.map(|v| match parent_id.as_ref() {
1080 Some(pid) => {
1081 loro_common::translate_mergeable_marker_value(pid, key.as_ref(), v)
1082 }
1083 None => v,
1084 });
1085 ans.push(TxnContainerDiff {
1086 idx: container_idx,
1087 diff: Diff::Map(ResolvedMapDelta::new().with_entry(
1088 key,
1089 ResolvedMapValue {
1090 value: value.map(|v| ValueOrHandler::from_value(v, &doc)),
1091 idlp: IdLp::new(peer, lamport),
1092 },
1093 )),
1094 });
1095 }
1096 EventHint::Tree(tree_diff) => {
1097 let mut diff = TreeDiff::default();
1098 diff.diff.extend(tree_diff);
1099 ans.push(TxnContainerDiff {
1100 idx: container_idx,
1101 diff: Diff::Tree(diff),
1102 });
1103 }
1104 EventHint::Move { from, to, value } => {
1105 let mut a = DeltaRopeBuilder::new()
1106 .retain(from as usize, Default::default())
1107 .delete(1)
1108 .build();
1109 a.compose(
1110 &DeltaRopeBuilder::new()
1111 .retain(to as usize, Default::default())
1112 .insert(
1113 ArrayVec::from([ValueOrHandler::from_value(value, &doc)]),
1114 ListDeltaMeta { from_move: true },
1115 )
1116 .build(),
1117 );
1118 ans.push(TxnContainerDiff {
1119 idx: container_idx,
1120 diff: Diff::List(a),
1121 });
1122 }
1123 EventHint::SetList { index, value } => {
1124 ans.push(TxnContainerDiff {
1125 idx: container_idx,
1126 diff: Diff::List(
1127 DeltaRopeBuilder::new()
1128 .retain(index, Default::default())
1129 .delete(1)
1130 .insert(
1131 ArrayVec::from([ValueOrHandler::from_value(value, &doc)]),
1132 Default::default(),
1133 )
1134 .build(),
1135 ),
1136 });
1137 }
1138 EventHint::MarkEnd => {
1139 // do nothing
1140 }
1141 #[cfg(feature = "counter")]
1142 EventHint::Counter(diff) => {
1143 ans.push(TxnContainerDiff {
1144 idx: container_idx,
1145 diff: Diff::Counter(diff),
1146 });
1147 }
1148 }
1149
1150 // Update lamport for this hint's operations
1151 lamport += ops_for_hint
1152 .iter()
1153 .map(|x| x.content_len() as Lamport)
1154 .sum::<Lamport>();
1155 }
1156
1157 debug_assert!(
1158 current_hint.is_none(),
1159 "Unused event hint: {current_hint:?}"
1160 );
1161 }
1162
1163 ans
1164}
1165
1166/// Whether `op` is the kind of op `hint` was recorded for.
1167fn op_matches_hint(op: &Op, hint: &EventHint) -> bool {
1168 match &op.content {
1169 InnerContent::List(list_op) => matches!(
1170 (list_op, hint),
1171 (InnerListOp::StyleStart { .. }, EventHint::Mark { .. })
1172 | (InnerListOp::StyleEnd, EventHint::MarkEnd)
1173 | (InnerListOp::InsertText { .. }, EventHint::InsertText { .. })
1174 | (
1175 InnerListOp::Delete(_),
1176 EventHint::DeleteText { .. } | EventHint::DeleteList(_)
1177 )
1178 | (InnerListOp::Insert { .. }, EventHint::InsertList { .. })
1179 | (InnerListOp::Move { .. }, EventHint::Move { .. })
1180 | (InnerListOp::Set { .. }, EventHint::SetList { .. })
1181 ),
1182 InnerContent::Map(_) => matches!(hint, EventHint::Map { .. }),
1183 InnerContent::Tree(_) => matches!(hint, EventHint::Tree(_)),
1184 #[cfg(feature = "counter")]
1185 InnerContent::Future(crate::op::FutureInnerContent::Counter(_)) => {
1186 matches!(hint, EventHint::Counter(_))
1187 }
1188 InnerContent::Future(_) => false,
1189 }
1190}
1191
1192#[cfg(test)]
1193mod tests {
1194 use super::*;
1195 use crate::{cursor::PosType, version::Frontiers};
1196
1197 #[test]
1198 fn txn_creation_rolls_back_in_txn_after_peer_conflict() {
1199 let doc = LoroDoc::new();
1200 doc.set_detached_editing(true);
1201 doc.set_peer_id(7).unwrap();
1202
1203 let text = doc.get_text("text");
1204 let mut txn = doc.txn().unwrap();
1205 text.insert_with_txn(&mut txn, 0, "a", PosType::Unicode)
1206 .unwrap();
1207 txn.commit().unwrap();
1208
1209 doc.checkout(&Frontiers::default()).unwrap();
1210 doc.set_peer_id(7).unwrap();
1211
1212 let err = doc
1213 .txn()
1214 .expect_err("stale detached frontiers should reject reusing the same peer");
1215 assert!(matches!(
1216 err,
1217 LoroError::ConcurrentOpsWithSamePeerID { peer: 7, .. }
1218 ));
1219 assert!(!doc.app_state().lock().is_in_txn());
1220 }
1221}