Skip to main content

camel_processor/
throttler.rs

1use std::future::Future;
2use std::pin::Pin;
3use std::sync::Mutex;
4use std::task::{Context, Poll};
5use std::time::{Duration, Instant};
6
7use tower::Service;
8
9use camel_api::{BoxProcessor, CamelError, Exchange, ThrottleStrategy, ThrottlerConfig, Value};
10
11const CAMEL_STOP: &str = "CamelStop";
12
13struct RateLimiter {
14    tokens: f64,
15    max_tokens: f64,
16    refill_rate: f64,
17    last_refill: Instant,
18}
19
20impl RateLimiter {
21    fn new(max_requests: usize, period: Duration) -> Self {
22        let refill_rate = max_requests as f64 / period.as_secs_f64();
23        Self {
24            tokens: max_requests as f64,
25            max_tokens: max_requests as f64,
26            refill_rate,
27            last_refill: Instant::now(),
28        }
29    }
30
31    fn try_acquire(&mut self) -> bool {
32        let now = Instant::now();
33        let elapsed = now.duration_since(self.last_refill).as_secs_f64();
34        if elapsed > 0.0 {
35            self.tokens = (self.tokens + elapsed * self.refill_rate).min(self.max_tokens);
36            self.last_refill = now;
37        }
38        if self.tokens >= 1.0 {
39            self.tokens -= 1.0;
40            true
41        } else {
42            false
43        }
44    }
45
46    fn time_until_next_token(&self) -> Duration {
47        if self.tokens >= 1.0 {
48            Duration::ZERO
49        } else {
50            let tokens_needed = 1.0 - self.tokens;
51            Duration::from_secs_f64(tokens_needed / self.refill_rate)
52        }
53    }
54}
55
56#[derive(Clone)]
57pub struct ThrottlerService {
58    config: ThrottlerConfig,
59    limiter: std::sync::Arc<Mutex<RateLimiter>>,
60    next: BoxProcessor,
61}
62
63impl ThrottlerService {
64    pub fn new(config: ThrottlerConfig, next: BoxProcessor) -> Self {
65        let limiter = RateLimiter::new(config.max_requests, config.period);
66        Self {
67            config,
68            limiter: std::sync::Arc::new(Mutex::new(limiter)),
69            next,
70        }
71    }
72}
73
74impl Service<Exchange> for ThrottlerService {
75    type Response = Exchange;
76    type Error = CamelError;
77    type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
78
79    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
80        self.next.poll_ready(cx)
81    }
82
83    fn call(&mut self, mut exchange: Exchange) -> Self::Future {
84        let config = self.config.clone();
85        let limiter = self.limiter.clone();
86        let mut next = self.next.clone();
87
88        Box::pin(async move {
89            let acquired = {
90                let mut limiter = limiter.lock().unwrap();
91                limiter.try_acquire()
92            };
93
94            if acquired {
95                next.call(exchange).await
96            } else {
97                match config.strategy {
98                    ThrottleStrategy::Delay => {
99                        loop {
100                            let wait_time = {
101                                let limiter = limiter.lock().unwrap();
102                                limiter.time_until_next_token()
103                            };
104                            if wait_time > Duration::ZERO {
105                                tokio::time::sleep(wait_time).await;
106                            }
107                            let acquired = {
108                                let mut limiter = limiter.lock().unwrap();
109                                limiter.try_acquire()
110                            };
111                            if acquired {
112                                break;
113                            }
114                            // Yield to avoid tight spinning when concurrent tasks
115                            // wake simultaneously and contend for the same token.
116                            tokio::task::yield_now().await;
117                        }
118                        next.call(exchange).await
119                    }
120                    ThrottleStrategy::Reject => Err(CamelError::ProcessorError(
121                        "Throttled: rate limit exceeded".to_string(),
122                    )),
123                    ThrottleStrategy::Drop => {
124                        exchange.set_property(CAMEL_STOP, Value::Bool(true));
125                        Ok(exchange)
126                    }
127                }
128            }
129        })
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    use camel_api::{BoxProcessorExt, Message};
137    use tower::ServiceExt;
138
139    fn passthrough() -> BoxProcessor {
140        BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) }))
141    }
142
143    #[tokio::test]
144    async fn test_throttler_allows_under_limit() {
145        let config = ThrottlerConfig::new(5, Duration::from_secs(1));
146        let mut svc = ThrottlerService::new(config, passthrough());
147
148        for _ in 0..5 {
149            let ex = Exchange::new(Message::new("test"));
150            let result = svc.ready().await.unwrap().call(ex).await;
151            assert!(result.is_ok());
152        }
153    }
154
155    #[tokio::test]
156    async fn test_throttler_delay_strategy_queues_message() {
157        let config = ThrottlerConfig::new(1, Duration::from_millis(100));
158        let mut svc = ThrottlerService::new(config, passthrough());
159
160        let ex1 = Exchange::new(Message::new("first"));
161        let result1 = svc.ready().await.unwrap().call(ex1).await;
162        assert!(result1.is_ok());
163
164        let start = Instant::now();
165        let ex2 = Exchange::new(Message::new("second"));
166        let result2 = svc.ready().await.unwrap().call(ex2).await;
167        let elapsed = start.elapsed();
168        assert!(result2.is_ok());
169        assert!(elapsed >= Duration::from_millis(50));
170    }
171
172    #[tokio::test]
173    async fn test_throttler_reject_strategy_returns_error() {
174        let config =
175            ThrottlerConfig::new(1, Duration::from_secs(10)).strategy(ThrottleStrategy::Reject);
176        let mut svc = ThrottlerService::new(config, passthrough());
177
178        let ex1 = Exchange::new(Message::new("first"));
179        let _ = svc.ready().await.unwrap().call(ex1).await;
180
181        let ex2 = Exchange::new(Message::new("second"));
182        let result = svc.ready().await.unwrap().call(ex2).await;
183        assert!(result.is_err());
184        let err = result.unwrap_err().to_string();
185        assert!(err.contains("Throttled"));
186    }
187
188    #[tokio::test]
189    async fn test_throttler_drop_strategy_sets_camel_stop() {
190        let config =
191            ThrottlerConfig::new(1, Duration::from_secs(10)).strategy(ThrottleStrategy::Drop);
192        let mut svc = ThrottlerService::new(config, passthrough());
193
194        let ex1 = Exchange::new(Message::new("first"));
195        let _ = svc.ready().await.unwrap().call(ex1).await;
196
197        let ex2 = Exchange::new(Message::new("second"));
198        let result = svc.ready().await.unwrap().call(ex2).await.unwrap();
199        assert_eq!(result.property(CAMEL_STOP), Some(&Value::Bool(true)));
200    }
201
202    #[tokio::test]
203    async fn test_throttler_token_replenishment() {
204        let config = ThrottlerConfig::new(1, Duration::from_millis(50));
205        let mut svc = ThrottlerService::new(config, passthrough());
206
207        let ex1 = Exchange::new(Message::new("first"));
208        let _ = svc.ready().await.unwrap().call(ex1).await;
209
210        tokio::time::sleep(Duration::from_millis(100)).await;
211
212        let ex2 = Exchange::new(Message::new("second"));
213        let result = svc.ready().await.unwrap().call(ex2).await;
214        assert!(result.is_ok());
215    }
216}