forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

event.rs573 lines, 17.7 KiBHistoryRawDownload
1use enum_as_inner::EnumAsInner;
2use itertools::Itertools;
3use loro_delta::{array_vec::ArrayVec, delta_trait::DeltaAttr, DeltaItem, DeltaRope};
4use rustc_hash::FxHashMap;
5use serde::{Deserialize, Serialize};
6use smallvec::SmallVec;
7
8use crate::{
9 container::richtext::richtext_state::RichtextStateChunk,
10 delta::{Delta, MapDelta, Meta, MovableListInnerDelta, ResolvedMapDelta, TreeDelta, TreeDiff},
11 diff_calc::DiffMode,
12 handler::ValueOrHandler,
13 op::SliceWithId,
14 utils::string_slice::StringSlice,
15 InternalString,
16};
17
18use std::{borrow::Cow, hash::Hash};
19
20use loro_common::{ContainerID, LoroValue, TreeID};
21
22use crate::{container::idx::ContainerIdx, version::Frontiers};
23
24#[derive(Debug, Clone)]
25pub struct ContainerDiff {
26 pub id: ContainerID,
27 pub path: Vec<(ContainerID, Index)>,
28 pub(crate) idx: ContainerIdx,
29 pub is_unknown: bool,
30 pub diff: Diff,
31 /// Set when `diff` is a full-state revival of a container that kept its id and state.
32 pub(crate) kept: Option<KeptChange>,
33}
34
35impl ContainerDiff {
36 /// The container's actual change in this event, which differs from `diff` when `diff` is
37 /// a full-state revival of a container that kept its state. `None` means unchanged.
38 pub(crate) fn change(&self) -> Option<&Diff> {
39 match &self.kept {
40 None => Some(&self.diff),
41 Some(KeptChange::Unchanged) => None,
42 Some(KeptChange::Changed(d)) => Some(d),
43 }
44 }
45}
46
47/// Events and [`crate::undo::DiffBatch`]es describe a container that becomes visible with its
48/// full state, which is what a consumer that never saw it needs. A re-activated mergeable child
49/// (and every container it holds) keeps its id and its hidden state, so its actual change is
50/// recorded next to the full state. Undo, revert and the undo manager's transforms use it.
51/// See context/mergeable-containers.md.
52#[derive(Debug, Clone)]
53pub(crate) enum KeptChange {
54 Unchanged,
55 Changed(Diff),
56}
57
58impl KeptChange {
59 pub(crate) fn from_diff(diff: Diff) -> Self {
60 if diff.is_empty() {
61 KeptChange::Unchanged
62 } else {
63 KeptChange::Changed(diff)
64 }
65 }
66
67 /// `self` followed by `next`.
68 pub(crate) fn then(self, next: KeptChange) -> Self {
69 match (self, next) {
70 (KeptChange::Unchanged, x) | (x, KeptChange::Unchanged) => x,
71 (KeptChange::Changed(a), KeptChange::Changed(b)) => {
72 KeptChange::Changed(a.compose(b).unwrap())
73 }
74 }
75 }
76}
77
78/// The kind of the event trigger.
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
80pub enum EventTriggerKind {
81 /// The event is triggered by a local transaction.
82 Local,
83 /// The event is triggered by importing
84 Import,
85 /// The event is triggered by checkout
86 Checkout,
87}
88
89impl std::fmt::Display for EventTriggerKind {
90 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91 match self {
92 EventTriggerKind::Local => write!(f, "local"),
93 EventTriggerKind::Import => write!(f, "import"),
94 EventTriggerKind::Checkout => write!(f, "checkout"),
95 }
96 }
97}
98
99impl EventTriggerKind {
100 #[inline]
101 pub fn is_local(&self) -> bool {
102 matches!(self, EventTriggerKind::Local)
103 }
104
105 #[inline]
106 pub fn is_import(&self) -> bool {
107 matches!(self, EventTriggerKind::Import)
108 }
109
110 #[inline]
111 pub fn is_checkout(&self) -> bool {
112 matches!(self, EventTriggerKind::Checkout)
113 }
114}
115
116#[derive(Debug, Clone)]
117pub struct DiffEvent<'a> {
118 /// The receiver of the event.
119 pub current_target: Option<ContainerID>,
120 /// A list of events that should be received by the current target.
121 pub events: &'a [&'a ContainerDiff],
122 pub event_meta: &'a DocDiff,
123}
124
125/// It's the exposed event type.
126/// It's exposed to the user. The user can use this to apply the diff to their local state.
127///
128/// [DocDiff] may include the diff that calculated from several transactions and imports.
129/// They all should have the same origin and local flag.
130#[derive(Debug, Clone)]
131pub struct DocDiff {
132 pub from: Frontiers,
133 pub to: Frontiers,
134 pub origin: InternalString,
135 pub by: EventTriggerKind,
136 pub diff: Vec<ContainerDiff>,
137}
138
139#[derive(Debug, Clone)]
140pub(crate) struct InternalContainerDiff {
141 pub(crate) idx: ContainerIdx,
142 /// Indicates whether this event was generated by a container that has been resurrected during a checkout operation.
143 pub(crate) bring_back: bool,
144 pub(crate) diff: DiffVariant,
145 /// This mode decides how should we apply the diff.
146 pub(crate) diff_mode: DiffMode,
147 /// See [`ContainerDiff::kept`].
148 pub(crate) kept: Option<KeptChange>,
149}
150
151#[derive(Default, Debug, Clone, EnumAsInner)]
152pub(crate) enum DiffVariant {
153 #[default]
154 None,
155 Internal(InternalDiff),
156 External(Diff),
157}
158
159/// It's used for transmitting and recording the diff internally.
160///
161/// It can be convert into a [DocDiff].
162// Internally, we need to batch the diff then calculate the event. Because
163// we need to sort the diff by containers' created time, to make sure the
164// the path to each container is up-to-date.
165#[derive(Debug, Clone)]
166pub(crate) struct InternalDocDiff<'a> {
167 pub(crate) origin: InternalString,
168 pub(crate) by: EventTriggerKind,
169 /// The values inside this array is in random order
170 pub(crate) diff: Cow<'a, [InternalContainerDiff]>,
171 pub(crate) new_version: Cow<'a, Frontiers>,
172}
173
174impl InternalDocDiff<'_> {
175 pub fn into_owned(self) -> InternalDocDiff<'static> {
176 InternalDocDiff {
177 origin: self.origin,
178 by: self.by,
179 diff: Cow::Owned((*self.diff).to_owned()),
180 new_version: Cow::Owned((*self.new_version).to_owned()),
181 }
182 }
183
184 pub fn can_merge(&self, other: &Self) -> bool {
185 self.by == other.by
186 }
187}
188
189pub type Path = SmallVec<[Index; 4]>;
190
191#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, enum_as_inner::EnumAsInner)]
192pub enum Index {
193 Key(InternalString),
194 Seq(usize),
195 Node(TreeID),
196}
197
198impl std::fmt::Debug for Index {
199 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200 match self {
201 Self::Key(arg0) => write!(f, "Index::Key(\"{}\")", arg0),
202 Self::Seq(arg0) => write!(f, "Index::Seq({})", arg0),
203 Self::Node(arg0) => write!(f, "Index::Node({})", arg0),
204 }
205 }
206}
207
208impl std::fmt::Display for Index {
209 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
210 match self {
211 Index::Key(key) => write!(f, "{}", key),
212 Index::Seq(s) => write!(f, "{}", s),
213 Index::Node(id) => write!(f, "{}@{}", id.peer, id.counter),
214 }
215 }
216}
217
218impl From<usize> for Index {
219 fn from(s: usize) -> Self {
220 Index::Seq(s)
221 }
222}
223
224impl TryFrom<&str> for Index {
225 type Error = &'static str;
226 fn try_from(s: &str) -> Result<Self, &'static str> {
227 if s.is_empty() {
228 return Ok(Index::Key(InternalString::default()));
229 }
230
231 let c = s.chars().next().unwrap();
232 if c.is_ascii_digit() {
233 if let Ok(seq) = s.parse::<usize>() {
234 Ok(Index::Seq(seq))
235 } else if let Ok(id) = s.try_into() {
236 Ok(Index::Node(id))
237 } else {
238 Ok(Index::Key(InternalString::from(s)))
239 }
240 } else {
241 Ok(Index::Key(InternalString::from(s)))
242 }
243 }
244}
245
246impl DiffVariant {
247 pub fn compose(self, other: Self) -> Result<Self, Self> {
248 match (self, other) {
249 (DiffVariant::Internal(a), DiffVariant::Internal(b)) => {
250 Ok(DiffVariant::Internal(a.compose(b)?))
251 }
252 (DiffVariant::External(a), DiffVariant::External(b)) => {
253 Ok(DiffVariant::External(a.compose(b)?))
254 }
255 (a, _) => Err(a),
256 }
257 }
258
259 pub fn is_empty(&self) -> bool {
260 match self {
261 DiffVariant::Internal(diff) => diff.is_empty(),
262 DiffVariant::External(diff) => diff.is_empty(),
263 DiffVariant::None => true,
264 }
265 }
266}
267
268#[non_exhaustive]
269#[derive(Clone, Debug, EnumAsInner)]
270pub(crate) enum InternalDiff {
271 ListRaw(Delta<SliceWithId>),
272 /// This always uses entity indexes.
273 RichtextRaw(DeltaRope<RichtextStateChunk, ()>),
274 Map(MapDelta),
275 Tree(TreeDelta),
276 MovableList(MovableListInnerDelta),
277 #[cfg(feature = "counter")]
278 Counter(f64),
279 Unknown,
280}
281
282impl From<InternalDiff> for DiffVariant {
283 fn from(diff: InternalDiff) -> Self {
284 DiffVariant::Internal(diff)
285 }
286}
287
288#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
289pub struct ListDeltaMeta {
290 /// Whether the content of the insert is moved from
291 /// a deletion in the same delta and **the value is not changed**.
292 ///
293 /// If true, this op must be a move op under the hood.
294 /// But an insert created by a move op doesn't necessarily
295 /// have this flag, because the insert content may not
296 /// be moved from a deletion in the same delta.
297 pub from_move: bool,
298}
299
300impl Meta for ListDeltaMeta {
301 fn is_empty(&self) -> bool {
302 !self.from_move
303 }
304
305 fn compose(
306 &mut self,
307 other: &Self,
308 type_pair: (crate::delta::DeltaType, crate::delta::DeltaType),
309 ) {
310 // We can't have two Some because we don't have `move_from` for Retain.
311 // And this function is only called when composing a insert/retain with a retain.
312 if let (crate::delta::DeltaType::Insert, crate::delta::DeltaType::Insert) = type_pair {
313 unreachable!()
314 }
315
316 self.from_move = self.from_move || other.from_move;
317 }
318
319 fn is_mergeable(&self, other: &Self) -> bool {
320 self.from_move == other.from_move
321 }
322
323 fn merge(&mut self, _other: &Self) {}
324}
325
326impl DeltaAttr for ListDeltaMeta {
327 fn compose(&mut self, other: &Self) {
328 self.from_move = self.from_move || other.from_move;
329 }
330
331 fn attr_is_empty(&self) -> bool {
332 !self.from_move
333 }
334}
335
336pub type ListDiffInsertItem = ArrayVec<ValueOrHandler, 8>;
337pub type ListDiffItem = DeltaItem<ListDiffInsertItem, ListDeltaMeta>;
338pub type ListDiff = DeltaRope<ListDiffInsertItem, ListDeltaMeta>;
339
340#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
341pub struct TextMeta(pub FxHashMap<String, LoroValue>);
342
343impl From<TextMeta> for FxHashMap<String, LoroValue> {
344 fn from(value: TextMeta) -> Self {
345 value.0
346 }
347}
348
349impl From<FxHashMap<String, LoroValue>> for TextMeta {
350 fn from(value: FxHashMap<String, LoroValue>) -> Self {
351 TextMeta(value)
352 }
353}
354
355pub type TextDiffItem = DeltaItem<StringSlice, TextMeta>;
356pub type TextDiff = DeltaRope<StringSlice, TextMeta>;
357
358impl DeltaAttr for TextMeta {
359 fn compose(&mut self, other: &Self) {
360 for (key, value) in other.0.iter() {
361 self.0.insert(key.clone(), value.clone());
362 }
363 }
364
365 fn attr_is_empty(&self) -> bool {
366 self.0.is_empty()
367 }
368}
369
370/// Diff is the diff between two versions of a container.
371/// It's used to describe the change of a container and the events.
372///
373/// # Internal
374///
375/// Text index variants:
376///
377/// - When `wasm` is enabled, it should use utf16 indexes.
378/// - When `wasm` is disabled, it should use unicode indexes.
379#[non_exhaustive]
380#[derive(Clone, Debug, EnumAsInner)]
381pub enum Diff {
382 List(ListDiff),
383 /// - When feature `wasm` is enabled, it should use utf16 indexes.
384 /// - When feature `wasm` is disabled, it should use unicode indexes.
385 Text(TextDiff),
386 Map(ResolvedMapDelta),
387 Tree(TreeDiff),
388 #[cfg(feature = "counter")]
389 Counter(f64),
390 Unknown,
391}
392
393impl From<Diff> for DiffVariant {
394 fn from(diff: Diff) -> Self {
395 DiffVariant::External(diff)
396 }
397}
398
399impl InternalDiff {
400 pub(crate) fn is_empty(&self) -> bool {
401 match self {
402 InternalDiff::ListRaw(s) => s.is_empty(),
403 InternalDiff::RichtextRaw(t) => t.is_empty(),
404 InternalDiff::Map(m) => m.updated.is_empty(),
405 InternalDiff::Tree(t) => t.is_empty(),
406 InternalDiff::MovableList(t) => t.is_empty(),
407 // 0 is empty. A smaller nonzero delta such as 1e-17 is a real increment.
408 #[cfg(feature = "counter")]
409 InternalDiff::Counter(c) => *c == 0.0,
410 InternalDiff::Unknown => true,
411 }
412 }
413
414 pub(crate) fn compose(self, diff: InternalDiff) -> Result<Self, Self> {
415 // PERF: avoid clone
416 match (self, diff) {
417 (InternalDiff::ListRaw(a), InternalDiff::ListRaw(b)) => {
418 Ok(InternalDiff::ListRaw(a.compose(b)))
419 }
420 (InternalDiff::RichtextRaw(mut a), InternalDiff::RichtextRaw(b)) => {
421 a.compose(&b);
422 Ok(InternalDiff::RichtextRaw(a))
423 }
424 (InternalDiff::Map(a), InternalDiff::Map(b)) => Ok(InternalDiff::Map(a.compose(b))),
425 (InternalDiff::Tree(a), InternalDiff::Tree(b)) => Ok(InternalDiff::Tree(a.compose(b))),
426 (a, _) => Err(a),
427 }
428 }
429}
430
431impl Diff {
432 pub fn compose_ref(&mut self, diff: &Diff) {
433 match (self, diff) {
434 (Diff::List(a), Diff::List(b)) => {
435 a.compose(b);
436 }
437 (Diff::Text(a), Diff::Text(b)) => {
438 a.compose(b);
439 }
440 (Diff::Map(a), Diff::Map(b)) => {
441 // Move the accumulator out instead of cloning it, so composing
442 // a long run of fragments stays linear rather than O(n^2).
443 *a = std::mem::take(a).compose(b.clone());
444 }
445 (Diff::Tree(a), Diff::Tree(b)) => {
446 *a = std::mem::take(a).compose(b.clone());
447 }
448 #[cfg(feature = "counter")]
449 (Diff::Counter(a), Diff::Counter(b)) => *a += b,
450 // Unknown containers have no diff content
451 (Diff::Unknown, Diff::Unknown) => {}
452 (_, _) => unreachable!(),
453 }
454 }
455
456 pub fn compose(self, diff: Diff) -> Result<Self, Self> {
457 // PERF: avoid clone
458 match (self, diff) {
459 (Diff::List(mut a), Diff::List(b)) => {
460 a.compose(&b);
461 Ok(Diff::List(a))
462 }
463 (Diff::Text(mut a), Diff::Text(b)) => {
464 a.compose(&b);
465 Ok(Diff::Text(a))
466 }
467 (Diff::Map(a), Diff::Map(b)) => Ok(Diff::Map(a.compose(b))),
468
469 (Diff::Tree(a), Diff::Tree(b)) => Ok(Diff::Tree(a.compose(b))),
470 #[cfg(feature = "counter")]
471 (Diff::Counter(a), Diff::Counter(b)) => Ok(Diff::Counter(a + b)),
472 (a, _) => Err(a),
473 }
474 }
475
476 // Transform this diff based on the other diff
477 pub fn transform(&mut self, other: &Self, left_prior: bool) {
478 match (self, other) {
479 (Diff::List(a), Diff::List(b)) => a.transform_(b, left_prior),
480 (Diff::Text(a), Diff::Text(b)) => a.transform_(b, left_prior),
481 (Diff::Map(a), Diff::Map(b)) => a.transform(b, left_prior),
482 (Diff::Tree(a), Diff::Tree(b)) => a.transform(b, left_prior),
483 #[cfg(feature = "counter")]
484 (Diff::Counter(_a), Diff::Counter(_b)) => {
485 // Counter operations commute; no transformation is needed.
486 }
487 _ => {}
488 }
489 }
490
491 pub fn is_empty(&self) -> bool {
492 match self {
493 Diff::List(s) => s.is_empty(),
494 Diff::Text(t) => t.is_empty(),
495 Diff::Map(m) => m.updated.is_empty(),
496 Diff::Tree(t) => t.diff.is_empty(),
497 // Same rule as `InternalDiff`: only an exact 0 is an empty counter diff.
498 #[cfg(feature = "counter")]
499 Diff::Counter(c) => *c == 0.0,
500 Diff::Unknown => true,
501 }
502 }
503
504 #[allow(unused)]
505 pub(crate) fn concat(self, diff: Diff) -> Diff {
506 match (self, diff) {
507 (Diff::List(mut a), Diff::List(b)) => {
508 a.compose(&b);
509 Diff::List(a)
510 }
511 (Diff::Text(mut a), Diff::Text(b)) => {
512 a.compose(&b);
513 Diff::Text(a)
514 }
515 (Diff::Map(a), Diff::Map(b)) => {
516 let mut a = a;
517 for (k, v) in b.updated {
518 a = a.with_entry(k, v);
519 }
520 Diff::Map(a)
521 }
522
523 (Diff::Tree(a), Diff::Tree(b)) => Diff::Tree(a.extend(b.diff)),
524 #[cfg(feature = "counter")]
525 (Diff::Counter(a), Diff::Counter(b)) => Diff::Counter(a + b),
526 _ => unreachable!(),
527 }
528 }
529
530 /// Transform the cursor based on this diff
531 pub(crate) fn transform_cursor(&self, pos: usize, left_prior: bool) -> usize {
532 match self {
533 Diff::List(list) => list.transform_pos(pos, left_prior),
534 Diff::Text(text) => text.transform_pos(pos, left_prior),
535 _ => pos,
536 }
537 }
538}
539
540pub fn str_to_path(s: &str) -> Option<Vec<Index>> {
541 s.split('/').map(|x| x.try_into()).try_collect().ok()
542}
543
544pub fn path_to_str(path: &[Index]) -> String {
545 path.iter().map(|x| x.to_string()).join("/")
546}
547
548#[cfg(test)]
549mod test {
550 use std::sync::Arc;
551
552 use itertools::Itertools;
553 use loro_common::LoroValue;
554
555 use crate::{cursor::PosType, ApplyDiff, LoroDoc};
556
557 #[test]
558 fn test_text_event() {
559 let loro = LoroDoc::new();
560 let _g = loro.subscribe_root(Arc::new(|event| {
561 let mut value = LoroValue::String(Default::default());
562 value.apply_diff(&event.events.iter().map(|x| x.diff.clone()).collect_vec());
563 assert_eq!(value, "h223ello".into());
564 }));
565 let mut txn = loro.txn().unwrap();
566 let text = loro.get_text("id");
567 text.insert_with_txn(&mut txn, 0, "hello", PosType::Unicode)
568 .unwrap();
569 text.insert_with_txn(&mut txn, 1, "223", PosType::Unicode)
570 .unwrap();
571 txn.commit().unwrap();
572 }
573}