From 1f56cef64ebaee62ededbb519427dd805b7d9f19 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 20:36:47 -0800 Subject: [PATCH] fix(engine): image loaders start a file only while its largest size still fits the loaded-image limit When a drawing opened, each image loader checked the decoded total against the 2 GB limit before decoding and added the image's size only after, so up to four images of up to 512 MB each could decode at once past the limit. A loader now starts a file only while the images decoded so far, plus the largest image each file being decoded can become, fit under the limit, and otherwise waits for a file to finish. With no other file being decoded one file always starts, so the total runs past the limit by one image at most, as it does with a single loader. A file that fails to decode counts nothing. --- crates/engine/src/cmd/image.rs | 129 +++++++++++++++++++++++++++++++-- 1 file changed, 122 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/image.rs b/crates/engine/src/cmd/image.rs index daf46557b..60becab87 100644 --- a/crates/engine/src/cmd/image.rs +++ b/crates/engine/src/cmd/image.rs @@ -4,8 +4,8 @@ //! the drawing as a crossed-out frame. use std::collections::{BTreeMap, BTreeSet}; -use std::sync::Arc; -use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex, PoisonError}; use cadcraft_doc::{Drawing, EntityKind, Image, Raster}; use cadcraft_geom::Vec2; @@ -22,6 +22,9 @@ const MAX_IMAGE_FILES: usize = 1000; const MAX_IMAGE_BYTES: u64 = 256 << 20; /// Most decoded pixel bytes kept per drawing; images past it stay unloaded. const MAX_LOADED_BYTES: u64 = 2 << 30; +/// Most bytes one decoded image takes: the image reader decodes at most 128 million pixels, four +/// bytes each (`cadcraft_io::raster::MAX_IMAGE_PIXELS`). +const MAX_DECODED_BYTES: u64 = 512_000_000; /// Most image files decoded at the same time when a drawing opens. const MAX_LOADERS: usize = 4; /// Longest image path taken from a caller. @@ -166,13 +169,11 @@ fn over_limit(path: &str) -> String { /// what opening a drawing with large images waits for). The results are in the order of `paths`. fn decode_files(paths: &[&str], host: Option<&str>) -> Vec> { // Decoded bytes so far, shared by the loaders: past the limit no further file is started. - let decoded_bytes = AtomicU64::new(0); + let budget = Budget::default(); let load = |path: &str| -> std::result::Result { - if decoded_bytes.load(Ordering::Relaxed) > MAX_LOADED_BYTES { - return Err(format!("not loaded (more than {} MB of images)", MAX_LOADED_BYTES >> 20)); - } + let mut decoding = budget.start().ok_or_else(|| format!("not loaded (more than {} MB of images)", MAX_LOADED_BYTES >> 20))?; let r = read_file(path, host).and_then(|bytes| decode(&bytes))?; - decoded_bytes.fetch_add(bytes_of(&r), Ordering::Relaxed); + decoding.bytes = bytes_of(&r); Ok(r) }; let mut results: Vec>> = paths.iter().map(|_| None).collect(); @@ -203,6 +204,83 @@ fn decode_files(paths: &[&str], host: Option<&str>) -> Vec, + /// Signaled when a file finishes decoding. + finished: Condvar, +} + +/// Decoded bytes so far, and how many files are being decoded. +#[derive(Default)] +struct Spent { + decoded: u64, + decoding: u64, +} + +/// Whether a loader may start decoding a file. +#[derive(Debug, PartialEq)] +enum Admit { + Start, + /// Not until another file finishes. + Wait, + /// The images decoded so far are past the limit. + Full, +} + +impl Spent { + /// A file starts while the images decoded so far, and the largest image each file being + /// decoded can become, fit under `limit`. A file always starts when no other one is being + /// decoded, so that the images run past `limit` by one image at most. + fn admit(&mut self, limit: u64, largest: u64) -> Admit { + if self.decoded > limit { + return Admit::Full; + } + let reserved = self.decoding.saturating_add(1).saturating_mul(largest); + if self.decoding > 0 && self.decoded.saturating_add(reserved) > limit { + return Admit::Wait; + } + self.decoding = self.decoding.saturating_add(1); + Admit::Start + } + + /// A file finished decoding into `bytes` (0 when it failed). + fn finish(&mut self, bytes: u64) { + self.decoding = self.decoding.saturating_sub(1); + self.decoded = self.decoded.saturating_add(bytes); + } +} + +impl Budget { + /// Wait until a file may start decoding; `None` once the images decoded so far are past the + /// limit. + fn start(&self) -> Option> { + let mut spent = self.spent.lock().unwrap_or_else(PoisonError::into_inner); + loop { + match spent.admit(MAX_LOADED_BYTES, MAX_DECODED_BYTES) { + Admit::Start => return Some(Decoding { budget: self, bytes: 0 }), + Admit::Full => return None, + Admit::Wait => spent = self.finished.wait(spent).unwrap_or_else(PoisonError::into_inner), + } + } + } +} + +/// A file being decoded. Dropping it counts `bytes` as decoded and lets a waiting loader check +/// again, also when the decoding failed. +struct Decoding<'a> { + budget: &'a Budget, + bytes: u64, +} + +impl Drop for Decoding<'_> { + fn drop(&mut self) { + self.budget.spent.lock().unwrap_or_else(PoisonError::into_inner).finish(self.bytes); + self.budget.finished.notify_all(); + } +} + /// How many files are decoded at once: one per processor, at most [`MAX_LOADERS`] (each large /// image needs several hundred megabytes while it is decoded) and no more than there are files. fn loader_count(files: usize) -> usize { @@ -351,3 +429,40 @@ fn describe(d: &Drawing, path: &str, host: Option<&str>) -> Value { }; json!({ "path": path, "foundAt": found_at, "status": status, "pixels": loaded.map(|r| json!([r.width(), r.height()])) }) } + +#[cfg(test)] +mod tests { + use super::*; + + /// A file starts only while the largest image each file being decoded can become still fits, + /// one file always starts when none is being decoded, and none starts past the limit. + #[test] + fn loaders_start_files_within_the_limit() { + let mut s = Spent::default(); + // Room for two of the largest images. + assert_eq!(s.admit(10, 4), Admit::Start); + assert_eq!(s.admit(10, 4), Admit::Start); + assert_eq!(s.admit(10, 4), Admit::Wait); + s.finish(3); + assert_eq!(s.admit(10, 4), Admit::Wait, "3 decoded and two files that can become 4 each are past 10"); + s.finish(5); + // Over the limit only by the one file being decoded. + assert_eq!(s.admit(10, 4), Admit::Start); + s.finish(4); + assert_eq!(s.admit(10, 4), Admit::Full); + // A failed file counts nothing. + let mut s = Spent::default(); + assert_eq!(s.admit(10, 4), Admit::Start); + s.finish(0); + assert_eq!((s.decoded, s.decoding), (0, 0)); + } + + /// Files that fail still let the other loaders go on: every file gets a result. + #[test] + fn decode_files_finishes_when_every_file_fails() { + let paths = ["a.png", "b.png", "c.png", "d.png", "e.png", "f.png"]; + let results = decode_files(&paths, None); + assert_eq!(results.len(), paths.len()); + assert!(results.iter().all(std::result::Result::is_err), "none of these files exists"); + } +}