use std::path::{Path, PathBuf};
use std::process::Stdio;
pub const WIRE_LIMIT_BYTES: usize = 2 * 1024 * 1024;
pub const COPY_TARGET_BYTES: usize = 3 * 1024 * 1024 / 2;
pub const MAX_EDGE: u32 = 2048;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Stored {
pub original: PathBuf,
pub working: PathBuf,
pub bytes: usize,
pub working_bytes: usize,
pub size: Option<(u32, u32)>,
pub resized: bool,
}
impl Stored {
pub fn note(&self, name: &str) -> String {
let size = match self.size {
Some((w, h)) => format!("{w}×{h}"),
None => "unknown size".to_string(),
};
if self.resized {
let edge = self.size.map(|(w, h)| w.max(h)).unwrap_or(MAX_EDGE);
format!(
"[attached: {name} — the original is at {} ({} KB, {size}). You are looking at a \
{} px copy; use the original's path with `read_file` or a tool if you need the \
full resolution.]",
self.original.display(),
self.bytes / 1024,
edge.min(MAX_EDGE),
)
} else {
format!(
"[attached: {name} — {} KB, {size}, stored at {}. This is the original.]",
self.bytes / 1024,
self.original.display(),
)
}
}
}
#[derive(Debug, Clone)]
pub struct Store {
root: PathBuf,
max_total_bytes: u64,
helper: Option<Helper>,
}
impl Store {
pub fn new(root: PathBuf, max_total_bytes: u64) -> Self {
Self {
root,
max_total_bytes,
helper: Helper::probe(),
}
}
pub fn with_helper(mut self, helper: Option<Helper>) -> Self {
self.helper = helper;
self
}
pub fn root(&self) -> &Path {
&self.root
}
pub fn keep(
&self,
session: &str,
name: &str,
mime: &str,
bytes: &[u8],
) -> Result<Stored, String> {
if bytes.is_empty() {
return Err("the picture carries no bytes".to_string());
}
let (_, ext) = kind(mime, bytes)?;
let name = sanitise(name, ext);
let digest = hex16(bytes);
let dir = self.root.join(sanitise_segment(session));
let original = dir.join(format!("{digest}-{name}"));
std::fs::create_dir_all(&dir)
.map_err(|e| format!("could not make {}: {e}", dir.display()))?;
restrict(&dir, 0o700);
if !original.exists() {
let need = bytes.len() as u64;
let total = self.total_bytes();
if total + need > self.max_total_bytes {
let freed = self.prune(need)?;
if self.total_bytes() + need > self.max_total_bytes {
return Err(format!(
"the pictures on disk already hold {} MB of the {} MB budget{}; \
`/attachments clear` or a bigger `[attachments] max_total_bytes` makes \
room",
(self.total_bytes() - freed) / (1024 * 1024),
self.max_total_bytes / (1024 * 1024),
if freed > 0 {
format!(
", and pruning {} MB of the oldest was not enough",
freed / (1024 * 1024)
)
} else {
String::new()
}
));
}
}
write_private(&original, bytes)?;
} else {
touch(&original);
}
let size = dimensions(bytes);
if bytes.len() <= COPY_TARGET_BYTES {
return Ok(Stored {
working: original.clone(),
original,
bytes: bytes.len(),
working_bytes: bytes.len(),
size,
resized: false,
});
}
let Some(helper) = self.helper.clone() else {
return Err(format!(
"this picture is {} KB and has to be shrunk to {} KB for the request, and no \
helper was found to do it: install ImageMagick (`magick`), Python Pillow \
(`python3 -m pip install pillow`) or `ffmpeg`. The original is kept at {} — pass \
that path instead, and the agent can work on it at full size",
bytes.len() / 1024,
COPY_TARGET_BYTES / 1024,
original.display()
));
};
let stem = original
.file_stem()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_else(|| digest.clone());
let out_name = format!("{stem}-{MAX_EDGE}.{ext}");
let working = dir.join(out_name);
if !working.exists() {
shrink(helper, &original, &working, ext)?;
}
let working_bytes = std::fs::metadata(&working)
.map(|m| m.len() as usize)
.unwrap_or(0);
if working_bytes == 0 || working_bytes > WIRE_LIMIT_BYTES {
return Err(format!(
"the copy at {} is {} KB, still over the {} KB a request may carry — the original \
is kept at {}",
working.display(),
working_bytes / 1024,
WIRE_LIMIT_BYTES / 1024,
original.display()
));
}
Ok(Stored {
working,
original,
bytes: bytes.len(),
working_bytes,
size,
resized: true,
})
}
fn by_age(&self) -> Vec<(PathBuf, u64, std::time::SystemTime)> {
let mut out = Vec::new();
let Ok(sessions) = std::fs::read_dir(&self.root) else {
return out;
};
for session in sessions.flatten() {
let Ok(files) = std::fs::read_dir(session.path()) else {
continue;
};
for file in files.flatten() {
let Ok(meta) = file.metadata() else {
continue;
};
if !meta.is_file() {
continue;
}
let when = meta
.modified()
.or_else(|_| meta.accessed())
.unwrap_or(std::time::UNIX_EPOCH);
out.push((file.path(), meta.len(), when));
}
}
out.sort_by_key(|(_, _, when)| *when);
out
}
pub fn total_bytes(&self) -> u64 {
self.by_age().iter().map(|(_, len, _)| *len).sum()
}
pub fn prune(&self, need: u64) -> Result<u64, String> {
let mut freed = 0;
for (path, len, _) in self.by_age() {
if freed >= need {
break;
}
match std::fs::remove_file(&path) {
Ok(()) => freed += len,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(format!("could not remove {}: {e}", path.display())),
}
}
Ok(freed)
}
pub fn forget(&self, session: &str) -> Result<(), String> {
let dir = self.root.join(sanitise_segment(session));
match std::fs::remove_dir_all(&dir) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(format!("could not remove {}: {e}", dir.display())),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Helper {
Magick(PathBuf),
Pillow(PathBuf),
Ffmpeg(PathBuf),
}
impl Helper {
pub fn probe() -> Option<Self> {
for candidate in ["magick", "convert"] {
if let Some(path) = which(candidate) {
if works(&path, &["-version"]) {
return Some(Self::Magick(path));
}
}
}
if let Some(path) = which("python3") {
if works(
&path,
&[
"-c",
"import PIL.Image, sys; sys.exit(0 if PIL.Image.__version__ else 1)",
],
) {
return Some(Self::Pillow(path));
}
}
which("ffmpeg")
.filter(|path| works(path, &["-version"]))
.map(Self::Ffmpeg)
}
pub fn name(&self) -> String {
match self {
Self::Magick(p) => format!("ImageMagick ({})", p.display()),
Self::Pillow(p) => format!("Pillow via {}", p.display()),
Self::Ffmpeg(p) => format!("ffmpeg ({})", p.display()),
}
}
}
fn shrink(helper: Helper, from: &Path, to: &Path, ext: &str) -> Result<(), String> {
let jpeg = ext.eq_ignore_ascii_case("jpg") || ext.eq_ignore_ascii_case("jpeg");
let steps = if jpeg {
vec![(MAX_EDGE, 88), (MAX_EDGE, 78), (1536, 82), (1024, 80)]
} else {
vec![(MAX_EDGE, 0), (1536, 0), (1024, 0), (768, 0)]
};
let mut last = String::new();
for (edge, quality) in steps {
match run(helper.clone(), from, to, edge, quality) {
Ok(()) => {
let len = std::fs::metadata(to).map(|m| m.len() as usize).unwrap_or(0);
if len > 0 && len <= COPY_TARGET_BYTES {
return Ok(());
}
last = format!("{} KB at {edge} px", len / 1024);
}
Err(e) => last = e,
}
}
if to.exists() && std::fs::metadata(to).map(|m| m.len() as usize).unwrap_or(0) > 0 {
return Ok(());
}
Err(format!("could not shrink the picture ({last})"))
}
fn run(helper: Helper, from: &Path, to: &Path, edge: u32, quality: u32) -> Result<(), String> {
let (program, args) = match helper {
Helper::Magick(bin) => {
let mut args: Vec<String> = vec![
from.display().to_string(),
"-resize".into(),
format!("{edge}x{edge}>"),
"-strip".into(),
];
if quality > 0 {
args.push("-quality".into());
args.push(quality.to_string());
}
args.push(to.display().to_string());
(bin, args)
}
Helper::Pillow(bin) => {
let script = "import sys\n\
from PIL import Image\n\
src, dst, edge, quality = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4])\n\
im = Image.open(src)\n\
im.thumbnail((edge, edge))\n\
if quality:\n\
\x20 im.save(dst, quality=quality, optimize=True)\n\
else:\n\
\x20 im.save(dst, optimize=True)\n";
(
bin,
vec![
"-c".into(),
script.into(),
from.display().to_string(),
to.display().to_string(),
edge.to_string(),
quality.to_string(),
],
)
}
Helper::Ffmpeg(bin) => {
let mut args: Vec<String> = vec![
"-y".into(),
"-loglevel".into(),
"error".into(),
"-i".into(),
from.display().to_string(),
"-vf".into(),
format!(
"scale='min({edge},iw)':'min({edge},ih)':force_original_aspect_ratio=decrease"
),
];
if quality > 0 {
args.push("-q:v".into());
args.push((31u32.saturating_sub(quality / 4)).clamp(2, 31).to_string());
}
args.push(to.display().to_string());
(bin, args)
}
};
let out = std::process::Command::new(&program)
.args(&args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.output()
.map_err(|e| format!("{} could not run: {e}", program.display()))?;
if !out.status.success() {
let err = String::from_utf8_lossy(&out.stderr);
return Err(format!(
"{} failed on {}: {}",
program.display(),
from.display(),
err.lines().next().unwrap_or("no message")
));
}
Ok(())
}
fn which(bin: &str) -> Option<PathBuf> {
let path = std::env::var_os("PATH")?;
std::env::split_paths(&path)
.map(|dir| dir.join(bin))
.find(|p| p.is_file())
}
fn works(bin: &Path, args: &[&str]) -> bool {
std::process::Command::new(bin)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
fn kind(mime: &str, bytes: &[u8]) -> Result<(&'static str, &'static str), String> {
let found = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
("image/png", "png")
} else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
("image/jpeg", "jpg")
} else if bytes.len() > 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
("image/webp", "webp")
} else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
("image/gif", "gif")
} else {
return Err(format!(
"the bytes are not a picture this build can carry ({mime}); a picture has to be PNG, \
JPEG, WebP or GIF"
));
};
Ok(found)
}
pub fn dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
if bytes.len() > 24 && bytes.starts_with(b"\x89PNG\r\n\x1a\n") && &bytes[12..16] == b"IHDR" {
let w = u32::from_be_bytes(bytes[16..20].try_into().ok()?);
let h = u32::from_be_bytes(bytes[20..24].try_into().ok()?);
return Some((w, h));
}
if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
if bytes.len() < 10 {
return None;
}
let w = u16::from_le_bytes([bytes[6], bytes[7]]) as u32;
let h = u16::from_le_bytes([bytes[8], bytes[9]]) as u32;
return Some((w, h));
}
if bytes.len() > 30 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
return webp_size(bytes);
}
if bytes.starts_with(&[0xFF, 0xD8]) {
return jpeg_size(bytes);
}
None
}
fn jpeg_size(bytes: &[u8]) -> Option<(u32, u32)> {
let mut i = 2;
while i + 9 < bytes.len() {
if bytes[i] != 0xFF {
i += 1;
continue;
}
let marker = bytes[i + 1];
if (0xD0..=0xD9).contains(&marker) || marker == 0x01 {
i += 2;
continue;
}
let len = u16::from_be_bytes([bytes[i + 2], bytes[i + 3]]) as usize;
if (0xC0..=0xCF).contains(&marker) && !matches!(marker, 0xC4 | 0xC8 | 0xCC) {
let h = u16::from_be_bytes([bytes[i + 5], bytes[i + 6]]) as u32;
let w = u16::from_be_bytes([bytes[i + 7], bytes[i + 8]]) as u32;
return Some((w, h));
}
i += 2 + len;
}
None
}
fn webp_size(bytes: &[u8]) -> Option<(u32, u32)> {
let chunk = &bytes[12..16];
match chunk {
b"VP8X" if bytes.len() >= 30 => {
let w = 1 + u32::from_le_bytes([bytes[24], bytes[25], bytes[26], 0]);
let h = 1 + u32::from_le_bytes([bytes[27], bytes[28], bytes[29], 0]);
Some((w, h))
}
b"VP8 " if bytes.len() >= 30 => {
let w = u16::from_le_bytes([bytes[26], bytes[27]]) as u32 & 0x3FFF;
let h = u16::from_le_bytes([bytes[28], bytes[29]]) as u32 & 0x3FFF;
Some((w, h))
}
b"VP8L" if bytes.len() >= 25 => {
let bits = u32::from_le_bytes([bytes[21], bytes[22], bytes[23], bytes[24]]);
let w = (bits & 0x3FFF) + 1;
let h = ((bits >> 14) & 0x3FFF) + 1;
Some((w, h))
}
_ => None,
}
}
fn hex16(bytes: &[u8]) -> String {
let digest = ring::digest::digest(&ring::digest::SHA256, bytes);
digest.as_ref()[..8]
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
fn sanitise(name: &str, ext: &str) -> String {
let stem = name
.rsplit('/')
.next()
.unwrap_or("picture")
.rsplit_once('.')
.map(|(stem, _)| stem)
.unwrap_or(name);
let cleaned: String = stem
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
c
} else {
'-'
}
})
.collect();
let cleaned = cleaned.trim_matches('-');
let stem = if cleaned.is_empty() {
"picture"
} else {
cleaned
};
format!("{}.{ext}", stem.chars().take(40).collect::<String>())
}
fn sanitise_segment(session: &str) -> String {
let cleaned: String = session
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
c
} else {
'-'
}
})
.collect();
if cleaned.is_empty() {
"unknown".to_string()
} else {
cleaned
}
}
fn write_private(path: &Path, bytes: &[u8]) -> Result<(), String> {
use std::io::Write;
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.map_err(|e| format!("could not create {}: {e}", path.display()))?;
file.write_all(bytes)
.map_err(|e| format!("could not write {}: {e}", path.display()))?;
restrict(path, 0o600);
Ok(())
}
#[cfg(unix)]
fn restrict(path: &Path, mode: u32) {
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
}
#[cfg(not(unix))]
fn restrict(_path: &Path, _mode: u32) {}
fn touch(path: &Path) {
if let Ok(file) = std::fs::OpenOptions::new().read(true).open(path) {
let _ = file.set_modified(std::time::SystemTime::now());
}
}
#[cfg(test)]
mod tests {
use super::*;
pub fn png(width: u32, height: u32, rgb: [u8; 3]) -> Vec<u8> {
let mut raw = Vec::with_capacity((height * (1 + width * 3)) as usize);
for y in 0..height {
raw.push(0); for x in 0..width {
raw.extend_from_slice(&[
rgb[0].wrapping_add((x % 251) as u8),
rgb[1].wrapping_add((y % 241) as u8),
rgb[2],
]);
}
}
let zlib = stored_zlib(&raw);
let mut png = Vec::new();
png.extend_from_slice(b"\x89PNG\r\n\x1a\n");
let mut ihdr = Vec::new();
ihdr.extend_from_slice(&width.to_be_bytes());
ihdr.extend_from_slice(&height.to_be_bytes());
ihdr.extend_from_slice(&[8, 2, 0, 0, 0]); chunk(&mut png, b"IHDR", &ihdr);
chunk(&mut png, b"IDAT", &zlib);
chunk(&mut png, b"IEND", &[]);
png
}
fn chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
out.extend_from_slice(kind);
out.extend_from_slice(data);
let mut crc_input = kind.to_vec();
crc_input.extend_from_slice(data);
out.extend_from_slice(&crc(&crc_input).to_be_bytes());
}
fn crc(data: &[u8]) -> u32 {
let mut crc = 0xFFFF_FFFFu32;
for byte in data {
crc ^= *byte as u32;
for _ in 0..8 {
let mask = (crc & 1).wrapping_neg();
crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
}
}
!crc
}
fn stored_zlib(raw: &[u8]) -> Vec<u8> {
let mut out = vec![0x78, 0x01];
let mut rest = raw;
loop {
let take = rest.len().min(65535);
let last = take == rest.len();
out.push(if last { 1 } else { 0 });
out.extend_from_slice(&(take as u16).to_le_bytes());
out.extend_from_slice(&(!(take as u16)).to_le_bytes());
out.extend_from_slice(&rest[..take]);
rest = &rest[take..];
if last {
break;
}
}
let mut a: u32 = 1;
let mut b: u32 = 0;
for byte in raw {
a = (a + *byte as u32) % 65521;
b = (b + a) % 65521;
}
out.extend_from_slice(&((b << 16) | a).to_be_bytes());
out
}
fn store_with_helper() -> Option<(tempfile::TempDir, Store)> {
let helper = Helper::probe()?;
let dir = tempfile::tempdir().unwrap();
let store = Store::new(dir.path().join("attachments"), 2 * 1024 * 1024 * 1024)
.with_helper(Some(helper));
Some((dir, store))
}
fn store() -> (tempfile::TempDir, Store) {
let dir = tempfile::tempdir().unwrap();
let store = Store::new(dir.path().join("attachments"), 2 * 1024 * 1024 * 1024);
(dir, store)
}
#[test]
fn the_header_reads_the_size_without_decoding_anything() {
let picture = png(37, 19, [10, 20, 30]);
assert_eq!(dimensions(&picture), Some((37, 19)));
let mut jpeg = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10];
jpeg.extend_from_slice(&[0u8; 14]);
jpeg.extend_from_slice(&[0xFF, 0xC0, 0x00, 0x11, 0x08]);
jpeg.extend_from_slice(&[0x01, 0x2C]); jpeg.extend_from_slice(&[0x01, 0xF4]); jpeg.extend_from_slice(&[0u8; 12]);
assert_eq!(dimensions(&jpeg), Some((500, 300)));
assert_eq!(dimensions(b"not a picture"), None);
}
#[test]
fn a_small_picture_is_its_own_working_copy_and_is_written_once() {
let (_dir, store) = store();
let picture = png(64, 64, [1, 2, 3]);
let first = store.keep("s1", "shot.png", "image/png", &picture).unwrap();
assert!(!first.resized);
assert_eq!(first.working, first.original);
assert_eq!(std::fs::read(&first.original).unwrap(), picture);
let again = store.keep("s1", "shot.png", "image/png", &picture).unwrap();
assert_eq!(again.original, first.original);
assert!(again.note("shot.png").contains("This is the original"));
}
#[test]
fn the_original_is_byte_identical_and_the_directory_is_private() {
use std::os::unix::fs::PermissionsExt;
let (_dir, store) = store();
let picture = png(64, 64, [9, 9, 9]);
let kept = store
.keep("s1", "../../etc/passwd.png", "image/png", &picture)
.unwrap();
assert_eq!(std::fs::read(&kept.original).unwrap(), picture);
assert!(
kept.original.starts_with(store.root()),
"a name cannot escape the store: {}",
kept.original.display()
);
let mode = std::fs::metadata(&kept.original)
.unwrap()
.permissions()
.mode()
& 0o777;
assert_eq!(mode, 0o600);
let dir_mode = std::fs::metadata(kept.original.parent().unwrap())
.unwrap()
.permissions()
.mode()
& 0o777;
assert_eq!(dir_mode, 0o700);
}
#[test]
fn a_bigger_picture_is_kept_whole_and_shrunk_for_the_wire() {
let Some((_dir, store)) = store_with_helper() else {
return;
};
let picture = png(1200, 1200, [200, 30, 40]);
assert!(
picture.len() > COPY_TARGET_BYTES,
"the fixture has to be over the target: {} bytes",
picture.len()
);
let kept = store
.keep("s1", "photo.png", "image/png", &picture)
.unwrap_or_else(|why| panic!("{why}"));
assert!(kept.resized, "a picture over the target gets a copy");
assert_eq!(std::fs::read(&kept.original).unwrap(), picture);
assert_ne!(kept.working, kept.original);
assert!(
kept.working_bytes <= COPY_TARGET_BYTES,
"the copy is {} bytes",
kept.working_bytes
);
let copy = std::fs::read(&kept.working).unwrap();
let (w, h) = dimensions(©).expect("the copy is a picture");
assert!(w.max(h) <= MAX_EDGE, "{}×{}", w, h);
let note = kept.note("photo.png");
assert!(note.contains("copy"), "{note}");
assert!(
note.contains(&kept.original.display().to_string()),
"{note}"
);
}
#[test]
fn the_original_keeps_its_pixels_while_the_copy_is_smaller() {
let Some((_dir, store)) = store_with_helper() else {
return;
};
let picture = png(3000, 2000, [90, 120, 150]);
assert!(picture.len() > 8 * 1024 * 1024, "{} bytes", picture.len());
let kept = store
.keep("s1", "camera.png", "image/png", &picture)
.unwrap_or_else(|why| panic!("{why}"));
assert_eq!(std::fs::read(&kept.original).unwrap(), picture);
assert_eq!(dimensions(&picture), Some((3000, 2000)));
assert_eq!(kept.size, Some((3000, 2000)));
assert!(
kept.working_bytes <= COPY_TARGET_BYTES,
"{}",
kept.working_bytes
);
assert!(kept.working_bytes < kept.bytes);
let note = kept.note("camera.png");
assert!(note.contains("3000×2000"), "{note}");
assert!(note.contains("copy"), "{note}");
assert!(
note.contains(&kept.original.display().to_string()),
"{note}"
);
assert!(kept.working.exists());
assert_ne!(kept.working, kept.original);
}
#[test]
fn with_no_helper_the_original_is_still_kept_and_the_refusal_says_so() {
let (_dir, store) = store();
let store = store.with_helper(None);
let picture = png(1200, 1200, [5, 6, 7]);
let why = store
.keep("s1", "photo.png", "image/png", &picture)
.expect_err("no helper, no copy");
assert!(why.contains("ImageMagick"), "{why}");
assert!(why.contains("ffmpeg"), "{why}");
assert!(why.contains("original is kept"), "{why}");
}
#[test]
fn the_pillow_branch_shrinks_a_picture_on_its_own() {
let Some(pillow) = which("python3").filter(|p| works(p, &["-c", "import PIL.Image"]))
else {
return; };
let (_dir, store) = store();
let store = store.with_helper(Some(Helper::Pillow(pillow)));
let picture = png(1500, 900, [12, 200, 12]);
let kept = store.keep("s1", "wide.png", "image/png", &picture).unwrap();
assert!(kept.resized);
let copy = std::fs::read(&kept.working).unwrap();
let (w, h) = dimensions(©).expect("still a picture");
assert!(w.max(h) <= MAX_EDGE, "{}×{}", w, h);
assert!(
copy.len() < picture.len(),
"{} vs {}",
copy.len(),
picture.len()
);
}
#[test]
fn the_budget_prunes_the_oldest_first_and_then_refuses() {
let dir = tempfile::tempdir().unwrap();
let picture = png(1200, 1200, [1, 1, 1]);
let one = picture.len() as u64;
let Some(helper) = Helper::probe() else {
return;
};
let store = Store::new(dir.path().join("a"), one * 2).with_helper(Some(helper));
store.keep("old", "a.png", "image/png", &picture).unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
store.keep("new", "b.png", "image/png", &picture).unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
let third = png(1200, 1200, [2, 2, 2]);
store.keep("newer", "c.png", "image/png", &third).unwrap();
assert!(
std::fs::read_dir(store.root().join("old"))
.map(|mut d| d.next().is_none())
.unwrap_or(true),
"the oldest session was pruned"
);
assert!(
std::fs::read_dir(store.root().join("newer"))
.unwrap()
.count()
> 0
);
}
#[test]
fn a_budget_too_small_for_one_picture_names_the_budget() {
let dir = tempfile::tempdir().unwrap();
let picture = png(1200, 1200, [3, 3, 3]);
let store = Store::new(dir.path().join("a"), 1024);
let why = store
.keep("s1", "big.png", "image/png", &picture)
.expect_err("over budget");
assert!(why.contains("budget"), "{why}");
assert!(why.contains("max_total_bytes"), "{why}");
}
#[test]
fn forgetting_a_session_removes_its_pictures() {
let (_dir, store) = store();
let picture = png(32, 32, [0, 0, 0]);
let kept = store.keep("s1", "a.png", "image/png", &picture).unwrap();
store.forget("s1").unwrap();
assert!(!kept.original.exists());
store.forget("s1").unwrap(); }
#[test]
fn bytes_that_are_not_a_picture_are_refused_by_their_content_not_their_name() {
let (_dir, store) = store();
let why = store
.keep("s1", "notes.png", "image/png", b"plain text")
.expect_err("not a picture");
assert!(why.contains("not a picture"), "{why}");
}
#[test]
fn a_name_with_nothing_usable_in_it_still_lands_somewhere_sane() {
assert_eq!(sanitise("", "png"), "picture.png");
assert_eq!(sanitise("../../", "png"), "picture.png");
assert_eq!(sanitise("my shot.PNG", "png"), "my-shot.png");
}
}