truss-image 0.11.5

Image toolkit with a shared Rust core across the CLI, HTTP server, and WASM demo.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
//! On-disk transform and origin caching.
//!
//! # Design decisions
//!
//! **Sharded directory layout:** Cache entries are stored under
//! `<root>/ab/cd/ef/<sha256>`, splitting the first three byte-pairs of the hex key
//! into nested directories. This creates up to 4,096 intermediate directories and
//! prevents filesystem inode exhaustion or performance degradation when millions of
//! entries accumulate in a flat directory.
//!
//! **Atomic writes:** Cache entries are written to a temporary file (with a unique
//! PID + counter suffix) then renamed atomically. This ensures readers never see
//! partial data. Corrupted entries (detected during reads) are cleaned up
//! automatically.
//!
//! **mtime-based TTL:** Staleness is determined by file modification time rather
//! than an embedded timestamp. This keeps the on-disk format simple (media-type
//! header + raw bytes) and allows operators to touch files to extend their lifetime.
//!
//! **Optional size-based eviction:** When `TRUSS_CACHE_MAX_BYTES` is set to a
//! positive value, the cache performs LRU-style eviction after writes. Eviction
//! scans are throttled to at most once per 60 seconds to avoid expensive
//! directory walks on every cache write. When the variable is unset or `0`, no
//! size-based eviction is performed and operators should use external tools
//! (e.g., `tmpwatch`, `tmpreaper`, cron) for disk management.

use super::LogHandler;
use crate::MediaType;
use sha2::{Digest, Sha256};
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

use super::ServerConfig;
use super::http_parse::HttpRequest;
use super::metrics::CACHE_HITS_TOTAL;
use super::negotiate::{
    CacheHitStatus, ImageResponsePolicy, build_image_etag, build_image_response_headers,
    if_none_match_matches,
};
use super::response::HttpResponse;
use crate::core::default_lossy_target_quality;
use crate::{Fit, Position, Rotation, TransformOptions};

pub(super) const DEFAULT_CACHE_TTL_SECONDS: u64 = 3600;

/// Monotonically increasing counter used to generate unique temp-file suffixes
/// for cache writes.  Combined with the process ID this avoids collisions from
/// concurrent writers within the same process.
pub(super) static CACHE_TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);

/// On-disk transform cache using a sharded directory layout.
///
/// The cache stores transformed image bytes under `<root>/ab/cd/ef/<sha256_hex>`, where
/// `ab`, `cd`, `ef` are the first three byte-pairs of the hex-encoded cache key. Each file
/// starts with a media-type header line (e.g. `"jpeg\n"`) followed by the raw output bytes.
///
/// Staleness is determined by file modification time. Entries older than
/// [`DEFAULT_CACHE_TTL_SECONDS`] are treated as misses and overwritten on the next transform.
///
/// When `max_bytes` is set to a positive value, the cache performs LRU-style eviction
/// after each write to keep the total on-disk size under the configured limit.
/// Minimum interval between eviction scans (seconds).
const EVICTION_INTERVAL_SECS: u64 = 60;

pub(super) struct TransformCache {
    pub(super) root: PathBuf,
    pub(super) ttl: Duration,
    pub(super) log_handler: Option<LogHandler>,
    /// Maximum total cache size in bytes. `0` means unlimited (no eviction).
    pub(super) max_bytes: u64,
    /// Unix timestamp of the last eviction scan, used to throttle scans.
    last_eviction_secs: AtomicU64,
}

/// The result of a cache lookup.
#[derive(Debug)]
pub(super) enum CacheLookup {
    /// The entry was found and is still fresh.
    Hit {
        media_type: MediaType,
        body: Vec<u8>,
        age: Duration,
    },
    /// The entry was not found or is stale.
    Miss,
}

impl TransformCache {
    /// Creates a new transform cache rooted at the given directory.
    pub(super) fn new(root: PathBuf) -> Self {
        Self {
            root,
            ttl: Duration::from_secs(DEFAULT_CACHE_TTL_SECONDS),
            log_handler: None,
            max_bytes: 0,
            last_eviction_secs: AtomicU64::new(0),
        }
    }

    pub(super) fn with_log_handler(mut self, handler: Option<LogHandler>) -> Self {
        self.log_handler = handler;
        self
    }

