vtcode_safety/command_safety/
cache.rs1use hashbrown::HashMap;
7use std::sync::Arc;
8use tokio::sync::Mutex;
9
10#[derive(Clone, Debug)]
12pub struct CachedDecision {
13 pub(crate) is_safe: bool,
15 pub(crate) reason: String,
17 access_count: u64,
19}
20
21pub struct SafetyDecisionCache {
23 cache: Arc<Mutex<HashMap<String, CachedDecision>>>,
24 max_size: usize,
25}
26
27impl SafetyDecisionCache {
28 pub(crate) fn new(max_size: usize) -> Self {
30 Self {
31 cache: Arc::new(Mutex::new(HashMap::new())),
32 max_size,
33 }
34 }
35
36 pub fn default_cache() -> Self {
38 Self::new(1000)
39 }
40
41 pub(crate) async fn get(&self, command: &str) -> Option<CachedDecision> {
43 let mut cache = self.cache.lock().await;
44 if let Some(decision) = cache.get_mut(command) {
45 decision.access_count += 1;
46 return Some(decision.clone());
47 }
48 None
49 }
50
51 pub(crate) async fn put(&self, command: String, is_safe: bool, reason: String) {
53 let mut cache = self.cache.lock().await;
54
55 if cache.len() >= self.max_size
56 && !cache.contains_key(&command)
57 && let Some(least_used) = cache
58 .iter()
59 .min_by_key(|(_, decision)| decision.access_count)
60 .map(|(k, _)| k.clone())
61 {
62 drop(cache.remove(&least_used));
63 }
64
65 drop(cache.insert(command, CachedDecision { is_safe, reason, access_count: 1 }));
66 }
67
68 async fn clear(&self) {
70 let mut cache = self.cache.lock().await;
71 cache.clear();
72 }
73
74 async fn size(&self) -> usize {
76 let cache = self.cache.lock().await;
77 cache.len()
78 }
79
80 async fn stats(&self) -> CacheStats {
82 let cache = self.cache.lock().await;
83 let total_accesses: u64 = cache.values().map(|d| d.access_count).sum();
84 let entry_count = cache.len();
85
86 CacheStats { entry_count, total_accesses }
87 }
88}
89
90impl Clone for SafetyDecisionCache {
91 fn clone(&self) -> Self {
92 Self {
93 cache: Arc::clone(&self.cache),
94 max_size: self.max_size,
95 }
96 }
97}
98
99#[derive(Debug, Clone)]
101pub struct CacheStats {
102 entry_count: usize,
103 total_accesses: u64,
104}
105
106#[cfg(test)]
107mod tests {
108 use super::*;
109
110 #[tokio::test]
111 async fn cache_stores_and_retrieves() {
112 let cache = SafetyDecisionCache::new(10);
113 cache
114 .put("git status".to_string(), true, "git status allowed".to_string())
115 .await;
116
117 let decision = cache.get("git status").await;
118 assert!(decision.is_some());
119 assert!(decision.unwrap().is_safe);
120 }
121
122 #[tokio::test]
123 async fn cache_returns_none_for_missing_key() {
124 let cache = SafetyDecisionCache::new(10);
125 let decision = cache.get("missing").await;
126 assert!(decision.is_none());
127 }
128
129 #[tokio::test]
130 async fn cache_tracks_access_count() {
131 let cache = SafetyDecisionCache::new(10);
132 cache.put("cmd".to_string(), true, "allowed".to_string()).await;
133
134 let d1 = cache.get("cmd").await.unwrap();
135 assert_eq!(d1.access_count, 2);
136
137 let d2 = cache.get("cmd").await.unwrap();
138 assert_eq!(d2.access_count, 3);
139 }
140
141 #[tokio::test]
142 async fn cache_respects_max_size() {
143 let cache = SafetyDecisionCache::new(3);
144
145 cache.put("cmd1".to_string(), true, "allowed".to_string()).await;
146 cache.put("cmd2".to_string(), true, "allowed".to_string()).await;
147 cache.put("cmd3".to_string(), true, "allowed".to_string()).await;
148
149 assert_eq!(cache.size().await, 3);
150
151 cache.put("cmd4".to_string(), true, "allowed".to_string()).await;
153 assert_eq!(cache.size().await, 3);
154 }
155
156 #[tokio::test]
157 async fn cache_clears() {
158 let cache = SafetyDecisionCache::new(10);
159 cache.put("cmd".to_string(), true, "allowed".to_string()).await;
160 assert_eq!(cache.size().await, 1);
161
162 cache.clear().await;
163 assert_eq!(cache.size().await, 0);
164 }
165
166 #[tokio::test]
167 async fn cache_stats() {
168 let cache = SafetyDecisionCache::new(10);
169 cache.put("cmd1".to_string(), true, "allowed".to_string()).await;
170 cache.put("cmd2".to_string(), true, "allowed".to_string()).await;
171
172 let _d1 = cache.get("cmd1").await;
173 let _d2 = cache.get("cmd2").await;
174 let _d3 = cache.get("cmd2").await;
175
176 let stats = cache.stats().await;
177 assert_eq!(stats.entry_count, 2);
178 assert_eq!(stats.total_accesses, 5); }
180}