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 super::outdated_encode_reordered::ValueRegister; |
| 2 | use crate::{ |
| 3 | arena::SharedArena, |
| 4 | change::{Change, ChangeRef}, |
| 5 | container::{ |
| 6 | list::list_op::{DeleteSpan, DeleteSpanWithId, InnerListOp}, |
| 7 | map::MapSet, |
| 8 | richtext::TextStyleInfoFlag, |
| 9 | tree::tree_op::TreeOp, |
| 10 | }, |
| 11 | op::{FutureInnerContent, InnerContent, Op, ValueSlice}, |
| 12 | oplog::BlockChangeRef, |
| 13 | version::Frontiers, |
| 14 | OpLog, VersionVector, |
| 15 | }; |
| 16 | use either::Either; |
| 17 | use itertools::Itertools; |
| 18 | use json::{JsonChange, JsonOpContent, JsonSchema}; |
| 19 | use loro_common::{ |
| 20 | ContainerID, ContainerType, Counter, HasCounterSpan, HasId, IdLp, IdSpan, LoroError, |
| 21 | LoroResult, LoroValue, PeerID, TreeID, ID, |
| 22 | }; |
| 23 | use rle::{HasLength, RleVec, Sliceable}; |
| 24 | use std::sync::Arc; |
| 25 | |
| 26 | const SCHEMA_VERSION: u8 = 1; |
| 27 | |
| 28 | fn refine_vv(vv: &VersionVector, oplog: &OpLog) -> VersionVector { |
| 29 | let mut refined = VersionVector::new(); |
| 30 | for (&peer, &counter) in vv.iter() { |
| 31 | if counter <= 0 { |
| 32 | continue; |
| 33 | } |
| 34 | let end = oplog.vv().get(&peer).copied().unwrap_or(0); |
| 35 | if end <= counter { |
| 36 | refined.insert(peer, end); |
| 37 | } else { |
| 38 | refined.insert(peer, counter); |
| 39 | } |
| 40 | } |
| 41 | refined |
| 42 | } |
| 43 | |
| 44 | pub(crate) fn try_export_json<'a, 'c: 'a>( |
| 45 | oplog: &'c OpLog, |
| 46 | start_vv: &VersionVector, |
| 47 | end_vv: &VersionVector, |
| 48 | with_peer_compression: bool, |
| 49 | ) -> LoroResult<JsonSchema> { |
| 50 | let actual_start_vv = refine_vv(start_vv, oplog); |
| 51 | let actual_end_vv = refine_vv(end_vv, oplog); |
| 52 | |
| 53 | let frontiers = oplog.dag.try_vv_to_frontiers(&actual_start_vv)?; |
| 54 | |
| 55 | let diff_changes = init_encode(oplog, &actual_start_vv, &actual_end_vv); |
| 56 | // Legacy iteration records a bad block and skips it. Do not return that gap. |
| 57 | oplog.check_history_parsable()?; |
| 58 | if with_peer_compression { |
| 59 | let mut peer_register = ValueRegister::<PeerID>::new(); |
| 60 | let changes = encode_changes(&diff_changes, &oplog.arena, Some(&mut peer_register)); |
| 61 | Ok(JsonSchema { |
| 62 | changes, |
| 63 | schema_version: SCHEMA_VERSION, |
| 64 | peers: Some(peer_register.unwrap_vec()), |
| 65 | start_version: frontiers, |
| 66 | }) |
| 67 | } else { |
| 68 | let changes = encode_changes(&diff_changes, &oplog.arena, None); |
| 69 | Ok(JsonSchema { |
| 70 | changes, |
| 71 | schema_version: SCHEMA_VERSION, |
| 72 | peers: None, |
| 73 | start_version: frontiers, |
| 74 | }) |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | pub(crate) fn export_json_in_id_span(oplog: &OpLog, mut id_span: IdSpan) -> Vec<json::JsonChange> { |
| 79 | id_span.normalize_(); |
| 80 | if id_span.counter.end <= 0 { |
| 81 | return vec![]; |
| 82 | } |
| 83 | id_span.counter.start = id_span.counter.start.max(0); |
| 84 | id_span.counter.end = id_span.counter.end.max(0); |
| 85 | |
| 86 | let end = oplog.vv().get(&id_span.peer).copied().unwrap_or(0); |
| 87 | if id_span.counter.start >= end { |
| 88 | return vec![]; |
| 89 | } |
| 90 | |
| 91 | id_span.counter.end = id_span.counter.end.min(end); |
| 92 | let mut diff_changes: Vec<Either<BlockChangeRef, Change>> = Vec::new(); |
| 93 | while id_span.counter.start < id_span.counter.end { |
| 94 | let Some(change) = oplog.get_change_at(id_span.id_start()) else { |
| 95 | break; |
| 96 | }; |
| 97 | let ctr_end = change.ctr_end(); |
| 98 | if change.id.counter >= id_span.counter.start && change.ctr_end() <= id_span.counter.end { |
| 99 | diff_changes.push(Either::Left(change)); |
| 100 | } else { |
| 101 | let start = if change.id.counter < id_span.counter.start { |
| 102 | (id_span.counter.start - change.id.counter) as usize |
| 103 | } else { |
| 104 | 0 |
| 105 | }; |
| 106 | |
| 107 | let end = if change.ctr_end() > id_span.counter.end { |
| 108 | (id_span.counter.end - change.id.counter) as usize |
| 109 | } else { |
| 110 | change.atom_len() |
| 111 | }; |
| 112 | |
| 113 | diff_changes.push(Either::Right(change.slice(start, end))); |
| 114 | } |
| 115 | |
| 116 | id_span.counter.start = ctr_end; |
| 117 | } |
| 118 | |
| 119 | encode_changes(&diff_changes, &oplog.arena, None) |
| 120 | } |
| 121 | |
| 122 | pub(crate) fn decode_json_changes( |
| 123 | json: JsonSchema, |
| 124 | arena: &SharedArena, |
| 125 | ) -> LoroResult<Vec<Change>> { |
| 126 | decode_changes(json, arena) |
| 127 | } |
| 128 | |
| 129 | fn init_encode<'s, 'a: 's>( |
| 130 | oplog: &'a OpLog, |
| 131 | start_vv: &VersionVector, |
| 132 | end_vv: &VersionVector, |
| 133 | ) -> Vec<Either<BlockChangeRef, Change>> { |
| 134 | let mut diff_changes: Vec<Either<BlockChangeRef, Change>> = Vec::new(); |
| 135 | for change in oplog.iter_changes_peer_by_peer(start_vv, end_vv) { |
| 136 | let start_cnt = start_vv.get(&change.id.peer).copied().unwrap_or(0); |
| 137 | let end_cnt = end_vv.get(&change.id.peer).copied().unwrap_or(0); |
| 138 | if change.id.counter < start_cnt { |
| 139 | if change.ctr_end() <= start_cnt { |
| 140 | continue; |
| 141 | } |
| 142 | |
| 143 | let offset = start_cnt - change.id.counter; |
| 144 | let to = change |
| 145 | .atom_len() |
| 146 | .min((end_cnt - change.id.counter) as usize); |
| 147 | diff_changes.push(Either::Right(change.slice(offset as usize, to))); |
| 148 | } else if change.id.counter + change.atom_len() as i32 > end_cnt { |
| 149 | let len = end_cnt - change.id.counter; |
| 150 | diff_changes.push(Either::Right(change.slice(0, len as usize))); |
| 151 | } else { |
| 152 | diff_changes.push(Either::Left(change)); |
| 153 | } |
| 154 | } |
| 155 | diff_changes.sort_by_key(|x| match x { |
| 156 | Either::Left(c) => c.lamport, |
| 157 | Either::Right(c) => c.lamport, |
| 158 | }); |
| 159 | diff_changes |
| 160 | } |
| 161 | |
| 162 | fn register_id(id: &ID, peer_register: Option<&mut ValueRegister<PeerID>>) -> ID { |
| 163 | let peer = match peer_register { |
| 164 | Some(peer_register) => peer_register.register(&id.peer) as PeerID, |
| 165 | None => id.peer, |
| 166 | }; |
| 167 | ID::new(peer as PeerID, id.counter) |
| 168 | } |
| 169 | |
| 170 | fn register_idlp(idlp: &IdLp, peer_register: Option<&mut ValueRegister<PeerID>>) -> IdLp { |
| 171 | let peer = match peer_register { |
| 172 | Some(peer_register) => peer_register.register(&idlp.peer) as PeerID, |
| 173 | None => idlp.peer, |
| 174 | }; |
| 175 | IdLp { |
| 176 | peer, |
| 177 | lamport: idlp.lamport, |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | fn register_tree_id(tree: &TreeID, peer_register: Option<&mut ValueRegister<PeerID>>) -> TreeID { |
| 182 | TreeID { |
| 183 | peer: match peer_register { |
| 184 | Some(peer_register) => peer_register.register(&tree.peer) as PeerID, |
| 185 | None => tree.peer, |
| 186 | }, |
| 187 | counter: tree.counter, |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | fn register_container_id( |
| 192 | container: ContainerID, |
| 193 | peer_register: Option<&mut ValueRegister<PeerID>>, |
| 194 | ) -> ContainerID { |
| 195 | match container { |
| 196 | ContainerID::Normal { |
| 197 | peer, |
| 198 | counter, |
| 199 | container_type, |
| 200 | } => ContainerID::Normal { |
| 201 | peer: match peer_register { |
| 202 | Some(peer_register) => peer_register.register(&peer) as PeerID, |
| 203 | None => peer, |
| 204 | }, |
| 205 | counter, |
| 206 | container_type, |
| 207 | }, |
| 208 | r => r, |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | fn convert_container_id( |
| 213 | container: ContainerID, |
| 214 | peers: &Option<Vec<PeerID>>, |
| 215 | ) -> LoroResult<ContainerID> { |
| 216 | match container { |
| 217 | ContainerID::Normal { |
| 218 | peer, |
| 219 | counter, |
| 220 | container_type, |
| 221 | } => Ok(ContainerID::Normal { |
| 222 | peer: get_peer_from_peers(peers, peer)?, |
| 223 | counter, |
| 224 | container_type, |
| 225 | }), |
| 226 | r => Ok(r), |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | pub(crate) fn get_peer_from_peers(peers: &Option<Vec<PeerID>>, peer: PeerID) -> LoroResult<PeerID> { |
| 231 | match peers { |
| 232 | Some(peers) => peers.get(peer as usize).copied().ok_or_else(|| { |
| 233 | LoroError::DecodeError("peer index out of range in compressed peer table".into()) |
| 234 | }), |
| 235 | None => Ok(peer), |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | fn convert_id(id: &ID, peers: &Option<Vec<PeerID>>) -> LoroResult<ID> { |
| 240 | Ok(ID { |
| 241 | peer: get_peer_from_peers(peers, id.peer)?, |
| 242 | counter: id.counter, |
| 243 | }) |
| 244 | } |
| 245 | |
| 246 | fn convert_idlp(idlp: &IdLp, peers: &Option<Vec<PeerID>>) -> LoroResult<IdLp> { |
| 247 | Ok(IdLp { |
| 248 | lamport: idlp.lamport, |
| 249 | peer: get_peer_from_peers(peers, idlp.peer)?, |
| 250 | }) |
| 251 | } |
| 252 | |
| 253 | fn convert_tree_id(tree: &TreeID, peers: &Option<Vec<PeerID>>) -> LoroResult<TreeID> { |
| 254 | Ok(TreeID { |
| 255 | peer: get_peer_from_peers(peers, tree.peer)?, |
| 256 | counter: tree.counter, |
| 257 | }) |
| 258 | } |
| 259 | pub(crate) fn encode_change_to_json(change: ChangeRef<'_>, arena: &SharedArena) -> JsonSchema { |
| 260 | let f = change.deps.clone(); |
| 261 | let changes = vec![encode_change(change, arena, None)]; |
| 262 | JsonSchema { |
| 263 | changes, |
| 264 | schema_version: SCHEMA_VERSION, |
| 265 | peers: None, |
| 266 | start_version: f, |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | fn encode_changes( |
| 271 | diff_changes: &[Either<BlockChangeRef, Change>], |
| 272 | arena: &SharedArena, |
| 273 | mut peer_register: Option<&mut ValueRegister<PeerID>>, |
| 274 | ) -> Vec<json::JsonChange> { |
| 275 | let mut changes = Vec::with_capacity(diff_changes.len()); |
| 276 | for change in diff_changes.iter() { |
| 277 | let change: &Change = match change { |
| 278 | Either::Left(c) => c, |
| 279 | Either::Right(c) => c, |
| 280 | }; |
| 281 | let c = encode_change( |
| 282 | ChangeRef::from_change(change), |
| 283 | arena, |
| 284 | peer_register.as_deref_mut(), |
| 285 | ); |
| 286 | changes.push(c); |
| 287 | } |
| 288 | changes |
| 289 | } |
| 290 | |
| 291 | pub(crate) fn encode_change( |
| 292 | change: ChangeRef<'_, Op>, |
| 293 | arena: &SharedArena, |
| 294 | mut peer_register: Option<&mut ValueRegister<PeerID>>, |
| 295 | ) -> JsonChange { |
| 296 | let mut ops = Vec::with_capacity(change.ops.len()); |
| 297 | for Op { |
| 298 | counter, |
| 299 | container, |
| 300 | content, |
| 301 | } in change.ops.iter() |
| 302 | { |
| 303 | let mut container = arena.get_container_id(*container).unwrap(); |
| 304 | if container.is_normal() { |
| 305 | container = register_container_id(container, peer_register.as_deref_mut()); |
| 306 | } |
| 307 | let op = match container.container_type() { |
| 308 | ContainerType::List => match content { |
| 309 | InnerContent::List(list) => JsonOpContent::List(match list { |
| 310 | InnerListOp::Insert { slice, pos } => { |
| 311 | let mut values = slice.as_slice().to_vec(); |
| 312 | values.iter_mut().for_each(|x| { |
| 313 | if let LoroValue::Container(id) = x { |
| 314 | if id.is_normal() { |
| 315 | *id = register_container_id( |
| 316 | id.clone(), |
| 317 | peer_register.as_deref_mut(), |
| 318 | ); |
| 319 | } |
| 320 | } |
| 321 | }); |
| 322 | json::ListOp::Insert { |
| 323 | pos: *pos as u32, |
| 324 | value: values, |
| 325 | } |
| 326 | } |
| 327 | InnerListOp::Delete(DeleteSpanWithId { |
| 328 | id_start, |
| 329 | span: DeleteSpan { pos, signed_len }, |
| 330 | }) => json::ListOp::Delete { |
| 331 | pos: *pos as i32, |
| 332 | len: *signed_len as i32, |
| 333 | start_id: register_id(id_start, peer_register.as_deref_mut()), |
| 334 | }, |
| 335 | _ => unreachable!(), |
| 336 | }), |
| 337 | _ => unreachable!(), |
| 338 | }, |
| 339 | ContainerType::MovableList => match content { |
| 340 | InnerContent::List(list) => JsonOpContent::MovableList(match list { |
| 341 | InnerListOp::Insert { slice, pos } => { |
| 342 | let mut values = slice.as_slice().to_vec(); |
| 343 | values.iter_mut().for_each(|x| { |
| 344 | if let LoroValue::Container(id) = x { |
| 345 | if id.is_normal() { |
| 346 | *id = register_container_id( |
| 347 | id.clone(), |
| 348 | peer_register.as_deref_mut(), |
| 349 | ); |
| 350 | } |
| 351 | } |
| 352 | }); |
| 353 | json::MovableListOp::Insert { |
| 354 | pos: *pos as u32, |
| 355 | value: values, |
| 356 | } |
| 357 | } |
| 358 | InnerListOp::Delete(DeleteSpanWithId { |
| 359 | id_start, |
| 360 | span: DeleteSpan { pos, signed_len }, |
| 361 | }) => json::MovableListOp::Delete { |
| 362 | pos: *pos as i32, |
| 363 | len: *signed_len as i32, |
| 364 | start_id: register_id(id_start, peer_register.as_deref_mut()), |
| 365 | }, |
| 366 | InnerListOp::Move { |
| 367 | from, |
| 368 | elem_id: from_id, |
| 369 | to, |
| 370 | } => json::MovableListOp::Move { |
| 371 | from: *from, |
| 372 | to: *to, |
| 373 | elem_id: register_idlp(from_id, peer_register.as_deref_mut()), |
| 374 | }, |
| 375 | InnerListOp::Set { elem_id, value } => { |
| 376 | let value = if let LoroValue::Container(id) = value { |
| 377 | if id.is_normal() { |
| 378 | LoroValue::Container(register_container_id( |
| 379 | id.clone(), |
| 380 | peer_register.as_deref_mut(), |
| 381 | )) |
| 382 | } else { |
| 383 | value.clone() |
| 384 | } |
| 385 | } else { |
| 386 | value.clone() |
| 387 | }; |
| 388 | json::MovableListOp::Set { |
| 389 | elem_id: register_idlp(elem_id, peer_register.as_deref_mut()), |
| 390 | value, |
| 391 | } |
| 392 | } |
| 393 | _ => unreachable!(), |
| 394 | }), |
| 395 | _ => unreachable!(), |
| 396 | }, |
| 397 | ContainerType::Text => match content { |
| 398 | InnerContent::List(list) => JsonOpContent::Text(match list { |
| 399 | InnerListOp::InsertText { |
| 400 | slice, |
| 401 | unicode_len: _, |
| 402 | pos, |
| 403 | } => { |
| 404 | let text = String::from_utf8(slice.as_bytes().to_vec()).unwrap(); |
| 405 | json::TextOp::Insert { pos: *pos, text } |
| 406 | } |
| 407 | InnerListOp::Delete(DeleteSpanWithId { |
| 408 | id_start, |
| 409 | span: DeleteSpan { pos, signed_len }, |
| 410 | }) => json::TextOp::Delete { |
| 411 | pos: *pos as i32, |
| 412 | len: *signed_len as i32, |
| 413 | start_id: register_id(id_start, peer_register.as_deref_mut()), |
| 414 | }, |
| 415 | InnerListOp::StyleStart { |
| 416 | start, |
| 417 | end, |
| 418 | key, |
| 419 | value, |
| 420 | info, |
| 421 | } => json::TextOp::Mark { |
| 422 | start: *start, |
| 423 | end: *end, |
| 424 | style_key: key.to_string(), |
| 425 | style_value: value.clone(), |
| 426 | info: info.to_byte(), |
| 427 | }, |
| 428 | InnerListOp::StyleEnd => json::TextOp::MarkEnd, |
| 429 | _ => unreachable!(), |
| 430 | }), |
| 431 | _ => unreachable!(), |
| 432 | }, |
| 433 | ContainerType::Map => match content { |
| 434 | InnerContent::Map(MapSet { key, value }) => { |
| 435 | JsonOpContent::Map(if let Some(v) = value { |
| 436 | let value = if let LoroValue::Container(id) = v { |
| 437 | if id.is_normal() { |
| 438 | LoroValue::Container(register_container_id( |
| 439 | id.clone(), |
| 440 | peer_register.as_deref_mut(), |
| 441 | )) |
| 442 | } else { |
| 443 | v.clone() |
| 444 | } |
| 445 | } else { |
| 446 | v.clone() |
| 447 | }; |
| 448 | json::MapOp::Insert { |
| 449 | key: key.to_string(), |
| 450 | value, |
| 451 | } |
| 452 | } else { |
| 453 | json::MapOp::Delete { |
| 454 | key: key.to_string(), |
| 455 | } |
| 456 | }) |
| 457 | } |
| 458 | |
| 459 | _ => unreachable!(), |
| 460 | }, |
| 461 | |
| 462 | ContainerType::Tree => match content { |
| 463 | InnerContent::Tree(op) => JsonOpContent::Tree(match &**op { |
| 464 | TreeOp::Create { |
| 465 | target, |
| 466 | parent, |
| 467 | position, |
| 468 | } => json::TreeOp::Create { |
| 469 | target: register_tree_id(target, peer_register.as_deref_mut()), |
| 470 | parent: parent.map(|p| register_tree_id(&p, peer_register.as_deref_mut())), |
| 471 | fractional_index: position.clone(), |
| 472 | }, |
| 473 | TreeOp::Move { |
| 474 | target, |
| 475 | parent, |
| 476 | position, |
| 477 | } => json::TreeOp::Move { |
| 478 | target: register_tree_id(target, peer_register.as_deref_mut()), |
| 479 | parent: parent.map(|p| register_tree_id(&p, peer_register.as_deref_mut())), |
| 480 | fractional_index: position.clone(), |
| 481 | }, |
| 482 | TreeOp::Delete { target } => json::TreeOp::Delete { |
| 483 | target: register_tree_id(target, peer_register.as_deref_mut()), |
| 484 | }, |
| 485 | }), |
| 486 | _ => unreachable!(), |
| 487 | }, |
| 488 | ContainerType::Unknown(_) => { |
| 489 | let InnerContent::Future(FutureInnerContent::Unknown { prop, value }) = content |
| 490 | else { |
| 491 | unreachable!(); |
| 492 | }; |
| 493 | JsonOpContent::Future(json::FutureOpWrapper { |
| 494 | prop: *prop, |
| 495 | value: json::FutureOp::Unknown((**value).clone()), |
| 496 | }) |
| 497 | } |
| 498 | #[cfg(feature = "counter")] |
| 499 | ContainerType::Counter => { |
| 500 | let InnerContent::Future(f) = content else { |
| 501 | unreachable!() |
| 502 | }; |
| 503 | match f { |
| 504 | FutureInnerContent::Counter(x) => { |
| 505 | JsonOpContent::Future(json::FutureOpWrapper { |
| 506 | prop: 0, |
| 507 | value: json::FutureOp::Counter(super::OwnedValue::F64(*x)), |
| 508 | }) |
| 509 | } |
| 510 | _ => unreachable!(), |
| 511 | } |
| 512 | } |
| 513 | }; |
| 514 | ops.push(json::JsonOp { |
| 515 | counter: *counter, |
| 516 | container, |
| 517 | content: op, |
| 518 | }); |
| 519 | } |
| 520 | let c = json::JsonChange { |
| 521 | id: register_id(change.id, peer_register.as_deref_mut()), |
| 522 | ops, |
| 523 | deps: change |
| 524 | .deps |
| 525 | .iter() |
| 526 | // Make sure the order is deterministic |
| 527 | .sorted() |
| 528 | .map(|id| register_id(&id, peer_register.as_deref_mut())) |
| 529 | .collect(), |
| 530 | lamport: *change.lamport, |
| 531 | timestamp: *change.timestamp, |
| 532 | msg: change.commit_msg.as_deref().map(|x| x.to_string()), |
| 533 | }; |
| 534 | c |
| 535 | } |
| 536 | |
| 537 | fn decode_changes(json: JsonSchema, arena: &SharedArena) -> LoroResult<Vec<Change>> { |
| 538 | let JsonSchema { |
| 539 | schema_version, |
| 540 | start_version, |
| 541 | peers, |
| 542 | changes, |
| 543 | } = json; |
| 544 | if schema_version != SCHEMA_VERSION { |
| 545 | return Err(LoroError::DecodeError( |
| 546 | format!( |
| 547 | "unsupported json schema version: expected {SCHEMA_VERSION}, got {schema_version}" |
| 548 | ) |
| 549 | .into_boxed_str(), |
| 550 | )); |
| 551 | } |
| 552 | validate_json_frontiers(&start_version)?; |
| 553 | |
| 554 | let mut ans = Vec::with_capacity(changes.len()); |
| 555 | for json::JsonChange { |
| 556 | id, |
| 557 | timestamp, |
| 558 | deps, |
| 559 | lamport, |
| 560 | msg, |
| 561 | ops: json_ops, |
| 562 | } in changes |
| 563 | { |
| 564 | let id = convert_id(&id, &peers)?; |
| 565 | validate_json_id_counter(id, "change id")?; |
| 566 | let mut ops: RleVec<[Op; 1]> = RleVec::new(); |
| 567 | let mut expected_counter = id.counter; |
| 568 | if json_ops.is_empty() { |
| 569 | return Err(LoroError::DecodeError( |
| 570 | "invalid json change: change must contain at least one op".into(), |
| 571 | )); |
| 572 | } |
| 573 | |
| 574 | for op in json_ops { |
| 575 | let next_counter = validate_json_op_counter(expected_counter, &op)?; |
| 576 | let op = decode_op(op, arena, &peers)?; |
| 577 | validate_json_op_created_container_ids(id.peer, &op)?; |
| 578 | ops.push(op); |
| 579 | expected_counter = next_counter; |
| 580 | } |
| 581 | |
| 582 | let deps = deps |
| 583 | .into_iter() |
| 584 | .map(|id| convert_id(&id, &peers)) |
| 585 | .collect::<LoroResult<Vec<_>>>()?; |
| 586 | for dep in &deps { |
| 587 | validate_json_id_counter(*dep, "dependency id")?; |
| 588 | } |
| 589 | |
| 590 | let change = Change { |
| 591 | id, |
| 592 | timestamp, |
| 593 | deps: Frontiers::from_iter(deps), |
| 594 | lamport, |
| 595 | ops, |
| 596 | commit_msg: msg.map(|x| x.into()), |
| 597 | }; |
| 598 | ans.push(change); |
| 599 | } |
| 600 | Ok(ans) |
| 601 | } |
| 602 | |
| 603 | fn validate_json_frontiers(frontiers: &Frontiers) -> LoroResult<()> { |
| 604 | for id in frontiers.iter() { |
| 605 | validate_json_id_counter(id, "start version id")?; |
| 606 | } |
| 607 | |
| 608 | Ok(()) |
| 609 | } |
| 610 | |
| 611 | fn validate_json_id_counter(id: ID, name: &str) -> LoroResult<()> { |
| 612 | if id.counter < 0 { |
| 613 | return Err(LoroError::DecodeError( |
| 614 | format!("invalid json counter: {name} counter must be non-negative").into_boxed_str(), |
| 615 | )); |
| 616 | } |
| 617 | |
| 618 | Ok(()) |
| 619 | } |
| 620 | |
| 621 | fn validate_json_tree_id_counter(id: &TreeID, name: &str) -> LoroResult<()> { |
| 622 | if id.counter < 0 { |
| 623 | return Err(LoroError::DecodeError( |
| 624 | format!("invalid json counter: {name} counter must be non-negative").into_boxed_str(), |
| 625 | )); |
| 626 | } |
| 627 | |
| 628 | Ok(()) |
| 629 | } |
| 630 | |
| 631 | fn validate_json_container_id_counter(id: &ContainerID, name: &str) -> LoroResult<()> { |
| 632 | if let ContainerID::Normal { counter, .. } = id { |
| 633 | if *counter < 0 { |
| 634 | return Err(LoroError::DecodeError( |
| 635 | format!("invalid json counter: {name} counter must be non-negative") |
| 636 | .into_boxed_str(), |
| 637 | )); |
| 638 | } |
| 639 | } |
| 640 | |
| 641 | Ok(()) |
| 642 | } |
| 643 | |
| 644 | fn validate_json_op_counter(expected_counter: Counter, op: &json::JsonOp) -> LoroResult<Counter> { |
| 645 | let op_len = op.content.op_len(); |
| 646 | if op_len == 0 { |
| 647 | return Err(LoroError::DecodeError( |
| 648 | "invalid json op counter: op length must be greater than zero".into(), |
| 649 | )); |
| 650 | } |
| 651 | |
| 652 | if expected_counter < 0 || op.counter < 0 { |
| 653 | return Err(LoroError::DecodeError( |
| 654 | "invalid json op counter: op counters must be non-negative".into(), |
| 655 | )); |
| 656 | } |
| 657 | |
| 658 | let op_len = Counter::try_from(op_len).map_err(|_| { |
| 659 | LoroError::DecodeError("invalid json op counter: op length is too large".into()) |
| 660 | })?; |
| 661 | if op.counter != expected_counter { |
| 662 | return Err(LoroError::DecodeError( |
| 663 | "invalid json op counter: op counters must be contiguous with the change id".into(), |
| 664 | )); |
| 665 | } |
| 666 | |
| 667 | expected_counter |
| 668 | .checked_add(op_len) |
| 669 | .ok_or_else(|| LoroError::DecodeError("invalid json op counter: counter overflow".into())) |
| 670 | } |
| 671 | |
| 672 | fn validate_json_op_created_container_ids(peer: PeerID, op: &Op) -> LoroResult<()> { |
| 673 | match &op.content { |
| 674 | InnerContent::List(list) => match list { |
| 675 | InnerListOp::Insert { slice, .. } => { |
| 676 | for (offset, value) in slice.as_slice().iter().enumerate() { |
| 677 | let LoroValue::Container(id) = value else { |
| 678 | validate_json_value_has_no_container_refs(value)?; |
| 679 | continue; |
| 680 | }; |
| 681 | let offset = Counter::try_from(offset).map_err(|_| { |
| 682 | LoroError::DecodeError( |
| 683 | "invalid json container id: list offset is too large".into(), |
| 684 | ) |
| 685 | })?; |
| 686 | let counter = op.counter.checked_add(offset).ok_or_else(|| { |
| 687 | LoroError::DecodeError("invalid json container id: counter overflow".into()) |
| 688 | })?; |
| 689 | validate_json_created_container_id(id, ID::new(peer, counter))?; |
| 690 | } |
| 691 | } |
| 692 | InnerListOp::Set { value, .. } => { |
| 693 | if let LoroValue::Container(id) = value { |
| 694 | validate_json_created_container_id(id, ID::new(peer, op.counter))?; |
| 695 | } else { |
| 696 | validate_json_value_has_no_container_refs(value)?; |
| 697 | } |
| 698 | } |
| 699 | InnerListOp::Move { .. } |
| 700 | | InnerListOp::InsertText { .. } |
| 701 | | InnerListOp::Delete(_) |
| 702 | | InnerListOp::StyleEnd => {} |
| 703 | InnerListOp::StyleStart { value, .. } => { |
| 704 | validate_json_value_has_no_container_refs(value)?; |
| 705 | } |
| 706 | }, |
| 707 | InnerContent::Map(map) => { |
| 708 | if let Some(value) = &map.value { |
| 709 | if let LoroValue::Container(id) = value { |
| 710 | validate_json_created_container_id(id, ID::new(peer, op.counter))?; |
| 711 | } else { |
| 712 | validate_json_value_has_no_container_refs(value)?; |
| 713 | } |
| 714 | } |
| 715 | } |
| 716 | InnerContent::Tree(tree) => { |
| 717 | if let TreeOp::Create { target, .. } = tree.as_ref() { |
| 718 | validate_json_tree_create_target(target, ID::new(peer, op.counter))?; |
| 719 | } |
| 720 | } |
| 721 | InnerContent::Future(_) => {} |
| 722 | } |
| 723 | |
| 724 | Ok(()) |
| 725 | } |
| 726 | |
| 727 | fn validate_json_value_has_no_container_refs(value: &LoroValue) -> LoroResult<()> { |
| 728 | let mut stack = vec![value]; |
| 729 | while let Some(value) = stack.pop() { |
| 730 | match value { |
| 731 | LoroValue::Container(_) => { |
| 732 | return Err(LoroError::DecodeError( |
| 733 | "invalid json container id: container values must not be nested".into(), |
| 734 | )); |
| 735 | } |
| 736 | LoroValue::List(list) => { |
| 737 | stack.extend(list.iter()); |
| 738 | } |
| 739 | LoroValue::Map(map) => { |
| 740 | stack.extend(map.values()); |
| 741 | } |
| 742 | LoroValue::Null |
| 743 | | LoroValue::Bool(_) |
| 744 | | LoroValue::Double(_) |
| 745 | | LoroValue::I64(_) |
| 746 | | LoroValue::Binary(_) |
| 747 | | LoroValue::String(_) => {} |
| 748 | } |
| 749 | } |
| 750 | |
| 751 | Ok(()) |
| 752 | } |
| 753 | |
| 754 | fn validate_json_created_container_id(id: &ContainerID, expected_id: ID) -> LoroResult<()> { |
| 755 | let ContainerID::Normal { peer, counter, .. } = id else { |
| 756 | return Err(LoroError::DecodeError( |
| 757 | "invalid json container id: created child containers must be normal".into(), |
| 758 | )); |
| 759 | }; |
| 760 | |
| 761 | if *peer != expected_id.peer || *counter != expected_id.counter { |
| 762 | return Err(LoroError::DecodeError( |
| 763 | "invalid json container id: created child container id must match the op id".into(), |
| 764 | )); |
| 765 | } |
| 766 | |
| 767 | Ok(()) |
| 768 | } |
| 769 | |
| 770 | fn validate_json_tree_create_target(target: &TreeID, expected_id: ID) -> LoroResult<()> { |
| 771 | if target.peer != expected_id.peer || target.counter != expected_id.counter { |
| 772 | return Err(LoroError::DecodeError( |
| 773 | "invalid json tree target: tree create target must match the op id".into(), |
| 774 | )); |
| 775 | } |
| 776 | |
| 777 | Ok(()) |
| 778 | } |
| 779 | |
| 780 | fn decode_op(op: json::JsonOp, arena: &SharedArena, peers: &Option<Vec<PeerID>>) -> LoroResult<Op> { |
| 781 | let json::JsonOp { |
| 782 | counter, |
| 783 | container, |
| 784 | content, |
| 785 | } = op; |
| 786 | let container = convert_container_id(container, peers)?; |
| 787 | validate_json_container_id_counter(&container, "op container")?; |
| 788 | let idx = arena.register_container(&container); |
| 789 | let content = match container.container_type() { |
| 790 | ContainerType::Text => match content { |
| 791 | JsonOpContent::Text(text) => match text { |
| 792 | json::TextOp::Insert { pos, text } => { |
| 793 | let (slice, result) = arena.alloc_str_with_slice(&text); |
| 794 | InnerContent::List(InnerListOp::InsertText { |
| 795 | slice, |
| 796 | unicode_len: (result.end - result.start) as u32, |
| 797 | pos, |
| 798 | }) |
| 799 | } |
| 800 | json::TextOp::Delete { |
| 801 | pos, |
| 802 | len, |
| 803 | start_id: id_start, |
| 804 | } => { |
| 805 | let id_start = convert_id(&id_start, peers)?; |
| 806 | validate_json_id_counter(id_start, "text delete start id")?; |
| 807 | InnerContent::List(InnerListOp::Delete(DeleteSpanWithId { |
| 808 | id_start, |
| 809 | span: DeleteSpan { |
| 810 | pos: pos as isize, |
| 811 | signed_len: len as isize, |
| 812 | }, |
| 813 | })) |
| 814 | } |
| 815 | json::TextOp::Mark { |
| 816 | start, |
| 817 | end, |
| 818 | style_key, |
| 819 | style_value, |
| 820 | info, |
| 821 | } => InnerContent::List(InnerListOp::StyleStart { |
| 822 | start, |
| 823 | end, |
| 824 | key: style_key.into(), |
| 825 | value: style_value, |
| 826 | info: TextStyleInfoFlag::from_byte(info), |
| 827 | }), |
| 828 | json::TextOp::MarkEnd => InnerContent::List(InnerListOp::StyleEnd), |
| 829 | }, |
| 830 | _ => { |
| 831 | return Err(LoroError::DecodeError( |
| 832 | "invalid op content for text container".into(), |
| 833 | )) |
| 834 | } |
| 835 | }, |
| 836 | ContainerType::List => match content { |
| 837 | JsonOpContent::List(list) => match list { |
| 838 | json::ListOp::Insert { |
| 839 | pos, |
| 840 | value: mut values, |
| 841 | } => { |
| 842 | for v in values.iter_mut() { |
| 843 | if let LoroValue::Container(id) = v { |
| 844 | if id.is_normal() { |
| 845 | *id = convert_container_id(id.clone(), peers)?; |
| 846 | } |
| 847 | } |
| 848 | } |
| 849 | InnerContent::List(InnerListOp::Insert { |
| 850 | slice: ValueSlice::new(values), |
| 851 | pos: pos as usize, |
| 852 | }) |
| 853 | } |
| 854 | json::ListOp::Delete { pos, len, start_id } => { |
| 855 | let start_id = convert_id(&start_id, peers)?; |
| 856 | validate_json_id_counter(start_id, "list delete start id")?; |
| 857 | InnerContent::List(InnerListOp::Delete(DeleteSpanWithId { |
| 858 | id_start: start_id, |
| 859 | span: DeleteSpan { |
| 860 | pos: pos as isize, |
| 861 | signed_len: len as isize, |
| 862 | }, |
| 863 | })) |
| 864 | } |
| 865 | }, |
| 866 | _ => { |
| 867 | return Err(LoroError::DecodeError( |
| 868 | "invalid op content for list container".into(), |
| 869 | )) |
| 870 | } |
| 871 | }, |
| 872 | ContainerType::MovableList => match content { |
| 873 | JsonOpContent::MovableList(list) => match list { |
| 874 | json::MovableListOp::Insert { |
| 875 | pos, |
| 876 | value: mut values, |
| 877 | } => { |
| 878 | for v in values.iter_mut() { |
| 879 | if let LoroValue::Container(id) = v { |
| 880 | if id.is_normal() { |
| 881 | *id = convert_container_id(id.clone(), peers)?; |
| 882 | } |
| 883 | } |
| 884 | } |
| 885 | InnerContent::List(InnerListOp::Insert { |
| 886 | slice: ValueSlice::new(values), |
| 887 | pos: pos as usize, |
| 888 | }) |
| 889 | } |
| 890 | json::MovableListOp::Delete { pos, len, start_id } => { |
| 891 | let start_id = convert_id(&start_id, peers)?; |
| 892 | validate_json_id_counter(start_id, "movable list delete start id")?; |
| 893 | InnerContent::List(InnerListOp::Delete(DeleteSpanWithId { |
| 894 | id_start: start_id, |
| 895 | span: DeleteSpan { |
| 896 | pos: pos as isize, |
| 897 | signed_len: len as isize, |
| 898 | }, |
| 899 | })) |
| 900 | } |
| 901 | json::MovableListOp::Move { |
| 902 | from, |
| 903 | elem_id: from_id, |
| 904 | to, |
| 905 | } => { |
| 906 | let from_id = convert_idlp(&from_id, peers)?; |
| 907 | InnerContent::List(InnerListOp::Move { |
| 908 | from, |
| 909 | elem_id: from_id, |
| 910 | to, |
| 911 | }) |
| 912 | } |
| 913 | json::MovableListOp::Set { elem_id, mut value } => { |
| 914 | let elem_id = convert_idlp(&elem_id, peers)?; |
| 915 | if let LoroValue::Container(id) = &mut value { |
| 916 | *id = convert_container_id(id.clone(), peers)?; |
| 917 | } |
| 918 | InnerContent::List(InnerListOp::Set { elem_id, value }) |
| 919 | } |
| 920 | }, |
| 921 | _ => { |
| 922 | return Err(LoroError::DecodeError( |
| 923 | "invalid op content for movable list container".into(), |
| 924 | )) |
| 925 | } |
| 926 | }, |
| 927 | ContainerType::Map => match content { |
| 928 | JsonOpContent::Map(map) => match map { |
| 929 | json::MapOp::Insert { key, mut value } => { |
| 930 | if let LoroValue::Container(id) = &mut value { |
| 931 | *id = convert_container_id(id.clone(), peers)?; |
| 932 | } |
| 933 | InnerContent::Map(MapSet { |
| 934 | key: key.into(), |
| 935 | value: Some(value), |
| 936 | }) |
| 937 | } |
| 938 | json::MapOp::Delete { key } => InnerContent::Map(MapSet { |
| 939 | key: key.into(), |
| 940 | value: None, |
| 941 | }), |
| 942 | }, |
| 943 | _ => { |
| 944 | return Err(LoroError::DecodeError( |
| 945 | "invalid op content for map container".into(), |
| 946 | )) |
| 947 | } |
| 948 | }, |
| 949 | ContainerType::Tree => match content { |
| 950 | JsonOpContent::Tree(tree) => match tree { |
| 951 | json::TreeOp::Create { |
| 952 | target, |
| 953 | parent, |
| 954 | fractional_index, |
| 955 | } => { |
| 956 | let target = convert_tree_id(&target, peers)?; |
| 957 | validate_json_tree_id_counter(&target, "tree create target")?; |
| 958 | let parent = match parent { |
| 959 | Some(p) => { |
| 960 | let parent = convert_tree_id(&p, peers)?; |
| 961 | validate_json_tree_id_counter(&parent, "tree create parent")?; |
| 962 | Some(parent) |
| 963 | } |
| 964 | None => None, |
| 965 | }; |
| 966 | InnerContent::Tree(Arc::new(TreeOp::Create { |
| 967 | target, |
| 968 | parent, |
| 969 | position: fractional_index, |
| 970 | })) |
| 971 | } |
| 972 | json::TreeOp::Move { |
| 973 | target, |
| 974 | parent, |
| 975 | fractional_index, |
| 976 | } => { |
| 977 | let target = convert_tree_id(&target, peers)?; |
| 978 | validate_json_tree_id_counter(&target, "tree move target")?; |
| 979 | let parent = match parent { |
| 980 | Some(p) => { |
| 981 | let parent = convert_tree_id(&p, peers)?; |
| 982 | validate_json_tree_id_counter(&parent, "tree move parent")?; |
| 983 | Some(parent) |
| 984 | } |
| 985 | None => None, |
| 986 | }; |
| 987 | InnerContent::Tree(Arc::new(TreeOp::Move { |
| 988 | target, |
| 989 | parent, |
| 990 | position: fractional_index, |
| 991 | })) |
| 992 | } |
| 993 | json::TreeOp::Delete { target } => { |
| 994 | let target = convert_tree_id(&target, peers)?; |
| 995 | validate_json_tree_id_counter(&target, "tree delete target")?; |
| 996 | InnerContent::Tree(Arc::new(TreeOp::Delete { target })) |
| 997 | } |
| 998 | }, |
| 999 | _ => { |
| 1000 | return Err(LoroError::DecodeError( |
| 1001 | "invalid op content for tree container".into(), |
| 1002 | )) |
| 1003 | } |
| 1004 | }, |
| 1005 | ContainerType::Unknown(_) => match content { |
| 1006 | JsonOpContent::Future(json::FutureOpWrapper { |
| 1007 | prop, |
| 1008 | value: json::FutureOp::Unknown(value), |
| 1009 | }) => InnerContent::Future(FutureInnerContent::Unknown { |
| 1010 | prop, |
| 1011 | value: Box::new(value), |
| 1012 | }), |
| 1013 | _ => { |
| 1014 | return Err(LoroError::DecodeError( |
| 1015 | "invalid op content for unknown container".into(), |
| 1016 | )) |
| 1017 | } |
| 1018 | }, |
| 1019 | #[cfg(feature = "counter")] |
| 1020 | ContainerType::Counter => { |
| 1021 | let JsonOpContent::Future(json::FutureOpWrapper { prop: _, value }) = content else { |
| 1022 | return Err(LoroError::DecodeError( |
| 1023 | "invalid op content for counter container".into(), |
| 1024 | )); |
| 1025 | }; |
| 1026 | use crate::encoding::OwnedValue; |
| 1027 | match value { |
| 1028 | json::FutureOp::Counter(OwnedValue::F64(c)) |
| 1029 | | json::FutureOp::Unknown(OwnedValue::F64(c)) => { |
| 1030 | InnerContent::Future(FutureInnerContent::Counter(c)) |
| 1031 | } |
| 1032 | json::FutureOp::Counter(OwnedValue::I64(c)) |
| 1033 | | json::FutureOp::Unknown(OwnedValue::I64(c)) => { |
| 1034 | InnerContent::Future(FutureInnerContent::Counter(c as f64)) |
| 1035 | } |
| 1036 | _ => { |
| 1037 | return Err(LoroError::DecodeError( |
| 1038 | "invalid counter op value type".into(), |
| 1039 | )) |
| 1040 | } |
| 1041 | } |
| 1042 | } // Note: The Future Type need try to parse Op from the unknown content |
| 1043 | }; |
| 1044 | if let InnerContent::List(list_op) = &content { |
| 1045 | list_op.check_positions()?; |
| 1046 | } |
| 1047 | Ok(Op { |
| 1048 | counter, |
| 1049 | container: idx, |
| 1050 | content, |
| 1051 | }) |
| 1052 | } |
| 1053 | |
| 1054 | impl TryFrom<&str> for JsonSchema { |
| 1055 | type Error = serde_json::Error; |
| 1056 | |
| 1057 | fn try_from(value: &str) -> Result<Self, Self::Error> { |
| 1058 | serde_json::from_str(value) |
| 1059 | } |
| 1060 | } |
| 1061 | |
| 1062 | impl TryFrom<&String> for JsonSchema { |
| 1063 | type Error = serde_json::Error; |
| 1064 | |
| 1065 | fn try_from(value: &String) -> Result<Self, Self::Error> { |
| 1066 | serde_json::from_str(value) |
| 1067 | } |
| 1068 | } |
| 1069 | |
| 1070 | impl TryFrom<String> for JsonSchema { |
| 1071 | type Error = serde_json::Error; |
| 1072 | |
| 1073 | fn try_from(value: String) -> Result<Self, Self::Error> { |
| 1074 | serde_json::from_str(&value) |
| 1075 | } |
| 1076 | } |
| 1077 | |
| 1078 | pub mod json { |
| 1079 | use crate::{ |
| 1080 | encoding::OwnedValue, |
| 1081 | version::{Frontiers, VersionRange}, |
| 1082 | }; |
| 1083 | use fractional_index::FractionalIndex; |
| 1084 | use loro_common::{ContainerID, Counter, IdLp, Lamport, LoroValue, PeerID, TreeID, ID}; |
| 1085 | use serde::{Deserialize, Serialize}; |
| 1086 | use std::ops::Range; |
| 1087 | |
| 1088 | use super::{get_peer_from_peers, redact_value}; |
| 1089 | |
| 1090 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 1091 | pub struct JsonSchema { |
| 1092 | pub schema_version: u8, |
| 1093 | #[serde(with = "self::serde_impl::frontiers")] |
| 1094 | pub start_version: Frontiers, |
| 1095 | #[serde(with = "self::serde_impl::peer_id")] |
| 1096 | pub peers: Option<Vec<PeerID>>, |
| 1097 | pub changes: Vec<JsonChange>, |
| 1098 | } |
| 1099 | |
| 1100 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 1101 | pub struct JsonChange { |
| 1102 | #[serde(with = "self::serde_impl::id")] |
| 1103 | pub id: ID, |
| 1104 | pub timestamp: i64, |
| 1105 | #[serde(with = "self::serde_impl::deps")] |
| 1106 | pub deps: Vec<ID>, |
| 1107 | pub lamport: Lamport, |
| 1108 | pub msg: Option<String>, |
| 1109 | pub ops: Vec<JsonOp>, |
| 1110 | } |
| 1111 | |
| 1112 | impl JsonChange { |
| 1113 | pub fn checked_op_len(&self) -> Option<usize> { |
| 1114 | let Some(last_op) = self.ops.last() else { |
| 1115 | return Some(0); |
| 1116 | }; |
| 1117 | if last_op.counter < self.id.counter { |
| 1118 | return None; |
| 1119 | } |
| 1120 | |
| 1121 | let counter_delta = last_op.counter.checked_sub(self.id.counter)?; |
| 1122 | let counter_delta = usize::try_from(counter_delta).ok()?; |
| 1123 | counter_delta.checked_add(last_op.content.op_len()) |
| 1124 | } |
| 1125 | |
| 1126 | pub fn op_len(&self) -> usize { |
| 1127 | self.checked_op_len().unwrap_or(0) |
| 1128 | } |
| 1129 | } |
| 1130 | |
| 1131 | #[derive(Debug, Clone)] |
| 1132 | pub struct JsonOp { |
| 1133 | pub content: JsonOpContent, |
| 1134 | pub container: ContainerID, |
| 1135 | pub counter: i32, |
| 1136 | } |
| 1137 | |
| 1138 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 1139 | #[serde(untagged)] |
| 1140 | pub enum JsonOpContent { |
| 1141 | List(ListOp), |
| 1142 | MovableList(MovableListOp), |
| 1143 | Map(MapOp), |
| 1144 | Text(TextOp), |
| 1145 | Tree(TreeOp), |
| 1146 | // #[serde(with = "self::serde_impl::future_op")] |
| 1147 | Future(FutureOpWrapper), |
| 1148 | } |
| 1149 | |
| 1150 | impl JsonOpContent { |
| 1151 | pub fn op_len(&self) -> usize { |
| 1152 | match self { |
| 1153 | JsonOpContent::List(list_op) => list_op.op_len(), |
| 1154 | JsonOpContent::MovableList(movable_list_op) => movable_list_op.op_len(), |
| 1155 | JsonOpContent::Map(..) => 1, |
| 1156 | JsonOpContent::Text(text_op) => text_op.op_len(), |
| 1157 | JsonOpContent::Tree(..) => 1, |
| 1158 | JsonOpContent::Future(..) => 1, |
| 1159 | } |
| 1160 | } |
| 1161 | } |
| 1162 | |
| 1163 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 1164 | pub struct FutureOpWrapper { |
| 1165 | #[serde(flatten)] |
| 1166 | pub value: FutureOp, |
| 1167 | pub prop: i32, |
| 1168 | } |
| 1169 | |
| 1170 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 1171 | #[serde(tag = "type", rename_all = "snake_case")] |
| 1172 | pub enum ListOp { |
| 1173 | Insert { |
| 1174 | pos: u32, |
| 1175 | value: Vec<LoroValue>, |
| 1176 | }, |
| 1177 | Delete { |
| 1178 | pos: i32, |
| 1179 | len: i32, |
| 1180 | #[serde(with = "self::serde_impl::id")] |
| 1181 | start_id: ID, |
| 1182 | }, |
| 1183 | } |
| 1184 | |
| 1185 | impl ListOp { |
| 1186 | fn op_len(&self) -> usize { |
| 1187 | match self { |
| 1188 | ListOp::Insert { value: values, .. } => values.len(), |
| 1189 | ListOp::Delete { len, .. } => (*len).unsigned_abs() as usize, |
| 1190 | } |
| 1191 | } |
| 1192 | } |
| 1193 | |
| 1194 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 1195 | #[serde(tag = "type", rename_all = "snake_case")] |
| 1196 | pub enum MovableListOp { |
| 1197 | Insert { |
| 1198 | pos: u32, |
| 1199 | value: Vec<LoroValue>, |
| 1200 | }, |
| 1201 | Delete { |
| 1202 | pos: i32, |
| 1203 | len: i32, |
| 1204 | #[serde(with = "self::serde_impl::id")] |
| 1205 | start_id: ID, |
| 1206 | }, |
| 1207 | Move { |
| 1208 | from: u32, |
| 1209 | to: u32, |
| 1210 | #[serde(with = "self::serde_impl::idlp")] |
| 1211 | elem_id: IdLp, |
| 1212 | }, |
| 1213 | Set { |
| 1214 | #[serde(with = "self::serde_impl::idlp")] |
| 1215 | elem_id: IdLp, |
| 1216 | value: LoroValue, |
| 1217 | }, |
| 1218 | } |
| 1219 | |
| 1220 | impl MovableListOp { |
| 1221 | fn op_len(&self) -> usize { |
| 1222 | match self { |
| 1223 | MovableListOp::Insert { value: values, .. } => values.len(), |
| 1224 | MovableListOp::Delete { len, .. } => (*len).unsigned_abs() as usize, |
| 1225 | MovableListOp::Move { .. } => 1, |
| 1226 | MovableListOp::Set { .. } => 1, |
| 1227 | } |
| 1228 | } |
| 1229 | } |
| 1230 | |
| 1231 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 1232 | #[serde(tag = "type", rename_all = "snake_case")] |
| 1233 | pub enum MapOp { |
| 1234 | Insert { key: String, value: LoroValue }, |
| 1235 | Delete { key: String }, |
| 1236 | } |
| 1237 | |
| 1238 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 1239 | #[serde(tag = "type", rename_all = "snake_case")] |
| 1240 | pub enum TextOp { |
| 1241 | Insert { |
| 1242 | pos: u32, |
| 1243 | text: String, |
| 1244 | }, |
| 1245 | Delete { |
| 1246 | pos: i32, |
| 1247 | len: i32, |
| 1248 | #[serde(with = "self::serde_impl::id")] |
| 1249 | start_id: ID, |
| 1250 | }, |
| 1251 | Mark { |
| 1252 | start: u32, |
| 1253 | end: u32, |
| 1254 | style_key: String, |
| 1255 | style_value: LoroValue, |
| 1256 | info: u8, |
| 1257 | }, |
| 1258 | MarkEnd, |
| 1259 | } |
| 1260 | |
| 1261 | impl TextOp { |
| 1262 | fn op_len(&self) -> usize { |
| 1263 | match self { |
| 1264 | TextOp::Insert { text, .. } => text.chars().count(), |
| 1265 | TextOp::Delete { len, .. } => len.unsigned_abs() as usize, |
| 1266 | TextOp::Mark { .. } => 1, |
| 1267 | TextOp::MarkEnd => 1, |
| 1268 | } |
| 1269 | } |
| 1270 | } |
| 1271 | |
| 1272 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 1273 | #[serde(tag = "type", rename_all = "snake_case")] |
| 1274 | pub enum TreeOp { |
| 1275 | Create { |
| 1276 | #[serde(with = "self::serde_impl::tree_id")] |
| 1277 | target: TreeID, |
| 1278 | #[serde(with = "self::serde_impl::option_tree_id")] |
| 1279 | parent: Option<TreeID>, |
| 1280 | #[serde(default, with = "self::serde_impl::fractional_index")] |
| 1281 | fractional_index: FractionalIndex, |
| 1282 | }, |
| 1283 | Move { |
| 1284 | #[serde(with = "self::serde_impl::tree_id")] |
| 1285 | target: TreeID, |
| 1286 | #[serde(with = "self::serde_impl::option_tree_id")] |
| 1287 | parent: Option<TreeID>, |
| 1288 | #[serde(default, with = "self::serde_impl::fractional_index")] |
| 1289 | fractional_index: FractionalIndex, |
| 1290 | }, |
| 1291 | Delete { |
| 1292 | #[serde(with = "self::serde_impl::tree_id")] |
| 1293 | target: TreeID, |
| 1294 | }, |
| 1295 | } |
| 1296 | |
| 1297 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 1298 | #[serde(tag = "type", rename_all = "snake_case")] |
| 1299 | pub enum FutureOp { |
| 1300 | #[cfg(feature = "counter")] |
| 1301 | Counter(OwnedValue), |
| 1302 | Unknown(OwnedValue), |
| 1303 | } |
| 1304 | |
| 1305 | mod serde_impl { |
| 1306 | |
| 1307 | use loro_common::{ContainerID, ContainerType}; |
| 1308 | use serde::{ |
| 1309 | de::{Error, IgnoredAny, MapAccess, Visitor}, |
| 1310 | ser::SerializeStruct, |
| 1311 | Deserialize, Deserializer, Serialize, Serializer, |
| 1312 | }; |
| 1313 | |
| 1314 | #[allow(unused_imports)] |
| 1315 | use crate::encoding::OwnedValue; |
| 1316 | |
| 1317 | impl Serialize for super::JsonOp { |
| 1318 | fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 1319 | where |
| 1320 | S: Serializer, |
| 1321 | { |
| 1322 | let mut s = serializer.serialize_struct("Op", 3)?; |
| 1323 | s.serialize_field("container", &self.container.to_string())?; |
| 1324 | s.serialize_field("content", &self.content)?; |
| 1325 | s.serialize_field("counter", &self.counter)?; |
| 1326 | s.end() |
| 1327 | } |
| 1328 | } |
| 1329 | |
| 1330 | impl<'de> Deserialize<'de> for super::JsonOp { |
| 1331 | fn deserialize<D>(deserializer: D) -> Result<super::JsonOp, D::Error> |
| 1332 | where |
| 1333 | D: Deserializer<'de>, |
| 1334 | { |
| 1335 | struct __Visitor; |
| 1336 | |
| 1337 | impl<'de> Visitor<'de> for __Visitor { |
| 1338 | type Value = super::JsonOp; |
| 1339 | fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { |
| 1340 | formatter.write_str("struct Op") |
| 1341 | } |
| 1342 | |
| 1343 | fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> |
| 1344 | where |
| 1345 | A: MapAccess<'de>, |
| 1346 | { |
| 1347 | let mut container = None; |
| 1348 | let mut content = None; |
| 1349 | let mut counter = None; |
| 1350 | |
| 1351 | while let Some(key) = map.next_key::<String>()? { |
| 1352 | match key.as_str() { |
| 1353 | "container" => { |
| 1354 | if container.is_some() { |
| 1355 | return Err(A::Error::duplicate_field("container")); |
| 1356 | } |
| 1357 | let value = map.next_value::<String>()?; |
| 1358 | container = |
| 1359 | Some(ContainerID::try_from(value.as_str()).map_err( |
| 1360 | |_| A::Error::custom("invalid container id"), |
| 1361 | )?); |
| 1362 | } |
| 1363 | "content" => { |
| 1364 | if content.is_some() { |
| 1365 | return Err(A::Error::duplicate_field("content")); |
| 1366 | } |
| 1367 | content = Some(map.next_value::<serde_json::Value>()?); |
| 1368 | } |
| 1369 | "counter" => { |
| 1370 | if counter.is_some() { |
| 1371 | return Err(A::Error::duplicate_field("counter")); |
| 1372 | } |
| 1373 | counter = Some(map.next_value::<i32>()?); |
| 1374 | } |
| 1375 | _ => { |
| 1376 | let _ = map.next_value::<IgnoredAny>()?; |
| 1377 | } |
| 1378 | } |
| 1379 | } |
| 1380 | |
| 1381 | let container = |
| 1382 | container.ok_or_else(|| A::Error::missing_field("container"))?; |
| 1383 | let content = content.ok_or_else(|| A::Error::missing_field("content"))?; |
| 1384 | let op = json_op_content_from_value(&container, content)?; |
| 1385 | let counter = counter.ok_or_else(|| A::Error::missing_field("counter"))?; |
| 1386 | Ok(super::JsonOp { |
| 1387 | container, |
| 1388 | content: op, |
| 1389 | counter, |
| 1390 | }) |
| 1391 | } |
| 1392 | } |
| 1393 | const FIELDS: &[&str] = &["container", "content", "counter"]; |
| 1394 | deserializer.deserialize_struct("JsonOp", FIELDS, __Visitor) |
| 1395 | } |
| 1396 | } |
| 1397 | |
| 1398 | fn json_op_content_from_value<E: Error>( |
| 1399 | container: &ContainerID, |
| 1400 | value: serde_json::Value, |
| 1401 | ) -> Result<super::JsonOpContent, E> { |
| 1402 | match container.container_type() { |
| 1403 | ContainerType::List => serde_json::from_value(value) |
| 1404 | .map(super::JsonOpContent::List) |
| 1405 | .map_err(E::custom), |
| 1406 | ContainerType::MovableList => serde_json::from_value(value) |
| 1407 | .map(super::JsonOpContent::MovableList) |
| 1408 | .map_err(E::custom), |
| 1409 | ContainerType::Map => serde_json::from_value(value) |
| 1410 | .map(super::JsonOpContent::Map) |
| 1411 | .map_err(E::custom), |
| 1412 | ContainerType::Text => serde_json::from_value(value) |
| 1413 | .map(super::JsonOpContent::Text) |
| 1414 | .map_err(E::custom), |
| 1415 | ContainerType::Tree => serde_json::from_value(value) |
| 1416 | .map(super::JsonOpContent::Tree) |
| 1417 | .map_err(E::custom), |
| 1418 | ContainerType::Unknown(_) => serde_json::from_value(value) |
| 1419 | .map(super::JsonOpContent::Future) |
| 1420 | .map_err(E::custom), |
| 1421 | #[cfg(feature = "counter")] |
| 1422 | ContainerType::Counter => { |
| 1423 | match serde_json::from_value::<super::FutureOpWrapper>(value.clone()) { |
| 1424 | Ok(op) => Ok(super::JsonOpContent::Future(op)), |
| 1425 | Err(_) => { |
| 1426 | let value = |
| 1427 | serde_json::from_value::<OwnedValue>(value).map_err(E::custom)?; |
| 1428 | Ok(super::JsonOpContent::Future(super::FutureOpWrapper { |
| 1429 | prop: 0, |
| 1430 | value: super::FutureOp::Counter(value), |
| 1431 | })) |
| 1432 | } |
| 1433 | } |
| 1434 | } |
| 1435 | } |
| 1436 | } |
| 1437 | |
| 1438 | pub mod id { |
| 1439 | use loro_common::ID; |
| 1440 | use serde::{Deserialize, Deserializer, Serializer}; |
| 1441 | |
| 1442 | pub fn serialize<S>(id: &ID, s: S) -> Result<S::Ok, S::Error> |
| 1443 | where |
| 1444 | S: Serializer, |
| 1445 | { |
| 1446 | s.serialize_str(&id.to_string()) |
| 1447 | } |
| 1448 | |
| 1449 | pub fn deserialize<'de, 'a, D>(d: D) -> Result<ID, D::Error> |
| 1450 | where |
| 1451 | D: Deserializer<'de>, |
| 1452 | { |
| 1453 | // NOTE: https://github.com/serde-rs/serde/issues/2467 we use String here |
| 1454 | let str: String = Deserialize::deserialize(d)?; |
| 1455 | let id: ID = ID::try_from(str.as_str()) |
| 1456 | .map_err(|_| serde::de::Error::custom("invalid ID format"))?; |
| 1457 | Ok(id) |
| 1458 | } |
| 1459 | } |
| 1460 | |
| 1461 | pub mod frontiers { |
| 1462 | use itertools::Itertools; |
| 1463 | use loro_common::ID; |
| 1464 | use serde::{ser::SerializeMap, Deserializer, Serializer}; |
| 1465 | |
| 1466 | use crate::version::Frontiers; |
| 1467 | |
| 1468 | pub fn serialize<S>(f: &Frontiers, s: S) -> Result<S::Ok, S::Error> |
| 1469 | where |
| 1470 | S: Serializer, |
| 1471 | { |
| 1472 | let mut map = s.serialize_map(Some(f.len()))?; |
| 1473 | for id in f |
| 1474 | .iter() |
| 1475 | // Make sure the order is deterministic |
| 1476 | .sorted() |
| 1477 | { |
| 1478 | map.serialize_entry(&id.peer.to_string(), &id.counter)?; |
| 1479 | } |
| 1480 | map.end() |
| 1481 | } |
| 1482 | |
| 1483 | pub fn deserialize<'de, 'a, D>(d: D) -> Result<Frontiers, D::Error> |
| 1484 | where |
| 1485 | D: Deserializer<'de>, |
| 1486 | { |
| 1487 | struct __Visitor; |
| 1488 | impl<'de> serde::de::Visitor<'de> for __Visitor { |
| 1489 | type Value = Frontiers; |
| 1490 | fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { |
| 1491 | formatter.write_str("a Frontiers") |
| 1492 | } |
| 1493 | |
| 1494 | fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> |
| 1495 | where |
| 1496 | A: serde::de::MapAccess<'de>, |
| 1497 | { |
| 1498 | let mut f = Frontiers::default(); |
| 1499 | while let Some((k, v)) = map.next_entry::<String, i32>()? { |
| 1500 | f.push(ID::new( |
| 1501 | k.parse().map_err(|_| { |
| 1502 | serde::de::Error::custom("invalid peer id in frontiers") |
| 1503 | })?, |
| 1504 | v, |
| 1505 | )) |
| 1506 | } |
| 1507 | Ok(f) |
| 1508 | } |
| 1509 | } |
| 1510 | d.deserialize_map(__Visitor) |
| 1511 | } |
| 1512 | } |
| 1513 | |
| 1514 | pub mod deps { |
| 1515 | use loro_common::ID; |
| 1516 | use serde::{Deserialize, Deserializer, Serializer}; |
| 1517 | |
| 1518 | pub fn serialize<S>(deps: &[ID], s: S) -> Result<S::Ok, S::Error> |
| 1519 | where |
| 1520 | S: Serializer, |
| 1521 | { |
| 1522 | s.collect_seq(deps.iter().map(|x| x.to_string())) |
| 1523 | } |
| 1524 | |
| 1525 | pub fn deserialize<'de, 'a, D>(d: D) -> Result<Vec<ID>, D::Error> |
| 1526 | where |
| 1527 | D: Deserializer<'de>, |
| 1528 | { |
| 1529 | let deps: Vec<String> = Deserialize::deserialize(d)?; |
| 1530 | deps.into_iter() |
| 1531 | .map(|x| { |
| 1532 | ID::try_from(x.as_str()) |
| 1533 | .map_err(|_| serde::de::Error::custom("invalid ID in deps")) |
| 1534 | }) |
| 1535 | .collect::<Result<Vec<_>, _>>() |
| 1536 | } |
| 1537 | } |
| 1538 | |
| 1539 | pub mod peer_id { |
| 1540 | use loro_common::PeerID; |
| 1541 | use serde::{Deserialize, Deserializer, Serializer}; |
| 1542 | |
| 1543 | pub fn serialize<S>(peers: &Option<Vec<PeerID>>, s: S) -> Result<S::Ok, S::Error> |
| 1544 | where |
| 1545 | S: Serializer, |
| 1546 | { |
| 1547 | match peers { |
| 1548 | Some(peers) => s.collect_seq(peers.iter().map(|x| x.to_string())), |
| 1549 | None => s.serialize_none(), |
| 1550 | } |
| 1551 | } |
| 1552 | |
| 1553 | pub fn deserialize<'de, 'a, D>(d: D) -> Result<Option<Vec<PeerID>>, D::Error> |
| 1554 | where |
| 1555 | D: Deserializer<'de>, |
| 1556 | { |
| 1557 | let peers: Option<Vec<String>> = Deserialize::deserialize(d)?; |
| 1558 | peers |
| 1559 | .map(|x| { |
| 1560 | x.into_iter() |
| 1561 | .map(|x| { |
| 1562 | x.parse() |
| 1563 | .map_err(|_| serde::de::Error::custom("invalid peer id")) |
| 1564 | }) |
| 1565 | .collect::<Result<Vec<_>, _>>() |
| 1566 | }) |
| 1567 | .transpose() |
| 1568 | } |
| 1569 | } |
| 1570 | |
| 1571 | pub mod idlp { |
| 1572 | use loro_common::IdLp; |
| 1573 | use serde::{Deserialize, Deserializer, Serializer}; |
| 1574 | |
| 1575 | pub fn serialize<S>(idlp: &IdLp, s: S) -> Result<S::Ok, S::Error> |
| 1576 | where |
| 1577 | S: Serializer, |
| 1578 | { |
| 1579 | s.serialize_str(&idlp.to_string()) |
| 1580 | } |
| 1581 | |
| 1582 | pub fn deserialize<'de, 'a, D>(d: D) -> Result<IdLp, D::Error> |
| 1583 | where |
| 1584 | D: Deserializer<'de>, |
| 1585 | { |
| 1586 | let str: String = Deserialize::deserialize(d)?; |
| 1587 | let id: IdLp = IdLp::try_from(str.as_str()) |
| 1588 | .map_err(|_| serde::de::Error::custom("invalid IdLp format"))?; |
| 1589 | Ok(id) |
| 1590 | } |
| 1591 | } |
| 1592 | |
| 1593 | pub mod tree_id { |
| 1594 | use loro_common::TreeID; |
| 1595 | use serde::{Deserialize, Deserializer, Serializer}; |
| 1596 | |
| 1597 | pub fn serialize<S>(id: &TreeID, s: S) -> Result<S::Ok, S::Error> |
| 1598 | where |
| 1599 | S: Serializer, |
| 1600 | { |
| 1601 | s.serialize_str(&id.to_string()) |
| 1602 | } |
| 1603 | |
| 1604 | pub fn deserialize<'de, 'a, D>(d: D) -> Result<TreeID, D::Error> |
| 1605 | where |
| 1606 | D: Deserializer<'de>, |
| 1607 | { |
| 1608 | let str: String = Deserialize::deserialize(d)?; |
| 1609 | let id: TreeID = TreeID::try_from(str.as_str()) |
| 1610 | .map_err(|_| serde::de::Error::custom("invalid TreeID format"))?; |
| 1611 | Ok(id) |
| 1612 | } |
| 1613 | } |
| 1614 | |
| 1615 | pub mod option_tree_id { |
| 1616 | use loro_common::TreeID; |
| 1617 | use serde::{Deserialize, Deserializer, Serializer}; |
| 1618 | |
| 1619 | pub fn serialize<S>(id: &Option<TreeID>, s: S) -> Result<S::Ok, S::Error> |
| 1620 | where |
| 1621 | S: Serializer, |
| 1622 | { |
| 1623 | match id { |
| 1624 | Some(id) => s.serialize_str(&id.to_string()), |
| 1625 | None => s.serialize_none(), |
| 1626 | } |
| 1627 | } |
| 1628 | |
| 1629 | pub fn deserialize<'de, 'a, D>(d: D) -> Result<Option<TreeID>, D::Error> |
| 1630 | where |
| 1631 | D: Deserializer<'de>, |
| 1632 | { |
| 1633 | let str: Option<String> = Deserialize::deserialize(d)?; |
| 1634 | match str { |
| 1635 | Some(str) => { |
| 1636 | let id: TreeID = TreeID::try_from(str.as_str()) |
| 1637 | .map_err(|_| serde::de::Error::custom("invalid TreeID format"))?; |
| 1638 | Ok(Some(id)) |
| 1639 | } |
| 1640 | None => Ok(None), |
| 1641 | } |
| 1642 | } |
| 1643 | } |
| 1644 | |
| 1645 | pub mod fractional_index { |
| 1646 | use fractional_index::FractionalIndex; |
| 1647 | use serde::{Deserialize, Deserializer, Serializer}; |
| 1648 | |
| 1649 | pub fn serialize<S>(fi: &FractionalIndex, s: S) -> Result<S::Ok, S::Error> |
| 1650 | where |
| 1651 | S: Serializer, |
| 1652 | { |
| 1653 | s.serialize_str(&fi.to_string()) |
| 1654 | } |
| 1655 | |
| 1656 | pub fn deserialize<'de, 'a, D>(d: D) -> Result<FractionalIndex, D::Error> |
| 1657 | where |
| 1658 | D: Deserializer<'de>, |
| 1659 | { |
| 1660 | let str: String = Deserialize::deserialize(d)?; |
| 1661 | if !str.len().is_multiple_of(2) { |
| 1662 | return Err(serde::de::Error::custom( |
| 1663 | "invalid fractional index hex length", |
| 1664 | )); |
| 1665 | } |
| 1666 | |
| 1667 | let mut bytes = Vec::with_capacity(str.len() / 2); |
| 1668 | for i in 0..str.len() / 2 { |
| 1669 | let byte = u8::from_str_radix(&str[i * 2..i * 2 + 2], 16).map_err(|e| { |
| 1670 | serde::de::Error::custom(format!("invalid fractional index hex: {e}")) |
| 1671 | })?; |
| 1672 | bytes.push(byte); |
| 1673 | } |
| 1674 | |
| 1675 | Ok(FractionalIndex::from_bytes(bytes)) |
| 1676 | } |
| 1677 | } |
| 1678 | } |
| 1679 | |
| 1680 | #[derive(thiserror::Error, Debug, PartialEq, Eq)] |
| 1681 | pub enum RedactError { |
| 1682 | #[error("unknown operation type")] |
| 1683 | UnknownOperationType, |
| 1684 | #[error("invalid schema: {0}")] |
| 1685 | InvalidSchema(String), |
| 1686 | } |
| 1687 | |
| 1688 | fn invalid_schema(message: impl Into<String>) -> RedactError { |
| 1689 | RedactError::InvalidSchema(message.into()) |
| 1690 | } |
| 1691 | |
| 1692 | fn checked_redact_op_len(op: &JsonOp) -> Result<Counter, RedactError> { |
| 1693 | let len = op.content.op_len(); |
| 1694 | if len == 0 { |
| 1695 | return Err(invalid_schema("op length must be greater than zero")); |
| 1696 | } |
| 1697 | |
| 1698 | Counter::try_from(len).map_err(|_| invalid_schema("op length is too large")) |
| 1699 | } |
| 1700 | |
| 1701 | fn validate_redactable_change(change: &JsonChange) -> Result<usize, RedactError> { |
| 1702 | if change.id.counter < 0 { |
| 1703 | return Err(invalid_schema("change id counter must be non-negative")); |
| 1704 | } |
| 1705 | |
| 1706 | let mut expected_counter = change.id.counter; |
| 1707 | for op in &change.ops { |
| 1708 | if op.counter < 0 { |
| 1709 | return Err(invalid_schema("op counter must be non-negative")); |
| 1710 | } |
| 1711 | if op.counter != expected_counter { |
| 1712 | return Err(invalid_schema( |
| 1713 | "op counters must be contiguous with the change id", |
| 1714 | )); |
| 1715 | } |
| 1716 | |
| 1717 | let len = checked_redact_op_len(op)?; |
| 1718 | expected_counter = expected_counter |
| 1719 | .checked_add(len) |
| 1720 | .ok_or_else(|| invalid_schema("op counter overflow"))?; |
| 1721 | } |
| 1722 | |
| 1723 | let len = expected_counter |
| 1724 | .checked_sub(change.id.counter) |
| 1725 | .ok_or_else(|| invalid_schema("change counter overflow"))?; |
| 1726 | usize::try_from(len).map_err(|_| invalid_schema("change length is too large")) |
| 1727 | } |
| 1728 | |
| 1729 | /// Redacts sensitive content within the specified range by replacing it with default values. |
| 1730 | /// |
| 1731 | /// This method applies the following redaction rules: |
| 1732 | /// |
| 1733 | /// - Preserves delete and move operations without changes |
| 1734 | /// - Replaces text insertion content with the Unicode replacement character (U+FFFD) |
| 1735 | /// - Substitutes list and map insert values with `LoroValue::Null` |
| 1736 | /// - Maintains child container creation operations |
| 1737 | /// - Replaces text mark values with `LoroValue::Null` |
| 1738 | /// - Preserves map insertion and text annotation keys |
| 1739 | /// - Resets counter operations to zero |
| 1740 | /// - Leaves unknown operation types (from future Loro versions) unchanged |
| 1741 | /// |
| 1742 | /// This approach ensures sensitive data removal while preserving the document's overall |
| 1743 | /// structure. Redacted documents maintain seamless collaboration capabilities with both |
| 1744 | /// redacted and non-redacted versions. |
| 1745 | pub fn redact(json: &mut JsonSchema, range: VersionRange) -> Result<(), RedactError> { |
| 1746 | let peers = json.peers.clone(); |
| 1747 | let mut errors = Vec::new(); |
| 1748 | for change in json.changes.iter_mut() { |
| 1749 | let real_peer = get_peer_from_peers(&peers, change.id.peer) |
| 1750 | .map_err(|_| RedactError::InvalidSchema("peer index out of range".to_string()))?; |
| 1751 | let real_id = ID::new(real_peer, change.id.counter); |
| 1752 | let change_len = validate_redactable_change(change)?; |
| 1753 | if !range.has_overlap_with(real_id.to_span(change_len)) { |
| 1754 | continue; |
| 1755 | } |
| 1756 | |
| 1757 | let redact_range = range.get(&real_peer).copied().unwrap(); |
| 1758 | for op in change.ops.iter_mut() { |
| 1759 | if op.counter >= redact_range.1 { |
| 1760 | break; |
| 1761 | } |
| 1762 | |
| 1763 | let len = checked_redact_op_len(op)?; |
| 1764 | let op_end = op |
| 1765 | .counter |
| 1766 | .checked_add(len) |
| 1767 | .ok_or_else(|| invalid_schema("op counter overflow"))?; |
| 1768 | if op_end <= redact_range.0 { |
| 1769 | continue; |
| 1770 | } |
| 1771 | |
| 1772 | let result = redact_op( |
| 1773 | &mut op.content, |
| 1774 | redact_range.0.saturating_sub(op.counter).max(0).min(len) |
| 1775 | ..redact_range.1.saturating_sub(op.counter).max(0).min(len), |
| 1776 | ); |
| 1777 | match result { |
| 1778 | Ok(()) => {} |
| 1779 | Err(e) => errors.push(e), |
| 1780 | } |
| 1781 | } |
| 1782 | } |
| 1783 | |
| 1784 | if errors.is_empty() { |
| 1785 | Ok(()) |
| 1786 | } else { |
| 1787 | Err(errors.pop().unwrap()) |
| 1788 | } |
| 1789 | } |
| 1790 | |
| 1791 | fn redact_op(op: &mut JsonOpContent, range: Range<Counter>) -> Result<(), RedactError> { |
| 1792 | match op { |
| 1793 | JsonOpContent::List(list_op) => { |
| 1794 | match list_op { |
| 1795 | ListOp::Insert { value: values, .. } => { |
| 1796 | for i in range { |
| 1797 | redact_value(&mut values[i as usize]); |
| 1798 | } |
| 1799 | } |
| 1800 | ListOp::Delete { .. } => { |
| 1801 | // Delete op won't be changed |
| 1802 | } |
| 1803 | } |
| 1804 | } |
| 1805 | JsonOpContent::MovableList(movable_list_op) => { |
| 1806 | match movable_list_op { |
| 1807 | MovableListOp::Insert { value: values, .. } => { |
| 1808 | for i in range { |
| 1809 | redact_value(&mut values[i as usize]); |
| 1810 | } |
| 1811 | } |
| 1812 | MovableListOp::Delete { .. } | MovableListOp::Move { .. } => { |
| 1813 | // Delete and move ops won't be changed |
| 1814 | } |
| 1815 | MovableListOp::Set { value, .. } => { |
| 1816 | assert!(range.start == 0 && range.len() == 1); |
| 1817 | redact_value(value); |
| 1818 | } |
| 1819 | } |
| 1820 | } |
| 1821 | JsonOpContent::Map(map_op) => { |
| 1822 | match map_op { |
| 1823 | MapOp::Insert { value, .. } => { |
| 1824 | assert!(range.start == 0 && range.len() == 1); |
| 1825 | redact_value(value); |
| 1826 | } |
| 1827 | MapOp::Delete { .. } => { |
| 1828 | // Delete op won't be changed |
| 1829 | } |
| 1830 | } |
| 1831 | } |
| 1832 | JsonOpContent::Text(text_op) => { |
| 1833 | match text_op { |
| 1834 | TextOp::Insert { text, .. } => { |
| 1835 | let mut chars = vec![]; |
| 1836 | for (i, c) in text.chars().enumerate() { |
| 1837 | if i < range.start as usize || i >= range.end as usize { |
| 1838 | chars.push(c); |
| 1839 | } else { |
| 1840 | chars.push("� ".chars().next().unwrap()); |
| 1841 | } |
| 1842 | } |
| 1843 | *text = chars.into_iter().collect(); |
| 1844 | } |
| 1845 | TextOp::Delete { .. } => { |
| 1846 | // Delete op won't be changed |
| 1847 | } |
| 1848 | TextOp::Mark { style_value, .. } => { |
| 1849 | assert!(range.start == 0 && range.len() == 1); |
| 1850 | *style_value = LoroValue::Null; |
| 1851 | } |
| 1852 | TextOp::MarkEnd => { |
| 1853 | // MarkEnd won't be changed |
| 1854 | } |
| 1855 | } |
| 1856 | } |
| 1857 | JsonOpContent::Tree(..) => { |
| 1858 | // Creation of child container won't be changed |
| 1859 | } |
| 1860 | JsonOpContent::Future(future_op_wrapper) => match &mut future_op_wrapper.value { |
| 1861 | #[cfg(feature = "counter")] |
| 1862 | FutureOp::Counter(owned_value) => { |
| 1863 | *owned_value = OwnedValue::I64(0); |
| 1864 | } |
| 1865 | FutureOp::Unknown(..) => { |
| 1866 | return Err(RedactError::UnknownOperationType); |
| 1867 | } |
| 1868 | }, |
| 1869 | } |
| 1870 | |
| 1871 | Ok(()) |
| 1872 | } |
| 1873 | } |
| 1874 | |
| 1875 | fn redact_value(v: &mut LoroValue) { |
| 1876 | match v { |
| 1877 | LoroValue::Container(_) => {} |
| 1878 | _ => *v = LoroValue::Null, |
| 1879 | } |
| 1880 | } |
| 1881 | |
| 1882 | #[cfg(test)] |
| 1883 | mod tests { |
| 1884 | use crate::{LoroDoc, VersionVector}; |
| 1885 | |
| 1886 | #[test] |
| 1887 | fn json_range_version() { |
| 1888 | let doc = LoroDoc::new_auto_commit(); |
| 1889 | doc.set_peer_id(0).unwrap(); |
| 1890 | let list = doc.get_list("list"); |
| 1891 | list.insert(0, "a").unwrap(); |
| 1892 | list.insert(0, "b").unwrap(); |
| 1893 | list.insert(0, "c").unwrap(); |
| 1894 | let json = doc |
| 1895 | .export_json_updates( |
| 1896 | &VersionVector::from_iter(vec![(0, 1)]), |
| 1897 | &VersionVector::from_iter(vec![(0, 2)]), |
| 1898 | true, |
| 1899 | ) |
| 1900 | .unwrap(); |
| 1901 | assert_eq!(json.changes[0].ops.len(), 1); |
| 1902 | let json = doc |
| 1903 | .export_json_updates( |
| 1904 | &VersionVector::from_iter(vec![(0, 0)]), |
| 1905 | &VersionVector::from_iter(vec![(0, 2)]), |
| 1906 | true, |
| 1907 | ) |
| 1908 | .unwrap(); |
| 1909 | assert_eq!(json.changes[0].ops.len(), 2); |
| 1910 | } |
| 1911 | } |