    pub(super) fn with_max_bytes(mut self, max_bytes: u64) -> Self {
        self.max_bytes = max_bytes;
        self
    }

    pub(super) fn log(&self, msg: &str) {
        if let Some(handler) = &self.log_handler {
            handler(msg);
        } else {
            eprintln!("{msg}");
        }
    }

    /// Returns the sharded file path for the given cache key.
    ///
    /// # Panics
    ///
    /// Debug-asserts that `key` is a 64-character hex string (SHA-256 output).
    pub(super) fn entry_path(&self, key: &str) -> PathBuf {
        debug_assert!(
            key.len() == 64 && key.bytes().all(|b| b.is_ascii_hexdigit()),
            "cache key must be a 64-character hex string"
        );
        // Layout: <root>/ab/cd/ef/<key>
        // where ab, cd, ef are the first 6 hex characters split into pairs.
        let a = &key[0..2];
        let b = &key[2..4];
        let c = &key[4..6];
        self.root.join(a).join(b).join(c).join(key)
    }

    /// Looks up a cached transform result.
    ///
    /// Returns [`CacheLookup::Hit`] if the file exists, is readable, and its modification
    /// time is within the TTL. Returns [`CacheLookup::Miss`] otherwise.
    pub(super) fn get(&self, key: &str) -> CacheLookup {
        let path = self.entry_path(key);

        // Open a single file handle to avoid TOCTOU between read and metadata.
        let file = match fs::File::open(&path) {
            Ok(f) => f,
            Err(_) => return CacheLookup::Miss,
        };

        // Check staleness via mtime on the same file handle.
        let age = match file
            .metadata()
            .and_then(|m| m.modified())
            .and_then(|mtime| mtime.elapsed().map_err(io::Error::other))
        {
            Ok(age) => age,
            Err(_) => return CacheLookup::Miss,
        };

        if age > self.ttl {
            return CacheLookup::Miss;
        }

        let mut data = Vec::new();
        if io::Read::read_to_end(&mut &file, &mut data).is_err() {
            self.remove_corrupted(&path, "read failed");
            return CacheLookup::Miss;
        }

        // Parse the header line: "<media_type>\n<body>"
        let newline_pos = match data.iter().position(|&b| b == b'\n') {
            Some(pos) => pos,
            None => {
                self.remove_corrupted(&path, "missing header newline");
                return CacheLookup::Miss;
            }
        };
        let media_type_str = match std::str::from_utf8(&data[..newline_pos]) {
            Ok(s) => s,
            Err(_) => {
                self.remove_corrupted(&path, "invalid UTF-8 in header");
                return CacheLookup::Miss;
            }
        };
        let media_type = match MediaType::from_str(media_type_str) {
            Ok(mt) => mt,
            Err(_) => {
                self.remove_corrupted(&path, "unrecognized media type");
                return CacheLookup::Miss;
            }
        };

        // Remove the header in-place to avoid a second allocation.
        data.drain(..=newline_pos);

        CacheLookup::Hit {
            media_type,
            body: data,
            age,
        }
    }

    /// Removes a corrupted cache entry and logs the reason.
    fn remove_corrupted(&self, path: &Path, reason: &str) {
        self.log(&format!(
            "truss: removing corrupted cache entry ({reason}): {}",
            path.display()
        ));
        let _ = fs::remove_file(path);
    }

    /// Writes a transform result to the cache.
    ///
    /// Uses write-to-tempfile-then-rename for atomic writes, preventing readers from seeing
    /// partial data.
    pub(super) fn put(&self, key: &str, media_type: MediaType, body: &[u8]) {
        let path = self.entry_path(key);
        if let Some(parent) = path.parent()
            && let Err(err) = fs::create_dir_all(parent)
        {
            self.log(&format!("truss: cache mkdir failed: {err}"));
            return;
        }

        // Write to a temp file with a unique suffix, then rename atomically.
        let tmp_path = path.with_extension(unique_tmp_suffix());
        let mut header = media_type.as_name().as_bytes().to_vec();
        header.push(b'\n');

        let result = (|| -> io::Result<()> {
            let mut file = fs::File::create(&tmp_path)?;
            file.write_all(&header)?;
            file.write_all(body)?;
            drop(file);
            fs::rename(&tmp_path, &path)?;
            Ok(())
        })();

        if let Err(err) = result {
            self.log(&format!("truss: cache write failed: {err}"));
            // Clean up the temp file if it exists.
            let _ = fs::remove_file(&tmp_path);
        } else {
            self.maybe_evict();
        }
    }

