mirror of
https://github.com/storytold/figcraft.git
synced 2026-12-03 15:31:21 -05:00
fix(doc,format): address CodeRabbit review findings on client IDs, decode budget, and legacy snapshots
This commit is contained in:
+10
-1
@@ -396,9 +396,18 @@ impl Document {
|
||||
|
||||
/// Replace the document's raw node map and `next_id` counter (used by compact format loaders
|
||||
/// before [`Self::validate`] / [`Self::repair`]).
|
||||
///
|
||||
/// On a fresh single-user document (`client_id() == 0`) the saved `next_id` is preserved; on a
|
||||
/// document bound to a collaboration client the counter is normalized into that client's ID
|
||||
/// space so [`Self::alloc_id`] never emits cross-client IDs.
|
||||
pub fn set_raw_nodes(&mut self, nodes: impl IntoIterator<Item = (NodeId, Arc<Node>)>, next_id: NodeId) {
|
||||
self.nodes = nodes.into_iter().map(|(id, node)| (id, NodeArc(node))).collect();
|
||||
self.next_id.next = next_id.0;
|
||||
let client = self.next_id.client;
|
||||
if client == 0 {
|
||||
self.next_id.next = next_id.0;
|
||||
} else {
|
||||
self.set_client_id(client);
|
||||
}
|
||||
self.dirty = Dirty::default();
|
||||
}
|
||||
|
||||
|
||||
@@ -63,6 +63,7 @@ struct CompactDocWire {
|
||||
kind: FileKind,
|
||||
pages: Vec<NodeId>,
|
||||
nodes: BTreeMap<NodeId, CompactNodeEntry>,
|
||||
nodes_parsed_bytes: usize,
|
||||
vectors_raw: Option<Value>,
|
||||
next_id: NodeId,
|
||||
styles: Vec<Style>,
|
||||
@@ -134,7 +135,7 @@ struct DocParseState {
|
||||
name: Option<String>,
|
||||
kind: Option<FileKind>,
|
||||
pages: Option<Vec<NodeId>>,
|
||||
nodes: Option<BTreeMap<NodeId, CompactNodeEntry>>,
|
||||
nodes: Option<(BTreeMap<NodeId, CompactNodeEntry>, usize)>,
|
||||
vectors_raw: Option<Value>,
|
||||
next_id: Option<NodeId>,
|
||||
styles: Option<Vec<Style>>,
|
||||
@@ -156,11 +157,13 @@ struct DocParseState {
|
||||
|
||||
impl DocParseState {
|
||||
fn finish<E: DeError>(self) -> Result<CompactDocWire, E> {
|
||||
let (nodes, nodes_parsed_bytes) = self.nodes.ok_or_else(|| E::missing_field("nodes"))?;
|
||||
Ok(CompactDocWire {
|
||||
name: self.name.ok_or_else(|| E::missing_field("name"))?,
|
||||
kind: self.kind.unwrap_or_default(),
|
||||
pages: self.pages.ok_or_else(|| E::missing_field("pages"))?,
|
||||
nodes: self.nodes.ok_or_else(|| E::missing_field("nodes"))?,
|
||||
nodes,
|
||||
nodes_parsed_bytes,
|
||||
vectors_raw: self.vectors_raw,
|
||||
next_id: self.next_id.ok_or_else(|| E::missing_field("next_id"))?,
|
||||
styles: self.styles.unwrap_or_default(),
|
||||
@@ -217,7 +220,7 @@ struct NodesMapSeed {
|
||||
}
|
||||
|
||||
impl<'de> DeserializeSeed<'de> for NodesMapSeed {
|
||||
type Value = BTreeMap<NodeId, CompactNodeEntry>;
|
||||
type Value = (BTreeMap<NodeId, CompactNodeEntry>, usize);
|
||||
|
||||
fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
|
||||
deserializer.deserialize_map(NodesMapVisitor { budget: self.budget })
|
||||
@@ -229,7 +232,7 @@ struct NodesMapVisitor {
|
||||
}
|
||||
|
||||
impl<'de> Visitor<'de> for NodesMapVisitor {
|
||||
type Value = BTreeMap<NodeId, CompactNodeEntry>;
|
||||
type Value = (BTreeMap<NodeId, CompactNodeEntry>, usize);
|
||||
|
||||
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("a map of node ids to nodes")
|
||||
@@ -253,7 +256,7 @@ impl<'de> Visitor<'de> for NodesMapVisitor {
|
||||
}
|
||||
nodes.insert(id, entry);
|
||||
}
|
||||
Ok(nodes)
|
||||
Ok((nodes, charged))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -458,7 +461,11 @@ fn materialize(wire: CompactDocWire, budget: usize) -> Result<Document, FormatEr
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let mut charged: usize = vectors.iter().map(|v| est_vector_bytes(v)).fold(0usize, usize::saturating_add);
|
||||
// Carry forward the live raw-node subtotal from `NodesMapVisitor` so parsed nodes + vectors
|
||||
// cannot together exceed `budget` before resolution begins; resolution below then charges only
|
||||
// the incremental growth when each raw entry is replaced by its materialized node.
|
||||
let vectors_charge: usize = vectors.iter().map(|v| est_vector_bytes(v)).fold(0usize, usize::saturating_add);
|
||||
let mut charged: usize = wire.nodes_parsed_bytes.saturating_add(vectors_charge);
|
||||
if charged > budget {
|
||||
return Err(FormatError::Corrupt("document vectors exceed materialized memory budget".into()));
|
||||
}
|
||||
@@ -544,14 +551,11 @@ fn resolve_chain(
|
||||
let Some(entry) = raw.remove(&id) else { continue };
|
||||
let node = match entry {
|
||||
CompactNodeEntry::Full { mut node, vector_ref } => {
|
||||
// `est_node_bytes(&node)` was already charged in `NodesMapVisitor`.
|
||||
if let Some(idx) = vector_ref {
|
||||
let net = lookup_vector(vectors, idx)?;
|
||||
let base_charge = est_node_bytes(&node);
|
||||
let net_charge = est_vector_bytes(net);
|
||||
charge_budget(charged, base_charge.saturating_add(net_charge), budget)?;
|
||||
charge_budget(charged, est_vector_bytes(net), budget)?;
|
||||
node.kind = NodeKind::Vector { network: net.clone() };
|
||||
} else {
|
||||
charge_budget(charged, est_node_bytes(&node), budget)?;
|
||||
}
|
||||
*node
|
||||
}
|
||||
@@ -562,9 +566,11 @@ fn resolve_chain(
|
||||
Some(idx) => Some(lookup_vector(vectors, idx)?),
|
||||
None => None,
|
||||
};
|
||||
// Charge before cloning the source node or vector network to prevent OOM spikes.
|
||||
// `size_of::<Node>()` was already charged in `NodesMapVisitor`; charge the
|
||||
// incremental pre-clone cost before cloning to prevent OOM spikes.
|
||||
let pre_charge = est_node_bytes(src).saturating_add(vref_net.map_or(0, |v| est_vector_bytes(v)));
|
||||
charge_budget(charged, pre_charge, budget)?;
|
||||
let raw_mirror_charge = std::mem::size_of::<Node>();
|
||||
charge_budget(charged, pre_charge.saturating_sub(raw_mirror_charge), budget)?;
|
||||
let mut node = (**src).clone();
|
||||
node.id = m.id;
|
||||
node.source = Some(m.source);
|
||||
@@ -576,7 +582,8 @@ fn resolve_chain(
|
||||
node.kind = NodeKind::Vector { network: net.clone() };
|
||||
}
|
||||
apply_mirror_patch(&mut node, m.patch);
|
||||
let extra = est_node_bytes(&node).saturating_sub(pre_charge);
|
||||
let accounted = pre_charge.max(raw_mirror_charge);
|
||||
let extra = est_node_bytes(&node).saturating_sub(accounted);
|
||||
charge_budget(charged, extra, budget)?;
|
||||
node
|
||||
}
|
||||
|
||||
@@ -35,6 +35,12 @@ impl<'a> CompactDocument<'a> {
|
||||
enforce_reload_budget(doc, &mut mirrors, &mut vectors, &mut vector_refs);
|
||||
Self { doc, mirrors, vectors, vector_refs }
|
||||
}
|
||||
|
||||
/// Whether this serialization emits any compact-only structures (mirrored deltas or hoisted
|
||||
/// `"vectors"` entries). When `false`, the emitted JSON is byte-compatible with legacy readers.
|
||||
pub(crate) fn is_compact(&self) -> bool {
|
||||
!self.mirrors.is_empty() || !self.vectors.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Identifies every node whose `source` pointer chain reaches a live non-cyclic root.
|
||||
|
||||
@@ -436,3 +436,42 @@ fn mirrored_instance_corner_style_override_roundtrips() {
|
||||
assert_docs_exact(&doc, &back);
|
||||
assert_eq!(back.node(target_id).unwrap().corners.style, figcraft_doc::geom::CornerStyle::Chamfer);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_active_document_keeps_version_and_branch_snapshots_legacy() {
|
||||
let active = Document::new("PlainActive");
|
||||
let rich = build_component_instances_doc(2, 4, 5);
|
||||
let versions = [Version::new("v1", "RichVersion", "", 1, Arc::new(rich.clone()))];
|
||||
let branches = [Branch {
|
||||
id: "b1".into(),
|
||||
name: "Feature".into(),
|
||||
time: 2,
|
||||
client: 0,
|
||||
state: BranchState::Active,
|
||||
base: Arc::new(rich.clone()),
|
||||
head: Arc::new(rich),
|
||||
versions: Vec::new(),
|
||||
}];
|
||||
let archive_bytes = save_bytes_with_history(&active, None, &versions, &branches).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&archive_bytes)).unwrap();
|
||||
for member in ["versions/v1.json", "branches/b1/base.json", "branches/b1/head.json"] {
|
||||
let mut text = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name(member).unwrap(), &mut text).unwrap();
|
||||
assert!(!text.contains("\"mirror\""), "{member} must stay legacy when document.json is legacy");
|
||||
assert!(!text.contains("\"vectors\""), "{member} must stay legacy when document.json is legacy");
|
||||
}
|
||||
let loaded = load_bytes_with_versions(&archive_bytes).unwrap();
|
||||
assert!(loaded.issues.is_empty());
|
||||
assert_eq!(loaded.versions.len(), 1);
|
||||
assert_eq!(loaded.branches.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_raw_nodes_keeps_active_client_id_space() {
|
||||
let mut doc = Document::new("ClientScoped");
|
||||
doc.set_client_id(7);
|
||||
let raw_nodes: Vec<(figcraft_doc::NodeId, Arc<figcraft_doc::Node>)> = doc.nodes().map(|n| (n.id, Arc::new(n.clone()))).collect();
|
||||
doc.set_raw_nodes(raw_nodes, figcraft_doc::NodeId(5));
|
||||
let next = doc.alloc_id();
|
||||
assert_eq!(next.0 >> 32, 7, "allocated id must stay in client 7's space");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user