1use std::num::NonZeroUsize;
16use std::path::{Path, PathBuf};
17use std::sync::{Arc, Condvar, Mutex, RwLock};
18use std::time::{Duration, Instant};
19use std::{fs::File, io::BufReader};
20
21use exif::{In, Reader as ExifReader, Tag};
22use lru::LruCache;
23
24use image::codecs::jpeg::JpegEncoder;
25use image::imageops::FilterType;
26use image::{DynamicImage, GenericImageView, ImageReader};
27
28use crate::services::image_utils::apply_exif_orientation;
29
30const THUMBNAIL_TIMEOUT: Duration = Duration::from_secs(10);
32
33static DECODER_LIMITER: std::sync::OnceLock<Arc<ConcurrencyLimiter>> = std::sync::OnceLock::new();
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41pub enum ThumbnailSize {
42 Small, Medium, Large, Original, }
47
48impl ThumbnailSize {
49 pub fn pixels(&self) -> u32 {
50 match self {
51 ThumbnailSize::Small => 260,
52 ThumbnailSize::Medium => 430,
53 ThumbnailSize::Large => 860,
54 ThumbnailSize::Original => u32::MAX,
55 }
56 }
57
58 pub fn dir_name(&self) -> &'static str {
59 match self {
60 ThumbnailSize::Small => "small",
61 ThumbnailSize::Medium => "medium",
62 ThumbnailSize::Large => "large",
63 ThumbnailSize::Original => "original",
64 }
65 }
66}
67
68#[derive(Debug, Clone)]
75pub struct ThumbnailEntry {
76 pub path: PathBuf,
77 pub file_size: u64,
78}
79
80const CACHE_ENTRY_CAPACITY: usize = 10_000;
86
87fn background_permits() -> usize {
91 std::thread::available_parallelism()
92 .map(|n| n.get() / 2)
93 .unwrap_or(1)
94 .clamp(1, 3)
95}
96
97struct ConcurrencyLimiter {
103 max: usize,
104 max_background: usize,
105 state: Mutex<LimiterState>,
106 cv: Condvar,
107}
108
109#[derive(Debug, Default)]
110struct LimiterState {
111 foreground_active: usize,
112 background_active: usize,
113 foreground_waiting: usize,
114}
115
116#[derive(Debug, Clone, Copy)]
117enum GenerationPriority {
118 Foreground,
119 Background,
120}
121
122impl ConcurrencyLimiter {
123 fn new(max: usize, max_background: usize) -> Self {
124 Self {
125 max,
126 max_background,
127 state: Mutex::new(LimiterState::default()),
128 cv: Condvar::new(),
129 }
130 }
131
132 fn acquire(self: &Arc<Self>, priority: GenerationPriority) -> ConcurrencyPermit {
136 let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
137 if matches!(priority, GenerationPriority::Foreground) {
138 state.foreground_waiting += 1;
139 }
140
141 loop {
142 let active = state.foreground_active + state.background_active;
143 let can_acquire = match priority {
144 GenerationPriority::Foreground => active < self.max,
145 GenerationPriority::Background => {
146 active < self.max
147 && state.background_active < self.max_background
148 && state.foreground_waiting == 0
149 }
150 };
151
152 if can_acquire {
153 match priority {
154 GenerationPriority::Foreground => {
155 state.foreground_waiting = state.foreground_waiting.saturating_sub(1);
156 state.foreground_active += 1;
157 }
158 GenerationPriority::Background => {
159 state.background_active += 1;
160 }
161 }
162 break;
163 }
164
165 state = self.cv.wait(state).unwrap_or_else(|e| e.into_inner());
166 }
167
168 ConcurrencyPermit {
169 limiter: self.clone(),
170 priority,
171 }
172 }
173
174 fn acquire_for(
177 self: &Arc<Self>,
178 priority: GenerationPriority,
179 timeout: Duration,
180 ) -> Option<ConcurrencyPermit> {
181 let deadline = Instant::now() + timeout;
182 let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
183 if matches!(priority, GenerationPriority::Foreground) {
184 state.foreground_waiting += 1;
185 }
186 loop {
187 let active = state.foreground_active + state.background_active;
188 let can_acquire = match priority {
189 GenerationPriority::Foreground => active < self.max,
190 GenerationPriority::Background => {
191 active < self.max
192 && state.background_active < self.max_background
193 && state.foreground_waiting == 0
194 }
195 };
196 if can_acquire {
197 if matches!(priority, GenerationPriority::Foreground) {
198 state.foreground_waiting = state.foreground_waiting.saturating_sub(1);
199 state.foreground_active += 1;
200 } else {
201 state.background_active += 1;
202 }
203 return Some(ConcurrencyPermit {
204 limiter: self.clone(),
205 priority,
206 });
207 }
208 let remaining = deadline.saturating_duration_since(Instant::now());
209 if remaining.is_zero() {
210 if matches!(priority, GenerationPriority::Foreground) {
211 state.foreground_waiting = state.foreground_waiting.saturating_sub(1);
212 }
213 return None;
214 }
215 let (next, timed_out) = self
216 .cv
217 .wait_timeout(state, remaining)
218 .unwrap_or_else(|e| e.into_inner());
219 state = next;
220 if timed_out.timed_out() {
221 if matches!(priority, GenerationPriority::Foreground) {
222 state.foreground_waiting = state.foreground_waiting.saturating_sub(1);
223 }
224 return None;
225 }
226 }
227 }
228
229 fn release(&self, priority: GenerationPriority) {
231 {
232 let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
233 match priority {
234 GenerationPriority::Foreground => {
235 state.foreground_active = state.foreground_active.saturating_sub(1);
236 }
237 GenerationPriority::Background => {
238 state.background_active = state.background_active.saturating_sub(1);
239 }
240 }
241 }
242 self.cv.notify_all();
243 }
244}
245
246struct ConcurrencyPermit {
247 limiter: Arc<ConcurrencyLimiter>,
248 priority: GenerationPriority,
249}
250
251impl Drop for ConcurrencyPermit {
252 fn drop(&mut self) {
253 self.limiter.release(self.priority);
254 }
255}
256
257struct GenerationDeduper {
258 active: Mutex<std::collections::HashSet<String>>,
259 cv: Condvar,
260}
261
262impl GenerationDeduper {
263 fn new() -> Self {
264 Self {
265 active: Mutex::new(std::collections::HashSet::new()),
266 cv: Condvar::new(),
267 }
268 }
269
270 fn enter(self: &Arc<Self>, key: String) -> GenerationGuard {
271 let mut active = self.active.lock().unwrap_or_else(|e| e.into_inner());
272 while active.contains(&key) {
273 active = self.cv.wait(active).unwrap_or_else(|e| e.into_inner());
274 }
275 active.insert(key.clone());
276 GenerationGuard {
277 deduper: self.clone(),
278 key,
279 }
280 }
281
282 fn leave(&self, key: &str) {
283 {
284 let mut active = self.active.lock().unwrap_or_else(|e| e.into_inner());
285 active.remove(key);
286 }
287 self.cv.notify_all();
288 }
289}
290
291struct GenerationGuard {
292 deduper: Arc<GenerationDeduper>,
293 key: String,
294}
295
296impl Drop for GenerationGuard {
297 fn drop(&mut self) {
298 self.deduper.leave(&self.key);
299 }
300}
301
302pub struct ThumbnailService {
304 drive_root: PathBuf,
308
309 cache: Arc<RwLock<LruCache<(String, ThumbnailSize), ThumbnailEntry>>>,
315
316 max_cache_bytes: u64,
318
319 current_cache_bytes: Arc<RwLock<u64>>,
321 accounting: Mutex<()>,
323 eviction: Mutex<()>,
326
327 generation_limiter: Arc<ConcurrencyLimiter>,
329
330 generating: Arc<GenerationDeduper>,
333}
334
335impl ThumbnailService {
336 pub fn new<P: AsRef<Path>>(drive_root: P, max_cache_gb: f64) -> std::io::Result<Self> {
338 let drive_root = drive_root.as_ref().to_path_buf();
339 let cache_dir = crate::services::cache_location::thumbnails_dir(&drive_root);
340
341 for size in [
343 ThumbnailSize::Small,
344 ThumbnailSize::Medium,
345 ThumbnailSize::Large,
346 ThumbnailSize::Original,
347 ] {
348 std::fs::create_dir_all(cache_dir.join(size.dir_name()))?;
349 }
350
351 let max_cache_bytes = (max_cache_gb * 1024.0 * 1024.0 * 1024.0) as u64;
352
353 let capacity = NonZeroUsize::new(CACHE_ENTRY_CAPACITY)
354 .expect("CACHE_ENTRY_CAPACITY is a non-zero compile-time constant");
355
356 Ok(Self {
357 drive_root,
358 cache: Arc::new(RwLock::new(LruCache::new(capacity))),
359 max_cache_bytes,
360 current_cache_bytes: Arc::new(RwLock::new(0)),
361 accounting: Mutex::new(()),
362 eviction: Mutex::new(()),
363 generation_limiter: Arc::new(ConcurrencyLimiter::new(4, background_permits())),
367 generating: Arc::new(GenerationDeduper::new()),
368 })
369 }
370
371 pub fn generate_thumbnail(
375 &self,
376 photo_path: &Path,
377 file_hash: &str,
378 orientation: i32,
379 size: ThumbnailSize,
380 ) -> Result<PathBuf, String> {
381 self.generate_thumbnail_with_priority(
382 photo_path,
383 file_hash,
384 orientation,
385 size,
386 GenerationPriority::Foreground,
387 false,
388 )
389 }
390
391 pub fn generate_thumbnail_background(
392 &self,
393 photo_path: &Path,
394 file_hash: &str,
395 orientation: i32,
396 size: ThumbnailSize,
397 ) -> Result<PathBuf, String> {
398 self.generate_thumbnail_with_priority(
399 photo_path,
400 file_hash,
401 orientation,
402 size,
403 GenerationPriority::Background,
404 false,
405 )
406 }
407
408 pub fn generate_background_batch(
416 &self,
417 items: &[(PathBuf, String, i32)],
418 size: ThumbnailSize,
419 force: bool,
420 cancel: &std::sync::atomic::AtomicBool,
421 ) -> Vec<Option<Result<PathBuf, String>>> {
422 use std::sync::atomic::{AtomicUsize, Ordering};
423 let results: Vec<Mutex<Option<Result<PathBuf, String>>>> =
424 items.iter().map(|_| Mutex::new(None)).collect();
425 let next = AtomicUsize::new(0);
426 let workers = background_permits().min(items.len()).max(1);
427 std::thread::scope(|scope| {
428 for _ in 0..workers {
429 scope.spawn(|| loop {
430 if cancel.load(Ordering::Relaxed) {
431 break;
432 }
433 let index = next.fetch_add(1, Ordering::Relaxed);
434 let Some((path, hash, orientation)) = items.get(index) else {
435 break;
436 };
437 let result = if force {
438 self.generate_thumbnail_background_forced(path, hash, *orientation, size)
439 } else {
440 self.generate_thumbnail_background(path, hash, *orientation, size)
441 };
442 *results[index].lock().unwrap_or_else(|e| e.into_inner()) = Some(result);
443 });
444 }
445 });
446 results
447 .into_iter()
448 .map(|slot| slot.into_inner().unwrap_or_else(|e| e.into_inner()))
449 .collect()
450 }
451
452 pub fn generate_thumbnail_background_forced(
456 &self,
457 photo_path: &Path,
458 file_hash: &str,
459 orientation: i32,
460 size: ThumbnailSize,
461 ) -> Result<PathBuf, String> {
462 self.generate_thumbnail_with_priority(
463 photo_path,
464 file_hash,
465 orientation,
466 size,
467 GenerationPriority::Background,
468 true,
469 )
470 }
471
472 fn generate_thumbnail_with_priority(
473 &self,
474 photo_path: &Path,
475 file_hash: &str,
476 orientation: i32,
477 size: ThumbnailSize,
478 priority: GenerationPriority,
479 force: bool,
480 ) -> Result<PathBuf, String> {
481 let thumb_path = self.thumbnail_path(file_hash, size);
482 if !force && self.try_existing_thumbnail(file_hash, size, &thumb_path) {
483 return Ok(thumb_path);
484 }
485
486 let key = format!("{}:{file_hash}", size.dir_name());
487 let _generation = self.generating.enter(key);
488 if !force && self.try_existing_thumbnail(file_hash, size, &thumb_path) {
489 return Ok(thumb_path);
490 }
491
492 let _permit = self.generation_limiter.acquire(priority);
493 let start = Instant::now();
494 self.generate_thumbnail_inner(photo_path, file_hash, orientation, size, start, force)
495 }
496
497 fn generate_thumbnail_inner(
499 &self,
500 photo_path: &Path,
501 file_hash: &str,
502 orientation: i32,
503 size: ThumbnailSize,
504 start: Instant,
505 force: bool,
506 ) -> Result<PathBuf, String> {
507 let thumb_path = self.thumbnail_path(file_hash, size);
509 if !force && self.try_existing_thumbnail(file_hash, size, &thumb_path) {
510 return Ok(thumb_path);
511 }
512
513 if let Some(parent) = thumb_path.parent() {
517 std::fs::create_dir_all(parent)
518 .map_err(|e| format!("Failed to create thumbnail subdirectory: {}", e))?;
519 }
520
521 if start.elapsed() > THUMBNAIL_TIMEOUT {
523 return Err("Thumbnail generation timed out before decode".to_string());
524 }
525
526 let img = Self::decode_with_timeout(photo_path, size)?;
534 let img = apply_exif_orientation(img, orientation);
535
536 if start.elapsed() > THUMBNAIL_TIMEOUT {
538 return Err("Thumbnail generation timed out after decode".to_string());
539 }
540
541 let thumb = if size == ThumbnailSize::Original {
543 img
544 } else {
545 self.create_thumbnail(&img, size)
546 };
547
548 if start.elapsed() > THUMBNAIL_TIMEOUT {
551 return Err("Thumbnail generation timed out after resize".to_string());
552 }
553
554 let quality = match size {
558 ThumbnailSize::Small => 78,
559 ThumbnailSize::Medium => 83,
560 ThumbnailSize::Large => 88,
561 ThumbnailSize::Original => 95,
562 };
563 let mut out =
564 tempfile::NamedTempFile::new_in(thumb_path.parent().expect("cache directory"))
565 .map_err(|e| format!("Failed to create thumbnail file: {}", e))?;
566 let mut encoder = JpegEncoder::new_with_quality(&mut out, quality);
567 encoder
568 .encode_image(&thumb)
569 .map_err(|e| format!("Failed to encode thumbnail: {}", e))?;
570 {
571 let _accounting = self
575 .accounting
576 .lock()
577 .unwrap_or_else(|error| error.into_inner());
578 let replaced_bytes = std::fs::metadata(&thumb_path).map(|m| m.len()).unwrap_or(0);
579 out.persist(&thumb_path)
580 .map_err(|e| format!("Failed to publish thumbnail: {e}"))?;
581 if let Ok(mut current) = self.current_cache_bytes.write() {
582 *current = current.saturating_sub(replaced_bytes);
583 }
584 }
585 self.add_to_cache(file_hash, size, &thumb_path);
586 self.track_cache_size(&thumb_path);
587 self.evict_if_needed(Some(&thumb_path));
588
589 Ok(thumb_path)
590 }
591
592 fn try_existing_thumbnail(
593 &self,
594 file_hash: &str,
595 size: ThumbnailSize,
596 thumb_path: &Path,
597 ) -> bool {
598 if !thumb_path.exists() {
599 return false;
600 }
601 let file_size = std::fs::metadata(thumb_path).map(|m| m.len()).unwrap_or(0);
602 if file_size == 0 {
603 return false;
604 }
605 if file_size <= 5000 && !Self::thumbnail_dimensions_are_adequate(thumb_path, size) {
610 return false;
611 }
612 self.add_to_cache(file_hash, size, thumb_path);
613 true
614 }
615
616 fn thumbnail_dimensions_are_adequate(thumb_path: &Path, size: ThumbnailSize) -> bool {
617 ImageReader::open(thumb_path)
618 .ok()
619 .and_then(|r| r.with_guessed_format().ok())
620 .and_then(|r| r.into_dimensions().ok())
621 .map(|(width, height)| {
622 (size == ThumbnailSize::Original && width > 0 && height > 0)
623 || width.max(height) >= size.pixels()
624 })
625 .unwrap_or(false)
626 }
627
628 fn decode_image_fast(
634 photo_path: &Path,
635 target_size: ThumbnailSize,
636 ) -> Result<DynamicImage, String> {
637 let ext = photo_path
643 .extension()
644 .and_then(|e| e.to_str())
645 .map(|e| e.to_ascii_lowercase());
646 if matches!(ext.as_deref(), Some("heic") | Some("heif"))
647 || ext
648 .as_deref()
649 .is_some_and(crate::services::image_io::is_raw_extension)
650 {
651 return crate::services::image_io::open_image(photo_path);
652 }
653
654 if matches!(ext.as_deref(), Some("jpg") | Some("jpeg")) {
655 if let Some(img) = Self::decode_embedded_jpeg_thumbnail(photo_path, target_size) {
656 return Ok(img);
657 }
658 }
659
660 let reader =
661 ImageReader::open(photo_path).map_err(|e| format!("Failed to open image: {}", e))?;
662
663 let reader = reader
665 .with_guessed_format()
666 .map_err(|e| format!("Failed to guess image format: {}", e))?;
667
668 let mut limits = image::Limits::default();
674 limits.max_alloc = Some(384 * 1024 * 1024);
675
676 let mut reader = reader;
677 reader.limits(limits);
678
679 let img = reader
680 .decode()
681 .map_err(|e| format!("Failed to decode image: {}", e))?;
682
683 Ok(img)
684 }
685
686 fn decode_with_timeout(
693 photo_path: &Path,
694 target_size: ThumbnailSize,
695 ) -> Result<DynamicImage, String> {
696 let decoder_permit = DECODER_LIMITER
697 .get_or_init(|| Arc::new(ConcurrencyLimiter::new(8, 8)))
698 .acquire_for(GenerationPriority::Foreground, THUMBNAIL_TIMEOUT)
699 .ok_or_else(|| "thumbnail decoder admission timed out; retry shortly".to_string())?;
700 let (tx, rx) = std::sync::mpsc::channel::<Result<DynamicImage, String>>();
701 let path = photo_path.to_path_buf();
702 std::thread::spawn(move || {
703 let _decoder_permit = decoder_permit;
704 let _ = tx.send(crate::services::image_io::catch_decode(&path, || {
705 Self::decode_image_fast(&path, target_size)
706 }));
707 });
708 match rx.recv_timeout(THUMBNAIL_TIMEOUT) {
709 Ok(result) => result,
710 Err(_) => Err(format!(
711 "decode timed out after {}s (source unreadable?)",
712 THUMBNAIL_TIMEOUT.as_secs()
713 )),
714 }
715 }
716
717 fn decode_embedded_jpeg_thumbnail(
718 photo_path: &Path,
719 target_size: ThumbnailSize,
720 ) -> Option<DynamicImage> {
721 let file = File::open(photo_path).ok()?;
722 let mut reader = BufReader::new(file);
723 let exif = ExifReader::new().read_from_container(&mut reader).ok()?;
724 let offset = exif
725 .get_field(Tag::JPEGInterchangeFormat, In::THUMBNAIL)
726 .and_then(|f| f.value.get_uint(0))? as usize;
727 let len = exif
728 .get_field(Tag::JPEGInterchangeFormatLength, In::THUMBNAIL)
729 .and_then(|f| f.value.get_uint(0))? as usize;
730 let end = offset.checked_add(len)?;
731 let bytes = exif.buf().get(offset..end)?;
732 let img = crate::services::image_io::catch_decode(photo_path, || {
733 image::load_from_memory(bytes).map_err(|e| e.to_string())
734 })
735 .ok()?;
736 let (width, height) = img.dimensions();
737 if width.max(height) < target_size.pixels() {
738 return None;
739 }
740 Some(img)
741 }
742
743 fn track_cache_size(&self, thumb_path: &Path) {
745 let file_size = std::fs::metadata(thumb_path).map(|m| m.len()).unwrap_or(0);
746 if let Ok(mut current) = self.current_cache_bytes.write() {
747 *current += file_size;
748 }
749 }
750
751 fn create_thumbnail(&self, img: &DynamicImage, size: ThumbnailSize) -> DynamicImage {
758 if size == ThumbnailSize::Original {
759 return img.clone();
760 }
761 let max_dim = size.pixels();
762 let (width, height) = img.dimensions();
763
764 let (new_width, new_height) = if width > height {
766 let ratio = max_dim as f64 / width as f64;
767 (max_dim, (height as f64 * ratio) as u32)
768 } else {
769 let ratio = max_dim as f64 / height as f64;
770 ((width as f64 * ratio) as u32, max_dim)
771 };
772
773 let filter = match size {
774 ThumbnailSize::Small => FilterType::Triangle,
775 ThumbnailSize::Medium => FilterType::CatmullRom,
776 ThumbnailSize::Large => FilterType::Lanczos3,
777 ThumbnailSize::Original => unreachable!("originals are not resized"),
778 };
779 img.resize(new_width, new_height, filter)
780 }
781
782 fn cache_dir(&self) -> PathBuf {
784 crate::services::cache_location::thumbnails_dir(&self.drive_root)
785 }
786
787 pub fn forget_cached_paths(&self) {
789 if let Ok(mut cache) = self.cache.write() {
790 cache.clear();
791 }
792 }
793
794 fn thumbnail_path(&self, file_hash: &str, size: ThumbnailSize) -> PathBuf {
797 let subdir = &file_hash[..2.min(file_hash.len())];
799
800 self.cache_dir()
801 .join(size.dir_name())
802 .join("v2")
803 .join(subdir)
804 .join(format!("{}.jpg", file_hash))
805 }
806
807 fn add_to_cache(&self, file_hash: &str, size: ThumbnailSize, path: &Path) {
809 let file_size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
810
811 let entry = ThumbnailEntry {
812 path: path.to_path_buf(),
813 file_size,
814 };
815
816 if let Ok(mut cache) = self.cache.write() {
817 cache.put((file_hash.to_string(), size), entry);
818 }
819 }
820
821 fn evict_if_needed(&self, protected: Option<&Path>) {
826 let _eviction_guard = match self.eviction.lock() {
827 Ok(guard) => guard,
828 Err(_) => return,
829 };
830 let current = match self.current_cache_bytes.read() {
831 Ok(v) => *v,
832 Err(_) => return,
833 };
834
835 if current <= self.max_cache_bytes {
836 return;
837 }
838
839 let target = self.max_cache_bytes * 80 / 100;
840 let mut freed = 0u64;
841
842 let tracked: std::collections::HashSet<PathBuf> = self
846 .cache
847 .read()
848 .map(|cache| cache.iter().map(|(_, entry)| entry.path.clone()).collect())
849 .unwrap_or_default();
850 for size in [
851 ThumbnailSize::Small,
852 ThumbnailSize::Medium,
853 ThumbnailSize::Large,
854 ThumbnailSize::Original,
855 ] {
856 for entry in walkdir::WalkDir::new(self.cache_dir().join(size.dir_name()).join("v2"))
857 .follow_links(false)
858 .follow_root_links(false)
859 .into_iter()
860 .filter_map(Result::ok)
861 {
862 if current.saturating_sub(freed) <= target {
863 break;
864 }
865 let path = entry.path();
866 if !entry.file_type().is_file()
867 || path.extension().is_none_or(|ext| ext != "jpg")
868 || tracked.contains(path)
869 || protected == Some(path)
870 {
871 continue;
872 }
873 if let Ok(metadata) = entry.metadata() {
874 if std::fs::remove_file(path).is_ok() {
875 freed += metadata.len();
876 }
877 }
878 }
879 }
880
881 loop {
885 if current.saturating_sub(freed) <= target {
886 break;
887 }
888 let popped = {
889 let mut cache = match self.cache.write() {
890 Ok(c) => c,
891 Err(_) => break,
892 };
893 cache.pop_lru()
894 };
895
896 let Some((key, entry)) = popped else { break };
897 if protected == Some(entry.path.as_path()) {
898 if let Ok(mut cache) = self.cache.write() {
899 cache.put(key, entry);
900 }
901 break;
902 }
903
904 if std::fs::remove_file(&entry.path).is_ok() {
905 freed += entry.file_size;
906 }
907
908 if current.saturating_sub(freed) <= target {
909 break;
910 }
911 }
912
913 if let Ok(mut current) = self.current_cache_bytes.write() {
914 *current = current.saturating_sub(freed);
915 }
916
917 tracing::info!("Evicted {} bytes from thumbnail cache", freed);
918 }
919
920 pub fn load_existing_thumbnails(&self) -> std::io::Result<()> {
922 self.load_existing_thumbnails_until(&std::sync::atomic::AtomicBool::new(false))
923 }
924
925 pub fn load_existing_thumbnails_until(
926 &self,
927 cancel: &std::sync::atomic::AtomicBool,
928 ) -> std::io::Result<()> {
929 let mut total_size = 0u64;
936
937 for size in [
938 ThumbnailSize::Small,
939 ThumbnailSize::Medium,
940 ThumbnailSize::Large,
941 ThumbnailSize::Original,
942 ] {
943 let size_dir = self.cache_dir().join(size.dir_name()).join("v2");
944
945 if !size_dir.exists() {
946 continue;
947 }
948
949 for subdir_entry in std::fs::read_dir(&size_dir)? {
950 let subdir_entry = subdir_entry?;
951 if !subdir_entry.file_type()?.is_dir() {
952 continue;
953 }
954
955 for file_entry in std::fs::read_dir(subdir_entry.path())? {
956 if cancel.load(std::sync::atomic::Ordering::Relaxed) {
957 return Ok(());
958 }
959 let file_entry = file_entry?;
960 if !file_entry.file_type()?.is_file() {
961 continue;
962 }
963 let path = file_entry.path();
964
965 if path.extension().map(|e| e == "jpg").unwrap_or(false) {
966 if let Some(stem) = path.file_stem() {
967 let hash = stem.to_string_lossy().to_string();
968 let file_size = file_entry.metadata()?.len();
969
970 total_size += file_size;
971
972 let entry = ThumbnailEntry {
973 path: path.clone(),
974 file_size,
975 };
976
977 if let Ok(mut cache) = self.cache.write() {
978 cache.put((hash, size), entry);
979 }
980 }
981 }
982 }
983 }
984 }
985
986 {
987 let _accounting = self
988 .accounting
989 .lock()
990 .unwrap_or_else(|error| error.into_inner());
991 if let Ok(mut current) = self.current_cache_bytes.write() {
992 *current = total_size;
993 }
994 }
995 self.evict_if_needed(None);
996
997 let count = self.cache.read().map(|c| c.len()).unwrap_or(0);
998 tracing::info!(
999 "Loaded {} existing thumbnails ({} MB)",
1000 count,
1001 total_size / 1024 / 1024
1002 );
1003
1004 Ok(())
1005 }
1006}
1007
1008#[cfg(test)]
1009mod tests {
1010 use super::*;
1011
1012 #[test]
1013 fn inventory_evicts_untracked_files_and_restarts_with_exact_accounting() {
1014 let dir = tempfile::tempdir().unwrap();
1015 let mut service = ThumbnailService::new(dir.path(), 1.0).unwrap();
1016 let folder = service.cache_dir().join("small/v2/ab");
1017 std::fs::create_dir_all(&folder).unwrap();
1018 for i in 0..CACHE_ENTRY_CAPACITY + 5 {
1019 std::fs::write(folder.join(format!("ab{i:08x}.jpg")), [1u8]).unwrap();
1020 }
1021 service.load_existing_thumbnails().unwrap();
1022 assert_eq!(service.cache.read().unwrap().len(), CACHE_ENTRY_CAPACITY);
1023 service.cache.write().unwrap().clear();
1026 service.max_cache_bytes = 10;
1027 service.evict_if_needed(None);
1028 let remaining = std::fs::read_dir(&folder).unwrap().count() as u64;
1029 assert!(remaining <= 8);
1030 assert_eq!(*service.current_cache_bytes.read().unwrap(), remaining);
1031 service.load_existing_thumbnails().unwrap();
1032 assert_eq!(*service.current_cache_bytes.read().unwrap(), remaining);
1033 }
1034
1035 #[test]
1036 fn repeated_inventory_does_not_double_count_published_renditions() {
1037 let dir = tempfile::tempdir().unwrap();
1038 let source = dir.path().join("source.png");
1039 DynamicImage::new_rgb8(48, 32).save(&source).unwrap();
1040 let service = ThumbnailService::new(dir.path(), 1.0).unwrap();
1041 let path = service
1042 .generate_thumbnail(&source, "abcdef12", 1, ThumbnailSize::Original)
1043 .unwrap();
1044 let size = std::fs::metadata(path).unwrap().len();
1045 service.load_existing_thumbnails().unwrap();
1046 service.load_existing_thumbnails().unwrap();
1047 assert_eq!(*service.current_cache_bytes.read().unwrap(), size);
1048 }
1049 use tempfile::tempdir;
1050
1051 #[test]
1052 fn test_thumbnail_path_generation() {
1053 let temp = tempdir().unwrap();
1054 let service = ThumbnailService::new(temp.path(), 1.0).unwrap();
1055
1056 let path = service.thumbnail_path("abcdef123456", ThumbnailSize::Medium);
1057
1058 assert!(path.to_string_lossy().contains("medium"));
1059 assert!(path.to_string_lossy().contains("ab")); assert!(path.to_string_lossy().contains("abcdef123456.jpg"));
1061 }
1062
1063 #[test]
1064 fn test_thumbnail_sizes() {
1065 assert_eq!(ThumbnailSize::Small.pixels(), 260);
1066 assert_eq!(ThumbnailSize::Medium.pixels(), 430);
1067 assert_eq!(ThumbnailSize::Large.pixels(), 860);
1068 }
1069
1070 #[test]
1071 fn test_cache_directories_created() {
1072 let temp = tempdir().unwrap();
1073 let _service = ThumbnailService::new(temp.path(), 1.0).unwrap();
1074
1075 assert!(temp.path().join(".photovault/thumbnails/small").exists());
1076 assert!(temp.path().join(".photovault/thumbnails/medium").exists());
1077 assert!(temp.path().join(".photovault/thumbnails/large").exists());
1078 }
1079
1080 #[test]
1081 fn small_but_dimensionally_valid_thumbnail_is_reused() {
1082 let temp = tempdir().unwrap();
1083 let service = ThumbnailService::new(temp.path(), 1.0).unwrap();
1084 let path = service.thumbnail_path("abcdef123456", ThumbnailSize::Small);
1085 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1086 DynamicImage::new_rgb8(ThumbnailSize::Small.pixels(), ThumbnailSize::Small.pixels())
1087 .save(&path)
1088 .unwrap();
1089
1090 assert!(std::fs::metadata(&path).unwrap().len() <= 5000);
1091 assert!(service.try_existing_thumbnail("abcdef123456", ThumbnailSize::Small, &path));
1092 }
1093
1094 #[test]
1095 fn test_generation_deduper_serializes_same_key() {
1096 let deduper = Arc::new(GenerationDeduper::new());
1097 let first = deduper.enter("medium:abc".into());
1098 let (tx, rx) = std::sync::mpsc::channel();
1099 let deduper_for_thread = deduper.clone();
1100
1101 let handle = std::thread::spawn(move || {
1102 let _second = deduper_for_thread.enter("medium:abc".into());
1103 tx.send(()).unwrap();
1104 });
1105
1106 assert!(rx.recv_timeout(Duration::from_millis(50)).is_err());
1107 drop(first);
1108 assert!(rx.recv_timeout(Duration::from_secs(1)).is_ok());
1109 handle.join().unwrap();
1110 }
1111
1112 #[test]
1113 fn test_concurrency_limiter_blocks_until_release() {
1114 use std::sync::Arc;
1115 use std::thread;
1116 use std::time::Duration;
1117
1118 let limiter = Arc::new(ConcurrencyLimiter::new(1, 1));
1119 let permit = limiter.acquire(GenerationPriority::Foreground);
1120
1121 let l = limiter.clone();
1125 let started = Arc::new(std::sync::atomic::AtomicBool::new(false));
1126 let s = started.clone();
1127 let handle = thread::spawn(move || {
1128 l.acquire(GenerationPriority::Foreground);
1129 s.store(true, std::sync::atomic::Ordering::Release);
1130 });
1131
1132 thread::sleep(Duration::from_millis(20));
1133 assert!(!started.load(std::sync::atomic::Ordering::Acquire));
1134
1135 drop(permit);
1136 handle.join().unwrap();
1137 assert!(started.load(std::sync::atomic::Ordering::Acquire));
1138 }
1139
1140 #[test]
1141 fn test_background_generation_is_capped() {
1142 use std::sync::mpsc;
1143 use std::sync::Arc;
1144 use std::thread;
1145 use std::time::Duration;
1146
1147 let limiter = Arc::new(ConcurrencyLimiter::new(4, 1));
1148 let permit = limiter.acquire(GenerationPriority::Background);
1149
1150 let (tx, rx) = mpsc::channel();
1151 let l = limiter.clone();
1152 let handle = thread::spawn(move || {
1153 let _permit = l.acquire(GenerationPriority::Background);
1154 tx.send(()).unwrap();
1155 });
1156
1157 thread::sleep(Duration::from_millis(20));
1158 assert!(rx.try_recv().is_err());
1159
1160 drop(permit);
1161 rx.recv_timeout(Duration::from_secs(1)).unwrap();
1162 handle.join().unwrap();
1163 }
1164
1165 #[test]
1166 fn test_waiting_foreground_generation_preempts_background() {
1167 use std::sync::mpsc;
1168 use std::sync::Arc;
1169 use std::thread;
1170 use std::time::Duration;
1171
1172 let limiter = Arc::new(ConcurrencyLimiter::new(1, 1));
1173 let permit = limiter.acquire(GenerationPriority::Background);
1174
1175 let (tx, rx) = mpsc::channel();
1176 let l = limiter.clone();
1177 let tx_foreground = tx.clone();
1178 let foreground = thread::spawn(move || {
1179 let _permit = l.acquire(GenerationPriority::Foreground);
1180 tx_foreground.send("foreground").unwrap();
1181 });
1182
1183 let deadline = std::time::Instant::now() + Duration::from_secs(1);
1186 loop {
1187 if limiter.state.lock().unwrap().foreground_waiting == 1 {
1188 break;
1189 }
1190 assert!(
1191 std::time::Instant::now() < deadline,
1192 "foreground waiter did not enter admission"
1193 );
1194 thread::yield_now();
1195 }
1196
1197 let l = limiter.clone();
1198 let background = thread::spawn(move || {
1199 let _permit = l.acquire(GenerationPriority::Background);
1200 tx.send("background").unwrap();
1201 });
1202
1203 assert!(rx.try_recv().is_err());
1204
1205 drop(permit);
1206 assert_eq!(
1207 rx.recv_timeout(Duration::from_secs(1)).unwrap(),
1208 "foreground"
1209 );
1210 assert_eq!(
1211 rx.recv_timeout(Duration::from_secs(1)).unwrap(),
1212 "background"
1213 );
1214
1215 foreground.join().unwrap();
1216 background.join().unwrap();
1217 }
1218}