    /// Runs LRU-style eviction if a maximum cache size is configured and exceeded.
    ///
    /// Scans all files under the cache root, sorts them by modification time
    /// (oldest first), and removes entries until the total size drops below
    /// `self.max_bytes`. Eviction scans are throttled to at most once per
    /// [`EVICTION_INTERVAL_SECS`]. Errors on individual files (e.g. concurrent
    /// deletion) are silently ignored.
    fn maybe_evict(&self) {
        if self.max_bytes == 0 {
            return;
        }
        // Throttle eviction scans to at most once per EVICTION_INTERVAL_SECS
        // to avoid O(n log n) directory walks on every cache write.
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        let last = self.last_eviction_secs.load(Ordering::Relaxed);
        if now.saturating_sub(last) < EVICTION_INTERVAL_SECS {
            return;
        }
        if self
            .last_eviction_secs
            .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
            .is_err()
        {
            return; // another thread won the race
        }
        if let Err(err) = self.evict_to_limit() {
            self.log(&format!("truss: cache eviction scan failed: {err}"));
        }
    }

    /// Performs the eviction scan and removal. Returns an error only if the
    /// top-level directory walk cannot be started.
    fn evict_to_limit(&self) -> io::Result<()> {
        let mut entries = collect_cache_entries(&self.root)?;
        let total_size: u64 = entries.iter().map(|e| e.size).sum();
        if total_size <= self.max_bytes {
            return Ok(());
        }

        // Sort oldest-first (largest mtime = most recently modified = keep).
        entries.sort_by_key(|e| e.mtime);

        let mut current_size = total_size;
        for entry in &entries {
            if current_size <= self.max_bytes {
                break;
            }
            if fs::remove_file(&entry.path).is_ok() {
                self.log(&format!(
                    "truss: cache eviction: removed {} ({} bytes)",
                    entry.path.display(),
                    entry.size
                ));
                current_size = current_size.saturating_sub(entry.size);
            }
        }
        Ok(())
    }
}

/// A cache file entry used during eviction scanning.
struct CacheEntry {
    path: PathBuf,
    size: u64,
    /// Modification time as duration since `UNIX_EPOCH`. Entries with smaller
    /// values are older and evicted first.
    mtime: Duration,
}

/// Recursively collects all regular files under `root` with their size and
/// modification time. Temp files (containing `.tmp.`) are skipped.
fn collect_cache_entries(root: &Path) -> io::Result<Vec<CacheEntry>> {
    let mut entries = Vec::new();
    collect_entries_recursive(root, &mut entries);
    Ok(entries)
}

fn collect_entries_recursive(dir: &Path, entries: &mut Vec<CacheEntry>) {
    let read_dir = match fs::read_dir(dir) {
        Ok(rd) => rd,
        Err(_) => return,
    };
    for entry in read_dir.flatten() {
        let path = entry.path();
        if path.is_dir() {
            collect_entries_recursive(&path, entries);
        } else if path.is_file() {
            // Skip temp files from in-flight writes.
            if let Some(name) = path.file_name().and_then(|n| n.to_str())
                && name.contains(".tmp.")
            {
                continue;
            }
            if let Ok(meta) = fs::metadata(&path) {
                let size = meta.len();
                let mtime = meta
                    .modified()
                    .ok()
                    .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                    .unwrap_or(Duration::ZERO);
                entries.push(CacheEntry { path, size, mtime });
            }
        }
    }
}

/// On-disk origin response cache for remote URL fetches.
///
/// Caches raw source bytes fetched from remote URLs so repeated requests for the same
/// remote source avoid redundant HTTP round-trips. This sits in front of the transform
/// cache in the cache hierarchy (design doc section 8.1).
///
/// The cache key is the SHA-256 of the canonical URL string. The stored value is the
/// raw source bytes with no header. Staleness uses the same mtime-based TTL as the
/// transform cache.
pub(super) struct OriginCache {
    root: PathBuf,
    pub(super) ttl: Duration,
    log_handler: Option<LogHandler>,
}

