Skip to main content

eclipse_core/
attachments.rs

1//! `#499`: pictures on disk — the original at full size, and a copy small enough for the wire.
2//!
3//! A picture rides in every later request of the session, so a 2 MiB ceiling on what goes on the
4//! wire is right. Applying that ceiling to the *file someone attached* was not: an 18 MB photo
5//! from a camera could not enter the conversation at all, and the only options it left — shrink it
6//! yourself, or put it on the box and pass a path — both lose the thing the person wanted.
7//!
8//! So two copies, and they mean different things:
9//!
10//! - **The original**, byte-identical to what was uploaded, under
11//!   `<root>/<session>/<sha256[:16]>-<name>.<ext>`. Never rewritten; the hash in the name means a
12//!   re-sent picture costs nothing and two sessions' copies stay distinct. A later turn can crop it
13//!   at full resolution, hand it to a render as a reference, or send it as a file.
14//! - **The working copy**, at or under [`COPY_TARGET_BYTES`], sent to the model. Shrunk to
15//!   [`MAX_EDGE`] and then by quality, in that order, because resolution is what a model reads.
16//!   PNG stays PNG (a screenshot re-encoded as JPEG rings around text, which is exactly what the
17//!   model was asked about); JPEG stays JPEG at q88.
18//!
19//! A picture already under the target needs no second file: the original *is* the working copy, and
20//! `Stored::resized` says so. That is the common case — a screenshot — and it costs one write.
21//!
22//! Nothing here calls a network, and nothing here modifies a file it did not create. The store is
23//! `0600` in a `0700` directory, and [`Store::prune`] is least-recently-used against a byte budget,
24//! because an 18 MB-per-photo default with no ceiling fills a disk.
25
26use std::path::{Path, PathBuf};
27use std::process::Stdio;
28
29/// The wire limit a picture has to fit: what rides in the request body and in the history.
30pub const WIRE_LIMIT_BYTES: usize = 2 * 1024 * 1024;
31
32/// What a working copy aims for, so it has headroom under [`WIRE_LIMIT_BYTES`] rather than exactly
33/// touching it — base64 padding and a header's own overhead are not worth a refusal.
34pub const COPY_TARGET_BYTES: usize = 3 * 1024 * 1024 / 2;
35
36/// The longest edge a working copy keeps. Enough for a model to read text in a screenshot and to
37/// see detail in a photo, and small enough that the copy is a fraction of the original.
38pub const MAX_EDGE: u32 = 2048;
39
40/// A picture kept on disk.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Stored {
43    /// The file exactly as uploaded.
44    pub original: PathBuf,
45    /// What the model is shown — the original itself when no shrink was needed.
46    pub working: PathBuf,
47    /// Bytes in the original.
48    pub bytes: usize,
49    /// Bytes in the working copy.
50    pub working_bytes: usize,
51    /// The original's pixel size, when the header could be read.
52    pub size: Option<(u32, u32)>,
53    /// Whether a second file was derived.
54    pub resized: bool,
55}
56
57impl Stored {
58    /// The line the user message carries, so the model knows it is looking at a copy and where the
59    /// real file is (`#499` acceptance 2). One sentence, no second paragraph.
60    pub fn note(&self, name: &str) -> String {
61        let size = match self.size {
62            Some((w, h)) => format!("{w}×{h}"),
63            None => "unknown size".to_string(),
64        };
65        if self.resized {
66            let edge = self.size.map(|(w, h)| w.max(h)).unwrap_or(MAX_EDGE);
67            format!(
68                "[attached: {name} — the original is at {} ({} KB, {size}). You are looking at a \
69                 {} px copy; use the original's path with `read_file` or a tool if you need the \
70                 full resolution.]",
71                self.original.display(),
72                self.bytes / 1024,
73                edge.min(MAX_EDGE),
74            )
75        } else {
76            format!(
77                "[attached: {name} — {} KB, {size}, stored at {}. This is the original.]",
78                self.bytes / 1024,
79                self.original.display(),
80            )
81        }
82    }
83}
84
85/// Where pictures are kept, and how much room they may take.
86#[derive(Debug, Clone)]
87pub struct Store {
88    root: PathBuf,
89    max_total_bytes: u64,
90    /// The resize helper this process will use, probed once by [`Store::probe`].
91    helper: Option<Helper>,
92}
93
94impl Store {
95    /// `<state_dir>/attachments`, or the `[attachments] dir` override.
96    pub fn new(root: PathBuf, max_total_bytes: u64) -> Self {
97        Self {
98            root,
99            max_total_bytes,
100            helper: Helper::probe(),
101        }
102    }
103
104    /// The same store with a named helper — a test's only way to exercise the Pillow branch on a
105    /// machine that also has ImageMagick (`#499` acceptance 6).
106    pub fn with_helper(mut self, helper: Option<Helper>) -> Self {
107        self.helper = helper;
108        self
109    }
110
111    pub fn root(&self) -> &Path {
112        &self.root
113    }
114
115    /// Keep a picture: the original untouched, and a working copy that fits the wire.
116    ///
117    /// Bytes are written once per distinct picture — the file name is the hash, so a re-sent
118    /// picture is a touch for the LRU clock and no write.
119    pub fn keep(
120        &self,
121        session: &str,
122        name: &str,
123        mime: &str,
124        bytes: &[u8],
125    ) -> Result<Stored, String> {
126        if bytes.is_empty() {
127            return Err("the picture carries no bytes".to_string());
128        }
129        let (_, ext) = kind(mime, bytes)?;
130        let name = sanitise(name, ext);
131        let digest = hex16(bytes);
132        let dir = self.root.join(sanitise_segment(session));
133        let original = dir.join(format!("{digest}-{name}"));
134        std::fs::create_dir_all(&dir)
135            .map_err(|e| format!("could not make {}: {e}", dir.display()))?;
136        restrict(&dir, 0o700);
137        if !original.exists() {
138            let need = bytes.len() as u64;
139            let total = self.total_bytes();
140            if total + need > self.max_total_bytes {
141                let freed = self.prune(need)?;
142                if self.total_bytes() + need > self.max_total_bytes {
143                    return Err(format!(
144                        "the pictures on disk already hold {} MB of the {} MB budget{}; \
145                         `/attachments clear` or a bigger `[attachments] max_total_bytes` makes \
146                         room",
147                        (self.total_bytes() - freed) / (1024 * 1024),
148                        self.max_total_bytes / (1024 * 1024),
149                        if freed > 0 {
150                            format!(
151                                ", and pruning {} MB of the oldest was not enough",
152                                freed / (1024 * 1024)
153                            )
154                        } else {
155                            String::new()
156                        }
157                    ));
158                }
159            }
160            write_private(&original, bytes)?;
161        } else {
162            touch(&original);
163        }
164        let size = dimensions(bytes);
165        // Under the target: the original is what the model gets, and there is no second file.
166        if bytes.len() <= COPY_TARGET_BYTES {
167            return Ok(Stored {
168                working: original.clone(),
169                original,
170                bytes: bytes.len(),
171                working_bytes: bytes.len(),
172                size,
173                resized: false,
174            });
175        }
176        let Some(helper) = self.helper.clone() else {
177            return Err(format!(
178                "this picture is {} KB and has to be shrunk to {} KB for the request, and no \
179                 helper was found to do it: install ImageMagick (`magick`), Python Pillow \
180                 (`python3 -m pip install pillow`) or `ffmpeg`. The original is kept at {} — pass \
181                 that path instead, and the agent can work on it at full size",
182                bytes.len() / 1024,
183                COPY_TARGET_BYTES / 1024,
184                original.display()
185            ));
186        };
187        let stem = original
188            .file_stem()
189            .map(|s| s.to_string_lossy().to_string())
190            .unwrap_or_else(|| digest.clone());
191        let out_name = format!("{stem}-{MAX_EDGE}.{ext}");
192        let working = dir.join(out_name);
193        if !working.exists() {
194            shrink(helper, &original, &working, ext)?;
195        }
196        let working_bytes = std::fs::metadata(&working)
197            .map(|m| m.len() as usize)
198            .unwrap_or(0);
199        if working_bytes == 0 || working_bytes > WIRE_LIMIT_BYTES {
200            return Err(format!(
201                "the copy at {} is {} KB, still over the {} KB a request may carry — the original \
202                 is kept at {}",
203                working.display(),
204                working_bytes / 1024,
205                WIRE_LIMIT_BYTES / 1024,
206                original.display()
207            ));
208        }
209        Ok(Stored {
210            working,
211            original,
212            bytes: bytes.len(),
213            working_bytes,
214            size,
215            resized: true,
216        })
217    }
218
219    /// Every file and directory this store holds, oldest first — the pruning order.
220    fn by_age(&self) -> Vec<(PathBuf, u64, std::time::SystemTime)> {
221        let mut out = Vec::new();
222        let Ok(sessions) = std::fs::read_dir(&self.root) else {
223            return out;
224        };
225        for session in sessions.flatten() {
226            let Ok(files) = std::fs::read_dir(session.path()) else {
227                continue;
228            };
229            for file in files.flatten() {
230                let Ok(meta) = file.metadata() else {
231                    continue;
232                };
233                if !meta.is_file() {
234                    continue;
235                }
236                let when = meta
237                    .modified()
238                    .or_else(|_| meta.accessed())
239                    .unwrap_or(std::time::UNIX_EPOCH);
240                out.push((file.path(), meta.len(), when));
241            }
242        }
243        out.sort_by_key(|(_, _, when)| *when);
244        out
245    }
246
247    /// Bytes on disk across every session.
248    pub fn total_bytes(&self) -> u64 {
249        self.by_age().iter().map(|(_, len, _)| *len).sum()
250    }
251
252    /// Delete the oldest files until `need` bytes are freed, or nothing is left to delete.
253    ///
254    /// Least-recently-used, not per-session: the budget is about the disk, and a session nobody has
255    /// opened in a month is the right thing to lose. Returns the bytes freed.
256    pub fn prune(&self, need: u64) -> Result<u64, String> {
257        let mut freed = 0;
258        for (path, len, _) in self.by_age() {
259            if freed >= need {
260                break;
261            }
262            match std::fs::remove_file(&path) {
263                Ok(()) => freed += len,
264                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
265                Err(e) => return Err(format!("could not remove {}: {e}", path.display())),
266            }
267        }
268        // Directories are left alone: pruning deletes files, and a directory emptied by pruning is
269        // the caller's own attach in progress — `forget` is what removes a session's directory.
270        Ok(freed)
271    }
272
273    /// Remove every picture a session kept (`sessions delete`).
274    pub fn forget(&self, session: &str) -> Result<(), String> {
275        let dir = self.root.join(sanitise_segment(session));
276        match std::fs::remove_dir_all(&dir) {
277            Ok(()) => Ok(()),
278            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
279            Err(e) => Err(format!("could not remove {}: {e}", dir.display())),
280        }
281    }
282}
283
284/// One of the three helpers this build knows how to drive, chosen by what is installed.
285#[derive(Debug, Clone, PartialEq, Eq)]
286pub enum Helper {
287    /// ImageMagick 7's `magick`, or IM 6's `convert`.
288    Magick(PathBuf),
289    /// `python3` with Pillow importable.
290    Pillow(PathBuf),
291    Ffmpeg(PathBuf),
292}
293
294impl Helper {
295    /// The first that works, in the order the issue asked for: ImageMagick, Pillow, ffmpeg.
296    pub fn probe() -> Option<Self> {
297        for candidate in ["magick", "convert"] {
298            if let Some(path) = which(candidate) {
299                if works(&path, &["-version"]) {
300                    return Some(Self::Magick(path));
301                }
302            }
303        }
304        if let Some(path) = which("python3") {
305            if works(
306                &path,
307                &[
308                    "-c",
309                    "import PIL.Image, sys; sys.exit(0 if PIL.Image.__version__ else 1)",
310                ],
311            ) {
312                return Some(Self::Pillow(path));
313            }
314        }
315        which("ffmpeg")
316            .filter(|path| works(path, &["-version"]))
317            .map(Self::Ffmpeg)
318    }
319
320    /// What `doctor` says about it.
321    pub fn name(&self) -> String {
322        match self {
323            Self::Magick(p) => format!("ImageMagick ({})", p.display()),
324            Self::Pillow(p) => format!("Pillow via {}", p.display()),
325            Self::Ffmpeg(p) => format!("ffmpeg ({})", p.display()),
326        }
327    }
328}
329
330/// Shrink `from` into `to`, stepping quality first and resolution second.
331///
332/// Resolution is what a model reads, so it goes last: a 2048 px copy at q70 still has the text in
333/// it, and a 1024 px copy at q95 does not.
334fn shrink(helper: Helper, from: &Path, to: &Path, ext: &str) -> Result<(), String> {
335    let jpeg = ext.eq_ignore_ascii_case("jpg") || ext.eq_ignore_ascii_case("jpeg");
336    let steps = if jpeg {
337        vec![(MAX_EDGE, 88), (MAX_EDGE, 78), (1536, 82), (1024, 80)]
338    } else {
339        // PNG is lossless: the only step that works is fewer pixels.
340        vec![(MAX_EDGE, 0), (1536, 0), (1024, 0), (768, 0)]
341    };
342    let mut last = String::new();
343    for (edge, quality) in steps {
344        match run(helper.clone(), from, to, edge, quality) {
345            Ok(()) => {
346                let len = std::fs::metadata(to).map(|m| m.len() as usize).unwrap_or(0);
347                if len > 0 && len <= COPY_TARGET_BYTES {
348                    return Ok(());
349                }
350                last = format!("{} KB at {edge} px", len / 1024);
351            }
352            Err(e) => last = e,
353        }
354    }
355    // Something was written and is merely bigger than the target: the caller checks the hard limit,
356    // so a copy under the wire limit is still a copy worth sending.
357    if to.exists() && std::fs::metadata(to).map(|m| m.len() as usize).unwrap_or(0) > 0 {
358        return Ok(());
359    }
360    Err(format!("could not shrink the picture ({last})"))
361}
362
363fn run(helper: Helper, from: &Path, to: &Path, edge: u32, quality: u32) -> Result<(), String> {
364    let (program, args) = match helper {
365        Helper::Magick(bin) => {
366            let mut args: Vec<String> = vec![
367                from.display().to_string(),
368                "-resize".into(),
369                format!("{edge}x{edge}>"),
370                "-strip".into(),
371            ];
372            if quality > 0 {
373                args.push("-quality".into());
374                args.push(quality.to_string());
375            }
376            args.push(to.display().to_string());
377            (bin, args)
378        }
379        Helper::Pillow(bin) => {
380            // `thumbnail` keeps the aspect ratio and never enlarges; `sys.argv` keeps the script
381            // free of anything a shell would have to quote.
382            let script = "import sys\n\
383                          from PIL import Image\n\
384                          src, dst, edge, quality = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4])\n\
385                          im = Image.open(src)\n\
386                          im.thumbnail((edge, edge))\n\
387                          if quality:\n\
388                          \x20   im.save(dst, quality=quality, optimize=True)\n\
389                          else:\n\
390                          \x20   im.save(dst, optimize=True)\n";
391            (
392                bin,
393                vec![
394                    "-c".into(),
395                    script.into(),
396                    from.display().to_string(),
397                    to.display().to_string(),
398                    edge.to_string(),
399                    quality.to_string(),
400                ],
401            )
402        }
403        Helper::Ffmpeg(bin) => {
404            let mut args: Vec<String> = vec![
405                "-y".into(),
406                "-loglevel".into(),
407                "error".into(),
408                "-i".into(),
409                from.display().to_string(),
410                "-vf".into(),
411                format!(
412                    "scale='min({edge},iw)':'min({edge},ih)':force_original_aspect_ratio=decrease"
413                ),
414            ];
415            if quality > 0 {
416                args.push("-q:v".into());
417                // ffmpeg's JPEG scale is 2–31 and runs the other way.
418                args.push((31u32.saturating_sub(quality / 4)).clamp(2, 31).to_string());
419            }
420            args.push(to.display().to_string());
421            (bin, args)
422        }
423    };
424    let out = std::process::Command::new(&program)
425        .args(&args)
426        .stdin(Stdio::null())
427        .stdout(Stdio::null())
428        .stderr(Stdio::piped())
429        .output()
430        .map_err(|e| format!("{} could not run: {e}", program.display()))?;
431    if !out.status.success() {
432        let err = String::from_utf8_lossy(&out.stderr);
433        return Err(format!(
434            "{} failed on {}: {}",
435            program.display(),
436            from.display(),
437            err.lines().next().unwrap_or("no message")
438        ));
439    }
440    Ok(())
441}
442
443fn which(bin: &str) -> Option<PathBuf> {
444    let path = std::env::var_os("PATH")?;
445    std::env::split_paths(&path)
446        .map(|dir| dir.join(bin))
447        .find(|p| p.is_file())
448}
449
450fn works(bin: &Path, args: &[&str]) -> bool {
451    std::process::Command::new(bin)
452        .args(args)
453        .stdin(Stdio::null())
454        .stdout(Stdio::null())
455        .stderr(Stdio::null())
456        .status()
457        .map(|s| s.success())
458        .unwrap_or(false)
459}
460
461/// The extension for a picture, and a refusal for anything else — the same four types the wire
462/// carries, checked against the bytes rather than the header's word for them.
463fn kind(mime: &str, bytes: &[u8]) -> Result<(&'static str, &'static str), String> {
464    let found = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
465        ("image/png", "png")
466    } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
467        ("image/jpeg", "jpg")
468    } else if bytes.len() > 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
469        ("image/webp", "webp")
470    } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
471        ("image/gif", "gif")
472    } else {
473        return Err(format!(
474            "the bytes are not a picture this build can carry ({mime}); a picture has to be PNG, \
475             JPEG, WebP or GIF"
476        ));
477    };
478    Ok(found)
479}
480
481/// The pixel size, read from the header — PNG, JPEG, WebP and GIF, no decoder.
482///
483/// This is deliberately a header read and not a decode: it costs nothing, it cannot fail on a valid
484/// file the helpers can still open, and the number is only used to tell the model what it has.
485pub fn dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
486    if bytes.len() > 24 && bytes.starts_with(b"\x89PNG\r\n\x1a\n") && &bytes[12..16] == b"IHDR" {
487        let w = u32::from_be_bytes(bytes[16..20].try_into().ok()?);
488        let h = u32::from_be_bytes(bytes[20..24].try_into().ok()?);
489        return Some((w, h));
490    }
491    if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
492        if bytes.len() < 10 {
493            return None;
494        }
495        let w = u16::from_le_bytes([bytes[6], bytes[7]]) as u32;
496        let h = u16::from_le_bytes([bytes[8], bytes[9]]) as u32;
497        return Some((w, h));
498    }
499    if bytes.len() > 30 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
500        return webp_size(bytes);
501    }
502    if bytes.starts_with(&[0xFF, 0xD8]) {
503        return jpeg_size(bytes);
504    }
505    None
506}
507
508/// A JPEG's size lives in whichever start-of-frame marker comes first, after a run of segments.
509fn jpeg_size(bytes: &[u8]) -> Option<(u32, u32)> {
510    let mut i = 2;
511    while i + 9 < bytes.len() {
512        if bytes[i] != 0xFF {
513            i += 1;
514            continue;
515        }
516        let marker = bytes[i + 1];
517        // Standalone markers carry no length.
518        if (0xD0..=0xD9).contains(&marker) || marker == 0x01 {
519            i += 2;
520            continue;
521        }
522        let len = u16::from_be_bytes([bytes[i + 2], bytes[i + 3]]) as usize;
523        // SOF0..SOF15, except the four that are not frames (DHT, JPG, DAC).
524        if (0xC0..=0xCF).contains(&marker) && !matches!(marker, 0xC4 | 0xC8 | 0xCC) {
525            let h = u16::from_be_bytes([bytes[i + 5], bytes[i + 6]]) as u32;
526            let w = u16::from_be_bytes([bytes[i + 7], bytes[i + 8]]) as u32;
527            return Some((w, h));
528        }
529        i += 2 + len;
530    }
531    None
532}
533
534fn webp_size(bytes: &[u8]) -> Option<(u32, u32)> {
535    let chunk = &bytes[12..16];
536    match chunk {
537        b"VP8X" if bytes.len() >= 30 => {
538            let w = 1 + u32::from_le_bytes([bytes[24], bytes[25], bytes[26], 0]);
539            let h = 1 + u32::from_le_bytes([bytes[27], bytes[28], bytes[29], 0]);
540            Some((w, h))
541        }
542        b"VP8 " if bytes.len() >= 30 => {
543            let w = u16::from_le_bytes([bytes[26], bytes[27]]) as u32 & 0x3FFF;
544            let h = u16::from_le_bytes([bytes[28], bytes[29]]) as u32 & 0x3FFF;
545            Some((w, h))
546        }
547        b"VP8L" if bytes.len() >= 25 => {
548            let bits = u32::from_le_bytes([bytes[21], bytes[22], bytes[23], bytes[24]]);
549            let w = (bits & 0x3FFF) + 1;
550            let h = ((bits >> 14) & 0x3FFF) + 1;
551            Some((w, h))
552        }
553        _ => None,
554    }
555}
556
557/// The hash in the file name: the first 16 hex characters of SHA-256.
558fn hex16(bytes: &[u8]) -> String {
559    let digest = ring::digest::digest(&ring::digest::SHA256, bytes);
560    digest.as_ref()[..8]
561        .iter()
562        .map(|b| format!("{b:02x}"))
563        .collect()
564}
565
566/// A name safe to put on disk: no separators, no dots at the front, nothing shell-special.
567fn sanitise(name: &str, ext: &str) -> String {
568    let stem = name
569        .rsplit('/')
570        .next()
571        .unwrap_or("picture")
572        .rsplit_once('.')
573        .map(|(stem, _)| stem)
574        .unwrap_or(name);
575    let cleaned: String = stem
576        .chars()
577        .map(|c| {
578            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
579                c
580            } else {
581                '-'
582            }
583        })
584        .collect();
585    let cleaned = cleaned.trim_matches('-');
586    let stem = if cleaned.is_empty() {
587        "picture"
588    } else {
589        cleaned
590    };
591    format!("{}.{ext}", stem.chars().take(40).collect::<String>())
592}
593
594fn sanitise_segment(session: &str) -> String {
595    let cleaned: String = session
596        .chars()
597        .map(|c| {
598            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
599                c
600            } else {
601                '-'
602            }
603        })
604        .collect();
605    if cleaned.is_empty() {
606        "unknown".to_string()
607    } else {
608        cleaned
609    }
610}
611
612fn write_private(path: &Path, bytes: &[u8]) -> Result<(), String> {
613    use std::io::Write;
614    let mut file = std::fs::OpenOptions::new()
615        .write(true)
616        .create_new(true)
617        .open(path)
618        .map_err(|e| format!("could not create {}: {e}", path.display()))?;
619    file.write_all(bytes)
620        .map_err(|e| format!("could not write {}: {e}", path.display()))?;
621    restrict(path, 0o600);
622    Ok(())
623}
624
625#[cfg(unix)]
626fn restrict(path: &Path, mode: u32) {
627    use std::os::unix::fs::PermissionsExt;
628    let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
629}
630
631#[cfg(not(unix))]
632fn restrict(_path: &Path, _mode: u32) {}
633
634fn touch(path: &Path) {
635    // The mtime is the LRU clock, so a picture sent again has to read as recent — and nothing in
636    // the file may change to make that true.
637    if let Ok(file) = std::fs::OpenOptions::new().read(true).open(path) {
638        let _ = file.set_modified(std::time::SystemTime::now());
639    }
640}
641
642#[cfg(test)]
643mod tests {
644    use super::*;
645
646    /// A valid PNG of the requested size, built here rather than shipped as a fixture.
647    ///
648    /// The IDAT holds *stored* deflate blocks (no compression at all), which keeps the encoder to
649    /// arithmetic this file already has to do and makes a picture big enough to exercise the shrink
650    /// path without committing megabytes to the repository.
651    pub fn png(width: u32, height: u32, rgb: [u8; 3]) -> Vec<u8> {
652        let mut raw = Vec::with_capacity((height * (1 + width * 3)) as usize);
653        for y in 0..height {
654            raw.push(0); // filter: none
655            for x in 0..width {
656                // A pattern rather than a flat fill: a flat image compresses to nothing, and the
657                // point of this fixture is a file with real size.
658                raw.extend_from_slice(&[
659                    rgb[0].wrapping_add((x % 251) as u8),
660                    rgb[1].wrapping_add((y % 241) as u8),
661                    rgb[2],
662                ]);
663            }
664        }
665        let zlib = stored_zlib(&raw);
666        let mut png = Vec::new();
667        png.extend_from_slice(b"\x89PNG\r\n\x1a\n");
668        let mut ihdr = Vec::new();
669        ihdr.extend_from_slice(&width.to_be_bytes());
670        ihdr.extend_from_slice(&height.to_be_bytes());
671        ihdr.extend_from_slice(&[8, 2, 0, 0, 0]); // 8-bit RGB, no interlace
672        chunk(&mut png, b"IHDR", &ihdr);
673        chunk(&mut png, b"IDAT", &zlib);
674        chunk(&mut png, b"IEND", &[]);
675        png
676    }
677
678    fn chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
679        out.extend_from_slice(&(data.len() as u32).to_be_bytes());
680        out.extend_from_slice(kind);
681        out.extend_from_slice(data);
682        let mut crc_input = kind.to_vec();
683        crc_input.extend_from_slice(data);
684        out.extend_from_slice(&crc(&crc_input).to_be_bytes());
685    }
686
687    fn crc(data: &[u8]) -> u32 {
688        let mut crc = 0xFFFF_FFFFu32;
689        for byte in data {
690            crc ^= *byte as u32;
691            for _ in 0..8 {
692                let mask = (crc & 1).wrapping_neg();
693                crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
694            }
695        }
696        !crc
697    }
698
699    fn stored_zlib(raw: &[u8]) -> Vec<u8> {
700        let mut out = vec![0x78, 0x01];
701        let mut rest = raw;
702        loop {
703            let take = rest.len().min(65535);
704            let last = take == rest.len();
705            out.push(if last { 1 } else { 0 });
706            out.extend_from_slice(&(take as u16).to_le_bytes());
707            out.extend_from_slice(&(!(take as u16)).to_le_bytes());
708            out.extend_from_slice(&rest[..take]);
709            rest = &rest[take..];
710            if last {
711                break;
712            }
713        }
714        let mut a: u32 = 1;
715        let mut b: u32 = 0;
716        for byte in raw {
717            a = (a + *byte as u32) % 65521;
718            b = (b + a) % 65521;
719        }
720        out.extend_from_slice(&((b << 16) | a).to_be_bytes());
721        out
722    }
723
724    /// A store with a real helper, or `None` when this machine has none installed.
725    ///
726    /// A test that needs bytes actually shrunk has to skip where no resizer exists — CI has none of
727    /// the three — rather than assert something only this box can do. What the shrink *decides* is
728    /// covered by the step list and the size reader, which need no helper at all.
729    fn store_with_helper() -> Option<(tempfile::TempDir, Store)> {
730        let helper = Helper::probe()?;
731        let dir = tempfile::tempdir().unwrap();
732        let store = Store::new(dir.path().join("attachments"), 2 * 1024 * 1024 * 1024)
733            .with_helper(Some(helper));
734        Some((dir, store))
735    }
736
737    fn store() -> (tempfile::TempDir, Store) {
738        let dir = tempfile::tempdir().unwrap();
739        let store = Store::new(dir.path().join("attachments"), 2 * 1024 * 1024 * 1024);
740        (dir, store)
741    }
742
743    #[test]
744    fn the_header_reads_the_size_without_decoding_anything() {
745        let picture = png(37, 19, [10, 20, 30]);
746        assert_eq!(dimensions(&picture), Some((37, 19)));
747        // A JPEG built by hand: SOI, an APP0 segment, then SOF0 with the size.
748        let mut jpeg = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10];
749        jpeg.extend_from_slice(&[0u8; 14]);
750        jpeg.extend_from_slice(&[0xFF, 0xC0, 0x00, 0x11, 0x08]);
751        jpeg.extend_from_slice(&[0x01, 0x2C]); // 300 rows
752        jpeg.extend_from_slice(&[0x01, 0xF4]); // 500 columns
753        jpeg.extend_from_slice(&[0u8; 12]);
754        assert_eq!(dimensions(&jpeg), Some((500, 300)));
755        assert_eq!(dimensions(b"not a picture"), None);
756    }
757
758    #[test]
759    fn a_small_picture_is_its_own_working_copy_and_is_written_once() {
760        let (_dir, store) = store();
761        let picture = png(64, 64, [1, 2, 3]);
762        let first = store.keep("s1", "shot.png", "image/png", &picture).unwrap();
763        assert!(!first.resized);
764        assert_eq!(first.working, first.original);
765        assert_eq!(std::fs::read(&first.original).unwrap(), picture);
766        // The same bytes again: no second file, and the note says it is the original.
767        let again = store.keep("s1", "shot.png", "image/png", &picture).unwrap();
768        assert_eq!(again.original, first.original);
769        assert!(again.note("shot.png").contains("This is the original"));
770    }
771
772    #[test]
773    fn the_original_is_byte_identical_and_the_directory_is_private() {
774        use std::os::unix::fs::PermissionsExt;
775        let (_dir, store) = store();
776        let picture = png(64, 64, [9, 9, 9]);
777        let kept = store
778            .keep("s1", "../../etc/passwd.png", "image/png", &picture)
779            .unwrap();
780        assert_eq!(std::fs::read(&kept.original).unwrap(), picture);
781        assert!(
782            kept.original.starts_with(store.root()),
783            "a name cannot escape the store: {}",
784            kept.original.display()
785        );
786        let mode = std::fs::metadata(&kept.original)
787            .unwrap()
788            .permissions()
789            .mode()
790            & 0o777;
791        assert_eq!(mode, 0o600);
792        let dir_mode = std::fs::metadata(kept.original.parent().unwrap())
793            .unwrap()
794            .permissions()
795            .mode()
796            & 0o777;
797        assert_eq!(dir_mode, 0o700);
798    }
799
800    #[test]
801    fn a_bigger_picture_is_kept_whole_and_shrunk_for_the_wire() {
802        let Some((_dir, store)) = store_with_helper() else {
803            return;
804        };
805        let picture = png(1200, 1200, [200, 30, 40]);
806        assert!(
807            picture.len() > COPY_TARGET_BYTES,
808            "the fixture has to be over the target: {} bytes",
809            picture.len()
810        );
811        let kept = store
812            .keep("s1", "photo.png", "image/png", &picture)
813            .unwrap_or_else(|why| panic!("{why}"));
814        assert!(kept.resized, "a picture over the target gets a copy");
815        assert_eq!(std::fs::read(&kept.original).unwrap(), picture);
816        assert_ne!(kept.working, kept.original);
817        assert!(
818            kept.working_bytes <= COPY_TARGET_BYTES,
819            "the copy is {} bytes",
820            kept.working_bytes
821        );
822        let copy = std::fs::read(&kept.working).unwrap();
823        let (w, h) = dimensions(&copy).expect("the copy is a picture");
824        assert!(w.max(h) <= MAX_EDGE, "{}×{}", w, h);
825        let note = kept.note("photo.png");
826        assert!(note.contains("copy"), "{note}");
827        assert!(
828            note.contains(&kept.original.display().to_string()),
829            "{note}"
830        );
831    }
832
833    #[test]
834    fn the_original_keeps_its_pixels_while_the_copy_is_smaller() {
835        // The case the issue was filed about: a picture from a camera, far over the wire limit.
836        let Some((_dir, store)) = store_with_helper() else {
837            return;
838        };
839        let picture = png(3000, 2000, [90, 120, 150]);
840        assert!(picture.len() > 8 * 1024 * 1024, "{} bytes", picture.len());
841        let kept = store
842            .keep("s1", "camera.png", "image/png", &picture)
843            .unwrap_or_else(|why| panic!("{why}"));
844        // Acceptance 1 and 3: the file on disk is the upload, and it is still 3000×2000 — so a
845        // later turn can crop it at full resolution.
846        assert_eq!(std::fs::read(&kept.original).unwrap(), picture);
847        assert_eq!(dimensions(&picture), Some((3000, 2000)));
848        assert_eq!(kept.size, Some((3000, 2000)));
849        // Acceptance 1: the copy fits the wire.
850        assert!(
851            kept.working_bytes <= COPY_TARGET_BYTES,
852            "{}",
853            kept.working_bytes
854        );
855        assert!(kept.working_bytes < kept.bytes);
856        // Acceptance 2: the message says both facts, and names the copy a copy.
857        let note = kept.note("camera.png");
858        assert!(note.contains("3000×2000"), "{note}");
859        assert!(note.contains("copy"), "{note}");
860        assert!(
861            note.contains(&kept.original.display().to_string()),
862            "{note}"
863        );
864        // The copy is a second file, so the note's promise is true.
865        assert!(kept.working.exists());
866        assert_ne!(kept.working, kept.original);
867    }
868
869    #[test]
870    fn with_no_helper_the_original_is_still_kept_and_the_refusal_says_so() {
871        let (_dir, store) = store();
872        let store = store.with_helper(None);
873        let picture = png(1200, 1200, [5, 6, 7]);
874        let why = store
875            .keep("s1", "photo.png", "image/png", &picture)
876            .expect_err("no helper, no copy");
877        assert!(why.contains("ImageMagick"), "{why}");
878        assert!(why.contains("ffmpeg"), "{why}");
879        assert!(why.contains("original is kept"), "{why}");
880    }
881
882    #[test]
883    fn the_pillow_branch_shrinks_a_picture_on_its_own() {
884        let Some(pillow) = which("python3").filter(|p| works(p, &["-c", "import PIL.Image"]))
885        else {
886            return; // Pillow is not installed here: the ffmpeg branch covers this box.
887        };
888        let (_dir, store) = store();
889        let store = store.with_helper(Some(Helper::Pillow(pillow)));
890        let picture = png(1500, 900, [12, 200, 12]);
891        let kept = store.keep("s1", "wide.png", "image/png", &picture).unwrap();
892        assert!(kept.resized);
893        let copy = std::fs::read(&kept.working).unwrap();
894        let (w, h) = dimensions(&copy).expect("still a picture");
895        assert!(w.max(h) <= MAX_EDGE, "{}×{}", w, h);
896        assert!(
897            copy.len() < picture.len(),
898            "{} vs {}",
899            copy.len(),
900            picture.len()
901        );
902    }
903
904    #[test]
905    fn the_budget_prunes_the_oldest_first_and_then_refuses() {
906        let dir = tempfile::tempdir().unwrap();
907        let picture = png(1200, 1200, [1, 1, 1]);
908        let one = picture.len() as u64;
909        let Some(helper) = Helper::probe() else {
910            return;
911        };
912        let store = Store::new(dir.path().join("a"), one * 2).with_helper(Some(helper));
913        store.keep("old", "a.png", "image/png", &picture).unwrap();
914        std::thread::sleep(std::time::Duration::from_millis(20));
915        store.keep("new", "b.png", "image/png", &picture).unwrap();
916        // A third would exceed the budget: the oldest session's files go first, and the attach
917        // succeeds rather than being refused.
918        std::thread::sleep(std::time::Duration::from_millis(20));
919        let third = png(1200, 1200, [2, 2, 2]);
920        store.keep("newer", "c.png", "image/png", &third).unwrap();
921        assert!(
922            std::fs::read_dir(store.root().join("old"))
923                .map(|mut d| d.next().is_none())
924                .unwrap_or(true),
925            "the oldest session was pruned"
926        );
927        assert!(
928            std::fs::read_dir(store.root().join("newer"))
929                .unwrap()
930                .count()
931                > 0
932        );
933    }
934
935    #[test]
936    fn a_budget_too_small_for_one_picture_names_the_budget() {
937        let dir = tempfile::tempdir().unwrap();
938        let picture = png(1200, 1200, [3, 3, 3]);
939        let store = Store::new(dir.path().join("a"), 1024);
940        let why = store
941            .keep("s1", "big.png", "image/png", &picture)
942            .expect_err("over budget");
943        assert!(why.contains("budget"), "{why}");
944        assert!(why.contains("max_total_bytes"), "{why}");
945    }
946
947    #[test]
948    fn forgetting_a_session_removes_its_pictures() {
949        let (_dir, store) = store();
950        let picture = png(32, 32, [0, 0, 0]);
951        let kept = store.keep("s1", "a.png", "image/png", &picture).unwrap();
952        store.forget("s1").unwrap();
953        assert!(!kept.original.exists());
954        store.forget("s1").unwrap(); // idempotent
955    }
956
957    #[test]
958    fn bytes_that_are_not_a_picture_are_refused_by_their_content_not_their_name() {
959        let (_dir, store) = store();
960        let why = store
961            .keep("s1", "notes.png", "image/png", b"plain text")
962            .expect_err("not a picture");
963        assert!(why.contains("not a picture"), "{why}");
964    }
965
966    #[test]
967    fn a_name_with_nothing_usable_in_it_still_lands_somewhere_sane() {
968        assert_eq!(sanitise("", "png"), "picture.png");
969        assert_eq!(sanitise("../../", "png"), "picture.png");
970        assert_eq!(sanitise("my shot.PNG", "png"), "my-shot.png");
971    }
972}