| 1 | //! Building a new document from an import. |
| 2 | //! |
| 3 | //! The server's only way to write content. Everything else in this crate |
| 4 | //! reads; an import is the one place the server, rather than an editor, |
| 5 | //! decides what a document holds, and it decides from a file somebody |
| 6 | //! uploaded. So the input is not ProseMirror JSON and not anything yrs |
| 7 | //! would accept: it is a closed instruction list naming paragraphs, |
| 8 | //! headings with a level, and text runs whose marks are rows of |
| 9 | //! `fragment.rs`'s MARKS table. Only the text is free, and text only ever |
| 10 | //! lands in a text run. Nothing from a file can reach an attribute, a tag |
| 11 | //! name, or a mark this build cannot render. |
| 12 | //! |
| 13 | //! What comes out is what y-prosemirror itself writes for the same |
| 14 | //! ProseMirror document: one `XmlElement` per block named after its node |
| 15 | //! type, a heading's level as a number (not the string yrs' XML calls |
| 16 | //! would write), one `XmlText` per block carrying |
| 17 | //! its runs as a delta, each mark an attribute whose value is the mark's |
| 18 | //! (empty) attrs, and no child at all for an empty block. yrs encodes it; |
| 19 | //! nothing here writes Yjs bytes by hand. |
| 20 | //! |
| 21 | //! The whole list is decoded and checked before the document is touched, |
| 22 | //! and then written in one transaction, so a refusal leaves the document |
| 23 | //! exactly as it was: empty. |
| 24 | //! |
| 25 | //! # The instruction list, version 1 |
| 26 | //! |
| 27 | //! Little-endian throughout. |
| 28 | //! |
| 29 | //! ```text |
| 30 | //! u8 version (1) |
| 31 | //! u32 block count |
| 32 | //! per block: |
| 33 | //! u8 kind: 1 paragraph, 2 heading |
| 34 | //! u8 level, heading only: 1..=6 |
| 35 | //! u32 run count |
| 36 | //! per run: |
| 37 | //! u8 mark count, then per mark: u8 length, that many bytes of name |
| 38 | //! u32 text length in bytes, then that many bytes of UTF-8 |
| 39 | //! ``` |
| 40 | //! |
| 41 | //! A run's text is never empty and holds no control character; a run |
| 42 | //! carries at most one font mark and at most one size mark, and never |
| 43 | //! the same mark twice. Adjacent runs with the same marks are allowed and |
| 44 | //! are merged, as y-prosemirror merges them. Nothing may follow the last |
| 45 | //! block. |
| 46 | |
| 47 | use crate::fragment::MARKS; |
| 48 | use std::collections::BTreeSet; |
| 49 | use yrs::branch::{Branch, BranchPtr}; |
| 50 | use yrs::types::xml::{XmlDeltaPrelim, XmlIn}; |
| 51 | use yrs::types::{Attrs, Delta}; |
| 52 | use yrs::{Any, Doc, In, Map, MapRef, Transact, XmlElementPrelim, XmlFragment, XmlOut}; |
| 53 | |
| 54 | /// The instruction-list version this build reads. |
| 55 | pub const VERSION: u8 = 1; |
| 56 | |
| 57 | /// The largest instruction list accepted, in bytes. |
| 58 | pub const MAX_INPUT: usize = 8 << 20; |
| 59 | /// The most blocks one import may write. |
| 60 | pub const MAX_BLOCKS: u32 = 50_000; |
| 61 | /// The most runs one import may write, across every block. |
| 62 | pub const MAX_RUNS: u32 = 500_000; |
| 63 | |
| 64 | /// Why an instruction list was refused. None of them carries anything |
| 65 | /// from the input: a refusal is a code, never a quotation. |
| 66 | #[derive(Debug, PartialEq, Eq)] |
| 67 | pub enum BuildError { |
| 68 | /// The bytes do not follow the format above: a wrong version, an |
| 69 | /// unknown block kind or mark, a level out of range, a short read, |
| 70 | /// trailing bytes, empty or non-UTF-8 text, a control character, |
| 71 | /// or two marks of one kind on a run. |
| 72 | Malformed, |
| 73 | /// The list is well formed but larger than MAX_INPUT, MAX_BLOCKS or |
| 74 | /// MAX_RUNS allow. |
| 75 | Limit, |
| 76 | /// The document already has content. An import writes only into a |
| 77 | /// fresh document. |
| 78 | NotEmpty, |
| 79 | /// The document's client id is past `MAX_SAFE_CLIENT_ID`, so the |
| 80 | /// update would carry an id no browser can decode. |
| 81 | UnsafeClientId, |
| 82 | } |
| 83 | |
| 84 | /// The largest client id an import may write under: JavaScript's |
| 85 | /// Number.MAX_SAFE_INTEGER. lib0's decoder refuses a larger varuint, so an |
| 86 | /// update written under one is unreadable by every editor, while the |
| 87 | /// server, reading through yrs, would accept it without complaint. |
| 88 | pub const MAX_SAFE_CLIENT_ID: u64 = (1 << 53) - 1; |
| 89 | |
| 90 | /// The marks an import may write: every MARKS row except the retired |
| 91 | /// four-step sizes (`size_sm`, `size_lg`, `size_xl`, which the control no |
| 92 | /// longer offers) and `code`, which an import never produces. |
| 93 | fn allowed(name: &str) -> bool { |
| 94 | MARKS.iter().any(|(m, _, _)| *m == name) |
| 95 | && !matches!(name, "size_sm" | "size_lg" | "size_xl" | "code") |
| 96 | } |
| 97 | |
| 98 | struct Reader<'a> { |
| 99 | bytes: &'a [u8], |
| 100 | at: usize, |
| 101 | } |
| 102 | |
| 103 | impl<'a> Reader<'a> { |
| 104 | fn take(&mut self, n: usize) -> Result<&'a [u8], BuildError> { |
| 105 | let end = self.at.checked_add(n).ok_or(BuildError::Malformed)?; |
| 106 | let out = self.bytes.get(self.at..end).ok_or(BuildError::Malformed)?; |
| 107 | self.at = end; |
| 108 | Ok(out) |
| 109 | } |
| 110 | fn u8(&mut self) -> Result<u8, BuildError> { |
| 111 | Ok(self.take(1)?[0]) |
| 112 | } |
| 113 | fn u32(&mut self) -> Result<u32, BuildError> { |
| 114 | let b = self.take(4)?; |
| 115 | Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]])) |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | struct Run { |
| 120 | marks: BTreeSet<&'static str>, |
| 121 | text: String, |
| 122 | } |
| 123 | |
| 124 | fn marks(r: &mut Reader) -> Result<BTreeSet<&'static str>, BuildError> { |
| 125 | let count = r.u8()?; |
| 126 | let mut out = BTreeSet::new(); |
| 127 | let (mut font, mut size) = (false, false); |
| 128 | for _ in 0..count { |
| 129 | let len = r.u8()? as usize; |
| 130 | let name = std::str::from_utf8(r.take(len)?).map_err(|_| BuildError::Malformed)?; |
| 131 | if !allowed(name) { |
| 132 | return Err(BuildError::Malformed); |
| 133 | } |
| 134 | // The table's own &'static str, so nothing borrowed from the |
| 135 | // input survives the decode. |
| 136 | let name = MARKS |
| 137 | .iter() |
| 138 | .find(|(m, _, _)| *m == name) |
| 139 | .map(|(m, _, _)| *m) |
| 140 | .ok_or(BuildError::Malformed)?; |
| 141 | let is_font = name.starts_with("font_"); |
| 142 | let is_size = name.starts_with("size_"); |
| 143 | if (is_font && font) || (is_size && size) || !out.insert(name) { |
| 144 | return Err(BuildError::Malformed); |
| 145 | } |
| 146 | font |= is_font; |
| 147 | size |= is_size; |
| 148 | } |
| 149 | Ok(out) |
| 150 | } |
| 151 | |
| 152 | fn text(r: &mut Reader) -> Result<String, BuildError> { |
| 153 | let len = r.u32()? as usize; |
| 154 | let s = std::str::from_utf8(r.take(len)?).map_err(|_| BuildError::Malformed)?; |
| 155 | if s.is_empty() || s.chars().any(char::is_control) { |
| 156 | return Err(BuildError::Malformed); |
| 157 | } |
| 158 | Ok(s.to_string()) |
| 159 | } |
| 160 | |
| 161 | /// One decoded block: its prelim, and the heading level to set on it |
| 162 | /// once it is in the document. |
| 163 | struct Block { |
| 164 | prelim: XmlIn, |
| 165 | level: Option<u8>, |
| 166 | } |
| 167 | |
| 168 | fn block(r: &mut Reader, runs_left: &mut u32) -> Result<Block, BuildError> { |
| 169 | let (mut element, level) = match r.u8()? { |
| 170 | 1 => (XmlElementPrelim::empty("paragraph"), None), |
| 171 | 2 => { |
| 172 | let level = r.u8()?; |
| 173 | if !(1..=6).contains(&level) { |
| 174 | return Err(BuildError::Malformed); |
| 175 | } |
| 176 | (XmlElementPrelim::empty("heading"), Some(level)) |
| 177 | } |
| 178 | _ => return Err(BuildError::Malformed), |
| 179 | }; |
| 180 | let count = r.u32()?; |
| 181 | if count > *runs_left { |
| 182 | return Err(BuildError::Limit); |
| 183 | } |
| 184 | *runs_left -= count; |
| 185 | let mut runs: Vec<Run> = Vec::new(); |
| 186 | for _ in 0..count { |
| 187 | let run = Run { |
| 188 | marks: marks(r)?, |
| 189 | text: text(r)?, |
| 190 | }; |
| 191 | match runs.last_mut() { |
| 192 | Some(last) if last.marks == run.marks => last.text.push_str(&run.text), |
| 193 | _ => runs.push(run), |
| 194 | } |
| 195 | } |
| 196 | if !runs.is_empty() { |
| 197 | let delta = runs |
| 198 | .into_iter() |
| 199 | .map(|run| { |
| 200 | let attrs = if run.marks.is_empty() { |
| 201 | None |
| 202 | } else { |
| 203 | let attrs: Attrs = run |
| 204 | .marks |
| 205 | .iter() |
| 206 | .map(|m| ((*m).into(), Any::Map(Default::default()))) |
| 207 | .collect(); |
| 208 | Some(Box::new(attrs)) |
| 209 | }; |
| 210 | Delta::Inserted(In::Any(Any::from(run.text)), attrs) |
| 211 | }) |
| 212 | .collect(); |
| 213 | element.children.push(XmlIn::Text(XmlDeltaPrelim { |
| 214 | attributes: Default::default(), |
| 215 | delta, |
| 216 | })); |
| 217 | } |
| 218 | Ok(Block { |
| 219 | prelim: XmlIn::Element(element), |
| 220 | level, |
| 221 | }) |
| 222 | } |
| 223 | |
| 224 | /// Decodes and checks a whole instruction list, writing nothing. |
| 225 | fn decode(ops: &[u8]) -> Result<Vec<Block>, BuildError> { |
| 226 | if ops.len() > MAX_INPUT { |
| 227 | return Err(BuildError::Limit); |
| 228 | } |
| 229 | let mut r = Reader { bytes: ops, at: 0 }; |
| 230 | if r.u8()? != VERSION { |
| 231 | return Err(BuildError::Malformed); |
| 232 | } |
| 233 | let count = r.u32()?; |
| 234 | if count > MAX_BLOCKS { |
| 235 | return Err(BuildError::Limit); |
| 236 | } |
| 237 | let mut runs_left = MAX_RUNS; |
| 238 | let mut blocks = Vec::with_capacity(count as usize); |
| 239 | for _ in 0..count { |
| 240 | blocks.push(block(&mut r, &mut runs_left)?); |
| 241 | } |
| 242 | if r.at != ops.len() { |
| 243 | return Err(BuildError::Malformed); |
| 244 | } |
| 245 | Ok(blocks) |
| 246 | } |
| 247 | |
| 248 | /// Writes the document an instruction list describes into `doc`, which |
| 249 | /// must be empty. On any error `doc` is left untouched. |
| 250 | pub fn build(doc: &Doc, ops: &[u8]) -> Result<(), BuildError> { |
| 251 | if doc.client_id() > MAX_SAFE_CLIENT_ID { |
| 252 | return Err(BuildError::UnsafeClientId); |
| 253 | } |
| 254 | let blocks = decode(ops)?; |
| 255 | let root = doc.get_or_insert_xml_fragment(crate::FRAGMENT_ROOT); |
| 256 | let mut txn = doc.transact_mut(); |
| 257 | if root.len(&txn) != 0 { |
| 258 | return Err(BuildError::NotEmpty); |
| 259 | } |
| 260 | // Last block first, each at the front. yrs finds an index by walking |
| 261 | // the list from its start, so appending block by block is quadratic |
| 262 | // in the number of blocks (ten thousand took 1.6 s, past the host's |
| 263 | // one-second call limit); inserting at index 0 finds its place at |
| 264 | // once. The document is the same either way. |
| 265 | for b in blocks.into_iter().rev() { |
| 266 | let inserted = root.insert(&mut txn, 0, b.prelim); |
| 267 | if let (Some(level), XmlOut::Element(e)) = (b.level, inserted) { |
| 268 | // A heading's level is a number, as y-prosemirror writes it |
| 269 | // and as the editor's schema (`validate: "number"`) expects. |
| 270 | // yrs' XML attribute calls take only strings, but an |
| 271 | // element's attributes are its map, which is what Yjs' |
| 272 | // setAttribute writes too; so the number goes in through |
| 273 | // the map. |
| 274 | MapRef::from(BranchPtr::from(AsRef::<Branch>::as_ref(&e))).insert( |
| 275 | &mut txn, |
| 276 | "level", |
| 277 | Any::Number(level as f64), |
| 278 | ); |
| 279 | } |
| 280 | } |
| 281 | Ok(()) |
| 282 | } |
| 283 | |