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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
use carboncopy::{BoxFuture, Sink};
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{stdout, AsyncWriteExt, Stdout};
use tokio::runtime::Runtime;
use tokio::sync::mpsc::{unbounded_channel, UnboundedSender as DropTx};
use tokio::sync::Mutex;
use tokio::time::sleep;
pub struct BufSink<T: AsyncWriteExt + Unpin + Send + 'static> {
rt: Arc<Runtime>,
interior: Arc<Mutex<Interior<T>>>,
drop_chan_tx: DropTx<EmptySignal>,
}
impl<T: AsyncWriteExt + Unpin + Send + 'static> Sink for BufSink<T> {
fn sink_blocking(&self, entry: String) -> std::io::Result<()> {
self.rt.block_on(self.sink(entry))
}
fn sink(&self, entry: String) -> BoxFuture<std::io::Result<()>> {
Box::pin(async move {
let mut inner = self.interior.lock().await;
if let Some((buf, _)) = inner.buf.as_mut() {
let _ = buf.write(entry.as_bytes()).await;
Ok(())
} else {
if let Err(x) = inner.output_writer.write(entry.as_bytes()).await {
Err(x)
} else {
Ok(())
}
}
})
}
}
impl<T: AsyncWriteExt + Unpin + Send + 'static> Drop for BufSink<T> {
fn drop(&mut self) {
let _ = self.drop_chan_tx.send(EmptySignal);
}
}
impl<T: AsyncWriteExt + Unpin + Send + 'static> BufSink<T> {
pub fn new(opts: SinkOptions<T>) -> Self {
let interior = Arc::new(Mutex::new(Interior {
backlogged: false,
buf: if opts.buffer.is_none() {
None
} else {
let cap = opts.buffer.as_ref().unwrap();
Some((Vec::with_capacity(cap.0), cap.0))
},
output_writer: opts.output_writer,
}));
let (drop_tx, mut drop_rx) = unbounded_channel();
let rt = opts.tokio_runtime.clone();
let interior_clone = interior.clone();
let timeout_ms = opts.flush_timeout_ms;
rt.spawn(async move {
if interior_clone.lock().await.buf.is_some() {
loop {
let overflow = async {
loop {
{
let interior_check = interior_clone.lock().await;
if interior_check.buf.as_ref().unwrap().0.len()
>= interior_check.buf.as_ref().unwrap().1
{
return;
}
}
if timeout_ms > 1 {
sleep(Duration::from_millis(1)).await;
}
}
};
let timeout = async move {
sleep(Duration::from_millis(timeout_ms)).await;
};
tokio::select! {
_ = overflow => {
let _ = interior_clone.lock().await.flush().await;
}
_ = timeout => {
let _ = interior_clone.lock().await.flush().await;
}
_ = drop_rx.recv() => {
return;
}
}
}
} else {
return;
}
});
Self {
rt: rt,
interior: interior,
drop_chan_tx: drop_tx,
}
}
pub async fn flush(&self) -> std::io::Result<usize> {
self.interior.lock().await.flush().await
}
pub async fn backlogged(&self) -> bool {
self.interior.lock().await.backlogged()
}
}
struct Interior<T: AsyncWriteExt + Unpin + Send + 'static> {
backlogged: bool,
buf: Option<(Vec<u8>, usize)>,
output_writer: T,
}
impl<T: AsyncWriteExt + Unpin + Send + 'static> Interior<T> {
async fn flush(&mut self) -> Result<usize, std::io::Error> {
if self.buf.is_none() {
Ok(0)
} else {
let vec_len = self.buf.as_ref().unwrap().0.len();
if vec_len > 0 {
let mut written: usize = 0;
while vec_len > 0 {
let res = self
.output_writer
.write(self.buf.as_ref().unwrap().0.as_slice())
.await;
if let Ok(delta) = res {
if delta == 0 {
return res;
}
if delta == vec_len {
self.buf.as_mut().unwrap().0 =
Vec::with_capacity(self.buf.as_ref().unwrap().1);
self.backlogged = false;
} else {
self.buf.as_mut().unwrap().0.drain(0..delta);
self.backlogged = true;
}
written += delta;
} else {
self.backlogged = true;
return res;
}
}
Ok(written)
} else {
Ok(0)
}
}
}
fn backlogged(&self) -> bool {
self.backlogged
}
}
pub struct SinkOptions<T: AsyncWriteExt + Unpin + Send + 'static> {
pub buffer: Option<BufferOverflowThreshold>,
pub flush_timeout_ms: u64,
pub tokio_runtime: Arc<Runtime>,
pub output_writer: T,
}
impl Default for SinkOptions<Stdout> {
fn default() -> Self {
Self {
buffer: Some(BufferOverflowThreshold::new(64 * 1024).unwrap()),
flush_timeout_ms: 100,
tokio_runtime: Arc::new(Runtime::new().unwrap()),
output_writer: stdout(),
}
}
}
#[derive(Debug, PartialEq, Eq, Copy, Clone, Ord, PartialOrd)]
pub struct BufferOverflowThreshold(usize);
impl BufferOverflowThreshold {
pub fn new(cap: usize) -> Result<Self, ThresholdError> {
const KB: usize = 1024;
const GB: usize = 1024 * 1024 * 1024;
if cap >= 1 * KB && cap <= 1 * GB {
Ok(Self(cap))
} else if cap < 1 * KB {
Err(ThresholdError::LessThan1KB)
} else {
Err(ThresholdError::MoreThan1GB)
}
}
}
#[derive(Debug, PartialEq, Eq, Copy, Clone, Ord, PartialOrd)]
pub enum ThresholdError {
LessThan1KB,
MoreThan1GB,
}
impl fmt::Display for ThresholdError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::LessThan1KB => {
write!(
f,
"buffer overflow threshold can't be less than 1024 bytes (1KB)"
)
}
Self::MoreThan1GB => {
write!(
f,
"buffer overflow threshold can't be greater than 1024 * 1024 * 1024 bytes (1GB)",
)
}
}
}
}
struct EmptySignal;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn overflow_threshold() {
assert_eq!(
BufferOverflowThreshold::new(1000).err().unwrap(),
ThresholdError::LessThan1KB
);
assert_eq!(
BufferOverflowThreshold::new(1024 * 1024 * 1024 + 1)
.err()
.unwrap(),
ThresholdError::MoreThan1GB
);
}
#[test]
fn default_options_dont_panic() {
assert_eq!(100, SinkOptions::default().flush_timeout_ms);
}
#[test]
fn timeout_flush() {
let rt = Arc::new(Runtime::new().unwrap());
let opts = SinkOptions {
buffer: Some(BufferOverflowThreshold::new(64 * 1024).unwrap()),
flush_timeout_ms: 100,
tokio_runtime: rt.clone(),
output_writer: Vec::new(),
};
let mem_sink = Arc::new(BufSink::new(opts));
for i in 0..5 {
assert!(rt
.block_on(async {
mem_sink
.clone()
.sink(String::from(format!("hello world {}\n", i)))
.await
})
.is_ok());
}
let ref_output =
"hello world 0\nhello world 1\nhello world 2\nhello world 3\nhello world 4\n";
let output_before_flush_timeout =
rt.block_on(async { mem_sink.clone().interior.lock().await.output_writer.clone() });
assert_ne!(
ref_output,
std::str::from_utf8(output_before_flush_timeout.as_ref()).unwrap()
);
rt.block_on(async {
sleep(Duration::from_millis(150)).await;
});
let output_after_flush_timeout =
rt.block_on(async { mem_sink.clone().interior.lock().await.output_writer.clone() });
assert_eq!(
ref_output,
std::str::from_utf8(output_after_flush_timeout.as_ref()).unwrap()
);
}
#[test]
fn overflow_flush() {
let rt = Arc::new(Runtime::new().unwrap());
let opts = SinkOptions {
buffer: Some(BufferOverflowThreshold::new(1 * 1024).unwrap()),
flush_timeout_ms: 100,
tokio_runtime: rt.clone(),
output_writer: Vec::new(),
};
let mem_sink = Arc::new(BufSink::new(opts));
for _ in 0..1024 {
assert!(rt
.block_on(async { mem_sink.clone().sink(String::from("X")).await })
.is_ok());
}
let mut ref_output: String = vec!['X'; 1024].into_iter().collect();
let output_before_buf_overflow =
rt.block_on(async { mem_sink.clone().interior.lock().await.output_writer.clone() });
assert_ne!(
ref_output,
std::str::from_utf8(output_before_buf_overflow.as_ref()).unwrap()
);
assert!(rt
.block_on(async { mem_sink.clone().sink(String::from("X")).await })
.is_ok());
rt.block_on(async {
sleep(Duration::from_millis(1)).await;
});
ref_output.push('X');
let output_after_buf_overflow =
rt.block_on(async { mem_sink.clone().interior.lock().await.output_writer.clone() });
assert_eq!(
ref_output,
std::str::from_utf8(output_after_buf_overflow.as_ref()).unwrap()
);
}
}