summaryrefslogtreecommitdiffstats
path: root/crates/common/batcher/src/driver.rs
blob: 0f7c0ed5886dc5ffb5d3a1fa8b2d613d47af554c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
use crate::batchable::Batchable;
use crate::batcher::Batcher;
use crate::batcher::BatcherOutput;
use chrono::{DateTime, Utc};
use std::collections::BTreeSet;
use std::time::Duration;
use tokio::sync::mpsc::error::SendError;
use tokio::sync::mpsc::{Receiver, Sender};

/// Input message to the BatchDriver's input channel.
#[derive(Debug)]
pub enum BatchDriverInput<B: Batchable> {
    /// Message representing a new item to batch.
    Event(B),
    /// Message representing that the batching should finish and that
    /// any remaining batches should be immediately closed and sent to the output.
    Flush,
}

/// Output message from the BatchDriver's output channel.
#[derive(Debug)]
pub enum BatchDriverOutput<B: Batchable> {
    /// Message representing a batch of items.
    Batch(Vec<B>),
    /// Message representing that batching has finished.
    Flush,
}

/// The central API for using the batching algorithm.
/// Send items in, get batches out.
#[derive(Debug)]
pub struct BatchDriver<B: Batchable> {
    batcher: Batcher<B>,
    input: Receiver<BatchDriverInput<B>>,
    output: Sender<BatchDriverOutput<B>>,
    timers: BTreeSet<DateTime<Utc>>,
}

enum TimeTo {
    Unbounded,
    Future(std::time::Duration),
    Past(DateTime<Utc>),
}

impl<B: Batchable> BatchDriver<B> {
    /// Define the batching process and channels to interact with it.
    pub fn new(
        batcher: Batcher<B>,
        input: Receiver<BatchDriverInput<B>>,
        output: Sender<BatchDriverOutput<B>>,
    ) -> BatchDriver<B> {
        BatchDriver {
            batcher,
            input,
            output,
            timers: BTreeSet::new(),
        }
    }

    /// Start the batching - runs until receiving a Flush message
    pub async fn run(mut self) -> Result<(), SendError<BatchDriverOutput<B>>> {
        loop {
            let message = match self.time_to_next_timer() {
                TimeTo::Unbounded => self.recv(None),
                TimeTo::Future(timeout) => self.recv(Some(timeout)),
                TimeTo::Past(timer) => {
                    self.timers.remove(&timer);
                    self.time(Utc::now()).await?;
                    continue;
                }
            };

            match message.await {
                Err(_) => continue,                         // timer timeout expired
                Ok(None) => break,                          // input channel closed
                Ok(Some(BatchDriverInput::Flush)) => break, // we've been told to stop
                Ok(Some(BatchDriverInput::Event(event))) => self.event(event).await?,
            };
        }

        self.flush().await
    }

    async fn recv(
        &mut self,
        timeout: Option<Duration>,
    ) -> Result<Option<BatchDriverInput<B>>, tokio::time::error::Elapsed> {
        match timeout {
            None => Ok(self.input.recv().await),
            Some(timeout) => tokio::time::timeout(timeout, self.input.recv()).await,
        }
    }

    fn time_to_next_timer(&self) -> TimeTo {
        match self.timers.iter().next() {
            None => TimeTo::Unbounded,
            Some(timer) => {
                let signed_duration = timer.signed_duration_since(Utc::now());
                match signed_duration.to_std() {
                    Ok(d) => TimeTo::Future(d),
                    Err(_) => TimeTo::Past(*timer),
                }
            }
        }
    }

    async fn event(&mut self, event: B) -> Result<(), SendError<BatchDriverOutput<B>>> {
        for action in self.batcher.event(Utc::now(), event) {
            match action {
                BatcherOutput::Batch(batch) => {
                    self.output.send(BatchDriverOutput::Batch(batch)).await?;
                }
                BatcherOutput::Timer(t) => {
                    self.timers.insert(t);
                }
            };
        }

        Ok(())
    }

    async fn time(&mut self, timer: DateTime<Utc>) -> Result<(), SendError<BatchDriverOutput<B>>> {
        for batch in self.batcher.time(timer) {
            self.output.send(BatchDriverOutput::Batch(batch)).await?;
        }

        Ok(())
    }

    async fn flush(self) -> Result<(), SendError<BatchDriverOutput<B>>> {
        for batch in self.batcher.flush() {
            self.output.send(BatchDriverOutput::Batch(batch)).await?;
        }

        self.output.send(BatchDriverOutput::Flush).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::batchable::Batchable;
    use crate::batcher::Batcher;
    use crate::config::BatchConfigBuilder;
    use crate::driver::BatchDriver;
    use chrono::{DateTime, Utc};
    use std::time::Duration;
    use tokio::sync::mpsc::error::SendError;
    use tokio::sync::mpsc::{channel, Receiver, Sender};
    use tokio::time::timeout;

    #[tokio::test]
    async fn flush_empty() -> Result<(), SendError<BatchDriverInput<TestBatchEvent>>> {
        let (input_send, mut output_recv) = spawn_driver();
        input_send.send(BatchDriverInput::Flush).await?;
        assert_recv_flush(&mut output_recv).await;
        Ok(())
    }

    #[tokio::test]
    async fn flush_one_batch() -> Result<(), SendError<BatchDriverInput<TestBatchEvent>>> {
        let (input_send, mut output_recv) = spawn_driver();

        let event1 = TestBatchEvent::new(1, Utc::now());
        input_send.send(BatchDriverInput::Event(event1)).await?;
        input_send.send(BatchDriverInput::Flush).await?;

        assert_recv_batch(&mut output_recv, vec![event1]).await;
        assert_recv_flush(&mut output_recv).await;

        Ok(())
    }

    #[tokio::test]
    async fn two_batches_with_timer() -> Result<(), SendError<BatchDriverInput<TestBatchEvent>>> {
        let (input_send, mut output_recv) = spawn_driver();

        let event1 = TestBatchEvent::new(1, Utc::now());
        input_send.send(BatchDriverInput::Event(event1)).await?;

        assert_recv_batch(&mut output_recv, vec![event1]).await;

        let event2 = TestBatchEvent::new(2, Utc::now());
        input_send.send(BatchDriverInput::Event(event2)).await?;

        assert_recv_batch(&mut output_recv, vec![event2]).await;

        Ok(())
    }

    async fn assert_recv_batch(
        output_recv: &mut Receiver<BatchDriverOutput<TestBatchEvent>>,
        expected: Vec<TestBatchEvent>,
    ) {
        match timeout(Duration::from_secs(10), output_recv.recv()).await {
            Ok(Some(BatchDriverOutput::Batch(batch))) => assert_batch(batch, expected),
            other => panic!("Failed to receive batch: {:?}", other),
        }
    }

    fn assert_batch(batch: Vec<TestBatchEvent>, expected: Vec<TestBatchEvent>) {
        assert_eq!(batch.len(), expected.len());

        for event in &batch {
            if !expected.contains(event) {
                panic!("Failed to find: {:?}", event);
            }
        }
    }

    async fn assert_recv_flush(output_recv: &mut Receiver<BatchDriverOutput<TestBatchEvent>>) {
        match timeout(Duration::from_secs(10), output_recv.recv()).await {
            Ok(Some(BatchDriverOutput::Flush)) => {}
            other => panic!("Failed to receive flush: {:?}", other),
        }
    }

    fn spawn_driver() -> (
        Sender<BatchDriverInput<TestBatchEvent>>,
        Receiver<BatchDriverOutput<TestBatchEvent>>,
    ) {
        let (