mirror of
https://github.com/storytold/lightcraft.git
synced 2026-11-25 03:53:53 +01:00
address review: catalog writes stop at the readable size; raw reads wait at the memory gate; one pixel bound for cached previews
This commit is contained in:
1 parent
333190cf9e
commit
f2b53fe0d8
4 files changed
+61
-7
No files matched your search
@@ -188,7 +188,7 @@ impl Store for FsStore {
|
||||
}
|
||||
let tmp = self.path(&format!("{name}.tmp"));
|
||||
let written = (|| {
|
||||
let mut w = Counter { inner: io::BufWriter::with_capacity(1 << 20, create_staging(&tmp)?), n: 0 };
|
||||
let mut w = Counter { inner: io::BufWriter::with_capacity(1 << 20, create_staging(&tmp)?), n: 0, limit: MAX_READ };
|
||||
fill(&mut w)?;
|
||||
w.flush()?;
|
||||
let f = w.inner.into_inner().map_err(|e| e.into_error())?;
|
||||
@@ -290,14 +290,19 @@ impl Store for FsStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// Counts the bytes written through it.
|
||||
/// Counts the bytes written through it, and refuses more than [`MAX_READ`]: a file this store cannot read
|
||||
/// back is not committed over the one it can (the write fails and the old file stays).
|
||||
struct Counter<W> {
|
||||
inner: W,
|
||||
n: u64,
|
||||
limit: u64,
|
||||
}
|
||||
|
||||
impl<W: io::Write> io::Write for Counter<W> {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
if self.n.saturating_add(buf.len() as u64) > self.limit {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, format!("more than the {} bytes a catalog file may hold", self.limit)));
|
||||
}
|
||||
let k = self.inner.write(buf)?;
|
||||
self.n += k as u64;
|
||||
Ok(k)
|
||||
@@ -402,3 +407,17 @@ mod tests_staging {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod counter_tests {
|
||||
use super::Counter;
|
||||
use std::io::Write;
|
||||
|
||||
#[test]
|
||||
fn a_counter_refuses_what_passes_its_limit() {
|
||||
let mut c = Counter { inner: Vec::new(), n: 0, limit: 8 };
|
||||
c.write_all(b"12345678").unwrap();
|
||||
assert_eq!(c.write(b"9").unwrap_err().kind(), std::io::ErrorKind::InvalidData);
|
||||
assert_eq!(c.inner, b"12345678");
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,9 @@ use super::{
|
||||
Path, PathBuf, Photo, PoisonError, RunError, Source, SystemTime, denoise_bayer, product,
|
||||
};
|
||||
|
||||
/// Samples at or above this (white = 1) are clipped: the model leaves them as the camera recorded them.
|
||||
/// Most bytes of a raw file read for a denoise product.
|
||||
const MAX_RAW_BYTES: u64 = 8 << 30;
|
||||
/// Samples at or above this (white = 1) are clipped: the model leaves them as the camera recorded them.
|
||||
const CLIP: f32 = 0.99;
|
||||
|
||||
/// The model in use.
|
||||
@@ -167,6 +167,10 @@ pub(crate) fn make_product(spec: &JobSpec, progress: Option<&Progress>) -> Resul
|
||||
let bytes = match &spec.read {
|
||||
Some(r) => r(&spec.path).map_err(MakeError::Failed)?,
|
||||
None => {
|
||||
// the file's size is held at the memory gate while it is read, as every decode does: a large file waits
|
||||
// for the memory in use to drain before its bytes are allocated
|
||||
let len = std::fs::metadata(&spec.path).map_or(0, |m| usize::try_from(m.len()).unwrap_or(usize::MAX));
|
||||
let _reading = crate::memory::work_gate().acquire(len);
|
||||
lightcraft_catalog::safe_file::read_regular(&spec.path, MAX_RAW_BYTES).map_err(|e| MakeError::Failed(format!("{}: {e}", spec.path)))?
|
||||
}
|
||||
};
|
||||
|
||||
@@ -207,7 +207,8 @@ impl DiskCache {
|
||||
let more = limit.saturating_sub(head.len() as u64);
|
||||
(&mut f).take(more).read_to_end(&mut head).ok()?;
|
||||
if let Some(dims) = jpeg_dims(&head) {
|
||||
return Some(dims);
|
||||
// a picture past the decode bound is not one `get` would return: not reported as kept
|
||||
return Some(dims).filter(|&(w, h)| w.checked_mul(h).is_some_and(|n| n <= MAX_THUMB_PIXELS));
|
||||
}
|
||||
if (head.len() as u64) < limit {
|
||||
// the whole file was read
|
||||
@@ -474,7 +475,12 @@ pub fn is_cache_file(shard: &str, name: &str) -> bool {
|
||||
|
||||
/// Encode a thumbnail as the cache stores it (JPEG, RGB, 4:2:0).
|
||||
pub fn encode_jpeg(img: &Rgba8) -> Option<Vec<u8>> {
|
||||
if img.width == 0 || img.height == 0 || img.width > u16::MAX as usize || img.height > u16::MAX as usize {
|
||||
if img.width == 0
|
||||
|| img.height == 0
|
||||
|| img.width > u16::MAX as usize
|
||||
|| img.height > u16::MAX as usize
|
||||
|| img.width.checked_mul(img.height)? > MAX_THUMB_PIXELS
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut rgb = Vec::with_capacity(img.width * img.height * 3);
|
||||
@@ -488,8 +494,10 @@ pub fn encode_jpeg(img: &Rgba8) -> Option<Vec<u8>> {
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Most pixels of a cached thumbnail (a 5120 x 6400 image; thumbnails and previews are far smaller).
|
||||
const MAX_THUMB_PIXELS: usize = 32 << 20;
|
||||
/// Most pixels of a cached picture, read or written (16384 x 16384: above a 150 MP medium-format full-size preview). The
|
||||
/// same bound applies to what is written, to what `dims` reports and to what `get` decodes, so a stored preview is
|
||||
/// always one that reads back.
|
||||
const MAX_THUMB_PIXELS: usize = 256 << 20;
|
||||
|
||||
/// How much of a cached file [`DiskCache::dims`] reads: the JPEG headers this cache writes come
|
||||
/// first and are a few hundred bytes.
|
||||
|
||||
@@ -852,6 +852,29 @@ fn dims_finds_a_size_marker_past_the_first_few_kib() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// What is written, reported by `dims` and decoded share one pixel bound.
|
||||
#[test]
|
||||
fn the_pixel_bound_is_the_same_for_write_dims_and_read() {
|
||||
use crate::disk::encode_jpeg;
|
||||
// too big to write (the size is checked before any pixel is read)
|
||||
assert!(encode_jpeg(&Rgba8 { width: 20_000, height: 20_000, data: Vec::new() }).is_none());
|
||||
let dir = temp_dir("pixel-bound");
|
||||
let d = DiskCache::new(&dir, 1 << 28);
|
||||
let key = hash_bytes(b"bound");
|
||||
assert!(d.put(key, &gradient(40, 30, 5)));
|
||||
assert_eq!(d.dims(key), Some((40, 30)));
|
||||
// a file whose header claims 20 000 x 20 000: not reported as kept, and not decoded
|
||||
let file = files_under(&dir).into_iter().find(|f| f.ends_with(disk::EXT)).expect("the cached file");
|
||||
let path = dir.join(file);
|
||||
let mut jpeg = std::fs::read(&path).unwrap();
|
||||
let sof = jpeg.windows(2).position(|w| w == [0xFF, 0xC0]).unwrap();
|
||||
jpeg[sof + 5..sof + 9].copy_from_slice(&[0x4E, 0x20, 0x4E, 0x20]);
|
||||
std::fs::write(&path, jpeg).unwrap();
|
||||
assert_eq!(d.dims(key), None);
|
||||
assert!(d.get(key).is_none());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A picture bigger than the room pruning leaves is removed by the pruning its own write starts: `put` says it
|
||||
/// was not kept (CodeRabbit on #3077).
|
||||
#[test]
|
||||
|
||||
Reference in new issue
Block a user