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 | use std::{ |
| 2 | collections::{BTreeMap, BTreeSet}, |
| 3 | marker::PhantomData, |
| 4 | ops::Bound, |
| 5 | sync::Arc, |
| 6 | }; |
| 7 | |
| 8 | use crate::sync::Mutex; |
| 9 | use either::Either; |
| 10 | use enum_as_inner::EnumAsInner; |
| 11 | use enum_dispatch::enum_dispatch; |
| 12 | use generic_btree::rle::{HasLength as _, Sliceable}; |
| 13 | use loro_common::{ |
| 14 | ContainerType, Counter, HasLamport, IdFull, IdLp, InternalString, LoroValue, PeerID, ID, |
| 15 | }; |
| 16 | use rle::HasLength; |
| 17 | use rustc_hash::{FxHashMap, FxHashSet}; |
| 18 | |
| 19 | use crate::{ |
| 20 | change::{Change, Lamport}, |
| 21 | container::{ |
| 22 | idx::ContainerIdx, |
| 23 | list::list_op::InnerListOp, |
| 24 | richtext::{richtext_state::RichtextStateChunk, AnchorType, StyleOp}, |
| 25 | tree::tree_op::TreeOp, |
| 26 | }, |
| 27 | delta::MapValue, |
| 28 | diff_calc::tree::{MoveLamportAndID, TreeCacheForDiff}, |
| 29 | encoding::value_register::ValueRegister, |
| 30 | op::{InnerContent, RichOp, SliceWithId}, |
| 31 | oplog::ChangeStore, |
| 32 | state::{ContainerCreationContext, GcStore, TreeParentId}, |
| 33 | OpLog, VersionVector, |
| 34 | }; |
| 35 | |
| 36 | /// A cache for the history of a container. |
| 37 | /// |
| 38 | /// There are cases where a container needs a view of the history of the container. |
| 39 | /// For example, when switching to an older version, a map container may need to know the value of a key at a certain version. |
| 40 | /// This cache provides a faster way to do that than scanning the oplog. |
| 41 | #[derive(Debug)] |
| 42 | pub(crate) struct ContainerHistoryCache { |
| 43 | change_store: ChangeStore, |
| 44 | shallow_root_state: Option<Arc<GcStore>>, |
| 45 | for_checkout: Option<ForCheckout>, |
| 46 | for_importing: Option<FxHashMap<ContainerIdx, HistoryCacheForImporting>>, |
| 47 | /// Maps whose shallow-root entries are already in the checkout index. |
| 48 | /// Map entries are seeded per container on first use; see |
| 49 | /// [`Self::ensure_shallow_map_seeded`]. |
| 50 | shallow_maps_seeded: FxHashSet<ContainerIdx>, |
| 51 | } |
| 52 | |
| 53 | #[derive(Debug, Default)] |
| 54 | pub(crate) struct ForCheckout { |
| 55 | pub(crate) map: MapHistoryCache, |
| 56 | pub(crate) movable_list: MovableListHistoryCache, |
| 57 | } |
| 58 | |
| 59 | #[derive(Clone, Copy)] |
| 60 | pub(crate) struct HasImportingCacheMark { |
| 61 | _private: PhantomData<()>, |
| 62 | } |
| 63 | |
| 64 | impl HistoryCacheTrait for ForCheckout { |
| 65 | fn insert(&mut self, op: &RichOp) { |
| 66 | match op.raw_op().container.get_type() { |
| 67 | ContainerType::Map => self.map.insert(op), |
| 68 | ContainerType::MovableList => self.movable_list.insert(op), |
| 69 | _ => {} |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | impl ContainerHistoryCache { |
| 75 | pub(crate) fn new(change_store: ChangeStore, gc: Option<Arc<GcStore>>) -> Self { |
| 76 | Self { |
| 77 | change_store, |
| 78 | for_checkout: Default::default(), |
| 79 | for_importing: Default::default(), |
| 80 | shallow_root_state: gc, |
| 81 | shallow_maps_seeded: Default::default(), |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | pub(crate) fn insert_by_new_change( |
| 86 | &mut self, |
| 87 | change: &Change, |
| 88 | for_checkout: bool, |
| 89 | for_importing: bool, |
| 90 | ) { |
| 91 | if self.for_checkout.is_none() && self.for_importing.is_none() { |
| 92 | return; |
| 93 | } |
| 94 | |
| 95 | for op in change.ops.iter() { |
| 96 | match op.container.get_type() { |
| 97 | ContainerType::Map | ContainerType::MovableList |
| 98 | if self.for_checkout.is_some() && for_checkout => |
| 99 | { |
| 100 | let rich_op = RichOp::new_by_change(change, op); |
| 101 | self.for_checkout.as_mut().unwrap().insert(&rich_op) |
| 102 | } |
| 103 | ContainerType::Tree if self.for_importing.is_some() && for_importing => { |
| 104 | let container_idx = op.container; |
| 105 | let rich_op = RichOp::new_by_change(change, op); |
| 106 | let manager = self |
| 107 | .for_importing |
| 108 | .as_mut() |
| 109 | .unwrap() |
| 110 | .entry(container_idx) |
| 111 | .or_insert_with(|| match op.container.get_type() { |
| 112 | ContainerType::Tree => { |
| 113 | HistoryCacheForImporting::Tree(TreeOpGroup::default()) |
| 114 | } |
| 115 | _ => unreachable!(), |
| 116 | }); |
| 117 | manager.insert(&rich_op) |
| 118 | } |
| 119 | _ => continue, |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | pub(crate) fn get_checkout_index(&mut self) -> &ForCheckout { |
| 125 | self.ensure_all_caches_exist(); |
| 126 | self.for_checkout.as_ref().unwrap() |
| 127 | } |
| 128 | |
| 129 | pub(crate) fn ensure_all_caches_exist(&mut self) { |
| 130 | let mut record_for_checkout = false; |
| 131 | let mut record_for_importing = false; |
| 132 | if self.for_checkout.is_none() { |
| 133 | self.for_checkout = Some(ForCheckout::default()); |
| 134 | record_for_checkout = true; |
| 135 | } |
| 136 | |
| 137 | if self.for_importing.is_none() { |
| 138 | self.for_importing = Some(FxHashMap::default()); |
| 139 | record_for_importing = true; |
| 140 | } |
| 141 | |
| 142 | if !record_for_checkout && !record_for_importing { |
| 143 | return; |
| 144 | } |
| 145 | |
| 146 | self.init_cache_by_visit_all_change_slow(record_for_checkout, record_for_importing); |
| 147 | } |
| 148 | |
| 149 | pub(crate) fn ensure_importing_caches_exist(&mut self) -> HasImportingCacheMark { |
| 150 | if self.for_importing.is_some() { |
| 151 | return HasImportingCacheMark { |
| 152 | _private: PhantomData, |
| 153 | }; |
| 154 | } |
| 155 | |
| 156 | self.for_importing = Some(FxHashMap::default()); |
| 157 | self.init_cache_by_visit_all_change_slow(false, true); |
| 158 | HasImportingCacheMark { |
| 159 | _private: PhantomData, |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | fn init_cache_by_visit_all_change_slow(&mut self, for_checkout: bool, for_importing: bool) { |
| 164 | if self.for_checkout.is_none() && self.for_importing.is_none() { |
| 165 | return; |
| 166 | } |
| 167 | |
| 168 | if !for_checkout && !for_importing { |
| 169 | return; |
| 170 | } |
| 171 | |
| 172 | self.change_store.visit_all_changes(&mut |c| { |
| 173 | for op in c.ops.iter() { |
| 174 | match op.container.get_type() { |
| 175 | ContainerType::Map | ContainerType::MovableList |
| 176 | if self.for_checkout.is_some() && for_checkout => |
| 177 | { |
| 178 | let rich_op = RichOp::new_by_change(c, op); |
| 179 | self.for_checkout.as_mut().unwrap().insert(&rich_op) |
| 180 | } |
| 181 | ContainerType::Tree if self.for_importing.is_some() && for_importing => { |
| 182 | let container_idx = op.container; |
| 183 | let rich_op = RichOp::new_by_change(c, op); |
| 184 | let manager = self |
| 185 | .for_importing |
| 186 | .as_mut() |
| 187 | .unwrap() |
| 188 | .entry(container_idx) |
| 189 | .or_insert_with(|| match op.container.get_type() { |
| 190 | ContainerType::Tree => { |
| 191 | HistoryCacheForImporting::Tree(TreeOpGroup::default()) |
| 192 | } |
| 193 | _ => unreachable!(), |
| 194 | }); |
| 195 | manager.insert(&rich_op) |
| 196 | } |
| 197 | _ => continue, |
| 198 | } |
| 199 | } |
| 200 | }); |
| 201 | |
| 202 | let default_ctx = ContainerCreationContext { |
| 203 | configure: &Default::default(), |
| 204 | peer: 0, |
| 205 | }; |
| 206 | |
| 207 | if let Some(state) = self.shallow_root_state.as_ref() { |
| 208 | ensure_cov::notify_cov( |
| 209 | "loro_internal::history_cache::init_cache_by_visit_all_change_slow::visit_gc", |
| 210 | ); |
| 211 | let mut store = state.store.lock(); |
| 212 | // Maps are seeded per container on first use, so only movable lists |
| 213 | // and trees are loaded here; decoding every container of a large |
| 214 | // shallow root dominated the first concurrent map import. |
| 215 | for idx in store.tree_and_movable_list_idxs() { |
| 216 | let Some(c) = store.get_mut(idx) else { |
| 217 | continue; |
| 218 | }; |
| 219 | match idx.get_type() { |
| 220 | ContainerType::Text | ContainerType::List | ContainerType::Unknown(_) => { |
| 221 | continue |
| 222 | } |
| 223 | #[cfg(feature = "counter")] |
| 224 | ContainerType::Counter => continue, |
| 225 | ContainerType::Map => continue, |
| 226 | ContainerType::MovableList => {} |
| 227 | ContainerType::Tree => {} |
| 228 | } |
| 229 | |
| 230 | let state = c.get_state_mut(idx, default_ctx); |
| 231 | |
| 232 | match state { |
| 233 | crate::state::State::MapState(m) => { |
| 234 | if for_checkout { |
| 235 | let c = self.for_checkout.as_mut().unwrap(); |
| 236 | for (k, v) in m.iter() { |
| 237 | c.map.record_shallow_root_state_entry(idx, k, v); |
| 238 | } |
| 239 | } |
| 240 | } |
| 241 | crate::state::State::MovableListState(l) => { |
| 242 | for (idlp, elem) in l.elements() { |
| 243 | if for_checkout { |
| 244 | let c = self.for_checkout.as_mut().unwrap(); |
| 245 | let item = l.get_list_item(elem.pos).unwrap(); |
| 246 | c.movable_list.record_shallow_root_state( |
| 247 | item.id, |
| 248 | idlp.peer, |
| 249 | idlp.lamport.into(), |
| 250 | elem.value.clone(), |
| 251 | ); |
| 252 | } |
| 253 | } |
| 254 | } |
| 255 | crate::state::State::TreeState(t) => { |
| 256 | if for_importing { |
| 257 | let c = self.for_importing.as_mut().unwrap(); |
| 258 | let tree = c.entry(idx).or_insert_with(|| { |
| 259 | HistoryCacheForImporting::Tree(Default::default()) |
| 260 | }); |
| 261 | // Deleted nodes are seeded too: a retained op can revive a node |
| 262 | // deleted before the shallow root (e.g. move a child out of a |
| 263 | // deleted parent), and the diff calculator then needs the node's |
| 264 | // subtree at the root to re-create it and to retreat later moves. |
| 265 | tree.as_tree_mut().unwrap().record_shallow_root_state( |
| 266 | t.tree_nodes() |
| 267 | .into_iter() |
| 268 | .chain(t.deleted_tree_nodes()) |
| 269 | .map(|node| MoveLamportAndID { |
| 270 | id: node.last_move_op, |
| 271 | op: Arc::new(if node.parent == TreeParentId::Deleted { |
| 272 | TreeOp::Delete { target: node.id } |
| 273 | } else { |
| 274 | TreeOp::Create { |
| 275 | target: node.id, |
| 276 | parent: node.parent.tree_id(), |
| 277 | position: node.fractional_index.clone(), |
| 278 | } |
| 279 | }), |
| 280 | effected: true, |
| 281 | }) |
| 282 | .collect(), |
| 283 | ); |
| 284 | } |
| 285 | } |
| 286 | _ => unreachable!(), |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | pub(crate) fn get_tree( |
| 293 | &self, |
| 294 | container_idx: &ContainerIdx, |
| 295 | _: HasImportingCacheMark, |
| 296 | ) -> Option<&TreeOpGroup> { |
| 297 | self.for_importing |
| 298 | .as_ref() |
| 299 | .unwrap() |
| 300 | .get(container_idx) |
| 301 | .map(|group| match group { |
| 302 | HistoryCacheForImporting::Tree(tree) => tree, |
| 303 | }) |
| 304 | } |
| 305 | |
| 306 | pub(crate) fn has_cache(&self) -> bool { |
| 307 | self.for_checkout.is_some() |
| 308 | } |
| 309 | |
| 310 | pub(crate) fn free(&mut self) { |
| 311 | self.for_checkout = None; |
| 312 | self.shallow_maps_seeded.clear(); |
| 313 | } |
| 314 | |
| 315 | pub(crate) fn free_all(&mut self) { |
| 316 | self.for_checkout = None; |
| 317 | self.for_importing = None; |
| 318 | self.shallow_maps_seeded.clear(); |
| 319 | } |
| 320 | |
| 321 | pub(crate) fn set_shallow_root_store(&mut self, shallow_root_store: Option<Arc<GcStore>>) { |
| 322 | self.shallow_root_state = shallow_root_store; |
| 323 | self.shallow_maps_seeded.clear(); |
| 324 | } |
| 325 | |
| 326 | /// Ensure the checkout index exists and holds `idx`'s shallow-root map entries. |
| 327 | /// |
| 328 | /// Map entries are only read per container (`MapDiffCalculator` asks for its |
| 329 | /// own container's changed keys), so each map is seeded the first time a |
| 330 | /// diff needs it instead of seeding every map in the shallow root up front. |
| 331 | pub(crate) fn ensure_shallow_map_seeded(&mut self, idx: ContainerIdx) { |
| 332 | self.ensure_all_caches_exist(); |
| 333 | if !self.shallow_maps_seeded.insert(idx) { |
| 334 | return; |
| 335 | } |
| 336 | let Some(state) = self.shallow_root_state.as_ref() else { |
| 337 | return; |
| 338 | }; |
| 339 | let default_ctx = ContainerCreationContext { |
| 340 | configure: &Default::default(), |
| 341 | peer: 0, |
| 342 | }; |
| 343 | let mut store = state.store.lock(); |
| 344 | let Some(c) = store.get_mut(idx) else { |
| 345 | return; |
| 346 | }; |
| 347 | if let crate::state::State::MapState(m) = c.get_state_mut(idx, default_ctx) { |
| 348 | let cache = self.for_checkout.as_mut().unwrap(); |
| 349 | for (k, v) in m.iter() { |
| 350 | cache.map.record_shallow_root_state_entry(idx, k, v); |
| 351 | } |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | /// Whether the movable list `idx` holds `elem_id` in the shallow root state. |
| 356 | /// |
| 357 | /// Elements created before the shallow root cannot be resolved from the trimmed |
| 358 | /// history; the checkout index only knows the ones still alive at the root |
| 359 | /// (`MovableListHistoryCache::record_shallow_root_state`). |
| 360 | pub(crate) fn shallow_root_has_movable_list_elem( |
| 361 | &self, |
| 362 | idx: ContainerIdx, |
| 363 | elem_id: IdLp, |
| 364 | ) -> bool { |
| 365 | let Some(state) = self.shallow_root_state.as_ref() else { |
| 366 | return false; |
| 367 | }; |
| 368 | let mut store = state.store.lock(); |
| 369 | let Some(c) = store.get_mut(idx) else { |
| 370 | return false; |
| 371 | }; |
| 372 | let ctx = ContainerCreationContext { |
| 373 | configure: &Default::default(), |
| 374 | peer: 0, |
| 375 | }; |
| 376 | match c.get_state_mut(idx, ctx) { |
| 377 | crate::state::State::MovableListState(l) => { |
| 378 | l.elements().contains_key(&elem_id.compact()) |
| 379 | } |
| 380 | _ => false, |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | pub(crate) fn find_text_chunks_in( |
| 385 | &self, |
| 386 | idx: ContainerIdx, |
| 387 | target_span: loro_common::IdSpan, |
| 388 | ) -> Vec<RichtextStateChunk> { |
| 389 | ensure_cov::notify_cov("loro_internal::history_cache::find_text_chunks_in"); |
| 390 | let Some(state) = self.shallow_root_state.as_ref() else { |
| 391 | return Vec::new(); |
| 392 | }; |
| 393 | |
| 394 | let mut binding = state.store.lock(); |
| 395 | let Some(text) = binding.get_mut(idx) else { |
| 396 | return Vec::new(); |
| 397 | }; |
| 398 | |
| 399 | let text_state = text |
| 400 | .get_state( |
| 401 | idx, |
| 402 | ContainerCreationContext { |
| 403 | configure: &Default::default(), |
| 404 | peer: 0, |
| 405 | }, |
| 406 | ) |
| 407 | .as_richtext_state() |
| 408 | .unwrap(); |
| 409 | |
| 410 | // TODO: FIXME: This could be super slow in some cases |
| 411 | let mut ans = Vec::new(); |
| 412 | text_state.iter_raw(&mut |chunk| { |
| 413 | let c_span = chunk.get_id_span(); |
| 414 | if let Some(range) = target_span.get_slice_range_on(&c_span) { |
| 415 | let c = chunk.slice(range.0..range.1); |
| 416 | ans.push(c); |
| 417 | } |
| 418 | }); |
| 419 | |
| 420 | ans.sort_unstable_by_key(|x| x.counter()); |
| 421 | let mut normalized = Vec::with_capacity(ans.len()); |
| 422 | let mut covered_end = target_span.counter.start; |
| 423 | for chunk in ans { |
| 424 | let span = chunk.get_id_span(); |
| 425 | let start = span.counter.start.max(covered_end); |
| 426 | let end = span.counter.end.min(target_span.counter.end); |
| 427 | if start >= end { |
| 428 | continue; |
| 429 | } |
| 430 | |
| 431 | normalized.push( |
| 432 | chunk.slice( |
| 433 | (start - span.counter.start) as usize..(end - span.counter.start) as usize, |
| 434 | ), |
| 435 | ); |
| 436 | covered_end = end; |
| 437 | } |
| 438 | |
| 439 | normalized |
| 440 | } |
| 441 | |
| 442 | pub(crate) fn find_text_chunks_in_shallow_root_order( |
| 443 | &self, |
| 444 | idx: ContainerIdx, |
| 445 | ) -> Vec<RichtextStateChunk> { |
| 446 | ensure_cov::notify_cov( |
| 447 | "loro_internal::history_cache::find_text_chunks_in_shallow_root_order", |
| 448 | ); |
| 449 | let Some(state) = self.shallow_root_state.as_ref() else { |
| 450 | return Vec::new(); |
| 451 | }; |
| 452 | |
| 453 | let mut binding = state.store.lock(); |
| 454 | let Some(text) = binding.get_mut(idx) else { |
| 455 | return Vec::new(); |
| 456 | }; |
| 457 | |
| 458 | let text_state = text |
| 459 | .get_state( |
| 460 | idx, |
| 461 | ContainerCreationContext { |
| 462 | configure: &Default::default(), |
| 463 | peer: 0, |
| 464 | }, |
| 465 | ) |
| 466 | .as_richtext_state() |
| 467 | .unwrap(); |
| 468 | |
| 469 | let mut ans = Vec::new(); |
| 470 | text_state.iter_raw(&mut |chunk| { |
| 471 | ans.push(chunk.slice(0..chunk.rle_len())); |
| 472 | }); |
| 473 | |
| 474 | ans |
| 475 | } |
| 476 | |
| 477 | pub(crate) fn find_text_style_end_in_shallow_root( |
| 478 | &self, |
| 479 | idx: ContainerIdx, |
| 480 | style_start_id: ID, |
| 481 | ) -> Option<(StyleOp, usize)> { |
| 482 | ensure_cov::notify_cov("loro_internal::history_cache::find_text_style_end_in_shallow_root"); |
| 483 | let state = self.shallow_root_state.as_ref()?; |
| 484 | |
| 485 | let mut binding = state.store.lock(); |
| 486 | let text = binding.get_mut(idx)?; |
| 487 | |
| 488 | let text_state = text |
| 489 | .get_state( |
| 490 | idx, |
| 491 | ContainerCreationContext { |
| 492 | configure: &Default::default(), |
| 493 | peer: 0, |
| 494 | }, |
| 495 | ) |
| 496 | .as_richtext_state() |
| 497 | .unwrap(); |
| 498 | |
| 499 | let mut entity_index = 0; |
| 500 | let mut ans = None; |
| 501 | text_state.iter_raw(&mut |chunk| { |
| 502 | if ans.is_some() { |
| 503 | return; |
| 504 | } |
| 505 | |
| 506 | match chunk { |
| 507 | RichtextStateChunk::Text(text) => { |
| 508 | entity_index += text.unicode_len() as usize; |
| 509 | } |
| 510 | RichtextStateChunk::Style { style, anchor_type } => { |
| 511 | if style.id() == style_start_id && *anchor_type == AnchorType::End { |
| 512 | ans = Some((style.as_ref().clone(), entity_index.saturating_sub(1))); |
| 513 | } |
| 514 | entity_index += 1; |
| 515 | } |
| 516 | } |
| 517 | }); |
| 518 | |
| 519 | ans |
| 520 | } |
| 521 | |
| 522 | pub(crate) fn find_list_chunks_in( |
| 523 | &self, |
| 524 | idx: ContainerIdx, |
| 525 | target_span: loro_common::IdSpan, |
| 526 | ) -> Vec<SliceWithId> { |
| 527 | ensure_cov::notify_cov("loro_internal::history_cache::find_list_chunks_in"); |
| 528 | let Some(state) = self.shallow_root_state.as_ref() else { |
| 529 | return Vec::new(); |
| 530 | }; |
| 531 | |
| 532 | let mut binding = state.store.lock(); |
| 533 | let Some(list) = binding.get_mut(idx) else { |
| 534 | return Vec::new(); |
| 535 | }; |
| 536 | |
| 537 | let list_state = list.get_state( |
| 538 | idx, |
| 539 | ContainerCreationContext { |
| 540 | configure: &Default::default(), |
| 541 | peer: 0, |
| 542 | }, |
| 543 | ); |
| 544 | |
| 545 | let mut ans = Vec::with_capacity(target_span.atom_len()); |
| 546 | match list_state { |
| 547 | crate::state::State::ListState(list) => { |
| 548 | for v in list.iter_with_id() { |
| 549 | if target_span.contains(v.id.id()) { |
| 550 | ans.push(SliceWithId { |
| 551 | values: Either::Right(v.v.clone()), |
| 552 | id: v.id, |
| 553 | elem_id: None, |
| 554 | }) |
| 555 | } |
| 556 | } |
| 557 | } |
| 558 | crate::state::State::MovableListState(list) => { |
| 559 | for (move_id, elem_id, v) in list.iter_with_last_move_id_and_elem_id() { |
| 560 | if target_span.contains(move_id.id()) { |
| 561 | ans.push(SliceWithId { |
| 562 | values: Either::Right(v.clone()), |
| 563 | id: move_id, |
| 564 | elem_id: Some(elem_id), |
| 565 | }) |
| 566 | } |
| 567 | } |
| 568 | } |
| 569 | _ => unreachable!(), |
| 570 | } |
| 571 | |
| 572 | ans.sort_unstable_by_key(|x| x.id.counter); |
| 573 | ans |
| 574 | } |
| 575 | } |
| 576 | |
| 577 | #[enum_dispatch(OpGroupTrait)] |
| 578 | #[derive(Debug, EnumAsInner)] |
| 579 | pub(crate) enum HistoryCacheForImporting { |
| 580 | Tree(TreeOpGroup), |
| 581 | } |
| 582 | |
| 583 | impl HistoryCacheForImporting { |
| 584 | fn insert(&mut self, op: &RichOp) { |
| 585 | match self { |
| 586 | HistoryCacheForImporting::Tree(t) => t.insert(op), |
| 587 | } |
| 588 | } |
| 589 | } |
| 590 | |
| 591 | #[enum_dispatch] |
| 592 | trait HistoryCacheTrait { |
| 593 | fn insert(&mut self, op: &RichOp); |
| 594 | } |
| 595 | |
| 596 | #[derive(Debug, Clone)] |
| 597 | pub(crate) struct GroupedMapOpInfo<T = Option<LoroValue>> { |
| 598 | pub(crate) value: T, |
| 599 | pub(crate) lamport: Lamport, |
| 600 | pub(crate) peer: PeerID, |
| 601 | } |
| 602 | |
| 603 | impl<T> PartialEq for GroupedMapOpInfo<T> { |
| 604 | fn eq(&self, other: &Self) -> bool { |
| 605 | self.lamport == other.lamport && self.peer == other.peer |
| 606 | } |
| 607 | } |
| 608 | |
| 609 | impl<T> Eq for GroupedMapOpInfo<T> {} |
| 610 | |
| 611 | impl<T> PartialOrd for GroupedMapOpInfo<T> { |
| 612 | fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { |
| 613 | Some(self.cmp(other)) |
| 614 | } |
| 615 | } |
| 616 | |
| 617 | impl<T> Ord for GroupedMapOpInfo<T> { |
| 618 | fn cmp(&self, other: &Self) -> std::cmp::Ordering { |
| 619 | self.lamport |
| 620 | .cmp(&other.lamport) |
| 621 | .then_with(|| self.peer.cmp(&other.peer)) |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | #[derive(Debug, Clone)] |
| 626 | struct MapHistoryCacheEntry { |
| 627 | container: ContainerIdx, |
| 628 | key: u32, |
| 629 | lamport: Lamport, |
| 630 | peer: PeerID, |
| 631 | counter_or_value: Either<Counter, Box<Option<LoroValue>>>, |
| 632 | } |
| 633 | |
| 634 | impl PartialEq for MapHistoryCacheEntry { |
| 635 | fn eq(&self, other: &Self) -> bool { |
| 636 | self.container == other.container |
| 637 | && self.key == other.key |
| 638 | && self.lamport == other.lamport |
| 639 | && self.peer == other.peer |
| 640 | } |
| 641 | } |
| 642 | |
| 643 | impl Eq for MapHistoryCacheEntry {} |
| 644 | |
| 645 | impl PartialOrd for MapHistoryCacheEntry { |
| 646 | fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { |
| 647 | Some(self.cmp(other)) |
| 648 | } |
| 649 | } |
| 650 | |
| 651 | impl Ord for MapHistoryCacheEntry { |
| 652 | fn cmp(&self, other: &Self) -> std::cmp::Ordering { |
| 653 | self.container |
| 654 | .cmp(&other.container) |
| 655 | .then_with(|| self.key.cmp(&other.key)) |
| 656 | .then_with(|| self.lamport.cmp(&other.lamport)) |
| 657 | .then_with(|| self.peer.cmp(&other.peer)) |
| 658 | } |
| 659 | } |
| 660 | |
| 661 | #[derive(Debug, Default)] |
| 662 | pub(crate) struct MapHistoryCache { |
| 663 | keys: ValueRegister<InternalString>, |
| 664 | map: BTreeSet<MapHistoryCacheEntry>, |
| 665 | } |
| 666 | |
| 667 | impl HistoryCacheTrait for MapHistoryCache { |
| 668 | fn insert(&mut self, op: &RichOp) { |
| 669 | let container = op.raw_op().container; |
| 670 | let key = match &op.raw_op().content { |
| 671 | InnerContent::Map(map) => map.key.clone(), |
| 672 | _ => unreachable!(), |
| 673 | }; |
| 674 | |
| 675 | let key_idx = self.keys.register(&key); |
| 676 | self.map.insert(MapHistoryCacheEntry { |
| 677 | container, |
| 678 | key: key_idx as u32, |
| 679 | lamport: op.lamport(), |
| 680 | peer: op.peer, |
| 681 | counter_or_value: Either::Left(op.counter()), |
| 682 | }); |
| 683 | } |
| 684 | } |
| 685 | |
| 686 | impl MapHistoryCache { |
| 687 | fn record_shallow_root_state_entry( |
| 688 | &mut self, |
| 689 | idx: ContainerIdx, |
| 690 | k: &InternalString, |
| 691 | v: &MapValue, |
| 692 | ) { |
| 693 | let key_idx = self.keys.register(k); |
| 694 | self.map.insert(MapHistoryCacheEntry { |
| 695 | container: idx, |
| 696 | key: key_idx as u32, |
| 697 | lamport: v.lamport(), |
| 698 | peer: v.peer, |
| 699 | counter_or_value: Either::Right(Box::new(v.value.clone())), |
| 700 | }); |
| 701 | } |
| 702 | |
| 703 | /// The entry of the op that wins `key` at `vv`, if any. |
| 704 | fn latest_entry_at_vv( |
| 705 | &self, |
| 706 | container: ContainerIdx, |
| 707 | key: u32, |
| 708 | vv: &VersionVector, |
| 709 | ) -> Option<&MapHistoryCacheEntry> { |
| 710 | let bound = |lamport, peer| MapHistoryCacheEntry { |
| 711 | container, |
| 712 | key, |
| 713 | lamport, |
| 714 | peer, |
| 715 | counter_or_value: Either::Left(0), |
| 716 | }; |
| 717 | self.map |
| 718 | .range(bound(0, 0)..=bound(Lamport::MAX, PeerID::MAX)) |
| 719 | .rev() |
| 720 | .find(|entry| match &entry.counter_or_value { |
| 721 | Either::Left(cnt) => vv.get(&entry.peer).copied().unwrap_or(0) > *cnt, |
| 722 | // Shallow-root entries are part of every version the doc can reach. |
| 723 | Either::Right(_) => true, |
| 724 | }) |
| 725 | } |
| 726 | |
| 727 | fn entry_info(entry: &MapHistoryCacheEntry, oplog: &OpLog) -> GroupedMapOpInfo { |
| 728 | let value = match &entry.counter_or_value { |
| 729 | Either::Left(cnt) => { |
| 730 | let op = oplog |
| 731 | .get_op_that_includes(ID::new(entry.peer, *cnt)) |
| 732 | .unwrap(); |
| 733 | debug_assert_eq!(op.atom_len(), 1); |
| 734 | match &op.content { |
| 735 | InnerContent::Map(map) => map.value.clone(), |
| 736 | _ => unreachable!(), |
| 737 | } |
| 738 | } |
| 739 | Either::Right(v) => (**v).clone(), |
| 740 | }; |
| 741 | GroupedMapOpInfo { |
| 742 | value, |
| 743 | lamport: entry.lamport, |
| 744 | peer: entry.peer, |
| 745 | } |
| 746 | } |
| 747 | |
| 748 | /// For each key, the op that wins it at `to_vv` when that differs from the |
| 749 | /// op that wins it at `from_vv`; `None` when no op sets the key at `to_vv`. |
| 750 | /// |
| 751 | /// Every key whose value can differ between two versions must have been |
| 752 | /// written by an op inside the replayed span, so a diff only ever needs the |
| 753 | /// candidate keys instead of the whole container. This keeps map diffing |
| 754 | /// proportional to the update instead of to the size of the map. |
| 755 | /// |
| 756 | /// Winners are compared by op id only, so only the `to` value is ever |
| 757 | /// fetched. A different winner can still carry an equal value; the caller's |
| 758 | /// state has the `from` value and tells the two cases apart (see |
| 759 | /// `MapDiffCalculator::calculate_diff`). |
| 760 | pub fn changed_winners_for_keys( |
| 761 | &self, |
| 762 | container: ContainerIdx, |
| 763 | from_vv: &VersionVector, |
| 764 | to_vv: &VersionVector, |
| 765 | keys: impl Iterator<Item = InternalString>, |
| 766 | oplog: &OpLog, |
| 767 | ) -> Vec<(InternalString, Option<GroupedMapOpInfo>)> { |
| 768 | let mut ans = Vec::new(); |
| 769 | for key in keys { |
| 770 | let Some(key_idx) = self.keys.get(&key) else { |
| 771 | continue; |
| 772 | }; |
| 773 | let key_idx = key_idx as u32; |
| 774 | let from = self.latest_entry_at_vv(container, key_idx, from_vv); |
| 775 | let to = self.latest_entry_at_vv(container, key_idx, to_vv); |
| 776 | match (from, to) { |
| 777 | (None, None) => {} |
| 778 | (Some(_), None) => ans.push((key, None)), |
| 779 | (Some(a), Some(b)) if a.lamport == b.lamport && a.peer == b.peer => {} |
| 780 | (_, Some(b)) => ans.push((key, Some(Self::entry_info(b, oplog)))), |
| 781 | } |
| 782 | } |
| 783 | |
| 784 | ans |
| 785 | } |
| 786 | } |
| 787 | |
| 788 | #[derive(Debug, Clone)] |
| 789 | pub(crate) struct GroupedTreeOpInfo { |
| 790 | pub(crate) counter: Counter, |
| 791 | pub(crate) value: Arc<TreeOp>, |
| 792 | } |
| 793 | |
| 794 | #[derive(Debug, Default)] |
| 795 | pub(crate) struct TreeOpGroup { |
| 796 | ops: BTreeMap<IdLp, GroupedTreeOpInfo>, |
| 797 | tree_for_diff: Mutex<TreeCacheForDiff>, |
| 798 | } |
| 799 | |
| 800 | impl HistoryCacheTrait for TreeOpGroup { |
| 801 | fn insert(&mut self, op: &RichOp) { |
| 802 | let tree_op = op.raw_op().content.as_tree().unwrap(); |
| 803 | self.ops.insert( |
| 804 | op.idlp(), |
| 805 | GroupedTreeOpInfo { |
| 806 | value: tree_op.clone(), |
| 807 | counter: op.raw_op().counter, |
| 808 | }, |
| 809 | ); |
| 810 | } |
| 811 | } |
| 812 | |
| 813 | impl TreeOpGroup { |
| 814 | pub fn ops(&self) -> &BTreeMap<IdLp, GroupedTreeOpInfo> { |
| 815 | &self.ops |
| 816 | } |
| 817 | |
| 818 | pub fn tree(&self) -> &Mutex<TreeCacheForDiff> { |
| 819 | &self.tree_for_diff |
| 820 | } |
| 821 | |
| 822 | pub(crate) fn record_shallow_root_state(&mut self, nodes: Vec<MoveLamportAndID>) { |
| 823 | let mut tree = self.tree_for_diff.lock(); |
| 824 | for node in nodes.iter() { |
| 825 | self.ops.insert( |
| 826 | node.id.idlp(), |
| 827 | GroupedTreeOpInfo { |
| 828 | counter: node.id.counter, |
| 829 | value: node.op.clone(), |
| 830 | }, |
| 831 | ); |
| 832 | } |
| 833 | tree.init_tree_with_shallow_root_version(nodes); |
| 834 | } |
| 835 | } |
| 836 | |
| 837 | #[derive(Debug, Default)] |
| 838 | pub(crate) struct MovableListHistoryCache { |
| 839 | move_set: BTreeSet<MovableListInnerDeltaEntry>, |
| 840 | set_set: BTreeSet<MovableListSetDeltaEntry>, |
| 841 | } |
| 842 | |
| 843 | #[derive(Debug, Eq, PartialEq, Clone)] |
| 844 | struct MovableListInnerDeltaEntry { |
| 845 | element_lamport: Lamport, |
| 846 | element_peer: PeerID, |
| 847 | lamport: Lamport, |
| 848 | peer: PeerID, |
| 849 | counter: Counter, |
| 850 | } |
| 851 | |
| 852 | #[derive(Debug, Eq, PartialEq, Clone)] |
| 853 | struct MovableListSetDeltaEntry { |
| 854 | element_lamport: Lamport, |
| 855 | element_peer: PeerID, |
| 856 | lamport: Lamport, |
| 857 | peer: PeerID, |
| 858 | counter_or_value: Either<Counter, Box<LoroValue>>, |
| 859 | } |
| 860 | |
| 861 | impl Ord for MovableListInnerDeltaEntry { |
| 862 | fn cmp(&self, other: &Self) -> std::cmp::Ordering { |
| 863 | self.element_lamport |
| 864 | .cmp(&other.element_lamport) |
| 865 | .then_with(|| self.element_peer.cmp(&other.element_peer)) |
| 866 | .then_with(|| self.lamport.cmp(&other.lamport)) |
| 867 | .then_with(|| self.peer.cmp(&other.peer)) |
| 868 | } |
| 869 | } |
| 870 | |
| 871 | impl PartialOrd for MovableListInnerDeltaEntry { |
| 872 | fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { |
| 873 | Some(self.cmp(other)) |
| 874 | } |
| 875 | } |
| 876 | |
| 877 | impl PartialOrd for MovableListSetDeltaEntry { |
| 878 | fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { |
| 879 | Some(self.cmp(other)) |
| 880 | } |
| 881 | } |
| 882 | |
| 883 | impl Ord for MovableListSetDeltaEntry { |
| 884 | fn cmp(&self, other: &Self) -> std::cmp::Ordering { |
| 885 | self.element_lamport |
| 886 | .cmp(&other.element_lamport) |
| 887 | .then_with(|| self.element_peer.cmp(&other.element_peer)) |
| 888 | .then_with(|| self.lamport.cmp(&other.lamport)) |
| 889 | .then_with(|| self.peer.cmp(&other.peer)) |
| 890 | } |
| 891 | } |
| 892 | |
| 893 | impl HistoryCacheTrait for MovableListHistoryCache { |
| 894 | fn insert(&mut self, op: &RichOp) { |
| 895 | let cur_id = op.id_full(); |
| 896 | match &op.op().content { |
| 897 | InnerContent::List(l) => match l { |
| 898 | crate::container::list::list_op::InnerListOp::Move { elem_id, .. } => { |
| 899 | self.move_set.insert(MovableListInnerDeltaEntry { |
| 900 | element_lamport: elem_id.lamport, |
| 901 | element_peer: elem_id.peer, |
| 902 | lamport: cur_id.lamport, |
| 903 | peer: cur_id.peer, |
| 904 | counter: cur_id.counter, |
| 905 | }); |
| 906 | } |
| 907 | crate::container::list::list_op::InnerListOp::Set { elem_id, .. } => { |
| 908 | self.set_set.insert(MovableListSetDeltaEntry { |
| 909 | element_lamport: elem_id.lamport, |
| 910 | element_peer: elem_id.peer, |
| 911 | lamport: cur_id.lamport, |
| 912 | peer: cur_id.peer, |
| 913 | counter_or_value: Either::Left(cur_id.counter), |
| 914 | }); |
| 915 | } |
| 916 | _ => {} |
| 917 | }, |
| 918 | _ => unreachable!(), |
| 919 | } |
| 920 | } |
| 921 | } |
| 922 | |
| 923 | impl MovableListHistoryCache { |
| 924 | pub(crate) fn record_shallow_root_state( |
| 925 | &mut self, |
| 926 | id: IdFull, |
| 927 | elem_peer: PeerID, |
| 928 | elem_lamport: Lamport, |
| 929 | value: LoroValue, |
| 930 | ) { |
| 931 | self.set_set.insert(MovableListSetDeltaEntry { |
| 932 | element_lamport: elem_lamport, |
| 933 | element_peer: elem_peer, |
| 934 | lamport: id.lamport, |
| 935 | peer: id.peer, |
| 936 | counter_or_value: Either::Right(Box::new(value.clone())), |
| 937 | }); |
| 938 | self.move_set.insert(MovableListInnerDeltaEntry { |
| 939 | element_lamport: elem_lamport, |
| 940 | element_peer: elem_peer, |
| 941 | lamport: id.lamport, |
| 942 | peer: id.peer, |
| 943 | counter: id.counter, |
| 944 | }); |
| 945 | } |
| 946 | |
| 947 | pub(crate) fn last_value( |
| 948 | &self, |
| 949 | key: IdLp, |
| 950 | vv: &VersionVector, |
| 951 | max_lamport: Lamport, |
| 952 | oplog: &OpLog, |
| 953 | ) -> Option<GroupedMapOpInfo<LoroValue>> { |
| 954 | self.set_set |
| 955 | .range(( |
| 956 | Bound::Included(MovableListSetDeltaEntry { |
| 957 | element_lamport: key.lamport, |
| 958 | element_peer: key.peer, |
| 959 | lamport: 0, |
| 960 | peer: 0, |
| 961 | counter_or_value: Either::Left(0), |
| 962 | }), |
| 963 | Bound::Excluded(MovableListSetDeltaEntry { |
| 964 | element_lamport: key.lamport, |
| 965 | element_peer: key.peer, |
| 966 | lamport: max_lamport, |
| 967 | peer: PeerID::MAX, |
| 968 | counter_or_value: Either::Left(Counter::MAX), |
| 969 | }), |
| 970 | )) |
| 971 | .rev() |
| 972 | .find(|e| { |
| 973 | let counter = match &e.counter_or_value { |
| 974 | Either::Left(c) => *c, |
| 975 | Either::Right(_) => -1, |
| 976 | }; |
| 977 | vv.get(&e.peer).copied().unwrap_or(0) > counter |
| 978 | }) |
| 979 | .map_or_else( |
| 980 | || { |
| 981 | let id = oplog.idlp_to_id(key).unwrap(); |
| 982 | if vv.get(&id.peer).copied().unwrap_or(0) <= id.counter { |
| 983 | return None; |
| 984 | } |
| 985 | let op = oplog.get_op_that_includes(id).unwrap(); |
| 986 | let offset = id.counter - op.counter; |
| 987 | match &op.content { |
| 988 | InnerContent::List(InnerListOp::Insert { slice, .. }) => { |
| 989 | let value = slice.as_slice()[offset as usize].clone(); |
| 990 | Some(GroupedMapOpInfo { |
| 991 | value, |
| 992 | lamport: key.lamport, |
| 993 | peer: id.peer, |
| 994 | }) |
| 995 | } |
| 996 | _ => { |
| 997 | unreachable!() |
| 998 | } |
| 999 | } |
| 1000 | }, |
| 1001 | |e| { |
| 1002 | let (lamport, value) = match &e.counter_or_value { |
| 1003 | Either::Left(c) => { |
| 1004 | let id = ID::new(e.peer, *c); |
| 1005 | let op = oplog.get_op_that_includes(id).unwrap(); |
| 1006 | debug_assert_eq!(op.atom_len(), 1); |
| 1007 | let lamport = op.lamport(); |
| 1008 | match &op.content { |
| 1009 | InnerContent::List(InnerListOp::Set { value, .. }) => { |
| 1010 | (lamport, value.clone()) |
| 1011 | } |
| 1012 | _ => { |
| 1013 | unreachable!() |
| 1014 | } |
| 1015 | } |
| 1016 | } |
| 1017 | Either::Right(v) => (e.lamport, v.as_ref().clone()), |
| 1018 | }; |
| 1019 | Some(GroupedMapOpInfo { |
| 1020 | value: value.clone(), |
| 1021 | lamport, |
| 1022 | peer: e.peer, |
| 1023 | }) |
| 1024 | }, |
| 1025 | ) |
| 1026 | } |
| 1027 | |
| 1028 | pub(crate) fn last_pos( |
| 1029 | &self, |
| 1030 | key: IdLp, |
| 1031 | vv: &VersionVector, |
| 1032 | max_lamport: Lamport, |
| 1033 | oplog: &OpLog, |
| 1034 | ) -> Option<IdFull> { |
| 1035 | self.move_set |
| 1036 | .range(( |
| 1037 | Bound::Included(MovableListInnerDeltaEntry { |
| 1038 | element_lamport: key.lamport, |
| 1039 | element_peer: key.peer, |
| 1040 | lamport: 0, |
| 1041 | peer: 0, |
| 1042 | counter: 0, |
| 1043 | }), |
| 1044 | Bound::Excluded(MovableListInnerDeltaEntry { |
| 1045 | element_lamport: key.lamport, |
| 1046 | element_peer: key.peer, |
| 1047 | lamport: max_lamport, |
| 1048 | peer: PeerID::MAX, |
| 1049 | counter: Counter::MAX, |
| 1050 | }), |
| 1051 | )) |
| 1052 | .rev() |
| 1053 | .find(|e| vv.get(&e.peer).copied().unwrap_or(0) > e.counter) |
| 1054 | .map_or_else( |
| 1055 | || { |
| 1056 | let id = oplog.idlp_to_id(key).unwrap(); |
| 1057 | if vv.get(&id.peer).copied().unwrap_or(0) > id.counter { |
| 1058 | Some(IdFull::new(id.peer, id.counter, key.lamport)) |
| 1059 | } else { |
| 1060 | None |
| 1061 | } |
| 1062 | }, |
| 1063 | |e| { |
| 1064 | let id = ID::new(e.peer, e.counter); |
| 1065 | let lamport = oplog.get_lamport_at(id).unwrap_or(e.lamport); |
| 1066 | Some(IdFull::new(e.peer, e.counter, lamport)) |
| 1067 | }, |
| 1068 | ) |
| 1069 | } |
| 1070 | } |