ferrite_cache/
types.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
use std::{collections::HashMap, path::PathBuf, sync::Arc, time::Instant};
use tracing::{debug, info};

use crate::CacheResult;
use tokio::sync::oneshot;

// Define all possible cache operations as an enum
#[derive(Debug)]
pub enum CacheRequest {
    // Request to cache and get an image
    CacheImage {
        path:        PathBuf,
        response_tx: oneshot::Sender<CacheResult<Arc<ImageData>>>,
    },
    // Request to get an already cached image
    GetImage {
        path:        PathBuf,
        response_tx: oneshot::Sender<CacheResult<Arc<ImageData>>>,
    },
    // Additional message types can be added here as needed
}

// Structure to handle communication with the cache manager
pub struct CacheHandle {
    request_tx: tokio::sync::mpsc::UnboundedSender<CacheRequest>,
}

impl CacheHandle {
    pub fn new(
        request_tx: tokio::sync::mpsc::UnboundedSender<CacheRequest>,
    ) -> Self {
        Self {
            request_tx,
        }
    }

    // Public API for requesting an image - this hides the channel communication
    pub fn get_image(&self, path: PathBuf) -> CacheResult<Arc<ImageData>> {
        // Create a one-shot channel for the response
        let (response_tx, response_rx) = oneshot::channel();

        // Send the request through the unbounded channel
        self.request_tx
            .send(CacheRequest::GetImage {
                path,
                response_tx,
            })
            .map_err(|_| {
                crate::CacheError::Config(
                    "Cache manager is shutdown".to_string(),
                )
            })?;

        // Wait for and return the response
        response_rx.blocking_recv().map_err(|_| {
            crate::CacheError::Config(
                "Cache manager stopped responding".to_string(),
            )
        })?
    }

    // Method to explicitly request caching an image
    pub fn cache_image(&self, path: PathBuf) -> CacheResult<Arc<ImageData>> {
        let (response_tx, response_rx) = oneshot::channel();

        self.request_tx
            .send(CacheRequest::CacheImage {
                path,
                response_tx,
            })
            .map_err(|_| {
                crate::CacheError::Config(
                    "Cache manager is shutdown".to_string(),
                )
            })?;

        response_rx.blocking_recv().map_err(|_| {
            crate::CacheError::Config(
                "Cache manager stopped responding".to_string(),
            )
        })?
    }
}

#[derive(Debug, Clone)]
pub struct ImageData {
    data:        Arc<Vec<u8>>,
    dimensions:  (u32, u32),
    accessed_at: Instant,
}

impl ImageData {
    pub fn new(data: Vec<u8>, dimensions: (u32, u32)) -> Self {
        debug!(
            width = dimensions.0,
            height = dimensions.1,
            size_bytes = data.len(),
            "Creating new ImageData instance"
        );

        Self {
            data: Arc::new(data),
            dimensions,
            accessed_at: Instant::now(),
        }
    }

    pub fn dimensions(&self) -> (u32, u32) {
        self.dimensions
    }

    pub fn data(&self) -> Arc<Vec<u8>> {
        self.data.clone()
    }

    pub fn touch(&mut self) {
        let previous = self.accessed_at;
        self.accessed_at = Instant::now();

        debug!(
            last_access = ?previous,
            new_access = ?self.accessed_at,
            "Updated image access time"
        );
    }

    pub fn simulate_copy(&self) -> Vec<u8> {
        // Simulate copying the full decoded image data
        self.data.to_vec()
    }
}

#[derive(Clone)]
pub struct CacheConfig {
    pub max_image_count: usize,
    pub thread_count:    usize,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            max_image_count: 100, thread_count: 4
        }
    }
}

pub(crate) struct CacheState {
    pub entries:  HashMap<PathBuf, ImageData>,
    pub lru_list: Vec<PathBuf>,
}

impl CacheState {
    pub fn new() -> Self {
        debug!("Initializing new cache state");

        Self {
            entries: HashMap::new(), lru_list: Vec::new()
        }
    }
}