1use crate::{Command, CommandBatch, RabiaError, Result};
2use std::collections::VecDeque;
3use std::time::{Duration, Instant};
4use tokio::sync::mpsc;
5use tokio::time::timeout;
6
7#[derive(Debug, Clone)]
9pub struct BatchConfig {
10 pub max_batch_size: usize,
12 pub max_batch_delay: Duration,
14 pub buffer_capacity: usize,
16 pub adaptive: bool,
18}
19
20impl Default for BatchConfig {
21 fn default() -> Self {
22 Self {
23 max_batch_size: 100,
24 max_batch_delay: Duration::from_millis(10),
25 buffer_capacity: 1000,
26 adaptive: true,
27 }
28 }
29}
30
31#[derive(Debug, Clone, Default)]
33pub struct BatchStats {
34 pub total_commands: usize,
35 pub total_batches: usize,
36 pub average_batch_size: f64,
37 pub commands_dropped: usize,
38 pub flush_timeouts: usize,
39 pub adaptive_adjustments: usize,
40}
41
42impl BatchStats {
43 pub fn record_batch(&mut self, batch_size: usize) {
44 self.total_commands += batch_size;
45 self.total_batches += 1;
46 self.average_batch_size = self.total_commands as f64 / self.total_batches as f64;
47 }
48}
49
50pub struct CommandBatcher {
52 config: BatchConfig,
53 buffer: VecDeque<Command>,
54 stats: BatchStats,
55 last_flush: Instant,
56 adaptive_batch_size: usize,
57}
58
59impl CommandBatcher {
60 pub fn new(config: BatchConfig) -> Self {
61 let adaptive_batch_size = config.max_batch_size;
62 let buffer_capacity = config.buffer_capacity;
63 Self {
64 config,
65 buffer: VecDeque::with_capacity(buffer_capacity),
66 stats: BatchStats::default(),
67 last_flush: Instant::now(),
68 adaptive_batch_size,
69 }
70 }
71
72 pub fn add_command(&mut self, command: Command) -> Result<Option<CommandBatch>> {
74 if self.buffer.len() >= self.config.buffer_capacity {
76 self.stats.commands_dropped += 1;
77 return Err(RabiaError::internal("Command buffer overflow"));
78 }
79
80 self.buffer.push_back(command);
81
82 if self.buffer.len() >= self.current_batch_size() {
84 return Ok(Some(self.flush_batch()));
85 }
86
87 if self.last_flush.elapsed() >= self.config.max_batch_delay && !self.buffer.is_empty() {
89 self.stats.flush_timeouts += 1;
90 return Ok(Some(self.flush_batch()));
91 }
92
93 Ok(None)
94 }
95
96 pub fn flush(&mut self) -> Option<CommandBatch> {
98 if self.buffer.is_empty() {
99 None
100 } else {
101 Some(self.flush_batch())
102 }
103 }
104
105 pub fn stats(&self) -> &BatchStats {
107 &self.stats
108 }
109
110 pub fn update_config(&mut self, config: BatchConfig) {
112 self.adaptive_batch_size = config.max_batch_size;
113 self.config = config;
114 }
115
116 pub fn buffer_len(&self) -> usize {
118 self.buffer.len()
119 }
120
121 pub fn is_empty(&self) -> bool {
123 self.buffer.is_empty()
124 }
125
126 fn flush_batch(&mut self) -> CommandBatch {
127 let batch_size = self.current_batch_size().min(self.buffer.len());
128 let commands: Vec<Command> = self.buffer.drain(..batch_size).collect();
129
130 let batch = CommandBatch::new(commands);
131 self.stats.record_batch(batch.commands.len());
132 self.last_flush = Instant::now();
133
134 if self.config.adaptive {
136 self.adjust_adaptive_batch_size();
137 }
138
139 batch
140 }
141
142 fn current_batch_size(&self) -> usize {
143 if self.config.adaptive {
144 self.adaptive_batch_size
145 } else {
146 self.config.max_batch_size
147 }
148 }
149
150 fn adjust_adaptive_batch_size(&mut self) {
151 let size_ratio = self.stats.total_batches as f64 / (self.stats.flush_timeouts + 1) as f64;
154
155 if size_ratio > 2.0 && self.adaptive_batch_size < self.config.max_batch_size {
156 self.adaptive_batch_size =
158 (self.adaptive_batch_size * 11 / 10).min(self.config.max_batch_size);
159 self.stats.adaptive_adjustments += 1;
160 } else if size_ratio < 0.5 && self.adaptive_batch_size > 10 {
161 self.adaptive_batch_size = (self.adaptive_batch_size * 9 / 10).max(10);
163 self.stats.adaptive_adjustments += 1;
164 }
165 }
166}
167
168pub struct AsyncCommandBatcher {
170 command_tx: mpsc::UnboundedSender<Command>,
171 batch_rx: mpsc::UnboundedReceiver<CommandBatch>,
172 #[allow(dead_code)]
173 stats_tx: mpsc::UnboundedSender<BatchStats>,
174 _task_handle: tokio::task::JoinHandle<()>,
175}
176
177impl AsyncCommandBatcher {
178 pub fn new(config: BatchConfig) -> Self {
179 let (command_tx, mut command_rx) = mpsc::unbounded_channel();
180 let (batch_tx, batch_rx) = mpsc::unbounded_channel();
181 let (stats_tx, mut stats_rx) = mpsc::unbounded_channel();
182
183 let config_clone = config.clone();
184 let task_handle = tokio::spawn(async move {
185 let mut batcher = CommandBatcher::new(config_clone);
186 let mut flush_interval = tokio::time::interval(config.max_batch_delay);
187
188 loop {
189 tokio::select! {
190 command = command_rx.recv() => {
192 match command {
193 Some(cmd) => {
194 match batcher.add_command(cmd) {
195 Ok(Some(batch)) => {
196 if batch_tx.send(batch).is_err() {
197 break; }
199 }
200 Ok(None) => {} Err(_) => {} }
203 }
204 None => break, }
206 }
207
208 _ = flush_interval.tick() => {
210 if let Some(batch) = batcher.flush() {
211 if batch_tx.send(batch).is_err() {
212 break; }
214 }
215 }
216
217 _ = stats_rx.recv() => {
219 }
221 }
222 }
223 });
224
225 Self {
226 command_tx,
227 batch_rx,
228 stats_tx,
229 _task_handle: task_handle,
230 }
231 }
232
233 pub fn add_command(&self, command: Command) -> Result<()> {
235 self.command_tx
236 .send(command)
237 .map_err(|_| RabiaError::internal("Batcher task has stopped"))
238 }
239
240 pub async fn next_batch(&mut self) -> Option<CommandBatch> {
242 self.batch_rx.recv().await
243 }
244
245 pub fn try_next_batch(&mut self) -> Option<CommandBatch> {
247 self.batch_rx.try_recv().ok()
248 }
249
250 pub async fn next_batch_timeout(&mut self, duration: Duration) -> Result<CommandBatch> {
252 timeout(duration, self.batch_rx.recv())
253 .await
254 .map_err(|_| RabiaError::Timeout {
255 operation: "batch receive".to_string(),
256 })?
257 .ok_or_else(|| RabiaError::internal("Batcher task has stopped"))
258 }
259}
260
261pub struct BatchProcessor {
263 transform_fn: Option<fn(&mut Command)>,
265 parallel: bool,
267}
268
269impl BatchProcessor {
270 pub fn new() -> Self {
271 Self {
272 transform_fn: None,
273 parallel: false,
274 }
275 }
276
277 pub fn with_transform(mut self, transform_fn: fn(&mut Command)) -> Self {
278 self.transform_fn = Some(transform_fn);
279 self
280 }
281
282 pub fn with_parallel(mut self, parallel: bool) -> Self {
283 self.parallel = parallel;
284 self
285 }
286
287 pub async fn process_batch<F, Fut>(
289 &self,
290 batch: CommandBatch,
291 mut processor: F,
292 ) -> Result<Vec<bytes::Bytes>>
293 where
294 F: FnMut(&Command) -> Fut,
295 Fut: std::future::Future<Output = Result<bytes::Bytes>>,
296 {
297 let mut commands = batch.commands;
298
299 if let Some(transform) = self.transform_fn {
301 for command in &mut commands {
302 transform(command);
303 }
304 }
305
306 if self.parallel && commands.len() > 1 {
307 let futures = commands.iter().map(&mut processor);
309 let results = futures_util::future::try_join_all(futures).await?;
310 Ok(results)
311 } else {
312 let mut results = Vec::with_capacity(commands.len());
314 for command in &commands {
315 results.push(processor(command).await?);
316 }
317 Ok(results)
318 }
319 }
320}
321
322impl Default for BatchProcessor {
323 fn default() -> Self {
324 Self::new()
325 }
326}
327
328#[cfg(test)]
329mod tests {
330 use super::*;
331
332 #[test]
333 fn test_command_batcher_basic() {
334 let config = BatchConfig {
335 max_batch_size: 3,
336 max_batch_delay: Duration::from_millis(100),
337 buffer_capacity: 10,
338 adaptive: false,
339 };
340
341 let mut batcher = CommandBatcher::new(config);
342
343 assert!(batcher
345 .add_command(Command::new("SET key1 value1"))
346 .unwrap()
347 .is_none());
348 assert!(batcher
349 .add_command(Command::new("SET key2 value2"))
350 .unwrap()
351 .is_none());
352
353 let batch = batcher
355 .add_command(Command::new("SET key3 value3"))
356 .unwrap();
357 assert!(batch.is_some());
358
359 let batch = batch.unwrap();
360 assert_eq!(batch.commands.len(), 3);
361 }
362
363 #[test]
364 fn test_batcher_flush() {
365 let config = BatchConfig::default();
366 let mut batcher = CommandBatcher::new(config);
367
368 batcher
369 .add_command(Command::new("SET key1 value1"))
370 .unwrap();
371 batcher
372 .add_command(Command::new("SET key2 value2"))
373 .unwrap();
374
375 let batch = batcher.flush().unwrap();
376 assert_eq!(batch.commands.len(), 2);
377 assert!(batcher.is_empty());
378 }
379
380 #[tokio::test]
381 async fn test_async_command_batcher() {
382 let config = BatchConfig {
383 max_batch_size: 2,
384 max_batch_delay: Duration::from_millis(50),
385 buffer_capacity: 10,
386 adaptive: false,
387 };
388
389 let mut async_batcher = AsyncCommandBatcher::new(config);
390
391 async_batcher
393 .add_command(Command::new("SET key1 value1"))
394 .unwrap();
395 async_batcher
396 .add_command(Command::new("SET key2 value2"))
397 .unwrap();
398
399 let batch = async_batcher.next_batch().await.unwrap();
401 assert_eq!(batch.commands.len(), 2);
402 }
403
404 #[tokio::test]
405 async fn test_async_batcher_timeout() {
406 let config = BatchConfig {
407 max_batch_size: 10,
408 max_batch_delay: Duration::from_millis(50),
409 buffer_capacity: 10,
410 adaptive: false,
411 };
412
413 let mut async_batcher = AsyncCommandBatcher::new(config);
414
415 async_batcher
417 .add_command(Command::new("SET key1 value1"))
418 .unwrap();
419
420 let batch = async_batcher
422 .next_batch_timeout(Duration::from_millis(100))
423 .await
424 .unwrap();
425 assert_eq!(batch.commands.len(), 1);
426 }
427
428 #[tokio::test]
429 async fn test_batch_processor() {
430 let processor = BatchProcessor::new().with_parallel(false);
431
432 let commands = vec![
433 Command::new("SET key1 value1"),
434 Command::new("SET key2 value2"),
435 ];
436 let batch = CommandBatch::new(commands);
437
438 let results = processor
439 .process_batch(batch, |cmd| {
440 let data = cmd.data.clone();
441 async move {
442 Ok(bytes::Bytes::from(format!(
443 "processed: {}",
444 String::from_utf8_lossy(&data)
445 )))
446 }
447 })
448 .await
449 .unwrap();
450
451 assert_eq!(results.len(), 2);
452 assert!(results[0].starts_with(b"processed:"));
453 }
454}