impl OriginCache {
    /// Creates a new origin cache rooted at `<cache_root>/origin/`.
    pub(super) fn new(cache_root: &Path) -> Self {
        Self {
            root: cache_root.join("origin"),
            ttl: Duration::from_secs(DEFAULT_CACHE_TTL_SECONDS),
            log_handler: None,
        }
    }

    pub(super) fn with_log_handler(mut self, handler: Option<LogHandler>) -> Self {
        self.log_handler = handler;
        self
    }

    fn log(&self, msg: &str) {
        if let Some(handler) = &self.log_handler {
            handler(msg);
        } else {
            eprintln!("{msg}");
        }
    }

    /// Returns the sharded file path for the given URL and namespace.
    fn entry_path(&self, namespace: &str, url: &str) -> PathBuf {
        let mut hasher = Sha256::new();
        hasher.update(namespace.as_bytes());
        hasher.update(b":");
        hasher.update(url.as_bytes());
        let key = hex::encode(hasher.finalize());
        let a = &key[0..2];
        let b = &key[2..4];
        let c = &key[4..6];
        self.root.join(a).join(b).join(c).join(&key)
    }

    /// Looks up cached source bytes for a remote URL within the given namespace.
    pub(super) fn get(&self, namespace: &str, url: &str) -> Option<Vec<u8>> {
        let path = self.entry_path(namespace, url);
        let file = fs::File::open(&path).ok()?;

        let age = file
            .metadata()
            .and_then(|m| m.modified())
            .and_then(|mtime| mtime.elapsed().map_err(io::Error::other))
            .ok()?;

        if age > self.ttl {
            return None;
        }

        let mut data = Vec::new();
        io::Read::read_to_end(&mut &file, &mut data).ok()?;
        Some(data)
    }

    /// Writes fetched source bytes to the origin cache within the given namespace.
    pub(super) fn put(&self, namespace: &str, url: &str, body: &[u8]) {
        let path = self.entry_path(namespace, url);
        if let Some(parent) = path.parent()
            && let Err(err) = fs::create_dir_all(parent)
        {
            self.log(&format!("truss: origin cache mkdir failed: {err}"));
            return;
        }

        let tmp_path = path.with_extension(unique_tmp_suffix());
        let result = (|| -> io::Result<()> {
            let mut file = fs::File::create(&tmp_path)?;
            file.write_all(body)?;
            drop(file);
            fs::rename(&tmp_path, &path)?;
            Ok(())
        })();

        if let Err(err) = result {
            self.log(&format!("truss: origin cache write failed: {err}"));
            let _ = fs::remove_file(&tmp_path);
        }
    }
}

/// Returns a unique temporary-file suffix for cache writes.
///
/// The suffix combines the process ID with a monotonically increasing counter
/// so that concurrent writers within the same process never collide on the
/// same temp path (the previous PID-only scheme could).
pub(super) fn unique_tmp_suffix() -> String {
    let seq = CACHE_TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
    format!("tmp.{}.{seq}", std::process::id())
}

