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
use fehler::{throw, throws};
use rand::Rng;
use rusoto_core::{Region, RusotoError};
use rusoto_firehose::{KinesisFirehoseClient, PutRecordBatchError, PutRecordBatchInput};
use crate::buffer::Buffer;
use crate::error::Error;
use crate::put_record_batcher::PutRecordBatcher;
pub struct Producer<C: PutRecordBatcher> {
buf: Buffer,
client: C,
stream_name: String,
}
pub type KinesisFirehoseProducer = Producer<KinesisFirehoseClient>;
impl Producer<KinesisFirehoseClient> {
#[throws]
pub fn new(stream_name: String) -> Self {
Self {
buf: Buffer::new(),
client: KinesisFirehoseClient::new(Region::default()),
stream_name,
}
}
}
impl<C: PutRecordBatcher> Producer<C> {
#[throws]
pub async fn produce(&mut self, mut rec: String) {
rec += "\n";
self.buf.check_record_too_large(&rec)?;
if self.buf.is_overfull_with(&rec) {
self.flush().await?;
}
self.buf.add_rec(rec);
}
#[allow(unreachable_code)]
#[throws]
pub async fn flush(&mut self) {
if self.buf.is_empty() {
return;
}
let recs = self.buf.as_owned_vec();
let mut records_to_try = recs;
let max_attempts = 10;
let mut attempts_left: i32 = max_attempts;
while attempts_left > 0 {
log::trace!("flushing; attempts_left: {}", attempts_left);
attempts_left -= 1;
let req = PutRecordBatchInput {
delivery_stream_name: self.stream_name.clone(),
records: records_to_try.clone(),
};
let res = self.client._put_record_batch(req).await;
if let Err(RusotoError::Service(PutRecordBatchError::ServiceUnavailable(err))) = res {
let dur = Self::sleep_duration(max_attempts - attempts_left);
log::debug!(
"service unavailable: {}. sleeping for {} millis & retrying",
err,
dur.as_millis()
);
tokio::time::sleep(dur).await;
continue;
}
let res = res?;
if res.failed_put_count > 0 {
records_to_try = res
.request_responses
.into_iter()
.enumerate()
.filter_map(|(i, rr)| {
rr.error_code.map(|_| records_to_try[i].clone())
})
.collect::<Vec<_>>();
continue;
}
self.buf.clear();
return;
}
throw!(Error::TooManyAttempts);
}
#[throws]
pub fn with_client(client: C, stream_name: String) -> Self {
Self {
buf: Buffer::new(),
client,
stream_name,
}
}
fn sleep_duration(attempt: i32) -> tokio::time::Duration {
let mut rng = rand::thread_rng();
let rand_factor = 0.5;
let absolute_max = 10_000;
let ivl = (1. + (attempt as f64).powf(1.15)) * 100.;
let rand_ivl = ivl * (rng.gen_range((1. - rand_factor)..(1. + rand_factor)));
let millis = (rand_ivl.ceil() as u64).min(absolute_max);
tokio::time::Duration::from_millis(millis)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::put_record_batcher::MockPutRecordBatcher;
macro_rules! assert_err {
($expression:expr, $($pattern:tt)+) => {
match $expression {
$($pattern)+ => (),
ref e => panic!("expected `{}` but got `{:?}`", stringify!($($pattern)+), e),
}
}
}
#[tokio::test]
async fn it_works_or_something() {
let mocker = MockPutRecordBatcher::new();
let buf_ref = mocker.buf_ref();
let mut producer = Producer::with_client(mocker, "mf-test-2".to_string()).unwrap();
producer.produce("hi".to_string()).await.unwrap();
producer.flush().await.expect("flush pls");
let len = {
let buf = buf_ref.lock().unwrap();
let buf = buf.borrow();
buf.len()
};
assert_eq!(len, 1);
}
#[tokio::test]
async fn it_retries_and_fails() {
let mocker = MockPutRecordBatcher::with_fail_times(100);
let mut producer = Producer::with_client(mocker, "mf-test-2".to_string()).unwrap();
producer.produce("message 1".to_string()).await.unwrap();
let res = producer.flush().await.expect_err("expect err");
assert_err!(res, Error::TooManyAttempts);
}
#[tokio::test]
async fn it_retries_only_failed_records() {
let _ = env_logger::builder().is_test(true).try_init();
let mocker = MockPutRecordBatcher::with_fail_times(1);
let buf_ref = mocker.buf_ref();
let mut producer = Producer::with_client(mocker, "mf-test-2".to_string()).unwrap();
producer.produce("message 1".to_string()).await.unwrap();
producer.produce("message 2".to_string()).await.unwrap();
producer.flush().await.expect("failed to flush");
let buf = buf_ref.lock().unwrap();
let buf = buf.borrow();
assert_eq!(buf.len(), 2);
assert_eq!(
buf.iter()
.map(|r| std::str::from_utf8(&r.data).unwrap())
.collect::<Vec<_>>(),
vec!["message 2\n".to_string(), "message 1\n".to_string()]
);
}
#[tokio::test]
async fn it_uses_exponential_backoff() {
let mocker = MockPutRecordBatcher::with_svc_and_fail_times(5, 0);
let mut producer = Producer::with_client(mocker, "mf-test-2".to_string()).unwrap();
producer.produce("message 1".to_string()).await.unwrap();
let start = tokio::time::Instant::now();
producer.flush().await.expect("should eventually succeed");
let end = tokio::time::Instant::now();
assert!(end - start > tokio::time::Duration::from_millis(200));
}
}