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#[non_exhaustive]
52#[derive(Debug, Clone)]
53pub enum ExportMode<'a> {
54 Snapshot,
56 Updates { from: Cow<'a, VersionVector> },
58 UpdatesInRange { spans: Cow<'a, [IdSpan]> },
60 ShallowSnapshot(Cow<'a, Frontiers>),
62 StateOnly(Option<Cow<'a, Frontiers>>),
68 SnapshotAt { version: Cow<'a, Frontiers> },
71}
72
73impl<'a> ExportMode<'a> {
74 pub fn snapshot() -> Self {
76 ExportMode::Snapshot
77 }
78
79 pub fn updates(from: &'a VersionVector) -> Self {
81 ExportMode::Updates {
82 from: Cow::Borrowed(from),
83 }
84 }
85
86 pub fn updates_owned(from: VersionVector) -> Self {
88 ExportMode::Updates {
89 from: Cow::Owned(from),
90 }
91 }
92
93 pub fn all_updates() -> Self {
95 ExportMode::Updates {
96 from: Cow::Owned(Default::default()),
97 }
98 }
99
100 pub fn updates_in_range(spans: impl Into<Cow<'a, [IdSpan]>>) -> Self {
102 ExportMode::UpdatesInRange {
103 spans: spans.into(),
104 }
105 }
106
107 pub fn shallow_snapshot(frontiers: &'a Frontiers) -> Self {
109 ExportMode::ShallowSnapshot(Cow::Borrowed(frontiers))
110 }
111
112 pub fn shallow_snapshot_owned(frontiers: Frontiers) -> Self {
114 ExportMode::ShallowSnapshot(Cow::Owned(frontiers))
115 }
116
117 pub fn shallow_snapshot_since(id: ID) -> Self {
119 let frontiers = Frontiers::from_id(id);
120 ExportMode::ShallowSnapshot(Cow::Owned(frontiers))
121 }
122
123 pub fn state_only(frontiers: Option<&'a Frontiers>) -> Self {
129 ExportMode::StateOnly(frontiers.map(Cow::Borrowed))
130 }
131
132 pub fn snapshot_at(frontiers: &'a Frontiers) -> Self {
135 ExportMode::SnapshotAt {
136 version: Cow::Borrowed(frontiers),
137 }
138 }
139
140 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 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 oplog.try_apply_pending(latest_ids, Some(&mut imported));
279 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 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 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 f(&mut ans)?;
465
466 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 pub partial_start_vv: VersionVector,
538 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 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}