/// Computes a SHA-256 cache key from the source identifier, transform options, and
/// optionally the negotiated Accept value.
///
/// The canonical form follows the design specification (section 8.2):
/// ```text
/// SHA256(
///   canonical_source_identifier + "\n" +
///   canonical_transform_parameters + "\n" +
///   normalized_accept_if_negotiation_enabled_and_format_absent
/// )
/// ```
///
/// Auth-related parameters (`keyId`, `expires`, `signature`) are excluded. The `deadline`
/// field is excluded because it is an adapter concern, not a transform identity.
pub(super) fn compute_cache_key(
    source_identifier: &str,
    options: &TransformOptions,
    negotiated_accept: Option<&str>,
    watermark_identity: Option<&str>,
) -> String {
    use std::fmt::Write;

    let mut canonical = String::new();
    canonical.push_str(source_identifier);
    canonical.push('\n');

    // Build sorted canonical transform parameters.
    //
    // Where the core `TransformOptions::normalize()` method fills in defaults
    // (e.g. fit -> Contain, position -> Center when width+height are set), we
    // replicate the same defaults here so that the omitted-vs-explicit-default
    // distinction does not produce different cache keys for identical transforms.
    let has_bounded_resize = options.width.is_some() && options.height.is_some();

    let mut first = true;
    let mut push_param = |canonical: &mut String, k: &str, v: &str| {
        if !first {
            canonical.push('&');
        }
        first = false;
        canonical.push_str(k);
        canonical.push('=');
        canonical.push_str(v);
    };

    if options.auto_orient {
        push_param(&mut canonical, "autoOrient", "true");
    }
    if let Some(bg) = &options.background {
        let mut buf = String::new();
        let _ = write!(buf, "{:02x}{:02x}{:02x}{:02x}", bg.r, bg.g, bg.b, bg.a);
        push_param(&mut canonical, "background", &buf);
    }
    if let Some(blur) = options.blur {
        let mut buf = String::new();
        let _ = write!(buf, "{blur}");
        push_param(&mut canonical, "blur", &buf);
    }
    if let Some(crop) = options.crop {
        let buf = crop.to_string();
        push_param(&mut canonical, "crop", &buf);
    }
    if has_bounded_resize {
        let fit = options.fit.unwrap_or(Fit::Contain);
        push_param(&mut canonical, "fit", fit.as_name());
    }
    if let Some(format) = options.format {
        push_param(&mut canonical, "format", format.as_name());
    }
    if let Some(h) = options.height {
        let buf = h.to_string();
        push_param(&mut canonical, "height", &buf);
    }
    if options.optimize != crate::OptimizeMode::None {
        push_param(&mut canonical, "optimize", options.optimize.as_name());
    }
    if has_bounded_resize {
        let pos = options.position.unwrap_or(Position::Center);
        push_param(&mut canonical, "position", pos.as_name());
    }
    if options.preserve_exif {
        push_param(&mut canonical, "preserveExif", "true");
    }
    if let Some(q) = options.quality {
        let buf = q.to_string();
        push_param(&mut canonical, "quality", &buf);
    }
    if let Some(target_quality) = options.target_quality {
        let buf = target_quality.to_string();
        push_param(&mut canonical, "targetQuality", &buf);
    } else if matches!(
        options.optimize,
        crate::OptimizeMode::Auto | crate::OptimizeMode::Lossy
    ) && options.quality.is_none()
        && let Some(format) = options.format
        && let Some(target_quality) = default_lossy_target_quality(format)
    {
        let buf = target_quality.to_string();
        push_param(&mut canonical, "targetQuality", &buf);
    }
    if options.rotate != Rotation::Deg0 {
        let buf = options.rotate.as_degrees().to_string();
        push_param(&mut canonical, "rotate", &buf);
    }
    if let Some(sharpen) = options.sharpen {
        let mut buf = String::new();
        let _ = write!(buf, "{sharpen}");
        push_param(&mut canonical, "sharpen", &buf);
    }
    if options.strip_metadata {
        push_param(&mut canonical, "stripMetadata", "true");
    }
    if let Some(w) = options.width {
        let buf = w.to_string();
        push_param(&mut canonical, "width", &buf);
    }

    canonical.push('\n');
    if let Some(accept) = negotiated_accept {
        canonical.push_str(accept);
    }
    canonical.push('\n');
    if let Some(wm) = watermark_identity {
        canonical.push_str(wm);
    }

    let digest = Sha256::digest(canonical.as_bytes());
    hex::encode(digest)
}

/// Computes a stable identity string for watermark parameters that can be
/// included in cache key computation. The identity is a SHA-256 hex digest
/// of the watermark URL, position, opacity, and margin concatenated with
/// newline separators.
pub(super) fn compute_watermark_identity(
    url: &str,
    position: &str,
    opacity: u8,
    margin: u32,
) -> String {
    let mut hasher = Sha256::new();
    hasher.update(b"watermark\n");
    hasher.update(url.as_bytes());
    hasher.update(b"\n");
    hasher.update(position.as_bytes());
    hasher.update(b"\n");
    hasher.update(opacity.to_string().as_bytes());
    hasher.update(b"\n");
    hasher.update(margin.to_string().as_bytes());
    hex::encode(hasher.finalize())
}

