project_note
Clone
https://git.tahinli.com/Tahinli/project_note.git
0 watching·0 forks·Rust·3.6 MiB·c49f5e7·Tahinli·1 month ago·2 commits
| 1 | //! Fast snapshot encoding and decoding. |
| 2 | //! |
| 3 | //! # Layout |
| 4 | //! |
| 5 | //! - u32 in little endian for len of bytes for oplog |
| 6 | //! - oplog bytes |
| 7 | //! - u32 in little endian for len of bytes for state |
| 8 | //! - state bytes |
| 9 | //! - u32 in little endian for len of bytes for gc |
| 10 | //! - gc bytes |
| 11 | //! |
| 12 | //! All of `oplog bytes`, `state bytes` and `gc bytes` are encoded KV store bytes. |
| 13 | //! |
| 14 | //! |
| 15 | //! |
| 16 | use std::io::{Read, Write}; |
| 17 | |
| 18 | use crate::{ |
| 19 | change::Change, encoding::shallow_snapshot, oplog::ChangeStore, version::Frontiers, LoroDoc, |
| 20 | OpLog, VersionVector, |
| 21 | }; |
| 22 | use bytes::{Buf, Bytes}; |
| 23 | use loro_common::{HasCounterSpan, IdSpan, InternalString, LoroEncodeError, LoroError, LoroResult}; |
| 24 | |
| 25 | use super::{EncodedBlobMode, ImportBlobMetadata, ParsedHeaderAndBody}; |
| 26 | pub(crate) const EMPTY_MARK: &[u8] = b"E"; |
| 27 | pub(crate) struct Snapshot { |
| 28 | pub oplog_bytes: Bytes, |
| 29 | pub state_bytes: Option<Bytes>, |
| 30 | pub shallow_root_state_bytes: Bytes, |
| 31 | } |
| 32 | |
| 33 | impl Snapshot { |
| 34 | pub(super) fn encoded_len(&self) -> Option<usize> { |
| 35 | let state_len = self |
| 36 | .state_bytes |
| 37 | .as_ref() |
| 38 | .map_or(EMPTY_MARK.len(), Bytes::len); |
| 39 | u32::try_from(self.oplog_bytes.len()).ok()?; |
| 40 | u32::try_from(state_len).ok()?; |
| 41 | u32::try_from(self.shallow_root_state_bytes.len()).ok()?; |
| 42 | (3 * std::mem::size_of::<u32>()) |
| 43 | .checked_add(self.oplog_bytes.len())? |
| 44 | .checked_add(state_len)? |
| 45 | .checked_add(self.shallow_root_state_bytes.len()) |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | pub(super) fn _encode_snapshot<W: Write>(s: &Snapshot, w: &mut W) { |
| 50 | w.write_all(&(s.oplog_bytes.len() as u32).to_le_bytes()) |
| 51 | .unwrap(); |
| 52 | w.write_all(&s.oplog_bytes).unwrap(); |
| 53 | let state_bytes = s.state_bytes.as_deref().unwrap_or(EMPTY_MARK); |
| 54 | w.write_all(&(state_bytes.len() as u32).to_le_bytes()) |
| 55 | .unwrap(); |
| 56 | w.write_all(state_bytes).unwrap(); |
| 57 | w.write_all(&(s.shallow_root_state_bytes.len() as u32).to_le_bytes()) |
| 58 | .unwrap(); |
| 59 | w.write_all(&s.shallow_root_state_bytes).unwrap(); |
| 60 | } |
| 61 | |
| 62 | pub(super) fn _decode_snapshot_bytes(bytes: Bytes) -> LoroResult<Snapshot> { |
| 63 | let mut r = bytes.reader(); |
| 64 | let oplog_bytes_len = read_u32_le(&mut r)? as usize; |
| 65 | if r.get_ref().len() < oplog_bytes_len { |
| 66 | return Err(LoroError::DecodeError( |
| 67 | "decode_snapshot: invalid oplog bytes length" |
| 68 | .to_string() |
| 69 | .into_boxed_str(), |
| 70 | )); |
| 71 | } |
| 72 | let oplog_bytes = r.get_mut().copy_to_bytes(oplog_bytes_len); |
| 73 | let state_bytes_len = read_u32_le(&mut r)? as usize; |
| 74 | if r.get_ref().len() < state_bytes_len { |
| 75 | return Err(LoroError::DecodeError( |
| 76 | "decode_snapshot: invalid state bytes length" |
| 77 | .to_string() |
| 78 | .into_boxed_str(), |
| 79 | )); |
| 80 | } |
| 81 | let state_bytes = r.get_mut().copy_to_bytes(state_bytes_len); |
| 82 | let state_bytes = if state_bytes == EMPTY_MARK { |
| 83 | None |
| 84 | } else { |
| 85 | Some(state_bytes) |
| 86 | }; |
| 87 | let shallow_bytes_len = read_u32_le(&mut r)? as usize; |
| 88 | if r.get_ref().len() < shallow_bytes_len { |
| 89 | return Err(LoroError::DecodeError( |
| 90 | "decode_snapshot: invalid shallow root bytes length" |
| 91 | .to_string() |
| 92 | .into_boxed_str(), |
| 93 | )); |
| 94 | } |
| 95 | let shallow_root_state_bytes = r.get_mut().copy_to_bytes(shallow_bytes_len); |
| 96 | if r.get_ref().has_remaining() { |
| 97 | return Err(LoroError::DecodeError( |
| 98 | "decode_snapshot: trailing bytes after snapshot" |
| 99 | .to_string() |
| 100 | .into_boxed_str(), |
| 101 | )); |
| 102 | } |
| 103 | |
| 104 | Ok(Snapshot { |
| 105 | oplog_bytes, |
| 106 | state_bytes, |
| 107 | shallow_root_state_bytes, |
| 108 | }) |
| 109 | } |
| 110 | |
| 111 | pub(super) fn _decode_snapshot_meta_partial(bytes: &[u8]) -> LoroResult<(&[u8], bool)> { |
| 112 | let mut r = bytes; |
| 113 | let oplog_bytes_len = read_u32_le_slice(&mut r)? as usize; |
| 114 | if r.len() < oplog_bytes_len { |
| 115 | return Err(LoroError::DecodeDataCorruptionError); |
| 116 | } |
| 117 | let oplog_bytes = &r[..oplog_bytes_len]; |
| 118 | r = &r[oplog_bytes_len..]; |
| 119 | let state_bytes_len = read_u32_le_slice(&mut r)? as usize; |
| 120 | if r.len() < state_bytes_len { |
| 121 | return Err(LoroError::DecodeDataCorruptionError); |
| 122 | } |
| 123 | r = &r[state_bytes_len..]; |
| 124 | let shallow_bytes_len = read_u32_le_slice(&mut r)? as usize; |
| 125 | if r.len() < shallow_bytes_len { |
| 126 | return Err(LoroError::DecodeDataCorruptionError); |
| 127 | } |
| 128 | r = &r[shallow_bytes_len..]; |
| 129 | if !r.is_empty() { |
| 130 | return Err(LoroError::DecodeDataCorruptionError); |
| 131 | } |
| 132 | |
| 133 | Ok((oplog_bytes, shallow_bytes_len > 0)) |
| 134 | } |
| 135 | |
| 136 | fn read_u32_le_slice(r: &mut &[u8]) -> LoroResult<u32> { |
| 137 | let mut buf = [0; 4]; |
| 138 | r.read_exact(&mut buf) |
| 139 | .map_err(|_| LoroError::DecodeDataCorruptionError)?; |
| 140 | Ok(u32::from_le_bytes(buf)) |
| 141 | } |
| 142 | |
| 143 | fn read_u32_le(r: &mut bytes::buf::Reader<Bytes>) -> LoroResult<u32> { |
| 144 | let mut buf = [0; 4]; |
| 145 | r.read_exact(&mut buf).map_err(|_| { |
| 146 | LoroError::DecodeError( |
| 147 | "decode_snapshot: unexpected end of snapshot bytes" |
| 148 | .to_string() |
| 149 | .into_boxed_str(), |
| 150 | ) |
| 151 | })?; |
| 152 | Ok(u32::from_le_bytes(buf)) |
| 153 | } |
| 154 | |
| 155 | pub(crate) fn decode_snapshot( |
| 156 | doc: &LoroDoc, |
| 157 | bytes: Bytes, |
| 158 | origin: InternalString, |
| 159 | ) -> LoroResult<()> { |
| 160 | let snapshot = _decode_snapshot_bytes(bytes)?; |
| 161 | decode_snapshot_inner(snapshot, doc, origin) |
| 162 | } |
| 163 | |
| 164 | pub(crate) fn decode_snapshot_inner( |
| 165 | snapshot: Snapshot, |
| 166 | doc: &LoroDoc, |
| 167 | origin: InternalString, |
| 168 | ) -> Result<(), LoroError> { |
| 169 | let Snapshot { |
| 170 | oplog_bytes, |
| 171 | state_bytes, |
| 172 | shallow_root_state_bytes, |
| 173 | } = snapshot; |
| 174 | ensure_cov::notify_cov("loro_internal::import::fast_snapshot::decode_snapshot"); |
| 175 | let mut oplog = doc.oplog().lock(); |
| 176 | if !oplog.is_empty() { |
| 177 | return Err(LoroError::DecodeError( |
| 178 | "decode_snapshot: cannot import snapshot into a non-empty doc" |
| 179 | .to_string() |
| 180 | .into_boxed_str(), |
| 181 | )); |
| 182 | } |
| 183 | |
| 184 | let mut state = doc.app_state().lock(); |
| 185 | |
| 186 | state.check_before_decode_snapshot()?; |
| 187 | |
| 188 | if !state.frontiers.is_empty() { |
| 189 | return Err(LoroError::DecodeError( |
| 190 | "decode_snapshot: app state frontiers must be empty before import" |
| 191 | .to_string() |
| 192 | .into_boxed_str(), |
| 193 | )); |
| 194 | } |
| 195 | |
| 196 | if !oplog.frontiers().is_empty() { |
| 197 | return Err(LoroError::DecodeError( |
| 198 | "decode_snapshot: oplog frontiers must be empty before import" |
| 199 | .to_string() |
| 200 | .into_boxed_str(), |
| 201 | )); |
| 202 | } |
| 203 | let need_calc = state_bytes.is_none(); |
| 204 | let checkout_origin = origin.clone(); |
| 205 | |
| 206 | let arena_checkpoint = oplog.arena.checkpoint_for_rollback(); |
| 207 | let decode_result = (|| -> LoroResult<()> { |
| 208 | oplog.decode_change_store(oplog_bytes)?; |
| 209 | let state_frontiers; |
| 210 | if shallow_root_state_bytes.is_empty() { |
| 211 | ensure_cov::notify_cov("loro_internal::import::snapshot::normal"); |
| 212 | if let Some(bytes) = state_bytes { |
| 213 | state.store.decode(bytes)?; |
| 214 | } |
| 215 | state_frontiers = oplog.frontiers().clone(); |
| 216 | } else { |
| 217 | ensure_cov::notify_cov("loro_internal::import::snapshot::gc"); |
| 218 | let shallow_root_state_frontiers = state.store.decode_gc( |
| 219 | shallow_root_state_bytes.clone(), |
| 220 | oplog.dag().shallow_since_frontiers().clone(), |
| 221 | doc.config.clone(), |
| 222 | )?; |
| 223 | state.store.decode_state_by_two_bytes( |
| 224 | shallow_root_state_bytes, |
| 225 | state_bytes.unwrap_or_default(), |
| 226 | )?; |
| 227 | |
| 228 | let shallow_root_store = state.shallow_root_store().cloned(); |
| 229 | oplog.with_history_cache(|h| { |
| 230 | h.set_shallow_root_store(shallow_root_store); |
| 231 | }); |
| 232 | |
| 233 | if need_calc { |
| 234 | ensure_cov::notify_cov("shallow_snapshot::need_calc"); |
| 235 | state_frontiers = shallow_root_state_frontiers.ok_or_else(|| { |
| 236 | LoroError::DecodeError( |
| 237 | "decode_snapshot: shallow root frontiers are missing" |
| 238 | .to_string() |
| 239 | .into_boxed_str(), |
| 240 | ) |
| 241 | })?; |
| 242 | } else { |
| 243 | ensure_cov::notify_cov("shallow_snapshot::dont_need_calc"); |
| 244 | state_frontiers = oplog.frontiers().clone(); |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | state.init_with_states_and_version(state_frontiers, &oplog, vec![], false, origin)?; |
| 249 | Ok(()) |
| 250 | })(); |
| 251 | |
| 252 | if let Err(e) = decode_result { |
| 253 | state.reset_to_empty_for_failed_snapshot_import(); |
| 254 | oplog.reset_to_empty_for_failed_snapshot_import(arena_checkpoint, &mut state); |
| 255 | return Err(e); |
| 256 | } |
| 257 | drop(state); |
| 258 | drop(oplog); |
| 259 | if need_calc { |
| 260 | doc.set_detached(true); |
| 261 | if let Err(e) = doc._checkout_to_latest_without_commit_as_import(false, checkout_origin) { |
| 262 | doc.set_detached(false); |
| 263 | let mut oplog = doc.oplog().lock(); |
| 264 | let mut state = doc.app_state().lock(); |
| 265 | state.reset_to_empty_for_failed_snapshot_import(); |
| 266 | oplog.reset_to_empty_for_failed_snapshot_import(arena_checkpoint, &mut state); |
| 267 | return Err(e); |
| 268 | } |
| 269 | debug_assert_eq!(doc.state_frontiers(), doc.oplog_frontiers()); |
| 270 | } |
| 271 | |
| 272 | Ok(()) |
| 273 | } |
| 274 | |
| 275 | impl OpLog { |
| 276 | pub(super) fn decode_change_store(&mut self, bytes: bytes::Bytes) -> LoroResult<()> { |
| 277 | let v = self.change_store().import_all(bytes)?; |
| 278 | self.dag.set_version_by_fast_snapshot_import(v)?; |
| 279 | self.refresh_visible_op_count(); |
| 280 | Ok(()) |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | pub(crate) fn encode_snapshot_inner(doc: &LoroDoc) -> Result<Snapshot, LoroEncodeError> { |
| 285 | encode_snapshot_inner_with(doc, shallow_snapshot::CachedShallowRoot::Prune) |
| 286 | } |
| 287 | |
| 288 | /// Snapshot for `LoroDoc::fork`: a shallow doc's cached root is copied |
| 289 | /// verbatim instead of being filtered. |
| 290 | pub(crate) fn encode_snapshot_inner_for_fork(doc: &LoroDoc) -> Result<Snapshot, LoroEncodeError> { |
| 291 | encode_snapshot_inner_with(doc, shallow_snapshot::CachedShallowRoot::Verbatim) |
| 292 | } |
| 293 | |
| 294 | fn encode_snapshot_inner_with( |
| 295 | doc: &LoroDoc, |
| 296 | cached_root: shallow_snapshot::CachedShallowRoot, |
| 297 | ) -> Result<Snapshot, LoroEncodeError> { |
| 298 | assert!(doc.drop_pending_events().is_empty()); |
| 299 | let old_state_frontiers = doc.state_frontiers(); |
| 300 | let was_detached = doc.is_detached(); |
| 301 | let oplog = doc.oplog().lock(); |
| 302 | let mut state = doc.app_state().lock(); |
| 303 | let is_gc = state.store.shallow_root_store().is_some(); |
| 304 | if is_gc { |
| 305 | // TODO: PERF: this can be optimized by reusing the bytes of gc store |
| 306 | let f = oplog.shallow_since_frontiers().clone(); |
| 307 | drop(state); |
| 308 | drop(oplog); |
| 309 | let (snapshot, _) = shallow_snapshot::export_shallow_snapshot_inner(doc, &f, cached_root)?; |
| 310 | return Ok(snapshot); |
| 311 | } |
| 312 | |
| 313 | assert!(!state.is_in_txn()); |
| 314 | let oplog_bytes = oplog.encode_change_store(); |
| 315 | if oplog.is_shallow() { |
| 316 | assert_eq!( |
| 317 | oplog.shallow_since_frontiers(), |
| 318 | state.store.shallow_root_frontiers().unwrap() |
| 319 | ); |
| 320 | } |
| 321 | if was_detached { |
| 322 | let latest = oplog.frontiers().clone(); |
| 323 | drop(state); |
| 324 | drop(oplog); |
| 325 | doc._checkout_without_emitting(&latest, false, true) |
| 326 | .unwrap(); |
| 327 | state = doc.app_state().lock(); |
| 328 | } |
| 329 | // Every container referenced by applied ops/diffs already has a store entry |
| 330 | // (`ensure_containers_created_by_op` / `ensure_containers_created_by_internal_diff`), so a |
| 331 | // full snapshot does not need to walk the alive-container graph: flushing the store and |
| 332 | // exporting the kv bytes is sufficient, and it keeps snapshot-backed state lazy. Only |
| 333 | // shallow snapshot export still derives the alive set (to filter retained keys). |
| 334 | let snapshot: Result<Snapshot, LoroEncodeError> = Ok(Snapshot { |
| 335 | oplog_bytes, |
| 336 | state_bytes: Some(state.store.encode()), |
| 337 | shallow_root_state_bytes: Bytes::new(), |
| 338 | }); |
| 339 | if was_detached { |
| 340 | drop(state); |
| 341 | doc._checkout_without_emitting(&old_state_frontiers, false, true) |
| 342 | .unwrap(); |
| 343 | doc.drop_pending_events(); |
| 344 | } |
| 345 | |
| 346 | snapshot |
| 347 | } |
| 348 | |
| 349 | pub(crate) fn decode_oplog( |
| 350 | oplog: &mut OpLog, |
| 351 | bytes: &[u8], |
| 352 | values: crate::oplog::ImportedValues, |
| 353 | ) -> Result<Vec<Change>, LoroError> { |
| 354 | let oplog_len = bytes |
| 355 | .get(0..4) |
| 356 | .ok_or_else(|| LoroError::DecodeError("decode_oplog: missing length prefix".into()))?; |
| 357 | let oplog_len = u32::from_le_bytes( |
| 358 | oplog_len |
| 359 | .try_into() |
| 360 | .expect("slice length checked to be exactly 4"), |
| 361 | ) as usize; |
| 362 | let oplog_bytes = bytes |
| 363 | .get(4..4 + oplog_len) |
| 364 | .ok_or_else(|| LoroError::DecodeError("decode_oplog: invalid oplog length".into()))?; |
| 365 | let mut changes = |
| 366 | ChangeStore::decode_snapshot_for_updates(oplog_bytes.to_vec().into(), oplog, values)?; |
| 367 | changes.sort_unstable_by_key(|x| x.lamport); |
| 368 | Ok(changes) |
| 369 | } |
| 370 | |
| 371 | pub(crate) fn encode_updates<W: std::io::Write>(doc: &LoroDoc, vv: &VersionVector, w: &mut W) { |
| 372 | let oplog = doc.oplog().lock(); |
| 373 | oplog.export_blocks_from(vv, w); |
| 374 | } |
| 375 | |
| 376 | pub(crate) fn encode_updates_in_range<W: std::io::Write>( |
| 377 | oplog: &OpLog, |
| 378 | spans: &[IdSpan], |
| 379 | w: &mut W, |
| 380 | ) { |
| 381 | oplog.export_blocks_in_range(spans, w); |
| 382 | } |
| 383 | |
| 384 | pub(crate) fn decode_updates(oplog: &mut OpLog, body: Bytes) -> Result<Vec<Change>, LoroError> { |
| 385 | let mut reader: &[u8] = body.as_ref(); |
| 386 | let mut index = 0; |
| 387 | let mut changes = Vec::new(); |
| 388 | while !reader.is_empty() { |
| 389 | let old_reader_len = reader.len(); |
| 390 | let len = leb128::read::unsigned(&mut reader) |
| 391 | .map_err(|_| LoroError::DecodeError("decode_updates: invalid block length".into()))? |
| 392 | as usize; |
| 393 | index += old_reader_len - reader.len(); |
| 394 | let end = index.checked_add(len).ok_or_else(|| { |
| 395 | LoroError::DecodeError("decode_updates: block length overflow".into()) |
| 396 | })?; |
| 397 | if end > body.len() { |
| 398 | return Err(LoroError::DecodeError( |
| 399 | "decode_updates: truncated block payload".into(), |
| 400 | )); |
| 401 | } |
| 402 | let block_bytes = body.slice(index..end); |
| 403 | changes.extend( |
| 404 | oplog |
| 405 | .change_store() |
| 406 | .decode_update_block(block_bytes, oplog.vv())?, |
| 407 | ); |
| 408 | index = end; |
| 409 | reader = &reader[len..]; |
| 410 | } |
| 411 | |
| 412 | changes.sort_unstable_by_key(|x| x.lamport); |
| 413 | Ok(changes) |
| 414 | } |
| 415 | |
| 416 | #[cfg(test)] |
| 417 | mod tests { |
| 418 | use super::*; |
| 419 | use crate::{ |
| 420 | encoding::ExportMode, handler::HandlerTrait, utils::kv_wrapper::KvWrapper, MapHandler, |
| 421 | }; |
| 422 | |
| 423 | fn snapshot_sections(doc: &LoroDoc) -> Snapshot { |
| 424 | let encoded = doc.export(ExportMode::Snapshot).unwrap(); |
| 425 | let parsed = crate::encoding::parse_header_and_body(&encoded, true).unwrap(); |
| 426 | _decode_snapshot_bytes(Bytes::copy_from_slice(parsed.body)).unwrap() |
| 427 | } |
| 428 | |
| 429 | #[test] |
| 430 | fn snapshot_encoded_len_matches_written_len() { |
| 431 | for snapshot in [ |
| 432 | Snapshot { |
| 433 | oplog_bytes: Bytes::from_static(b"oplog"), |
| 434 | state_bytes: Some(Bytes::from_static(b"state")), |
| 435 | shallow_root_state_bytes: Bytes::new(), |
| 436 | }, |
| 437 | Snapshot { |
| 438 | oplog_bytes: Bytes::new(), |
| 439 | state_bytes: None, |
| 440 | shallow_root_state_bytes: Bytes::from_static(b"shallow"), |
| 441 | }, |
| 442 | ] { |
| 443 | let expected_len = snapshot.encoded_len().unwrap(); |
| 444 | let mut encoded = Vec::new(); |
| 445 | _encode_snapshot(&snapshot, &mut encoded); |
| 446 | assert_eq!(encoded.len(), expected_len); |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | #[test] |
| 451 | fn decode_updates_rejects_truncated_block() { |
| 452 | let doc = LoroDoc::new(); |
| 453 | let mut oplog = doc.oplog.lock(); |
| 454 | let err = decode_updates(&mut oplog, Bytes::from_static(&[0x02, 0x01])) |
| 455 | .expect_err("truncated update block should be rejected"); |
| 456 | assert!(matches!(err, LoroError::DecodeError(_))); |
| 457 | } |
| 458 | |
| 459 | #[test] |
| 460 | fn full_export_round_trips_lazy_child_parent_conflict_but_shallow_rejects() { |
| 461 | fn doc_with_child(root: &str) -> (LoroDoc, loro_common::ContainerID) { |
| 462 | let doc = LoroDoc::new_auto_commit(); |
| 463 | doc.set_peer_id(42).unwrap(); |
| 464 | let child = doc |
| 465 | .get_map(root) |
| 466 | .insert_container("child", MapHandler::new_detached()) |
| 467 | .unwrap(); |
| 468 | child.insert("value", root).unwrap(); |
| 469 | let child_id = child.id(); |
| 470 | (doc, child_id) |
| 471 | } |
| 472 | |
| 473 | let (parent_a, child_a) = doc_with_child("parent-a"); |
| 474 | let (parent_b, child_b) = doc_with_child("parent-b"); |
| 475 | assert_eq!(child_a, child_b, "test setup needs the same child id"); |
| 476 | |
| 477 | let mut sections_a = snapshot_sections(&parent_a); |
| 478 | let sections_b = snapshot_sections(&parent_b); |
| 479 | let state_a = KvWrapper::new_mem(); |
| 480 | state_a |
| 481 | .import(sections_a.state_bytes.take().unwrap()) |
| 482 | .unwrap(); |
| 483 | let state_b = KvWrapper::new_mem(); |
| 484 | state_b.import(sections_b.state_bytes.unwrap()).unwrap(); |
| 485 | let child_key = child_a.to_bytes(); |
| 486 | state_a.insert(&child_key, state_b.get(&child_key).unwrap()); |
| 487 | |
| 488 | let target = LoroDoc::new(); |
| 489 | decode_snapshot_inner( |
| 490 | Snapshot { |
| 491 | oplog_bytes: sections_a.oplog_bytes, |
| 492 | state_bytes: Some(state_a.export()), |
| 493 | shallow_root_state_bytes: sections_a.shallow_root_state_bytes, |
| 494 | }, |
| 495 | &target, |
| 496 | Default::default(), |
| 497 | ) |
| 498 | .unwrap(); |
| 499 | |
| 500 | // Full snapshot export is a byte-faithful round-trip of the imported kv and does not |
| 501 | // re-derive the container graph, so it must succeed even with conflicting lazy parent |
| 502 | // metadata. The alive-container walk (and its validation) now only runs for shallow |
| 503 | // exports, which must still reject the conflict. |
| 504 | let reexported = target |
| 505 | .export(ExportMode::Snapshot) |
| 506 | .expect("full export round-trips lazy state without walking it"); |
| 507 | let reimported = LoroDoc::new(); |
| 508 | reimported.import(&reexported).unwrap(); |
| 509 | |
| 510 | let err = target |
| 511 | .export(ExportMode::StateOnly(None)) |
| 512 | .expect_err("shallow export walks the graph and must reject the conflict"); |
| 513 | assert!(err.to_string().contains("snapshot state encodes parent")); |
| 514 | } |
| 515 | |
| 516 | #[test] |
| 517 | fn full_export_round_trips_malformed_lazy_wrapper_but_shallow_rejects() { |
| 518 | let source = LoroDoc::new_auto_commit(); |
| 519 | source.get_map("root").insert("value", 1).unwrap(); |
| 520 | let mut sections = snapshot_sections(&source); |
| 521 | let state = KvWrapper::new_mem(); |
| 522 | state.import(sections.state_bytes.take().unwrap()).unwrap(); |
| 523 | let root = loro_common::ContainerID::new_root("root", crate::ContainerType::Map); |
| 524 | state.insert( |
| 525 | &root.to_bytes(), |
| 526 | Bytes::from(vec![crate::ContainerType::Map.to_u8()]), |
| 527 | ); |
| 528 | |
| 529 | let target = LoroDoc::new(); |
| 530 | decode_snapshot_inner( |
| 531 | Snapshot { |
| 532 | oplog_bytes: sections.oplog_bytes, |
| 533 | state_bytes: Some(state.export()), |
| 534 | shallow_root_state_bytes: sections.shallow_root_state_bytes, |
| 535 | }, |
| 536 | &target, |
| 537 | Default::default(), |
| 538 | ) |
| 539 | .unwrap(); |
| 540 | |
| 541 | // Full snapshot export no longer decodes lazy wrappers, so the malformed entry is |
| 542 | // round-tripped as-is; the error surfaces where the wrapper is actually read, e.g. the |
| 543 | // shallow-export walk. |
| 544 | target |
| 545 | .export(ExportMode::Snapshot) |
| 546 | .expect("full export round-trips lazy state without decoding it"); |
| 547 | |
| 548 | let err = target |
| 549 | .export(ExportMode::StateOnly(None)) |
| 550 | .expect_err("shallow export decodes the wrapper and must return an error"); |
| 551 | assert!(err.to_string().contains("Decode container state failed")); |
| 552 | } |
| 553 | } |
| 554 | |
| 555 | pub(crate) fn decode_snapshot_blob_meta( |
| 556 | parsed: ParsedHeaderAndBody, |
| 557 | ) -> LoroResult<ImportBlobMetadata> { |
| 558 | let (oplog_bytes, is_shallow) = _decode_snapshot_meta_partial(parsed.body)?; |
| 559 | let mode = if is_shallow { |
| 560 | EncodedBlobMode::ShallowSnapshot |
| 561 | } else { |
| 562 | EncodedBlobMode::Snapshot |
| 563 | }; |
| 564 | |
| 565 | let doc = LoroDoc::new(); |
| 566 | let mut oplog = doc.oplog.lock(); |
| 567 | oplog.decode_change_store(oplog_bytes.to_vec().into())?; |
| 568 | let timestamp = oplog.get_greatest_timestamp(oplog.dag.frontiers()); |
| 569 | let f = oplog.dag.shallow_since_frontiers().clone(); |
| 570 | let start_timestamp = oplog.get_timestamp_of_version(&f); |
| 571 | let change_num = oplog.change_store().change_num() as u32; |
| 572 | |
| 573 | Ok(ImportBlobMetadata { |
| 574 | mode, |
| 575 | partial_start_vv: oplog.dag.shallow_since_vv().to_vv(), |
| 576 | partial_end_vv: oplog.vv().clone(), |
| 577 | start_timestamp, |
| 578 | start_frontiers: f, |
| 579 | end_timestamp: timestamp, |
| 580 | change_num, |
| 581 | }) |
| 582 | } |
| 583 | |
| 584 | pub(crate) fn decode_updates_blob_meta( |
| 585 | parsed: ParsedHeaderAndBody, |
| 586 | ) -> LoroResult<ImportBlobMetadata> { |
| 587 | let doc = LoroDoc::new(); |
| 588 | let mut oplog = doc.oplog.lock(); |
| 589 | let changes = decode_updates(&mut oplog, parsed.body.to_vec().into())?; |
| 590 | let mut start_vv = VersionVector::new(); |
| 591 | let mut end_vv = VersionVector::new(); |
| 592 | for c in changes.iter() { |
| 593 | match start_vv.get(&c.id.peer).copied() { |
| 594 | Some(start) if start <= c.id.counter => {} |
| 595 | _ => { |
| 596 | start_vv.insert(c.id.peer, c.id.counter); |
| 597 | } |
| 598 | } |
| 599 | match end_vv.get(&c.id.peer).copied() { |
| 600 | Some(end) if end >= c.ctr_end() => {} |
| 601 | _ => { |
| 602 | end_vv.insert(c.id.peer, c.ctr_end()); |
| 603 | } |
| 604 | } |
| 605 | } |
| 606 | |
| 607 | let mut start_frontiers = Frontiers::new(); |
| 608 | for c in changes.iter() { |
| 609 | for dep in c.deps().iter() { |
| 610 | if let Some(start_counter) = start_vv.get(&dep.peer) { |
| 611 | if *start_counter > dep.counter { |
| 612 | start_frontiers.push(dep); |
| 613 | } |
| 614 | } else if end_vv.get(&dep.peer).is_none() { |
| 615 | start_frontiers.push(dep); |
| 616 | } |
| 617 | } |
| 618 | } |
| 619 | |
| 620 | Ok(ImportBlobMetadata { |
| 621 | mode: EncodedBlobMode::Updates, |
| 622 | partial_start_vv: start_vv, |
| 623 | partial_end_vv: end_vv, |
| 624 | start_timestamp: changes.first().map(|x| x.timestamp).unwrap_or(0), |
| 625 | start_frontiers, |
| 626 | end_timestamp: changes.last().map(|x| x.timestamp).unwrap_or(0), |
| 627 | change_num: changes.len() as u32, |
| 628 | }) |
| 629 | } |