Skip to main content

rabia_core/
batching.rs

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/// Configuration for batching behavior
8#[derive(Debug, Clone)]
9pub struct BatchConfig {
10    /// Maximum number of commands per batch
11    pub max_batch_size: usize,
12    /// Maximum time to wait before flushing a partial batch
13    pub max_batch_delay: Duration,
14    /// Buffer size for incoming commands
15    pub buffer_capacity: usize,
16    /// Enable adaptive batching based on load
17    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/// Statistics for batch processing
32#[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
50/// A high-performance command batcher that groups commands for efficient processing
51pub 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    /// Add a command to the batch buffer
73    pub fn add_command(&mut self, command: Command) -> Result<Option<CommandBatch>> {
74        // Check if buffer is full
75        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        // Check if we should flush based on size
83        if self.buffer.len() >= self.current_batch_size() {
84            return Ok(Some(self.flush_batch()));
85        }
86
87        // Check if we should flush based on time
88        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    /// Force flush current batch regardless of size or time
97    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    /// Get current statistics
106    pub fn stats(&self) -> &BatchStats {
107        &self.stats
108    }
109
110    /// Update configuration (for runtime tuning)
111    pub fn update_config(&mut self, config: BatchConfig) {
112        self.adaptive_batch_size = config.max_batch_size;
113        self.config = config;
114    }
115
116    /// Get current buffer length
117    pub fn buffer_len(&self) -> usize {
118        self.buffer.len()
119    }
120
121    /// Check if buffer is empty
122    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        // Adaptive batching: adjust batch size based on performance
135        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        // Simple adaptive algorithm: increase batch size if we're consistently flushing due to size
152        // decrease if we're often flushing due to timeout
153        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            // Mostly size-based flushes, can increase batch size
157            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            // Mostly timeout-based flushes, should decrease batch size
162            self.adaptive_batch_size = (self.adaptive_batch_size * 9 / 10).max(10);
163            self.stats.adaptive_adjustments += 1;
164        }
165    }
166}
167
168/// Async command batcher for concurrent scenarios
169pub 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                    // Process incoming commands
191                    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; // Receiver dropped
198                                        }
199                                    }
200                                    Ok(None) => {} // Command buffered
201                                    Err(_) => {} // Buffer overflow, command dropped
202                                }
203                            }
204                            None => break, // Command sender dropped
205                        }
206                    }
207
208                    // Periodic flush for time-based batching
209                    _ = flush_interval.tick() => {
210                        if let Some(batch) = batcher.flush() {
211                            if batch_tx.send(batch).is_err() {
212                                break; // Receiver dropped
213                            }
214                        }
215                    }
216
217                    // Handle stats requests
218                    _ = stats_rx.recv() => {
219                        // Stats request received, sender already has reference to send back
220                    }
221                }
222            }
223        });
224
225        Self {
226            command_tx,
227            batch_rx,
228            stats_tx,
229            _task_handle: task_handle,
230        }
231    }
232
233    /// Add a command for batching
234    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    /// Receive next batch (blocking)
241    pub async fn next_batch(&mut self) -> Option<CommandBatch> {
242        self.batch_rx.recv().await
243    }
244
245    /// Try to receive a batch without blocking
246    pub fn try_next_batch(&mut self) -> Option<CommandBatch> {
247        self.batch_rx.try_recv().ok()
248    }
249
250    /// Receive next batch with timeout
251    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
261/// Batch processor that applies multiple commands efficiently
262pub struct BatchProcessor {
263    /// Optional command transformation function
264    transform_fn: Option<fn(&mut Command)>,
265    /// Enable parallel processing for independent commands
266    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    /// Process a batch of commands efficiently
288    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        // Apply transformation if configured
300        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            // Process commands in parallel
308            let futures = commands.iter().map(&mut processor);
309            let results = futures_util::future::try_join_all(futures).await?;
310            Ok(results)
311        } else {
312            // Process commands sequentially
313            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        // Add commands one by one
344        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        // Third command should trigger flush
354        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        // Add commands
392        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        // Should get a batch immediately due to size limit
400        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        // Add a single command
416        async_batcher
417            .add_command(Command::new("SET key1 value1"))
418            .unwrap();
419
420        // Should get a batch after timeout
421        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}