vtcode_core/tools/resilience/
rate_limiter.rs1use anyhow::{Result, anyhow};
39use std::sync::{Mutex, MutexGuard};
40use std::time::Instant;
41
42#[derive(Debug, Clone, Copy)]
44pub struct RateLimiterConfig {
45 pub per_sec: u32,
47 pub burst: u32,
49}
50
51impl Default for RateLimiterConfig {
52 fn default() -> Self {
53 let per_sec = std::env::var("VTTOOL_RATE_LIMIT")
55 .ok()
56 .and_then(|v| v.parse().ok())
57 .unwrap_or(20);
58 let burst = std::env::var("VTTOOL_BURST")
59 .ok()
60 .and_then(|v| v.parse().ok())
61 .unwrap_or(per_sec.max(5));
62 RateLimiterConfig { per_sec, burst }
63 }
64}
65
66pub struct RateLimiterInner {
68 config: RateLimiterConfig,
69 tokens: u32,
71 last_refill: Instant,
73}
74
75impl RateLimiterInner {
76 fn new() -> Self {
77 Self::new_with_config(RateLimiterConfig::default())
78 }
79
80 pub fn new_with_config(config: RateLimiterConfig) -> Self {
81 Self {
82 config,
83 tokens: config.burst,
84 last_refill: Instant::now(),
85 }
86 }
87
88 fn refill(&mut self, speed_multiplier: f64) {
92 let now = Instant::now();
93 let elapsed = now.duration_since(self.last_refill);
94
95 let millis = elapsed.as_millis() as u64;
97
98 if millis < 50 {
100 return;
101 }
102
103 #[allow(
105 clippy::cast_sign_loss,
106 reason = "Intentional compatibility, platform, or test-only suppression."
107 )]
108 let effective_rate = ((self.config.per_sec as f64 * speed_multiplier).max(0.0)) as u64;
109
110 let added = u32::try_from(effective_rate.saturating_mul(millis) / 1000).unwrap_or(u32::MAX);
112
113 if added > 0 {
114 let effective_burst = self.config.burst as f64 * speed_multiplier.max(1.0);
115 #[allow(
116 clippy::cast_sign_loss,
117 reason = "Intentional compatibility, platform, or test-only suppression."
118 )]
119 let effective_burst: u32 =
120 if effective_burst.is_finite() && effective_burst >= 0.0 && effective_burst <= u32::MAX as f64 {
121 effective_burst as u32
122 } else {
123 u32::MAX
124 };
125 self.tokens = self.tokens.saturating_add(added).min(effective_burst);
126 self.last_refill = now;
127 }
128 }
129
130 pub fn try_acquire(&mut self) -> Result<()> {
132 self.try_acquire_scaled(1.0)
133 }
134
135 pub fn try_acquire_scaled(&mut self, speed_multiplier: f64) -> Result<()> {
137 self.refill(speed_multiplier);
138 if self.tokens == 0 {
139 Err(anyhow!("tool rate limit exceeded"))
140 } else {
141 self.tokens -= 1;
142 Ok(())
143 }
144 }
145}
146
147pub type RateLimiter = PerToolRateLimiter;
149
150use crate::types::CompactStr;
151use hashbrown::HashMap;
152use std::sync::LazyLock;
158
159pub static GLOBAL_RATE_LIMITER: LazyLock<Mutex<RateLimiterInner>> =
160 LazyLock::new(|| Mutex::new(RateLimiterInner::new()));
161
162pub struct PerToolRateLimiter {
165 buckets: HashMap<CompactStr, RateLimiterInner>,
167 default_config: RateLimiterConfig,
169}
170
171impl Default for PerToolRateLimiter {
172 fn default() -> Self {
173 Self::new()
174 }
175}
176
177impl PerToolRateLimiter {
178 pub fn new() -> Self {
180 Self {
181 buckets: HashMap::new(),
182 default_config: RateLimiterConfig::default(),
183 }
184 }
185
186 pub fn new_with_config(config: RateLimiterConfig) -> Self {
187 Self { buckets: HashMap::new(), default_config: config }
188 }
189
190 pub fn try_acquire_for(&mut self, tool_name: &str) -> Result<()> {
193 self.try_acquire_for_scaled(tool_name, 1.0)
194 }
195
196 pub fn try_acquire_for_scaled(&mut self, tool_name: &str, multiplier: f64) -> Result<()> {
198 let bucket = self
199 .buckets
200 .entry(CompactStr::from(tool_name))
201 .or_insert_with(|| RateLimiterInner::new_with_config(self.default_config));
202 bucket.try_acquire_scaled(multiplier)
203 }
204
205 pub fn acquire(&mut self, tool_name: &str) -> Result<()> {
207 self.try_acquire_for(tool_name)
208 }
209
210 pub fn is_limited(&mut self, tool_name: &str) -> bool {
212 if let Some(bucket) = self.buckets.get_mut(tool_name) {
213 bucket.refill(1.0); bucket.tokens == 0
215 } else {
216 false
217 }
218 }
219
220 pub fn reset_tool(&mut self, tool_name: &str) {
222 if let Some(bucket) = self.buckets.get_mut(tool_name) {
223 bucket.tokens = bucket.config.burst;
224 bucket.last_refill = Instant::now();
225 }
226 }
227}
228
229pub static PER_TOOL_RATE_LIMITER: LazyLock<Mutex<PerToolRateLimiter>> =
231 LazyLock::new(|| Mutex::new(PerToolRateLimiter::new()));
232
233pub fn try_acquire() -> Result<()> {
237 let mut guard: MutexGuard<'_, RateLimiterInner> =
238 GLOBAL_RATE_LIMITER.lock().map_err(|e| anyhow!("rate limiter poisoned: {e}"))?;
239 guard.try_acquire()
240}
241
242pub fn try_acquire_for(tool_name: &str) -> Result<()> {
245 let mut guard = PER_TOOL_RATE_LIMITER
246 .lock()
247 .map_err(|e| anyhow!("per-tool rate limiter poisoned: {e}"))?;
248 guard.try_acquire_for(tool_name)
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254
255 #[test]
256 fn test_global_limiter_allows_burst() {
257 let mut limiter = RateLimiterInner::new();
258 for _ in 0..limiter.config.burst {
260 limiter.try_acquire().unwrap();
261 }
262 assert!(limiter.try_acquire().is_err());
264 }
265
266 #[test]
267 fn test_per_tool_limiter_isolates_tools() {
268 let mut limiter = PerToolRateLimiter::new();
269 for _ in 0..5 {
271 let _ = limiter.try_acquire_for("tool_a");
272 }
273 limiter.try_acquire_for("tool_b").unwrap();
275 }
276
277 #[test]
278 fn test_reset_tool_restores_tokens() {
279 let mut limiter = PerToolRateLimiter::new();
280 let burst = limiter.default_config.burst;
282 for _ in 0..burst {
283 let _ = limiter.try_acquire_for("tool_x");
284 }
285 assert!(limiter.is_limited("tool_x"));
286 limiter.reset_tool("tool_x");
288 assert!(!limiter.is_limited("tool_x"));
289 }
290}