diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index eaba5d2b0..549852fb8 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -394,6 +394,14 @@ impl Document { NodeId(self.next_id.next) } + /// Replace the document's raw node map and `next_id` counter (used by compact format loaders + /// before [`Self::validate`] / [`Self::repair`]). + pub fn set_raw_nodes(&mut self, nodes: impl IntoIterator)>, next_id: NodeId) { + self.nodes = nodes.into_iter().map(|(id, node)| (id, NodeArc(node))).collect(); + self.next_id.next = next_id.0; + self.dirty = Dirty::default(); + } + /// The collaboration client ids are allocated for (0: none, a single-user document). pub fn client_id(&self) -> u32 { self.next_id.client diff --git a/crates/format/src/compact/decode.rs b/crates/format/src/compact/decode.rs new file mode 100644 index 000000000..9076f5b7a --- /dev/null +++ b/crates/format/src/compact/decode.rs @@ -0,0 +1,584 @@ +//! Streaming compact `.figcraft` document deserializer and mirror/vector resolver. +//! +//! Reads legacy v1 `document.json` and compact mirror/vector-table `document.json` in a single +//! streaming pass, resolving mirror chains iteratively with cycle detection and a materialized +//! memory budget against amplification bombs. + +use std::borrow::Cow; +use std::collections::{BTreeMap, HashMap}; +use std::fmt; +use std::sync::Arc; + +use craft_figcraft_format::{Header, MAX_DOCUMENT}; +use figcraft_doc::color::{BlendMode, Color, ColorProfile}; +use figcraft_doc::geom::Affine; +use figcraft_doc::{ + AnnotationCategory, Ballots, BoardTimer, Comment, DesignReview, DevSnapshot, Document, FileKind, ImagePreset, Libraries, Node, NodeId, NodeKind, + Style, Variables, VectorNetwork, Vote, VoteRecord, +}; +use serde::de::{DeserializeSeed, Error as DeError, IgnoredAny, MapAccess, Visitor}; +use serde::{Deserialize, Deserializer}; +use serde_json::Value; + +use super::fields::{MirrorPatch, apply_full_patch, apply_mirror_patch, deserialize_patch_field, est_node_bytes, est_vector_bytes}; +use crate::FormatError; + +/// Maximum number of nodes accepted in one `document.json`. +const MAX_NODES: usize = 5_000_000; +/// Minimum materialized memory budget (bytes) allowed for compact expansion. +const MIN_MATERIALIZED_BUDGET: usize = 16 * 1024 * 1024; +/// Maximum allowed materialized expansion ratio relative to input JSON byte length. +const MAX_EXPANSION_RATIO: usize = 256; + +/// Materialized memory ceiling for resolving mirrors and `vectorRef` entries. +pub(crate) fn materialized_budget(input_bytes: usize) -> usize { + input_bytes.saturating_mul(MAX_EXPANSION_RATIO).clamp(MIN_MATERIALIZED_BUDGET, MAX_DOCUMENT as usize) +} + +/// Parse a `document.json` string (legacy v1 or compact mirrors/vectors), checking the native +/// header and version first. +pub(crate) fn parse_compact_document(text: &str) -> Result<(Document, Header), FormatError> { + if !text.contains("\"mirror\"") && !text.contains("\"vectorRef\"") { + return craft_figcraft_format::read_document_json::(text).map_err(|e| match e { + craft_figcraft_format::ReadDocumentError::Json(error) => FormatError::Corrupt(error.to_string()), + craft_figcraft_format::ReadDocumentError::NewerVersion(error) => FormatError::Newer(error.0), + }); + } + parse_compact_document_with_budget(text, materialized_budget(text.len())) +} + +/// [`parse_compact_document`] with an explicit materialized memory budget. +pub(crate) fn parse_compact_document_with_budget(text: &str, budget: usize) -> Result<(Document, Header), FormatError> { + let header = craft_figcraft_format::read_header(text).map_err(|e| FormatError::Corrupt(e.to_string()))?; + craft_figcraft_format::check_version(&header).map_err(|e| FormatError::Newer(e.0))?; + let mut de = serde_json::Deserializer::from_str(text); + let wire = CompactDocSeed { budget }.deserialize(&mut de).map_err(|e| FormatError::Corrupt(e.to_string()))?; + de.end().map_err(|e| FormatError::Corrupt(e.to_string()))?; + let doc = materialize(wire, budget)?; + Ok((doc, header)) +} + +struct CompactDocWire { + name: String, + kind: FileKind, + pages: Vec, + nodes: BTreeMap, + vectors: Vec, + next_id: NodeId, + styles: Vec