Core: a bounded builder for imported documents (ABI 5).
docs_core_build writes a document from a closed instruction list: paragraphs, headings with a level, and text runs whose marks are rows of fragment.rs's MARKS table (minus the retired sizes and code). The whole list is decoded and checked before the fresh document is touched, then written in one transaction; any refusal leaves the document empty. What it writes is what y-prosemirror writes: one XmlText per block, marks as attributes with empty attrs, no child for an empty block, and a heading level as a number through the element's map (yrs' XML attribute calls only write strings, and the editor schema validates level as a number). Blocks are inserted last-first at index 0 because yrs walks to an index, which made appending quadratic (10,000 blocks: 1.6 s, now 0.15 s). Go: Runtime.Build (with a 5x allowance for the one build call; the result must still replay inside the ordinary limit, which a test holds at the reader's limit) and EncodeBuild. Tests seen red by mutation.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+818
−3
core/src/abi.rs+40 −0core/src/build.rs+270 −0core/src/fragment.rs+1 −1core/src/lib.rs+6 −1core/tests/build.rs+261 −0internal/core/build_test.go+130 −0internal/core/core.go+110 −1internal/core/testdata/docs_core.wasmbinary
CI passed — run details
diff --git a/core/src/abi.rs b/core/src/abi.rs| index b86b56e..e392367 100644 |
| --- a/core/src/abi.rs |
| +++ b/core/src/abi.rs |
| @@ -499,3 +499,43 @@ pub unsafe extern "C" fn docs_core_verify_snapshot(handle: u32, ptr: u32, len: u |
| } |
| } |
| } |
| + |
| +/// The instruction list was refused by `build`: see `BuildError::Malformed`. |
| +pub const ERR_BUILD_MALFORMED: i32 = -6; |
| +/// The instruction list exceeds one of `build`'s limits. |
| +pub const ERR_BUILD_LIMIT: i32 = -7; |
| +/// The handle's document is not empty; an import writes only into a |
| +/// fresh one. |
| +pub const ERR_BUILD_NOT_EMPTY: i32 = -8; |
| + |
| +pub fn build_slice(handle: u32, ops: &[u8]) -> i32 { |
| + match get_doc(handle) { |
| + None => ERR_NO_DOC, |
| + Some(doc) => match crate::build::build(&doc, ops) { |
| + Ok(()) => 0, |
| + Err(crate::build::BuildError::Malformed) => ERR_BUILD_MALFORMED, |
| + Err(crate::build::BuildError::Limit) => ERR_BUILD_LIMIT, |
| + Err(crate::build::BuildError::NotEmpty) => ERR_BUILD_NOT_EMPTY, |
| + }, |
| + } |
| +} |
| + |
| +/// Writes the document `build`'s instruction list describes into |
| +/// `handle`, which must be empty. 0 on success; on any error the |
| +/// document is unchanged. |
| +/// |
| +/// # Safety |
| +/// |
| +/// `ptr` and `len` must describe a byte range that lies entirely within |
| +/// this module's linear memory and is not mutated for the duration of |
| +/// this call. (Checked by `in_bounds` before any slice is constructed β |
| +/// this safety requirement covers what that check cannot see, such as |
| +/// concurrent mutation.) |
| +#[no_mangle] |
| +pub unsafe extern "C" fn docs_core_build(handle: u32, ptr: u32, len: u32) -> i32 { |
| + if !in_bounds(ptr, len) { |
| + return ERR_INVALID_LENGTH; |
| + } |
| + let bytes = std::slice::from_raw_parts(ptr as *const u8, len as usize); |
| + build_slice(handle, bytes) |
| +} |
diff --git a/core/src/build.rs b/core/src/build.rs| new file mode 100644 |
| index 0000000..e39509a |
| --- /dev/null |
| +++ b/core/src/build.rs |
| @@ -0,0 +1,270 @@ |
| +//! Building a new document from an import. |
| +//! |
| +//! The server's only way to write content. Everything else in this crate |
| +//! reads; an import is the one place the server, rather than an editor, |
| +//! decides what a document holds, and it decides from a file somebody |
| +//! uploaded. So the input is not ProseMirror JSON and not anything yrs |
| +//! would accept: it is a closed instruction list naming paragraphs, |
| +//! headings with a level, and text runs whose marks are rows of |
| +//! `fragment.rs`'s MARKS table. Only the text is free, and text only ever |
| +//! lands in a text run. Nothing from a file can reach an attribute, a tag |
| +//! name, or a mark this build cannot render. |
| +//! |
| +//! What comes out is what y-prosemirror itself writes for the same |
| +//! ProseMirror document: one `XmlElement` per block named after its node |
| +//! type, a heading's level as a number (not the string yrs' XML calls |
| +//! would write), one `XmlText` per block carrying |
| +//! its runs as a delta, each mark an attribute whose value is the mark's |
| +//! (empty) attrs, and no child at all for an empty block. yrs encodes it; |
| +//! nothing here writes Yjs bytes by hand. |
| +//! |
| +//! The whole list is decoded and checked before the document is touched, |
| +//! and then written in one transaction, so a refusal leaves the document |
| +//! exactly as it was: empty. |
| +//! |
| +//! # The instruction list, version 1 |
| +//! |
| +//! Little-endian throughout. |
| +//! |
| +//! ```text |
| +//! u8 version (1) |
| +//! u32 block count |
| +//! per block: |
| +//! u8 kind: 1 paragraph, 2 heading |
| +//! u8 level, heading only: 1..=6 |
| +//! u32 run count |
| +//! per run: |
| +//! u8 mark count, then per mark: u8 length, that many bytes of name |
| +//! u32 text length in bytes, then that many bytes of UTF-8 |
| +//! ``` |
| +//! |
| +//! A run's text is never empty and holds no control character; a run |
| +//! carries at most one font mark and at most one size mark, and never |
| +//! the same mark twice. Adjacent runs with the same marks are allowed and |
| +//! are merged, as y-prosemirror merges them. Nothing may follow the last |
| +//! block. |
| + |
| +use crate::fragment::MARKS; |
| +use std::collections::BTreeSet; |
| +use yrs::branch::{Branch, BranchPtr}; |
| +use yrs::types::xml::{XmlDeltaPrelim, XmlIn}; |
| +use yrs::types::{Attrs, Delta}; |
| +use yrs::{Any, Doc, In, Map, MapRef, Transact, XmlElementPrelim, XmlFragment, XmlOut}; |
| + |
| +/// The instruction-list version this build reads. |
| +pub const VERSION: u8 = 1; |
| + |
| +/// The largest instruction list accepted, in bytes. |
| +pub const MAX_INPUT: usize = 8 << 20; |
| +/// The most blocks one import may write. |
| +pub const MAX_BLOCKS: u32 = 50_000; |
| +/// The most runs one import may write, across every block. |
| +pub const MAX_RUNS: u32 = 500_000; |
| + |
| +/// Why an instruction list was refused. None of them carries anything |
| +/// from the input: a refusal is a code, never a quotation. |
| +#[derive(Debug, PartialEq, Eq)] |
| +pub enum BuildError { |
| + /// The bytes do not follow the format above: a wrong version, an |
| + /// unknown block kind or mark, a level out of range, a short read, |
| + /// trailing bytes, empty or non-UTF-8 text, a control character, |
| + /// or two marks of one kind on a run. |
| + Malformed, |
| + /// The list is well formed but larger than MAX_INPUT, MAX_BLOCKS or |
| + /// MAX_RUNS allow. |
| + Limit, |
| + /// The document already has content. An import writes only into a |
| + /// fresh document. |
| + NotEmpty, |
| +} |
| + |
| +/// The marks an import may write: every MARKS row except the retired |
| +/// four-step sizes (`size_sm`, `size_lg`, `size_xl`, which the control no |
| +/// longer offers) and `code`, which an import never produces. |
| +fn allowed(name: &str) -> bool { |
| + MARKS.iter().any(|(m, _, _)| *m == name) |
| + && !matches!(name, "size_sm" | "size_lg" | "size_xl" | "code") |
| +} |
| + |
| +struct Reader<'a> { |
| + bytes: &'a [u8], |
| + at: usize, |
| +} |
| + |
| +impl<'a> Reader<'a> { |
| + fn take(&mut self, n: usize) -> Result<&'a [u8], BuildError> { |
| + let end = self.at.checked_add(n).ok_or(BuildError::Malformed)?; |
| + let out = self.bytes.get(self.at..end).ok_or(BuildError::Malformed)?; |
| + self.at = end; |
| + Ok(out) |
| + } |
| + fn u8(&mut self) -> Result<u8, BuildError> { |
| + Ok(self.take(1)?[0]) |
| + } |
| + fn u32(&mut self) -> Result<u32, BuildError> { |
| + let b = self.take(4)?; |
| + Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]])) |
| + } |
| +} |
| + |
| +struct Run { |
| + marks: BTreeSet<&'static str>, |
| + text: String, |
| +} |
| + |
| +fn marks(r: &mut Reader) -> Result<BTreeSet<&'static str>, BuildError> { |
| + let count = r.u8()?; |
| + let mut out = BTreeSet::new(); |
| + let (mut font, mut size) = (false, false); |
| + for _ in 0..count { |
| + let len = r.u8()? as usize; |
| + let name = std::str::from_utf8(r.take(len)?).map_err(|_| BuildError::Malformed)?; |
| + if !allowed(name) { |
| + return Err(BuildError::Malformed); |
| + } |
| + // The table's own &'static str, so nothing borrowed from the |
| + // input survives the decode. |
| + let name = MARKS |
| + .iter() |
| + .find(|(m, _, _)| *m == name) |
| + .map(|(m, _, _)| *m) |
| + .ok_or(BuildError::Malformed)?; |
| + let is_font = name.starts_with("font_"); |
| + let is_size = name.starts_with("size_"); |
| + if (is_font && font) || (is_size && size) || !out.insert(name) { |
| + return Err(BuildError::Malformed); |
| + } |
| + font |= is_font; |
| + size |= is_size; |
| + } |
| + Ok(out) |
| +} |
| + |
| +fn text(r: &mut Reader) -> Result<String, BuildError> { |
| + let len = r.u32()? as usize; |
| + let s = std::str::from_utf8(r.take(len)?).map_err(|_| BuildError::Malformed)?; |
| + if s.is_empty() || s.chars().any(char::is_control) { |
| + return Err(BuildError::Malformed); |
| + } |
| + Ok(s.to_string()) |
| +} |
| + |
| +/// One decoded block: its prelim, and the heading level to set on it |
| +/// once it is in the document. |
| +struct Block { |
| + prelim: XmlIn, |
| + level: Option<u8>, |
| +} |
| + |
| +fn block(r: &mut Reader, runs_left: &mut u32) -> Result<Block, BuildError> { |
| + let (mut element, level) = match r.u8()? { |
| + 1 => (XmlElementPrelim::empty("paragraph"), None), |
| + 2 => { |
| + let level = r.u8()?; |
| + if !(1..=6).contains(&level) { |
| + return Err(BuildError::Malformed); |
| + } |
| + (XmlElementPrelim::empty("heading"), Some(level)) |
| + } |
| + _ => return Err(BuildError::Malformed), |
| + }; |
| + let count = r.u32()?; |
| + if count > *runs_left { |
| + return Err(BuildError::Limit); |
| + } |
| + *runs_left -= count; |
| + let mut runs: Vec<Run> = Vec::new(); |
| + for _ in 0..count { |
| + let run = Run { |
| + marks: marks(r)?, |
| + text: text(r)?, |
| + }; |
| + match runs.last_mut() { |
| + Some(last) if last.marks == run.marks => last.text.push_str(&run.text), |
| + _ => runs.push(run), |
| + } |
| + } |
| + if !runs.is_empty() { |
| + let delta = runs |
| + .into_iter() |
| + .map(|run| { |
| + let attrs = if run.marks.is_empty() { |
| + None |
| + } else { |
| + let attrs: Attrs = run |
| + .marks |
| + .iter() |
| + .map(|m| ((*m).into(), Any::Map(Default::default()))) |
| + .collect(); |
| + Some(Box::new(attrs)) |
| + }; |
| + Delta::Inserted(In::Any(Any::from(run.text)), attrs) |
| + }) |
| + .collect(); |
| + element.children.push(XmlIn::Text(XmlDeltaPrelim { |
| + attributes: Default::default(), |
| + delta, |
| + })); |
| + } |
| + Ok(Block { |
| + prelim: XmlIn::Element(element), |
| + level, |
| + }) |
| +} |
| + |
| +/// Decodes and checks a whole instruction list, writing nothing. |
| +fn decode(ops: &[u8]) -> Result<Vec<Block>, BuildError> { |
| + if ops.len() > MAX_INPUT { |
| + return Err(BuildError::Limit); |
| + } |
| + let mut r = Reader { bytes: ops, at: 0 }; |
| + if r.u8()? != VERSION { |
| + return Err(BuildError::Malformed); |
| + } |
| + let count = r.u32()?; |
| + if count > MAX_BLOCKS { |
| + return Err(BuildError::Limit); |
| + } |
| + let mut runs_left = MAX_RUNS; |
| + let mut blocks = Vec::with_capacity(count as usize); |
| + for _ in 0..count { |
| + blocks.push(block(&mut r, &mut runs_left)?); |
| + } |
| + if r.at != ops.len() { |
| + return Err(BuildError::Malformed); |
| + } |
| + Ok(blocks) |
| +} |
| + |
| +/// Writes the document an instruction list describes into `doc`, which |
| +/// must be empty. On any error `doc` is left untouched. |
| +pub fn build(doc: &Doc, ops: &[u8]) -> Result<(), BuildError> { |
| + let blocks = decode(ops)?; |
| + let root = doc.get_or_insert_xml_fragment(crate::FRAGMENT_ROOT); |
| + let mut txn = doc.transact_mut(); |
| + if root.len(&txn) != 0 { |
| + return Err(BuildError::NotEmpty); |
| + } |
| + // Last block first, each at the front. yrs finds an index by walking |
| + // the list from its start, so appending block by block is quadratic |
| + // in the number of blocks (ten thousand took 1.6 s, past the host's |
| + // one-second call limit); inserting at index 0 finds its place at |
| + // once. The document is the same either way. |
| + for b in blocks.into_iter().rev() { |
| + let inserted = root.insert(&mut txn, 0, b.prelim); |
| + if let (Some(level), XmlOut::Element(e)) = (b.level, inserted) { |
| + // A heading's level is a number, as y-prosemirror writes it |
| + // and as the editor's schema (`validate: "number"`) expects. |
| + // yrs' XML attribute calls take only strings, but an |
| + // element's attributes are its map, which is what Yjs' |
| + // setAttribute writes too; so the number goes in through |
| + // the map. |
| + MapRef::from(BranchPtr::from(AsRef::<Branch>::as_ref(&e))).insert( |
| + &mut txn, |
| + "level", |
| + Any::Number(level as f64), |
| + ); |
| + } |
| + } |
| + Ok(()) |
| +} |
diff --git a/core/src/fragment.rs b/core/src/fragment.rs| index 9cb4e68..2d365c1 100644 |
| --- a/core/src/fragment.rs |
| +++ b/core/src/fragment.rs |
| @@ -72,7 +72,7 @@ fn escape(s: &str, out: &mut String) { |
| /// that moving it is a change to the manifest and not to this table. |
| /// `font_serif` and `font_sans` are why: each was once the absence of a |
| /// mark, and became unsayable the moment it stopped being the default. |
| -const MARKS: &[(&str, &str, &str)] = &[ |
| +pub(crate) const MARKS: &[(&str, &str, &str)] = &[ |
| // One row per family in internal/fonts/fonts.json, in its order, so |
| // the last font mark on a run is the innermost span and the one the |
| // cascade draws; internal/fonts' ForMarks and fixtures/fonts.mjs |
diff --git a/core/src/lib.rs b/core/src/lib.rs| index e5fb37e..5dca4c4 100644 |
| --- a/core/src/lib.rs |
| +++ b/core/src/lib.rs |
| @@ -54,6 +54,7 @@ |
| //! above) rather than relying on `fastrand` to fail loudly when it can't β |
| //! it won't. |
| pub mod abi; |
| +pub mod build; |
| mod fragment; |
| mod snapshot; |
| pub use fragment::{fragment_html, fragment_json, fragment_text, ROOT as FRAGMENT_ROOT}; |
| @@ -96,9 +97,13 @@ extern "Rust" fn __getrandom_v03_custom( |
| /// call time, deep inside a request; bumping means it gets a refusal at |
| /// load time instead, which is the whole point of there being a version |
| /// here. |
| +/// |
| +/// Bumped to 5 for `docs_core_build`, which writes an imported document |
| +/// from `build`'s closed instruction list: the first export that puts |
| +/// content into a document rather than reading it out. |
| #[no_mangle] |
| pub extern "C" fn docs_core_abi_version() -> u32 { |
| - 4 |
| + 5 |
| } |
| use yrs::updates::decoder::Decode; |
diff --git a/core/tests/build.rs b/core/tests/build.rs| new file mode 100644 |
| index 0000000..7cbb28a |
| --- /dev/null |
| +++ b/core/tests/build.rs |
| @@ -0,0 +1,261 @@ |
| +use docs_core::abi::{ |
| + build_slice, doc_free, doc_new, json_string, ERR_BUILD_LIMIT, ERR_BUILD_MALFORMED, |
| + ERR_BUILD_NOT_EMPTY, ERR_NO_DOC, |
| +}; |
| +use docs_core::build::{build, BuildError, MAX_BLOCKS, VERSION}; |
| +use docs_core::{apply_update, fragment_html, fragment_json, snapshot_bytes, FRAGMENT_ROOT}; |
| +use yrs::branch::{Branch, BranchPtr}; |
| +use yrs::{Any, Doc, Map, MapRef, Options, Out, Text, Transact, XmlFragment, XmlOut}; |
| + |
| +fn fresh() -> Doc { |
| + Doc::with_options(Options::with_guid_and_client_id("build-test".into(), 9)) |
| +} |
| + |
| +/// A run: its marks and its text. |
| +type Run<'a> = (&'a [&'a str], &'a str); |
| +/// A block: its kind, its level (headings only) and its runs. |
| +type Block<'a> = (u8, u8, &'a [Run<'a>]); |
| + |
| +/// The instruction list for `blocks`. |
| +fn ops(blocks: &[Block]) -> Vec<u8> { |
| + let mut out = vec![VERSION]; |
| + out.extend((blocks.len() as u32).to_le_bytes()); |
| + for (kind, level, runs) in blocks { |
| + out.push(*kind); |
| + if *kind == 2 { |
| + out.push(*level); |
| + } |
| + out.extend((runs.len() as u32).to_le_bytes()); |
| + for (marks, text) in runs.iter() { |
| + out.push(marks.len() as u8); |
| + for m in marks.iter() { |
| + out.push(m.len() as u8); |
| + out.extend(m.as_bytes()); |
| + } |
| + out.extend((text.len() as u32).to_le_bytes()); |
| + out.extend(text.as_bytes()); |
| + } |
| + } |
| + out |
| +} |
| + |
| +#[test] |
| +fn builds_paragraphs_headings_and_marks() { |
| + let doc = fresh(); |
| + build( |
| + &doc, |
| + &ops(&[ |
| + (2, 2, &[(&[], "Title")]), |
| + ( |
| + 1, |
| + 0, |
| + &[ |
| + (&[], "Plain "), |
| + (&["strong"], "bold"), |
| + (&[], " then "), |
| + (&["em", "font_sans", "size_14"], "styled"), |
| + ], |
| + ), |
| + (1, 0, &[]), |
| + ]), |
| + ) |
| + .unwrap(); |
| + assert_eq!( |
| + fragment_json(&doc), |
| + r#"{"type":"doc","content":[{"type":"heading","attrs":{"level":2},"content":[{"type":"text","text":"Title"}]},{"type":"paragraph","content":[{"type":"text","text":"Plain "},{"type":"text","text":"bold","marks":[{"type":"strong"}]},{"type":"text","text":" then "},{"type":"text","text":"styled","marks":[{"type":"font_sans"},{"type":"size_14"},{"type":"em"}]}]},{"type":"paragraph","content":[]}]}"# |
| + ); |
| + assert_eq!( |
| + fragment_html(&doc), |
| + "<h2>Title</h2><p>Plain <strong>bold</strong> then <span class=\"docs-font-sans\"><span class=\"docs-size-14\"><em>styled</em></span></span></p><p></p>" |
| + ); |
| +} |
| + |
| +/// y-prosemirror writes a heading's level as a number and the editor's |
| +/// schema validates it as one; a string level is what yrs' own XML |
| +/// attribute calls would have written. |
| +#[test] |
| +fn a_heading_level_is_a_number() { |
| + let doc = fresh(); |
| + build(&doc, &ops(&[(2, 3, &[(&[], "H")])])).unwrap(); |
| + let root = doc.get_or_insert_xml_fragment(FRAGMENT_ROOT); |
| + let txn = doc.transact(); |
| + let Some(XmlOut::Element(h)) = root.get(&txn, 0) else { |
| + panic!("no heading") |
| + }; |
| + let level = MapRef::from(BranchPtr::from(AsRef::<Branch>::as_ref(&h))).get(&txn, "level"); |
| + assert!( |
| + matches!(level, Some(Out::Any(Any::Number(n))) if n == 3.0), |
| + "level {level:?}" |
| + ); |
| +} |
| + |
| +/// An empty block has no child at all, as y-prosemirror writes one; and |
| +/// a block's runs share one XmlText. |
| +#[test] |
| +fn one_text_per_block_and_none_when_empty() { |
| + let doc = fresh(); |
| + build( |
| + &doc, |
| + &ops(&[(1, 0, &[(&[], "a"), (&["strong"], "b")]), (1, 0, &[])]), |
| + ) |
| + .unwrap(); |
| + let root = doc.get_or_insert_xml_fragment(FRAGMENT_ROOT); |
| + let txn = doc.transact(); |
| + let lens: Vec<u32> = root |
| + .children(&txn) |
| + .map(|c| match c { |
| + XmlOut::Element(e) => e.len(&txn), |
| + _ => panic!("not an element"), |
| + }) |
| + .collect(); |
| + assert_eq!(lens, vec![1, 0]); |
| +} |
| + |
| +#[test] |
| +fn an_unmarked_run_after_a_marked_one_inherits_nothing() { |
| + let doc = fresh(); |
| + build( |
| + &doc, |
| + &ops(&[(1, 0, &[(&["strong"], "a"), (&[], "b"), (&["em"], "c")])]), |
| + ) |
| + .unwrap(); |
| + assert_eq!(fragment_html(&doc), "<p><strong>a</strong>b<em>c</em></p>"); |
| +} |
| + |
| +#[test] |
| +fn adjacent_runs_with_the_same_marks_merge() { |
| + let doc = fresh(); |
| + build( |
| + &doc, |
| + &ops(&[(1, 0, &[(&["strong", "em"], "a"), (&["em", "strong"], "b")])]), |
| + ) |
| + .unwrap(); |
| + let root = doc.get_or_insert_xml_fragment(FRAGMENT_ROOT); |
| + let txn = doc.transact(); |
| + let Some(XmlOut::Element(p)) = root.get(&txn, 0) else { |
| + panic!() |
| + }; |
| + let Some(XmlOut::Text(t)) = p.get(&txn, 0) else { |
| + panic!() |
| + }; |
| + assert_eq!(t.diff(&txn, yrs::types::text::YChange::identity).len(), 1); |
| +} |
| + |
| +/// Every refusal leaves the document exactly as it was. |
| +#[test] |
| +fn refuses_malformed_lists_and_writes_nothing() { |
| + let good = ops(&[(1, 0, &[(&[], "x")])]); |
| + let mut wrong_version = good.clone(); |
| + wrong_version[0] = 2; |
| + let mut trailing = good.clone(); |
| + trailing.push(0); |
| + let truncated = good[..good.len() - 1].to_vec(); |
| + let mut bad_utf8 = good.clone(); |
| + *bad_utf8.last_mut().unwrap() = 0xff; |
| + let cases: Vec<(&str, Vec<u8>)> = vec![ |
| + ("empty input", vec![]), |
| + ("wrong version", wrong_version), |
| + ("trailing bytes", trailing), |
| + ("truncated", truncated), |
| + ("invalid utf-8", bad_utf8), |
| + ("unknown kind", { |
| + let mut v = good.clone(); |
| + v[5] = 3; |
| + v |
| + }), |
| + ("level 0", ops(&[(2, 0, &[(&[], "x")])])), |
| + ("level 7", ops(&[(2, 7, &[(&[], "x")])])), |
| + ("unknown mark", ops(&[(1, 0, &[(&["link"], "x")])])), |
| + ("retired size", ops(&[(1, 0, &[(&["size_lg"], "x")])])), |
| + ("code", ops(&[(1, 0, &[(&["code"], "x")])])), |
| + ( |
| + "two fonts", |
| + ops(&[(1, 0, &[(&["font_sans", "font_serif"], "x")])]), |
| + ), |
| + ("two sizes", ops(&[(1, 0, &[(&["size_8", "size_9"], "x")])])), |
| + ("same mark twice", ops(&[(1, 0, &[(&["em", "em"], "x")])])), |
| + ("empty text", ops(&[(1, 0, &[(&[], "")])])), |
| + ("tab", ops(&[(1, 0, &[(&[], "a\tb")])])), |
| + ("newline", ops(&[(1, 0, &[(&[], "a\nb")])])), |
| + ("nul", ops(&[(1, 0, &[(&[], "a\0b")])])), |
| + ( |
| + "a good block, then a bad one", |
| + ops(&[(1, 0, &[(&[], "fine")]), (1, 0, &[(&[], "")])]), |
| + ), |
| + ]; |
| + for (name, bytes) in cases { |
| + let doc = fresh(); |
| + let before = snapshot_bytes(&doc); |
| + assert_eq!(build(&doc, &bytes), Err(BuildError::Malformed), "{name}"); |
| + assert_eq!(snapshot_bytes(&doc), before, "{name} wrote something"); |
| + assert_eq!( |
| + fragment_json(&doc), |
| + r#"{"type":"doc","content":[]}"#, |
| + "{name}" |
| + ); |
| + } |
| +} |
| + |
| +#[test] |
| +fn refuses_past_its_limits() { |
| + let mut v = vec![VERSION]; |
| + v.extend((MAX_BLOCKS + 1).to_le_bytes()); |
| + assert_eq!(build(&fresh(), &v), Err(BuildError::Limit)); |
| + |
| + let mut v = vec![VERSION]; |
| + v.extend(1u32.to_le_bytes()); |
| + v.push(1); |
| + v.extend(u32::MAX.to_le_bytes()); |
| + assert_eq!(build(&fresh(), &v), Err(BuildError::Limit)); |
| + |
| + let big = vec![0u8; docs_core::build::MAX_INPUT + 1]; |
| + assert_eq!(build(&fresh(), &big), Err(BuildError::Limit)); |
| +} |
| + |
| +#[test] |
| +fn writes_only_into_an_empty_document() { |
| + let doc = fresh(); |
| + let list = ops(&[(1, 0, &[(&[], "x")])]); |
| + build(&doc, &list).unwrap(); |
| + let before = snapshot_bytes(&doc); |
| + assert_eq!(build(&doc, &list), Err(BuildError::NotEmpty)); |
| + assert_eq!(snapshot_bytes(&doc), before); |
| +} |
| + |
| +/// What is built replays, from its snapshot, into a second document as |
| +/// the same structure: the check the host makes before saving. |
| +#[test] |
| +fn the_snapshot_replays_to_the_same_structure() { |
| + let doc = fresh(); |
| + build( |
| + &doc, |
| + &ops(&[ |
| + (2, 1, &[(&["font_caladea"], "Γber π¦")]), |
| + (1, 0, &[(&["size_11"], "x")]), |
| + ]), |
| + ) |
| + .unwrap(); |
| + let replay = Doc::with_options(Options::with_guid_and_client_id("build-test".into(), 10)); |
| + apply_update(&replay, &snapshot_bytes(&doc)).unwrap(); |
| + assert_eq!(fragment_json(&replay), fragment_json(&doc)); |
| +} |
| + |
| +#[test] |
| +fn the_abi_reports_each_refusal_as_its_own_code() { |
| + let h = doc_new("abi-build", 3); |
| + assert_eq!(build_slice(h, &[]), ERR_BUILD_MALFORMED); |
| + let mut v = vec![VERSION]; |
| + v.extend((MAX_BLOCKS + 1).to_le_bytes()); |
| + assert_eq!(build_slice(h, &v), ERR_BUILD_LIMIT); |
| + assert_eq!(build_slice(h, &ops(&[(1, 0, &[(&[], "x")])])), 0); |
| + assert_eq!( |
| + build_slice(h, &ops(&[(1, 0, &[(&[], "x")])])), |
| + ERR_BUILD_NOT_EMPTY |
| + ); |
| + assert_eq!( |
| + json_string(h).unwrap(), |
| + r#"{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"x"}]}]}"# |
| + ); |
| + doc_free(h); |
| + assert_eq!(build_slice(h, &ops(&[])), ERR_NO_DOC); |
| +} |
diff --git a/internal/core/build_test.go b/internal/core/build_test.go| new file mode 100644 |
| index 0000000..bb8fbcc |
| --- /dev/null |
| +++ b/internal/core/build_test.go |
| @@ -0,0 +1,130 @@ |
| +package core_test |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "testing" |
| + |
| + "github.com/carlosframework/docs/internal/core" |
| +) |
| + |
| +func TestBuildWritesTheDocumentItDescribes(t *testing.T) { |
| + ctx := context.Background() |
| + rt, err := core.New(ctx) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer rt.Close(ctx) |
| + |
| + ops, err := core.EncodeBuild([]core.BuildBlock{ |
| + {Heading: 1, Runs: []core.BuildRun{{Text: "Title"}}}, |
| + {Runs: []core.BuildRun{{Text: "plain "}, {Marks: []string{"strong"}, Text: "bold"}}}, |
| + {}, |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + update, err := rt.Build(ctx, "6f1a1d1e-0000-4000-8000-000000000001", 41, ops) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + // Replayed into a second document, it is the same structure. |
| + h, err := rt.NewDoc(ctx, "6f1a1d1e-0000-4000-8000-000000000001", 42) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer h.Close(ctx) |
| + if err := h.Apply(ctx, update); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := h.JSON(ctx) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := `{"type":"doc","content":[{"type":"heading","attrs":{"level":1},"content":[{"type":"text","text":"Title"}]},{"type":"paragraph","content":[{"type":"text","text":"plain "},{"type":"text","text":"bold","marks":[{"type":"strong"}]}]},{"type":"paragraph","content":[]}]}` |
| + if got != want { |
| + t.Fatalf("replayed structure\n got %s\nwant %s", got, want) |
| + } |
| +} |
| + |
| +func TestBuildRefusesWhatTheBuilderRefuses(t *testing.T) { |
| + ctx := context.Background() |
| + rt, err := core.New(ctx) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer rt.Close(ctx) |
| + |
| + for name, blocks := range map[string][]core.BuildBlock{ |
| + "unknown mark": {{Runs: []core.BuildRun{{Marks: []string{"link"}, Text: "x"}}}}, |
| + "level 7": {{Heading: 7, Runs: []core.BuildRun{{Text: "x"}}}}, |
| + "empty run": {{Runs: []core.BuildRun{{Text: ""}}}}, |
| + "control": {{Runs: []core.BuildRun{{Text: "a\tb"}}}}, |
| + } { |
| + ops, err := core.EncodeBuild(blocks) |
| + if err != nil { |
| + t.Fatal(name, err) |
| + } |
| + if _, err := rt.Build(ctx, "6f1a1d1e-0000-4000-8000-000000000002", 1, ops); !errors.Is(err, core.ErrBuildMalformed) { |
| + t.Errorf("%s: got %v, want ErrBuildMalformed", name, err) |
| + } |
| + } |
| + |
| + many := make([]core.BuildBlock, 50_001) |
| + ops, err := core.EncodeBuild(many) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := rt.Build(ctx, "6f1a1d1e-0000-4000-8000-000000000003", 1, ops); !errors.Is(err, core.ErrBuildLimit) { |
| + t.Errorf("too many blocks: got %v, want ErrBuildLimit", err) |
| + } |
| +} |
| + |
| +// The largest import the reader lets through (internal/docx's |
| +// maxBlocks, maxRuns and maxText) must build inside Build's allowance and |
| +// then replay inside the ordinary call limit, which is what every later |
| +// opening of the document needs. |
| +func TestBuildAtTheReadersLimitFitsTheCallTimeout(t *testing.T) { |
| + ctx := context.Background() |
| + rt, err := core.New(ctx) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer rt.Close(ctx) |
| + |
| + // 10,000 blocks of four runs, 52 bytes each: 2 MiB of text. |
| + text := make([]byte, 52) |
| + for i := range text { |
| + text[i] = 'a' + byte(i%26) |
| + } |
| + blocks := make([]core.BuildBlock, 10_000) |
| + for i := range blocks { |
| + for r := 0; r < 4; r++ { |
| + run := core.BuildRun{Text: string(text)} |
| + if r%2 == 1 { |
| + run.Marks = []string{"strong", "font_sans", "size_14"} |
| + } |
| + blocks[i].Runs = append(blocks[i].Runs, run) |
| + } |
| + } |
| + ops, err := core.EncodeBuild(blocks) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + update, err := rt.Build(ctx, "6f1a1d1e-0000-4000-8000-000000000004", 1, ops) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h, err := rt.NewDoc(ctx, "6f1a1d1e-0000-4000-8000-000000000004", 2) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer h.Close(ctx) |
| + if err := h.Apply(ctx, update); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := h.HTML(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
diff --git a/internal/core/core.go b/internal/core/core.go| index b817f15..0510c87 100644 |
| --- a/internal/core/core.go |
| +++ b/internal/core/core.go |
| @@ -52,8 +52,10 @@ package core |
| import ( |
| "context" |
| _ "embed" |
| + "encoding/binary" |
| "errors" |
| "fmt" |
| + "math" |
| "time" |
| "github.com/tetratelabs/wazero" |
| @@ -76,7 +78,10 @@ var moduleWASM []byte |
| // side: the module and this binary ship embedded together with no |
| // version skew to tolerate, so the bump exists to catch a stale .wasm |
| // at load time instead of "unknown export" deep inside a request. |
| -const abiVersion = 4 |
| +// |
| +// Bumped to 5 for docs_core_build, which writes an imported document |
| +// (Runtime.Build). |
| +const abiVersion = 5 |
| // ABIVersion is abiVersion, exported for callers outside this package |
| // (snapshot storage and its tests) that need to know which ABI contract |
| @@ -779,3 +784,107 @@ func readOn(ctx context.Context, timeout time.Duration, mod api.Module, docHandl |
| } |
| return string(buf), nil |
| } |
| + |
| +// ErrBuildMalformed and ErrBuildLimit are Build's refusals of an |
| +// instruction list: one that does not follow core/src/build.rs's format, |
| +// and one past its limits. Neither carries anything from the list. |
| +// buildTimeoutFactor is how many ordinary call limits Build's one call |
| +// into the builder may take. See Build. |
| +const buildTimeoutFactor = 5 |
| + |
| +var ( |
| + ErrBuildMalformed = errors.New("core: import instructions are malformed") |
| + ErrBuildLimit = errors.New("core: import instructions exceed the builder's limits") |
| +) |
| + |
| +// Build writes the document an import instruction list describes |
| +// (core/src/build.rs) into a fresh document with this guid and client id, |
| +// and returns that document's whole state as one update. The list is |
| +// checked in full before anything is written, and the instance is |
| +// discarded either way, so a refusal or a trap leaves nothing behind. |
| +// |
| +// The build call alone may run for buildTimeoutFactor times the usual |
| +// limit. Writing a document costs about three times what applying the |
| +// result costs, and the result must still apply within the ordinary |
| +// limit every time the document is opened; the instance a slow build |
| +// runs in is thrown away regardless, so the longer allowance risks |
| +// nothing that the ordinary one protects. |
| +func (r *Runtime) Build(ctx context.Context, guid string, clientID uint64, ops []byte) ([]byte, error) { |
| + h, err := r.NewDoc(ctx, guid, clientID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer h.Close(ctx) |
| + |
| + ptr, err := allocIn(ctx, r.callTimeout, h.mod, uint64(len(ops))) |
| + if err != nil { |
| + return nil, fmt.Errorf("core: build: alloc: %w", err) |
| + } |
| + defer freeIn(ctx, r.callTimeout, h.mod, ptr, uint64(len(ops))) |
| + if !h.mod.Memory().Write(uint32(ptr), ops) { |
| + return nil, fmt.Errorf("core: build: writing %d bytes at %d: out of range", len(ops), ptr) |
| + } |
| + rc, err := callGuest(ctx, buildTimeoutFactor*r.callTimeout, h.mod.ExportedFunction("docs_core_build"), h.handle, ptr, uint64(len(ops))) |
| + if err != nil { |
| + return nil, fmt.Errorf("core: build trapped or timed out: %w", err) |
| + } |
| + switch code := int32(rc[0]); code { |
| + case 0: |
| + case -6: |
| + return nil, ErrBuildMalformed |
| + case -7: |
| + return nil, ErrBuildLimit |
| + default: |
| + return nil, fmt.Errorf("core: build refused: code %d", code) |
| + } |
| + return h.Snapshot(ctx) |
| +} |
| + |
| +// BuildBlock is one block of an import: a paragraph when Heading is 0, |
| +// otherwise a heading of that level (1 to 6). |
| +type BuildBlock struct { |
| + Heading int |
| + Runs []BuildRun |
| +} |
| + |
| +// BuildRun is one run of text and the names of its marks. |
| +type BuildRun struct { |
| + Marks []string |
| + Text string |
| +} |
| + |
| +// EncodeBuild writes blocks as core/src/build.rs's instruction list, |
| +// version 1. It checks only what the encoding itself needs (lengths that |
| +// fit their fields); everything else, the vocabulary included, is the |
| +// builder's to refuse. |
| +func EncodeBuild(blocks []BuildBlock) ([]byte, error) { |
| + out := []byte{1} |
| + out = binary.LittleEndian.AppendUint32(out, uint32(len(blocks))) |
| + for _, b := range blocks { |
| + if b.Heading == 0 { |
| + out = append(out, 1) |
| + } else { |
| + if b.Heading < 0 || b.Heading > 255 { |
| + return nil, ErrBuildMalformed |
| + } |
| + out = append(out, 2, byte(b.Heading)) |
| + } |
| + out = binary.LittleEndian.AppendUint32(out, uint32(len(b.Runs))) |
| + for _, r := range b.Runs { |
| + if len(r.Marks) > 255 || uint64(len(r.Text)) > math.MaxUint32 { |
| + return nil, ErrBuildLimit |
| + } |
| + out = append(out, byte(len(r.Marks))) |
| + for _, m := range r.Marks { |
| + if len(m) > 255 { |
| + return nil, ErrBuildMalformed |
| + } |
| + out = append(out, byte(len(m))) |
| + out = append(out, m...) |
| + } |
| + out = binary.LittleEndian.AppendUint32(out, uint32(len(r.Text))) |
| + out = append(out, r.Text...) |
| + } |
| + } |
| + return out, nil |
| +} |
diff --git a/internal/core/testdata/docs_core.wasm b/internal/core/testdata/docs_core.wasm| index 3418e63..f8c3955 100755 |
| Binary files a/internal/core/testdata/docs_core.wasm and b/internal/core/testdata/docs_core.wasm differ |