//! Semantic top-level edits on the existing CRDT, never a JSON reconstruction. use yrs::branch::{Branch, BranchPtr}; use yrs::{ Any, Doc, Map, MapRef, ReadTxn, Transact, XmlElementPrelim, XmlElementRef, XmlFragment, XmlOut, XmlTextPrelim, }; #[derive(Debug, PartialEq)] pub enum EditError { Invalid, Collision, Pending, TooLarge, } struct Edit<'a> { index: u32, delete: u32, blocks: Vec<(u8, &'a str)>, } fn number(input: &mut &[u8]) -> Result { if input.len() < 4 { return Err(EditError::Invalid); } let value = u32::from_be_bytes(input[..4].try_into().unwrap()); *input = &input[4..]; Ok(value) } // Count, then repeated index/delete/block-count u32 BE followed by initial // block encoding (level u8, UTF-8 byte-length u32 BE, bytes). pub fn edit(doc: &Doc, mut input: &[u8]) -> Result, EditError> { if input.len() > 128 * 1024 + 32 * 12 + 200 * 5 + 4 { return Err(EditError::TooLarge); } if doc.client_id() == 0 || doc.client_id() > u32::MAX as u64 { return Err(EditError::Invalid); } let count = number(&mut input)?; if count == 0 || count > 32 { return Err(EditError::Invalid); } let mut edits = Vec::new(); let (mut inserted, mut deleted, mut bytes) = (0u32, 0u32, 0usize); let mut previous = None; for _ in 0..count { let index = number(&mut input)?; let delete = number(&mut input)?; let n = number(&mut input)?; if n > 200 || delete > 200 || n == 0 && delete == 0 { return Err(EditError::Invalid); } inserted += n; deleted += delete; if inserted > 200 || deleted > 200 { return Err(EditError::TooLarge); } let end = index.checked_add(delete).ok_or(EditError::Invalid)?; if previous.is_some_and(|p| index >= p || end > p) { return Err(EditError::Invalid); } previous = Some(index); let mut blocks = Vec::new(); for _ in 0..n { let level = *input.first().ok_or(EditError::Invalid)?; input = &input[1..]; let len = number(&mut input)? as usize; if level > 6 || len > input.len() { return Err(EditError::Invalid); } bytes += len; if bytes > 128 * 1024 { return Err(EditError::TooLarge); } let text = std::str::from_utf8(&input[..len]).map_err(|_| EditError::Invalid)?; blocks.push((level, text)); input = &input[len..]; } edits.push(Edit { index, delete, blocks, }); } if !input.is_empty() { return Err(EditError::Invalid); } let root = doc.get_or_insert_xml_fragment(crate::FRAGMENT_ROOT); let mut txn = doc.transact_mut(); if txn.has_missing_updates() { return Err(EditError::Pending); } if txn.state_vector().get(&doc.client_id()) != 0 { return Err(EditError::Collision); } let len = root.len(&txn); if u64::from(len) + u64::from(inserted) <= u64::from(deleted) { return Err(EditError::Invalid); } if root .children(&txn) .any(|child| !matches!(child, XmlOut::Element(_))) { return Err(EditError::Invalid); } for e in &edits { if e.index > len || e.delete > len - e.index { return Err(EditError::Invalid); } for i in e.index..e.index + e.delete { match root.get(&txn, i) { Some(XmlOut::Element(node)) if (node.tag().as_ref() == "paragraph" || node.tag().as_ref() == "heading") && node .children(&txn) .all(|child| matches!(child, XmlOut::Text(_))) => {} _ => return Err(EditError::Invalid), } } } // No validation below can reject a partially applied request. for e in edits { if e.delete > 0 { root.remove_range(&mut txn, e.index, e.delete); } for (offset, (level, text)) in e.blocks.into_iter().enumerate() { let tag = if level == 0 { "paragraph" } else { "heading" }; let node = root.insert( &mut txn, e.index + offset as u32, XmlElementPrelim::empty(tag), ); if level > 0 { let branch = >::as_ref(&node); MapRef::from(BranchPtr::from(branch)).insert( &mut txn, "level", Any::Number(level as f64), ); } if !text.is_empty() { node.push_back(&mut txn, XmlTextPrelim::new(text)); } } } let update = txn.encode_update_v1(); if update.len() > 1 << 20 { return Err(EditError::TooLarge); } Ok(update) }