Merge #3151: Images: loaders start a file only while its largest size still fits the loaded-image limit

This commit is contained in:
Tanish Manku committed 2026-11-24 14:36:17 -07:00
commit b2c35cd100
1 file changed
+122 -7
+122 -7
View File
@@ -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;
@@ -27,6 +27,9 @@ const MAX_IMAGE_BASE64: u64 = MAX_IMAGE_BYTES.div_ceil(3) * 4;
const MAX_IMAGE_TEXT: u64 = MAX_IMAGE_BASE64 + MAX_IMAGE_BASE64 / 16;
/// 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.
@@ -183,13 +186,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<std::result::Result<Raster, String>> {
// 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<Raster, String> {
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<Option<std::result::Result<Raster, String>>> = paths.iter().map(|_| None).collect();
@@ -224,6 +225,83 @@ fn decode_files(paths: &[&str], host: Option<&str>) -> Vec<std::result::Result<R
results.into_iter().zip(paths).map(|(result, path)| result.unwrap_or_else(|| load(path))).collect()
}
/// The decoded bytes the loaders of one drawing share.
#[derive(Default)]
struct Budget {
spent: Mutex<Spent>,
/// 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<Decoding<'_>> {
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 {
@@ -384,3 +462,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");
}
}