ferrite_cache/
manager.rs

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
use crate::{
    types::{CacheConfig, CacheState, ImageData},
    CacheError,
    CacheResult,
    ImageLoadError,
};
use image::GenericImageView;
use std::{path::PathBuf, sync::Arc};
use tokio::sync::RwLock;
use tracing::{debug, info, warn};

pub struct CacheManager {
    config: CacheConfig,
    state:  Arc<RwLock<CacheState>>,
}

impl CacheManager {
    pub fn new(config: CacheConfig) -> Self {
        info!(
            max_images = config.max_image_count,
            "Initializing cache manager"
        );
        Self {
            config,
            state: Arc::new(RwLock::new(CacheState::new())),
        }
    }

    pub async fn get_image(
        &self,
        path: PathBuf,
    ) -> CacheResult<Arc<ImageData>> {
        debug!(path = ?path, "Image requested from cache");

        if let Some(image) = self.lookup_image(&path).await {
            info!(path = ?path, "Cache hit");
            return Ok(image);
        }

        info!(path = ?path, "Cache miss, loading from disk");
        let image = self.load_and_cache(path).await?;
        Ok(image)
    }

    async fn lookup_image(&self, path: &PathBuf) -> Option<Arc<ImageData>> {
        let mut state = self.state.write().await;

        if let Some(image) = state.entries.get(path) {
            debug!(path = ?path, "Found image in cache");
            let mut image_data = image.clone();
            image_data.touch();
            state
                .entries
                .insert(path.clone(), image_data.clone());
            self.update_lru(path, &mut state).await;
            return Some(Arc::new(image_data));
        }
        debug!(path = ?path, "Image not found in cache");
        None
    }

    async fn load_and_cache(
        &self,
        path: PathBuf,
    ) -> CacheResult<Arc<ImageData>> {
        debug!(path = ?path, "Loading image from filesystem");

        let image_data = tokio::fs::read(&path).await.map_err(|e| {
            warn!(
                path = ?path,
                error = ?e,
                "Failed to read image file"
            );
            CacheError::ImageLoad {
                path:   path.clone(),
                source: ImageLoadError::Io(e),
            }
        })?;

        let image = image::load_from_memory(&image_data).map_err(|e| {
            warn!(
                path = ?path,
                error = ?e,
                "Failed to parse image data"
            );
            CacheError::ImageLoad {
                path:   path.clone(),
                source: ImageLoadError::Format(e.to_string()),
            }
        })?;

        let dimensions = image.dimensions();
        info!(
            path = ?path,
            width = dimensions.0,
            height = dimensions.1,
            "Successfully loaded image"
        );

        let image_data = ImageData::new(image_data, dimensions);
        let mut state = self.state.write().await;

        if state.entries.len() >= self.config.max_image_count {
            if let Some(oldest) = state.lru_list.first().cloned() {
                info!(
                    path = ?oldest,
                    "Evicting least recently used image"
                );
                state.entries.remove(&oldest);
                state.lru_list.remove(0);
            }
        }

        debug!(
            path = ?path,
            cache_size = state.entries.len(),
            "Adding image to cache"
        );

        state
            .entries
            .insert(path.clone(), image_data.clone());
        state.lru_list.push(path);

        Ok(Arc::new(image_data))
    }

    async fn update_lru(&self, path: &PathBuf, state: &mut CacheState) {
        if let Some(pos) = state.lru_list.iter().position(|p| p == path) {
            state.lru_list.remove(pos);
        }
        state.lru_list.push(path.clone());
        debug!(
            path = ?path,
            list_size = state.lru_list.len(),
            "Updated LRU list"
        );
    }
}

impl Default for CacheManager {
    fn default() -> Self {
        Self::new(CacheConfig::default())
    }
}