Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

fix(xfa): queue each added data instance once per pass

aiongga07ad60d529d
diff --git a/crates/xfa/src/data.rs b/crates/xfa/src/data.rs
index 7c2efaf5e..87db6b998 100644
--- a/crates/xfa/src/data.rs
+++ b/crates/xfa/src/data.rs
@@ -1516,6 +1516,16 @@ fn element_markup(src: &str, n: roxmltree::Node) -> Option<String> {
Some(format!("{}{decls}{}", text.get(..name_end)?, text.get(name_end..)?))
}
+/// Most instance nodes one [`write_data_ops`] queues over all its passes (a removal starts a new
+/// pass, which asks for the instances again).
+const MAX_ENSURED: usize = 200_000;
+
+// Instance nodes write_data_ops has queued on this thread, for tests that bound its work.
+#[cfg(test)]
+thread_local! {
+ pub(crate) static ENSURED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
+}
+
/// Apply `ops` to the datasets packet, in order, as one rewrite of it: everything one script
/// event changed becomes a single new datasets stream. When the packet is already the stream
/// `reuse` (written earlier for the same event), that stream is replaced in place instead of
@@ -1525,6 +1535,9 @@ pub fn write_data_ops(doc: &mut Document, ops: &[DataOp], reuse: Option<ObjRef>)
let mut steps: Vec<Vec<Want>> = Vec::new();
let mut removes: Vec<Option<DataPath>> = Vec::new();
let mut run: Vec<Want> = Vec::new();
+ // Instances queued in this run, by parent and name: asking for more only queues the rest.
+ let mut queued: HashMap<(&DataPath, &str), usize> = HashMap::new();
+ let (mut ensured, mut capped) = (0usize, false);
let flush = |run: &mut Vec<Want>, steps: &mut Vec<Vec<Want>>, removes: &mut Vec<Option<DataPath>>| {
if !run.is_empty() {
let mut seen = std::collections::HashSet::new();
@@ -1541,7 +1554,17 @@ pub fn write_data_ops(doc: &mut Document, ops: &[DataOp], reuse: Option<ObjRef>)
run.push(Want { som: path_som(path), path: path.clone(), text: text.clone(), ensure: false });
}
DataOp::Instances { parent, name, count } => {
- for k in 0..(*count).min(MAX_INDEX) {
+ let done = queued.entry((parent, name.as_str())).or_insert(0);
+ while *done < (*count).min(MAX_INDEX) {
+ if ensured >= MAX_ENSURED {
+ capped = true;
+ break;
+ }
+ ensured += 1;
+ #[cfg(test)]
+ ENSURED.with(|n| n.set(n.get() + 1));
+ let k = *done;
+ *done += 1;
let mut path = parent.clone();
path.push((name.clone(), k));
run.push(Want { som: format!("{name}[{k}]"), path, text: String::new(), ensure: true });
@@ -1549,6 +1572,7 @@ pub fn write_data_ops(doc: &mut Document, ops: &[DataOp], reuse: Option<ObjRef>)
}
DataOp::Remove(path) if !path.is_empty() => {
flush(&mut run, &mut steps, &mut removes);
+ queued.clear();
steps.push(Vec::new());
removes.push(Some(path.clone()));
}
@@ -1564,7 +1588,11 @@ pub fn write_data_ops(doc: &mut Document, ops: &[DataOp], reuse: Option<ObjRef>)
None => Op::Values(w),
})
.collect();
- rewrite(doc, &plan, reuse)
+ let mut written = rewrite(doc, &plan, reuse)?;
+ if capped {
+ written.warnings.push(format!("XFA data instances not written past {MAX_ENSURED}: the rows were added and removed too often"));
+ }
+ Ok(written)
}
/// Put `bytes` in the document as a datasets stream: in place of `old` when that is the stream
diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs
index a101f219b..9aebee5bf 100644
--- a/crates/xfa/src/tests.rs
+++ b/crates/xfa/src/tests.rs
@@ -2711,3 +2711,34 @@ fn repeated_script_events_hold_a_bounded_amount_of_script() {
assert!(held <= crate::script::MAX_EVENT_SCRIPT_BYTES, "{held} bytes of script held by {} events", live.events.len());
assert!(live.truncated, "{held} bytes, {} events", live.events.len());
}
+
+/// Rows added one at a time (each op asking for one more instance) queue each instance node
+/// once, and removals in between don't let the queue grow without bound.
+#[test]
+fn added_instances_are_queued_once_each() {
+ use crate::data::{DataOp, ENSURED, write_data_ops};
+ let mut doc = Document::open(Arc::new(shell(&scripted_template()))).unwrap();
+ render_into(&mut doc).unwrap();
+ let table = som_to_path("form[0].page1[0].table[0]");
+ let ops: Vec<DataOp> = (1..=1000).map(|count| DataOp::Instances { parent: table.clone(), name: "row".into(), count }).collect();
+ ENSURED.with(|n| n.set(0));
+ let r = write_data_ops(&mut doc, &ops, None).unwrap();
+ assert!(r.written, "{r:?}");
+ assert_eq!(crate::data_of(&doc).unwrap().count(&table, "row"), 1000);
+ let queued = ENSURED.with(|n| n.get());
+ assert!(queued <= 2_000, "{queued} instance nodes queued for 1000 rows");
+ // Removals split the ops into separate passes; together they stay within the budget.
+ let ops: Vec<DataOp> = (0..300)
+ .flat_map(|_| {
+ [
+ DataOp::Instances { parent: table.clone(), name: "row".into(), count: 1000 },
+ DataOp::Remove(som_to_path("form[0].page1[0].table[0].row[999]")),
+ ]
+ })
+ .collect();
+ ENSURED.with(|n| n.set(0));
+ let r = write_data_ops(&mut doc, &ops, None).unwrap();
+ let queued = ENSURED.with(|n| n.get());
+ assert!(queued <= 200_000, "{queued} instance nodes queued");
+ assert!(r.warnings.iter().any(|w| w.contains("instances")), "{r:?}");
+}