oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1//! Semantic top-level edits on the existing CRDT, never a JSON reconstruction.
2use yrs::branch::{Branch, BranchPtr};
3use yrs::{
4 Any, Doc, Map, MapRef, ReadTxn, Transact, XmlElementPrelim, XmlElementRef, XmlFragment, XmlOut,
5 XmlTextPrelim,
6};
7
8#[derive(Debug, PartialEq)]
9pub enum EditError {
10 Invalid,
11 Collision,
12 Pending,
13 TooLarge,
14}
15
16struct Edit<'a> {
17 index: u32,
18 delete: u32,
19 blocks: Vec<(u8, &'a str)>,
20}
21
22fn number(input: &mut &[u8]) -> Result<u32, EditError> {
23 if input.len() < 4 {
24 return Err(EditError::Invalid);
25 }
26 let value = u32::from_be_bytes(input[..4].try_into().unwrap());
27 *input = &input[4..];
28 Ok(value)
29}
30
31// Count, then repeated index/delete/block-count u32 BE followed by initial
32// block encoding (level u8, UTF-8 byte-length u32 BE, bytes).
33pub fn edit(doc: &Doc, mut input: &[u8]) -> Result<Vec<u8>, EditError> {
34 if input.len() > 128 * 1024 + 32 * 12 + 200 * 5 + 4 {
35 return Err(EditError::TooLarge);
36 }
37 if doc.client_id() == 0 || doc.client_id() > u32::MAX as u64 {
38 return Err(EditError::Invalid);
39 }
40 let count = number(&mut input)?;
41 if count == 0 || count > 32 {
42 return Err(EditError::Invalid);
43 }
44 let mut edits = Vec::new();
45 let (mut inserted, mut deleted, mut bytes) = (0u32, 0u32, 0usize);
46 let mut previous = None;
47 for _ in 0..count {
48 let index = number(&mut input)?;
49 let delete = number(&mut input)?;
50 let n = number(&mut input)?;
51 if n > 200 || delete > 200 || n == 0 && delete == 0 {
52 return Err(EditError::Invalid);
53 }
54 inserted += n;
55 deleted += delete;
56 if inserted > 200 || deleted > 200 {
57 return Err(EditError::TooLarge);
58 }
59 let end = index.checked_add(delete).ok_or(EditError::Invalid)?;
60 if previous.is_some_and(|p| index >= p || end > p) {
61 return Err(EditError::Invalid);
62 }
63 previous = Some(index);
64 let mut blocks = Vec::new();
65 for _ in 0..n {
66 let level = *input.first().ok_or(EditError::Invalid)?;
67 input = &input[1..];
68 let len = number(&mut input)? as usize;
69 if level > 6 || len > input.len() {
70 return Err(EditError::Invalid);
71 }
72 bytes += len;
73 if bytes > 128 * 1024 {
74 return Err(EditError::TooLarge);
75 }
76 let text = std::str::from_utf8(&input[..len]).map_err(|_| EditError::Invalid)?;
77 blocks.push((level, text));
78 input = &input[len..];
79 }
80 edits.push(Edit {
81 index,
82 delete,
83 blocks,
84 });
85 }
86 if !input.is_empty() {
87 return Err(EditError::Invalid);
88 }
89 let root = doc.get_or_insert_xml_fragment(crate::FRAGMENT_ROOT);
90 let mut txn = doc.transact_mut();
91 if txn.has_missing_updates() {
92 return Err(EditError::Pending);
93 }
94 if txn.state_vector().get(&doc.client_id()) != 0 {
95 return Err(EditError::Collision);
96 }
97 let len = root.len(&txn);
98 if u64::from(len) + u64::from(inserted) <= u64::from(deleted) {
99 return Err(EditError::Invalid);
100 }
101 if root
102 .children(&txn)
103 .any(|child| !matches!(child, XmlOut::Element(_)))
104 {
105 return Err(EditError::Invalid);
106 }
107 for e in &edits {
108 if e.index > len || e.delete > len - e.index {
109 return Err(EditError::Invalid);
110 }
111 for i in e.index..e.index + e.delete {
112 match root.get(&txn, i) {
113 Some(XmlOut::Element(node))
114 if (node.tag().as_ref() == "paragraph" || node.tag().as_ref() == "heading")
115 && node
116 .children(&txn)
117 .all(|child| matches!(child, XmlOut::Text(_))) => {}
118 _ => return Err(EditError::Invalid),
119 }
120 }
121 }
122 // No validation below can reject a partially applied request.
123 for e in edits {
124 if e.delete > 0 {
125 root.remove_range(&mut txn, e.index, e.delete);
126 }
127 for (offset, (level, text)) in e.blocks.into_iter().enumerate() {
128 let tag = if level == 0 { "paragraph" } else { "heading" };
129 let node = root.insert(
130 &mut txn,
131 e.index + offset as u32,
132 XmlElementPrelim::empty(tag),
133 );
134 if level > 0 {
135 let branch = <XmlElementRef as AsRef<Branch>>::as_ref(&node);
136 MapRef::from(BranchPtr::from(branch)).insert(
137 &mut txn,
138 "level",
139 Any::Number(level as f64),
140 );
141 }
142 if !text.is_empty() {
143 node.push_back(&mut txn, XmlTextPrelim::new(text));
144 }
145 }
146 }
147 let update = txn.encode_update_v1();
148 if update.len() > 1 << 20 {
149 return Err(EditError::TooLarge);
150 }
151 Ok(update)
152}
153