Skip to main content

loro_internal/
encoding.rs

1pub(crate) mod arena;
2pub(crate) mod fast_snapshot;
3pub(crate) mod json_schema;
4mod outdated_encode_reordered;
5mod shallow_snapshot;
6pub(crate) mod value;
7pub(crate) mod value_register;
8pub(crate) use outdated_encode_reordered::{
9    decode_op, encode_op, get_op_prop, EncodedDeleteStartId, IterableEncodedDeleteStartId,
10};
11use outdated_encode_reordered::{import_changes_to_oplog, ImportChangesResult};
12pub(crate) use value::OwnedValue;
13
14use crate::change::Change;
15use crate::version::{Frontiers, VersionRange};
16use crate::LoroDoc;
17use crate::{oplog::OpLog, LoroError, VersionVector};
18use loro_common::{HasIdSpan, IdSpan, InternalString, LoroEncodeError, LoroResult, ID};
19use num_traits::{FromPrimitive, ToPrimitive};
20use std::borrow::Cow;
21
22/// The mode of the export.
23///
24/// Loro CRDT internally consists of two parts: document history and current document state.
25/// The export modes offer various options to meet different requirements.
26///
27/// - CRDT property: Documents maintain consistent states when they receive the same set of updates.
28/// - In real-time collaboration, peers typically only need to synchronize updates
29///   (operations/history) to achieve consistency.
30///
31/// ## Update Export
32///
33/// - Exports only the history part, containing multiple operations.
34/// - Suitable for real-time collaboration scenarios where peers only need to synchronize updates.
35///
36/// ## Snapshot Export
37///
38/// ### Default Snapshot
39///
40/// - Includes complete history and current full state.
41///
42/// ### Shallow Snapshot
43///
44/// - Contains the complete current state.
45/// - Retains partial history starting from a specified version.
46///
47/// ### State-only Snapshot
48///
49/// - Exports the state of the target version.
50/// - Includes a minimal set of operation history.
51#[non_exhaustive]
52#[derive(Debug, Clone)]
53pub enum ExportMode<'a> {
54    /// It contains the full history and the current state of the document.
55    Snapshot,
56    /// It contains the history since the `from` version vector.
57    Updates { from: Cow<'a, VersionVector> },
58    /// This mode exports the history in the specified range.
59    UpdatesInRange { spans: Cow<'a, [IdSpan]> },
60    /// The shallow snapshot only contains the history since the target frontiers
61    ShallowSnapshot(Cow<'a, Frontiers>),
62    /// The state only snapshot exports the state of the target version
63    /// with a minimal set of history (a few ops).
64    ///
65    /// It's a shallow snapshot with depth=1 at the target version.
66    /// If the target version is None, it will use the latest version as the target version.
67    StateOnly(Option<Cow<'a, Frontiers>>),
68    /// The snapshot at the specified frontiers. It contains the full history
69    /// till the target frontiers and the state at the target frontiers.
70    SnapshotAt { version: Cow<'a, Frontiers> },
71}
72
73impl<'a> ExportMode<'a> {
74    /// It contains the full history and the current state of the document.
75    pub fn snapshot() -> Self {
76        ExportMode::Snapshot
77    }
78
79    /// It contains the history since the `from` version vector.
80    pub fn updates(from: &'a VersionVector) -> Self {
81        ExportMode::Updates {
82            from: Cow::Borrowed(from),
83        }
84    }
85
86    /// It contains the history since the `from` version vector.
87    pub fn updates_owned(from: VersionVector) -> Self {
88        ExportMode::Updates {
89            from: Cow::Owned(from),
90        }
91    }
92
93    /// It contains all the history of the document.
94    pub fn all_updates() -> Self {
95        ExportMode::Updates {
96            from: Cow::Owned(Default::default()),
97        }
98    }
99
100    /// This mode exports the history in the specified range.
101    pub fn updates_in_range(spans: impl Into<Cow<'a, [IdSpan]>>) -> Self {
102        ExportMode::UpdatesInRange {
103            spans: spans.into(),
104        }
105    }
106
107    /// The shallow snapshot only contains the history since the target frontiers.
108    pub fn shallow_snapshot(frontiers: &'a Frontiers) -> Self {
109        ExportMode::ShallowSnapshot(Cow::Borrowed(frontiers))
110    }
111
112    /// The shallow snapshot only contains the history since the target frontiers.
113    pub fn shallow_snapshot_owned(frontiers: Frontiers) -> Self {
114        ExportMode::ShallowSnapshot(Cow::Owned(frontiers))
115    }
116
117    /// The shallow snapshot only contains the history since the target frontiers.
118    pub fn shallow_snapshot_since(id: ID) -> Self {
119        let frontiers = Frontiers::from_id(id);
120        ExportMode::ShallowSnapshot(Cow::Owned(frontiers))
121    }
122
123    /// The state only snapshot exports the state of the target version
124    /// with a minimal set of history (a few ops).
125    ///
126    /// It's a shallow snapshot with depth=1 at the target version.
127    /// If the target version is None, it will use the latest version as the target version.
128    pub fn state_only(frontiers: Option<&'a Frontiers>) -> Self {
129        ExportMode::StateOnly(frontiers.map(Cow::Borrowed))
130    }
131
132    /// The snapshot at the specified frontiers. It contains the full history
133    /// till the target frontiers and the state at the target frontiers.
134    pub fn snapshot_at(frontiers: &'a Frontiers) -> Self {
135        ExportMode::SnapshotAt {
136            version: Cow::Borrowed(frontiers),
137        }
138    }
139
140    /// This mode exports the history within the specified version vector.
141    pub fn updates_till(vv: &VersionVector) -> ExportMode<'static> {
142        let mut spans = Vec::with_capacity(vv.len());
143        for (peer, counter) in vv.iter() {
144            if *counter > 0 {
145                spans.push(IdSpan::new(*peer, 0, *counter));
146            }
147        }
148
149        ExportMode::UpdatesInRange {
150            spans: Cow::Owned(spans),
151        }
152    }
153}
154
155const MAGIC_BYTES: [u8; 4] = *b"loro";
156
157#[derive(Clone, Copy, Debug, PartialEq, Eq)]
158pub(crate) enum EncodeMode {
159    // This is a config option, it won't be used in encoding.
160    Auto = 255,
161    OutdatedRle = 1,
162    OutdatedSnapshot = 2,
163    FastSnapshot = 3,
164    FastUpdates = 4,
165}
166
167impl num_traits::FromPrimitive for EncodeMode {
168    #[allow(trivial_numeric_casts)]
169    #[inline]
170    fn from_i64(n: i64) -> Option<Self> {
171        match n {
172            n if n == EncodeMode::Auto as i64 => Some(EncodeMode::Auto),
173            n if n == EncodeMode::OutdatedRle as i64 => Some(EncodeMode::OutdatedRle),
174            n if n == EncodeMode::OutdatedSnapshot as i64 => Some(EncodeMode::OutdatedSnapshot),
175            n if n == EncodeMode::FastSnapshot as i64 => Some(EncodeMode::FastSnapshot),
176            n if n == EncodeMode::FastUpdates as i64 => Some(EncodeMode::FastUpdates),
177            _ => None,
178        }
179    }
180    #[inline]
181    fn from_u64(n: u64) -> Option<Self> {
182        Self::from_i64(n as i64)
183    }
184}
185
186impl num_traits::ToPrimitive for EncodeMode {
187    #[inline]
188    #[allow(trivial_numeric_casts)]
189    fn to_i64(&self) -> Option<i64> {
190        Some(match *self {
191            EncodeMode::Auto => EncodeMode::Auto as i64,
192            EncodeMode::OutdatedRle => EncodeMode::OutdatedRle as i64,
193            EncodeMode::OutdatedSnapshot => EncodeMode::OutdatedSnapshot as i64,
194            EncodeMode::FastSnapshot => EncodeMode::FastSnapshot as i64,
195            EncodeMode::FastUpdates => EncodeMode::FastUpdates as i64,
196        })
197    }
198    #[inline]
199    fn to_u64(&self) -> Option<u64> {
200        self.to_i64().map(|x| x as u64)
201    }
202}
203
204impl EncodeMode {
205    pub fn to_bytes(self) -> [u8; 2] {
206        let value = self.to_u16().unwrap();
207        value.to_be_bytes()
208    }
209
210    pub fn is_snapshot(self) -> bool {
211        matches!(
212            self,
213            EncodeMode::OutdatedSnapshot | EncodeMode::FastSnapshot
214        )
215    }
216}
217
218impl TryFrom<[u8; 2]> for EncodeMode {
219    type Error = LoroError;
220
221    fn try_from(value: [u8; 2]) -> Result<Self, Self::Error> {
222        let value = u16::from_be_bytes(value);
223        Self::from_u16(value).ok_or(LoroError::IncompatibleFutureEncodingError(value as usize))
224    }
225}
226
227#[derive(Debug, Clone, PartialEq, Eq, Default)]
228pub struct ImportStatus {
229    pub success: VersionRange,
230    pub pending: Option<VersionRange>,
231}
232
233pub(crate) fn decode_oplog(
234    oplog: &mut OpLog,
235    parsed: ParsedHeaderAndBody,
236) -> Result<ImportStatus, LoroError> {
237    let changes = decode_oplog_changes(oplog, parsed)?;
238    let result = apply_decoded_changes_to_oplog(oplog, changes);
239    if result.has_deps_before_shallow_root {
240        return Err(LoroError::ImportUpdatesThatDependsOnOutdatedVersion);
241    }
242
243    Ok(result.status)
244}
245
246pub(crate) fn decode_oplog_changes(
247    oplog: &mut OpLog,
248    parsed: ParsedHeaderAndBody,
249) -> Result<Vec<Change>, LoroError> {
250    let ParsedHeaderAndBody { mode, body, .. } = parsed;
251    match mode {
252        EncodeMode::OutdatedRle | EncodeMode::OutdatedSnapshot => {
253            Err(LoroError::ImportUnsupportedEncodingMode)
254        }
255        EncodeMode::FastSnapshot => fast_snapshot::decode_oplog(oplog, body),
256        EncodeMode::FastUpdates => fast_snapshot::decode_updates(oplog, body.to_vec().into()),
257        EncodeMode::Auto => unreachable!(),
258    }
259}
260
261pub(crate) struct ApplyDecodedChangesResult {
262    pub status: ImportStatus,
263    pub has_deps_before_shallow_root: bool,
264}
265
266pub(crate) fn apply_decoded_changes_to_oplog(
267    oplog: &mut OpLog,
268    changes: Vec<Change>,
269) -> ApplyDecodedChangesResult {
270    let ImportChangesResult {
271        mut imported,
272        latest_ids,
273        pending_changes,
274        changes_that_have_deps_before_shallow_root,
275    } = import_changes_to_oplog(changes, oplog);
276
277    // TODO: PERF: should we use hashmap to filter latest_ids with the same peer first?
278    oplog.try_apply_pending(latest_ids, Some(&mut imported));
279    // Applying previously parked pending ops can unlock deps of `pending_changes`.
280    // Those are applied here (and counted in `imported`); only still-blocked ones
281    // remain in the returned pending range.
282    let pending =
283        oplog.import_unknown_lamport_pending_changes(pending_changes, Some(&mut imported));
284    ApplyDecodedChangesResult {
285        status: ImportStatus {
286            success: imported,
287            pending: (!pending.is_empty()).then_some(pending),
288        },
289        has_deps_before_shallow_root: !changes_that_have_deps_before_shallow_root.is_empty(),
290    }
291}
292
293pub(crate) struct ParsedHeaderAndBody<'a> {
294    pub checksum: [u8; 16],
295    pub checksum_body: &'a [u8],
296    pub mode: EncodeMode,
297    pub body: &'a [u8],
298}
299
300const XXH_SEED: u32 = u32::from_le_bytes(*b"LORO");
301impl ParsedHeaderAndBody<'_> {
302    /// Return if the checksum is correct.
303    fn check_checksum(&self) -> LoroResult<()> {
304        match self.mode {
305            EncodeMode::OutdatedRle | EncodeMode::OutdatedSnapshot => {
306                if md5::compute(self.checksum_body).0 != self.checksum {
307                    return Err(LoroError::DecodeChecksumMismatchError);
308                }
309            }
310            EncodeMode::FastSnapshot | EncodeMode::FastUpdates => {
311                let mut expected_bytes = [0; 4];
312                expected_bytes.copy_from_slice(&self.checksum[12..16]);
313                let expected = u32::from_le_bytes(expected_bytes);
314                if xxhash_rust::xxh32::xxh32(self.checksum_body, XXH_SEED) != expected {
315                    return Err(LoroError::DecodeChecksumMismatchError);
316                }
317            }
318            EncodeMode::Auto => {
319                return Err(LoroError::DecodeError(
320                    "Invalid import mode `Auto` in encoded blob"
321                        .to_string()
322                        .into_boxed_str(),
323                ));
324            }
325        }
326
327        Ok(())
328    }
329}
330
331const MIN_HEADER_SIZE: usize = 22;
332pub(crate) fn parse_header_and_body(
333    bytes: &[u8],
334    check_checksum: bool,
335) -> Result<ParsedHeaderAndBody<'_>, LoroError> {
336    let reader = &bytes;
337    if bytes.len() < MIN_HEADER_SIZE {
338        return Err(LoroError::DecodeError("Invalid import data".into()));
339    }
340
341    let (magic_bytes, reader) = reader.split_at(4);
342    if magic_bytes != MAGIC_BYTES {
343        return Err(LoroError::DecodeError("Invalid magic bytes".into()));
344    }
345
346    let (checksum, reader) = reader.split_at(16);
347    let checksum_body = reader;
348    let (mode_bytes, reader) = reader.split_at(2);
349    let mode: EncodeMode = [mode_bytes[0], mode_bytes[1]].try_into()?;
350    if mode == EncodeMode::Auto {
351        return Err(LoroError::DecodeError(
352            "Invalid import mode `Auto` in encoded blob"
353                .to_string()
354                .into_boxed_str(),
355        ));
356    }
357    let mut checksum_arr = [0; 16];
358    checksum_arr.copy_from_slice(checksum);
359
360    let ans = ParsedHeaderAndBody {
361        mode,
362        checksum_body,
363        checksum: checksum_arr,
364        body: reader,
365    };
366
367    if check_checksum {
368        ans.check_checksum()?;
369    }
370    Ok(ans)
371}
372
373pub(crate) fn export_fast_snapshot(doc: &LoroDoc) -> Result<Vec<u8>, LoroEncodeError> {
374    let snapshot = fast_snapshot::encode_snapshot_inner(doc)?;
375    let expected_len = snapshot
376        .encoded_len()
377        .and_then(|len| MIN_HEADER_SIZE.checked_add(len))
378        .ok_or_else(|| LoroEncodeError::internal("snapshot length overflow"))?;
379    let encoded = encode_with_capacity(EncodeMode::FastSnapshot, expected_len, &mut |ans| {
380        fast_snapshot::_encode_snapshot(&snapshot, ans);
381        Ok(())
382    })?;
383    debug_assert_eq!(encoded.len(), expected_len);
384    Ok(encoded)
385}
386
387pub(crate) fn export_snapshot_at(
388    doc: &LoroDoc,
389    frontiers: &Frontiers,
390) -> Result<Vec<u8>, LoroEncodeError> {
391    check_target_version_reachable(doc, frontiers)?;
392    encode_with(EncodeMode::FastSnapshot, &mut |ans| {
393        shallow_snapshot::encode_snapshot_at(doc, frontiers, ans)
394    })
395}
396
397pub(crate) fn export_fast_updates(doc: &LoroDoc, vv: &VersionVector) -> Vec<u8> {
398    encode_with(EncodeMode::FastUpdates, &mut |ans| {
399        fast_snapshot::encode_updates(doc, vv, ans);
400        Ok(())
401    })
402    .unwrap()
403}
404
405pub(crate) fn export_fast_updates_in_range(oplog: &OpLog, spans: &[IdSpan]) -> Vec<u8> {
406    encode_with(EncodeMode::FastUpdates, &mut |ans| {
407        fast_snapshot::encode_updates_in_range(oplog, spans, ans);
408        Ok(())
409    })
410    .unwrap()
411}
412
413pub(crate) fn export_shallow_snapshot(
414    doc: &LoroDoc,
415    f: &Frontiers,
416) -> Result<Vec<u8>, LoroEncodeError> {
417    check_target_version_reachable(doc, f)?;
418    encode_with(EncodeMode::FastSnapshot, &mut |ans| {
419        shallow_snapshot::export_shallow_snapshot(doc, f, ans)?;
420        Ok(())
421    })
422}
423
424fn check_target_version_reachable(doc: &LoroDoc, f: &Frontiers) -> Result<(), LoroEncodeError> {
425    let oplog = doc.oplog.lock();
426    if !oplog.dag.can_export_shallow_snapshot_on(f) {
427        return Err(LoroEncodeError::FrontiersNotFound(format!("{f:?}")));
428    }
429
430    Ok(())
431}
432
433pub(crate) fn export_state_only_snapshot(
434    doc: &LoroDoc,
435    f: &Frontiers,
436) -> Result<Vec<u8>, LoroEncodeError> {
437    check_target_version_reachable(doc, f)?;
438    encode_with(EncodeMode::FastSnapshot, &mut |ans| {
439        shallow_snapshot::export_state_only_snapshot(doc, f, ans)?;
440        Ok(())
441    })
442}
443
444fn encode_with(
445    mode: EncodeMode,
446    f: &mut dyn FnMut(&mut Vec<u8>) -> Result<(), LoroEncodeError>,
447) -> Result<Vec<u8>, LoroEncodeError> {
448    encode_with_capacity(mode, MIN_HEADER_SIZE, f)
449}
450
451fn encode_with_capacity(
452    mode: EncodeMode,
453    capacity: usize,
454    f: &mut dyn FnMut(&mut Vec<u8>) -> Result<(), LoroEncodeError>,
455) -> Result<Vec<u8>, LoroEncodeError> {
456    // HEADER
457    let mut ans = Vec::with_capacity(capacity);
458    ans.extend(MAGIC_BYTES);
459    let checksum = [0; 16];
460    ans.extend(checksum);
461    ans.extend(mode.to_bytes());
462
463    // BODY
464    f(&mut ans)?;
465
466    // CHECKSUM in HEADER
467    let checksum_body = &ans[20..];
468    let checksum = xxhash_rust::xxh32::xxh32(checksum_body, XXH_SEED);
469    ans[16..20].copy_from_slice(&checksum.to_le_bytes());
470    Ok(ans)
471}
472
473pub(crate) fn decode_snapshot(
474    doc: &LoroDoc,
475    mode: EncodeMode,
476    body: &[u8],
477    origin: InternalString,
478) -> Result<ImportStatus, LoroError> {
479    match mode {
480        EncodeMode::OutdatedSnapshot => {
481            return Err(LoroError::ImportUnsupportedEncodingMode);
482        }
483        EncodeMode::FastSnapshot => {
484            fast_snapshot::decode_snapshot(doc, body.to_vec().into(), origin)?
485        }
486        _ => {
487            return Err(LoroError::DecodeError(
488                format!("Invalid snapshot encoding mode: {mode:?}").into_boxed_str(),
489            ));
490        }
491    };
492    Ok(ImportStatus {
493        success: VersionRange::from_vv(&doc.oplog_vv()),
494        pending: None,
495    })
496}
497
498#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
499pub enum EncodedBlobMode {
500    Snapshot,
501    OutdatedSnapshot,
502    ShallowSnapshot,
503    OutdatedRle,
504    Updates,
505}
506
507impl std::fmt::Display for EncodedBlobMode {
508    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
509        f.write_str(match self {
510            EncodedBlobMode::OutdatedRle => "outdated-update",
511            EncodedBlobMode::OutdatedSnapshot => "outdated-snapshot",
512            EncodedBlobMode::Snapshot => "snapshot",
513            EncodedBlobMode::ShallowSnapshot => "shallow-snapshot",
514            EncodedBlobMode::Updates => "update",
515        })
516    }
517}
518
519impl EncodedBlobMode {
520    pub fn is_snapshot(&self) -> bool {
521        matches!(
522            self,
523            EncodedBlobMode::Snapshot
524                | EncodedBlobMode::ShallowSnapshot
525                | EncodedBlobMode::OutdatedSnapshot
526        )
527    }
528}
529
530#[derive(Debug, Clone)]
531pub struct ImportBlobMetadata {
532    /// The partial start version vector.
533    ///
534    /// Import blob includes all the ops from `partial_start_vv` to `partial_end_vv`.
535    /// However, it does not constitute a complete version vector, as it only contains counters
536    /// from peers included within the import blob.
537    pub partial_start_vv: VersionVector,
538    /// The partial end version vector.
539    ///
540    /// Import blob includes all the ops from `partial_start_vv` to `partial_end_vv`.
541    /// However, it does not constitute a complete version vector, as it only contains counters
542    /// from peers included within the import blob.
543    pub partial_end_vv: VersionVector,
544    pub start_timestamp: i64,
545    pub start_frontiers: Frontiers,
546    pub end_timestamp: i64,
547    pub change_num: u32,
548    pub mode: EncodedBlobMode,
549}
550
551impl LoroDoc {
552    /// Decodes the metadata for an imported blob from the provided bytes.
553    pub fn decode_import_blob_meta(
554        blob: &[u8],
555        check_checksum: bool,
556    ) -> LoroResult<ImportBlobMetadata> {
557        let parsed = parse_header_and_body(blob, check_checksum)?;
558        match parsed.mode {
559            EncodeMode::Auto => unreachable!(),
560            EncodeMode::OutdatedRle | EncodeMode::OutdatedSnapshot => {
561                Err(LoroError::ImportUnsupportedEncodingMode)
562            }
563            EncodeMode::FastSnapshot => fast_snapshot::decode_snapshot_blob_meta(parsed),
564            EncodeMode::FastUpdates => fast_snapshot::decode_updates_blob_meta(parsed),
565        }
566    }
567}
568
569#[cfg(test)]
570mod test {
571    use super::*;
572    use loro_common::{loro_value, ContainerID, ContainerType, LoroValue, ID};
573
574    #[test]
575    fn fast_snapshot_envelope_has_exact_length_and_valid_checksum() {
576        let doc = LoroDoc::new_auto_commit();
577        doc.get_map("root").insert("key", "value").unwrap();
578        let encoded = doc.export(ExportMode::Snapshot).unwrap();
579        assert_eq!(&encoded[..4], &MAGIC_BYTES);
580        assert_eq!(&encoded[20..22], &EncodeMode::FastSnapshot.to_bytes());
581        let parsed = parse_header_and_body(&encoded, true).unwrap();
582        assert_eq!(parsed.mode, EncodeMode::FastSnapshot);
583        assert_eq!(encoded.len(), MIN_HEADER_SIZE + parsed.body.len());
584
585        let mut corrupted = encoded;
586        *corrupted.last_mut().unwrap() ^= 1;
587        assert!(matches!(
588            parse_header_and_body(&corrupted, true),
589            Err(LoroError::DecodeChecksumMismatchError)
590        ));
591    }
592
593    #[test]
594    fn test_value_encode_size() {
595        fn assert_size(value: LoroValue, max_size: usize) {
596            let size = postcard::to_allocvec(&value).unwrap().len();
597            assert!(
598                size <= max_size,
599                "value: {:?}, size: {}, max_size: {}",
600                value,
601                size,
602                max_size
603            );
604        }
605
606        assert_size(LoroValue::Null, 1);
607        assert_size(LoroValue::I64(1), 2);
608        assert_size(LoroValue::Double(1.), 9);
609        assert_size(LoroValue::Bool(true), 2);
610        assert_size(LoroValue::String("123".to_string().into()), 5);
611        assert_size(LoroValue::Binary(vec![1, 2, 3].into()), 5);
612        assert_size(
613            loro_value!({
614                "a": 1,
615                "b": 2,
616            }),
617            10,
618        );
619        assert_size(loro_value!([1, 2, 3]), 8);
620        assert_size(
621            LoroValue::Container(ContainerID::new_normal(ID::new(1, 1), ContainerType::Map)),
622            5,
623        );
624        assert_size(
625            LoroValue::Container(ContainerID::new_root("a", ContainerType::Map)),
626            5,
627        );
628    }
629}