Skip to main content

vibe_ticket/cache/
mod.rs

1use std::collections::HashMap;
2use std::sync::{Arc, RwLock};
3use std::time::{Duration, Instant};
4
5use crate::core::{Ticket, TicketId};
6
7/// A cached ticket entry with timestamp
8#[derive(Clone)]
9struct CachedEntry<T> {
10    data: T,
11    timestamp: Instant,
12}
13
14/// Thread-safe in-memory cache for tickets
15pub struct TicketCache {
16    /// Cache storage
17    cache: Arc<RwLock<HashMap<CacheKey, CachedEntry<CacheValue>>>>,
18    /// Time-to-live for cached entries
19    ttl: Duration,
20}
21
22/// Keys used in the cache
23#[derive(Clone, Debug, Hash, PartialEq, Eq)]
24enum CacheKey {
25    /// Single ticket by ID
26    Ticket(TicketId),
27    /// All tickets
28    AllTickets,
29}
30
31/// Values stored in the cache
32#[derive(Clone)]
33enum CacheValue {
34    /// Single ticket
35    Ticket(Box<Ticket>),
36    /// Multiple tickets
37    Tickets(Vec<Ticket>),
38}
39
40impl TicketCache {
41    /// Creates a new cache with the specified TTL
42    #[must_use]
43    pub fn new(ttl: Duration) -> Self {
44        Self {
45            cache: Arc::new(RwLock::new(HashMap::new())),
46            ttl,
47        }
48    }
49
50    /// Creates a new cache with a default TTL of 5 minutes
51    #[must_use]
52    pub fn with_default_ttl() -> Self {
53        Self::new(Duration::from_secs(300))
54    }
55
56    /// Gets a single ticket from cache
57    #[must_use]
58    pub fn get_ticket(&self, id: &TicketId) -> Option<Ticket> {
59        let entry = self
60            .cache
61            .read()
62            .ok()?
63            .get(&CacheKey::Ticket(id.clone()))?
64            .clone();
65
66        if self.is_expired(&entry.timestamp) {
67            return None;
68        }
69
70        match &entry.data {
71            CacheValue::Ticket(ticket) => Some((**ticket).clone()),
72            CacheValue::Tickets(_) => None,
73        }
74    }
75
76    /// Caches a single ticket
77    pub fn cache_ticket(&self, ticket: &Ticket) {
78        if let Ok(mut cache) = self.cache.write() {
79            let entry = CachedEntry {
80                data: CacheValue::Ticket(Box::new(ticket.clone())),
81                timestamp: Instant::now(),
82            };
83            cache.insert(CacheKey::Ticket(ticket.id.clone()), entry);
84        }
85    }
86
87    /// Gets all tickets from cache
88    #[must_use]
89    pub fn get_all_tickets(&self) -> Option<Vec<Ticket>> {
90        let entry = self.cache.read().ok()?.get(&CacheKey::AllTickets)?.clone();
91
92        if self.is_expired(&entry.timestamp) {
93            return None;
94        }
95
96        match &entry.data {
97            CacheValue::Tickets(tickets) => Some(tickets.clone()),
98            CacheValue::Ticket(_) => None,
99        }
100    }
101
102    /// Caches all tickets
103    pub fn cache_all_tickets(&self, tickets: &[Ticket]) {
104        if let Ok(mut cache) = self.cache.write() {
105            let entry = CachedEntry {
106                data: CacheValue::Tickets(tickets.to_vec()),
107                timestamp: Instant::now(),
108            };
109            cache.insert(CacheKey::AllTickets, entry);
110
111            // Also cache individual tickets
112            for ticket in tickets {
113                let ticket_entry = CachedEntry {
114                    data: CacheValue::Ticket(Box::new(ticket.clone())),
115                    timestamp: Instant::now(),
116                };
117                cache.insert(CacheKey::Ticket(ticket.id.clone()), ticket_entry);
118            }
119        }
120    }
121
122    /// Invalidates a specific ticket in the cache
123    pub fn invalidate_ticket(&self, id: &TicketId) {
124        if let Ok(mut cache) = self.cache.write() {
125            cache.remove(&CacheKey::Ticket(id.clone()));
126            // Also invalidate all tickets cache since it might contain outdated data
127            cache.remove(&CacheKey::AllTickets);
128        }
129    }
130
131    /// Invalidates all cached data
132    pub fn invalidate_all(&self) {
133        if let Ok(mut cache) = self.cache.write() {
134            cache.clear();
135        }
136    }
137
138    /// Checks if a timestamp has expired
139    fn is_expired(&self, timestamp: &Instant) -> bool {
140        timestamp.elapsed() > self.ttl
141    }
142
143    /// Removes expired entries from the cache
144    pub fn cleanup_expired(&self) {
145        if let Ok(mut cache) = self.cache.write() {
146            cache.retain(|_, entry| !self.is_expired(&entry.timestamp));
147        }
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154    use crate::core::{Priority, Status};
155    use std::thread;
156
157    fn create_test_ticket(suffix: &str) -> Ticket {
158        let id = format!("12345678-1234-1234-1234-{suffix:0>12}");
159        Ticket {
160            id: TicketId::parse_str(&id).unwrap(),
161            slug: format!("test-{suffix}"),
162            title: format!("Test Ticket {suffix}"),
163            description: String::new(),
164            priority: Priority::Medium,
165            status: Status::Todo,
166            tags: vec![],
167            created_at: chrono::Utc::now(),
168            started_at: None,
169            closed_at: None,
170            assignee: None,
171            tasks: vec![],
172            metadata: HashMap::new(),
173        }
174    }
175
176    #[test]
177    fn test_cache_and_retrieve_ticket() {
178        let cache = TicketCache::new(Duration::from_secs(60));
179        let ticket = create_test_ticket("1");
180
181        // Cache the ticket
182        cache.cache_ticket(&ticket);
183
184        // Retrieve it
185        let cached = cache.get_ticket(&ticket.id);
186        assert!(cached.is_some());
187        assert_eq!(cached.unwrap().id, ticket.id);
188    }
189
190    #[test]
191    fn test_cache_expiration() {
192        let cache = TicketCache::new(Duration::from_millis(100));
193        let ticket = create_test_ticket("2");
194
195        cache.cache_ticket(&ticket);
196
197        // Should exist immediately
198        assert!(cache.get_ticket(&ticket.id).is_some());
199
200        // Wait for expiration
201        thread::sleep(Duration::from_millis(150));
202
203        // Should be expired
204        assert!(cache.get_ticket(&ticket.id).is_none());
205    }
206
207    #[test]
208    fn test_cache_all_tickets() {
209        let cache = TicketCache::new(Duration::from_secs(60));
210        let tickets = vec![
211            create_test_ticket("3"),
212            create_test_ticket("4"),
213            create_test_ticket("5"),
214        ];
215
216        cache.cache_all_tickets(&tickets);
217
218        // Check all tickets cache
219        let cached_all = cache.get_all_tickets();
220        assert!(cached_all.is_some());
221        assert_eq!(cached_all.unwrap().len(), 3);
222
223        // Check individual tickets are also cached
224        assert!(cache.get_ticket(&tickets[0].id).is_some());
225        assert!(cache.get_ticket(&tickets[1].id).is_some());
226        assert!(cache.get_ticket(&tickets[2].id).is_some());
227    }
228
229    #[test]
230    fn test_cache_invalidation() {
231        let cache = TicketCache::new(Duration::from_secs(60));
232        let ticket = create_test_ticket("6");
233
234        cache.cache_ticket(&ticket);
235        assert!(cache.get_ticket(&ticket.id).is_some());
236
237        cache.invalidate_ticket(&ticket.id);
238        assert!(cache.get_ticket(&ticket.id).is_none());
239    }
240
241    #[test]
242    fn test_cleanup_expired() {
243        let cache = TicketCache::new(Duration::from_millis(100));
244        let ticket1 = create_test_ticket("7");
245        let ticket2 = create_test_ticket("8");
246
247        cache.cache_ticket(&ticket1);
248        thread::sleep(Duration::from_millis(150));
249        cache.cache_ticket(&ticket2);
250
251        // Before cleanup, expired ticket might still be in cache
252        cache.cleanup_expired();
253
254        // After cleanup, only non-expired ticket should remain
255        assert!(cache.get_ticket(&ticket1.id).is_none());
256        assert!(cache.get_ticket(&ticket2.id).is_some());
257    }
258}