pub(super) fn compute_watermark_content_identity(
    content_hash: &str,
    position: &str,
    opacity: u8,
    margin: u32,
) -> String {
    let mut hasher = Sha256::new();
    hasher.update(b"watermark-content\n");
    hasher.update(content_hash.as_bytes());
    hasher.update(b"\n");
    hasher.update(position.as_bytes());
    hasher.update(b"\n");
    hasher.update(opacity.to_string().as_bytes());
    hasher.update(b"\n");
    hasher.update(margin.to_string().as_bytes());
    hex::encode(hasher.finalize())
}

/// Attempts a cache lookup using a version-based source hash, which avoids reading
/// the full source bytes. Returns `Some(response)` on a cache hit (including `304`
/// for conditional requests). Returns `None` on miss or when a version-based lookup
/// is not possible (no version, no cache, or format not yet known).
pub(super) fn try_versioned_cache_lookup(
    versioned_hash: Option<&str>,
    options: &TransformOptions,
    request: &HttpRequest,
    response_policy: ImageResponsePolicy,
    config: &ServerConfig,
    watermark_identity: Option<&str>,
) -> Option<HttpResponse> {
    let source_hash = versioned_hash?;
    let cache_root = config.cache_root.as_ref()?;
    // We can only do a pre-lookup when the output format is already set, because
    // Accept negotiation requires sniffing the source to know the input type.
    options.format?;

    let cache =
        TransformCache::new(cache_root.clone()).with_log_handler(config.log_handler.clone());
    let cache_key = compute_cache_key(source_hash, options, None, watermark_identity);
    if let CacheLookup::Hit {
        media_type,
        body,
        age,
    } = cache.get(&cache_key)
    {
        CACHE_HITS_TOTAL.fetch_add(1, Ordering::Relaxed);
        let etag = build_image_etag(&body);
        let mut headers = build_image_response_headers(
            media_type,
            &etag,
            response_policy,
            false,
            CacheHitStatus::Hit,
            config.public_max_age_seconds,
            config.public_stale_while_revalidate_seconds,
            &config.custom_response_headers,
        );
        headers.push(("Age".to_string(), age.as_secs().to_string()));
        if matches!(response_policy, ImageResponsePolicy::PublicGet)
            && if_none_match_matches(request.header("if-none-match"), &etag)
        {
            return Some(HttpResponse::empty("304 Not Modified", headers));
        }
        return Some(HttpResponse::binary_with_headers(
            "200 OK",
            media_type.as_mime(),
            headers,
            body,
        ));
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cache_key_blur_full_precision() {
        let opts_a = TransformOptions {
            blur: Some(0.11),
            ..TransformOptions::default()
        };
        let opts_b = TransformOptions {
            blur: Some(0.14),
            ..TransformOptions::default()
        };
        let key_a = compute_cache_key("img.png", &opts_a, None, None);
        let key_b = compute_cache_key("img.png", &opts_b, None, None);
        assert_ne!(
            key_a, key_b,
            "blur=0.11 and blur=0.14 must produce different cache keys"
        );
    }

    #[test]
    fn cache_key_differs_by_optimize_mode() {
        let base = TransformOptions::default();
        let optimized = TransformOptions {
            optimize: crate::OptimizeMode::Auto,
            ..TransformOptions::default()
        };

        assert_ne!(
            compute_cache_key("img.png", &base, None, None),
            compute_cache_key("img.png", &optimized, None, None)
        );
    }

    #[test]
    fn cache_key_differs_by_target_quality() {
        let a = TransformOptions {
            format: Some(MediaType::Jpeg),
            optimize: crate::OptimizeMode::Lossy,
            target_quality: Some(crate::TargetQuality {
                metric: crate::QualityMetric::Ssim,
                value: 0.98,
            }),
            ..TransformOptions::default()
        };
        let b = TransformOptions {
            format: Some(MediaType::Jpeg),
            optimize: crate::OptimizeMode::Lossy,
            target_quality: Some(crate::TargetQuality {
                metric: crate::QualityMetric::Ssim,
                value: 0.99,
            }),
            ..TransformOptions::default()
        };

        assert_ne!(
            compute_cache_key("img.png", &a, None, None),
            compute_cache_key("img.png", &b, None, None)
        );
    }

    #[test]
    fn cache_key_matches_explicit_default_target_quality() {
        let implicit = TransformOptions {
            format: Some(MediaType::Jpeg),
            optimize: crate::OptimizeMode::Lossy,
            ..TransformOptions::default()
        };
        let explicit = TransformOptions {
            format: Some(MediaType::Jpeg),
            optimize: crate::OptimizeMode::Lossy,
            target_quality: default_lossy_target_quality(MediaType::Jpeg),
            ..TransformOptions::default()
        };

        assert_eq!(
            compute_cache_key("img.png", &implicit, None, None),
            compute_cache_key("img.png", &explicit, None, None)
        );
    }

    /// Helper to generate a deterministic 64-char hex key for testing.
    fn test_key(index: u8) -> String {
        let digest = Sha256::digest([index]);
        hex::encode(digest)
    }

    #[test]
    fn eviction_removes_oldest_entries_when_over_limit() {
        let dir = tempfile::tempdir().unwrap();
        let cache = TransformCache::new(dir.path().to_path_buf()).with_max_bytes(200);

        // Write four entries, each ~60 bytes on disk (header + body).
        // Total will exceed 200 bytes after all writes.
        let body = vec![0u8; 50];
        cache.put(&test_key(0), MediaType::Jpeg, &body);
        // Ensure distinct mtimes by touching the file timestamps manually.
        std::thread::sleep(std::time::Duration::from_millis(50));
        cache.put(&test_key(1), MediaType::Jpeg, &body);
        std::thread::sleep(std::time::Duration::from_millis(50));
        cache.put(&test_key(2), MediaType::Jpeg, &body);
        std::thread::sleep(std::time::Duration::from_millis(50));
        cache.put(&test_key(3), MediaType::Jpeg, &body);

        // Directly trigger eviction (maybe_evict is throttled in production).
        let _ = cache.evict_to_limit();

        // Collect remaining files.
        let remaining: Vec<_> = collect_cache_entries(dir.path())
            .unwrap()
            .into_iter()
            .map(|e| e.path)
            .collect();

        let total_size: u64 = collect_cache_entries(dir.path())
            .unwrap()
            .iter()
            .map(|e| e.size)
            .sum();

        assert!(
            total_size <= 200,
            "cache size {total_size} should be <= 200 after eviction"
        );
        // The most recent entry must survive.
        assert!(
            remaining.contains(&cache.entry_path(&test_key(3))),
            "newest entry should survive eviction"
        );
    }

    #[test]
    fn no_eviction_when_max_bytes_is_zero() {
        let dir = tempfile::tempdir().unwrap();
        let cache = TransformCache::new(dir.path().to_path_buf()).with_max_bytes(0);

        let body = vec![0u8; 100];
        for i in 0..5 {
            cache.put(&test_key(i), MediaType::Jpeg, &body);
        }

        let entries = collect_cache_entries(dir.path()).unwrap();
        assert_eq!(
            entries.len(),
            5,
            "all entries should survive when max_bytes is 0"
        );
    }

    #[test]
    fn no_eviction_when_under_limit() {
        let dir = tempfile::tempdir().unwrap();
        // Set a very generous limit.
        let cache = TransformCache::new(dir.path().to_path_buf()).with_max_bytes(1_000_000);

        let body = vec![0u8; 50];
        for i in 0..3 {
            cache.put(&test_key(i), MediaType::Jpeg, &body);
        }

        let entries = collect_cache_entries(dir.path()).unwrap();
        assert_eq!(
            entries.len(),
            3,
            "all entries should survive when under limit"
        );
    }

    #[test]
    fn collect_cache_entries_skips_temp_files() {
        let dir = tempfile::tempdir().unwrap();
        let cache = TransformCache::new(dir.path().to_path_buf());

        // Write a normal entry.
        cache.put(&test_key(0), MediaType::Jpeg, b"data");

        // Create a temp file that should be skipped.
        let key = test_key(1);
        let path = cache.entry_path(&key);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        let tmp_path = path.with_extension("tmp.12345.0");
        fs::write(&tmp_path, b"partial").unwrap();

        let entries = collect_cache_entries(dir.path()).unwrap();
        assert_eq!(entries.len(), 1, "temp files should be excluded from scan");
    }
}