Repository navigation
Expand file tree
/
Copy pathsink.rs
More file actions
1293 lines (1094 loc) · 39.5 KB
/
Copy pathsink.rs
File metadata and controls
1293 lines (1094 loc) · 39.5 KB
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
25
10BC8
9
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! This module contains all our internal sink utilities
//!
//! All vector "sinks" are built around the `Sink` type which
//! we use to "push" events into. Within the different types of
//! vector "sinks" we need to support three main use cases:
//!
//! - Streaming sinks
//! - Single partition batching
//! - Multiple partition batching
//!
//! For each of these types this module provides one external type
//! that can be used within sinks. The simplest type being the `StreamSink`
//! type should be used when you do not want to batch events but you want
//! to _stream_ them to the downstream service. `BatchSink` and `PartitonBatchSink`
//! are similar in the sense that they both take some `tower::Service`, `Batch` and
//! `Acker` and will provide full batching, request dipstaching and acking based on
//! the settings passed.
//!
//! For more advanced use cases like http based sinks, one should use the
//! `BatchedHttpSink` type, which is a wrapper for `BatchSink` and `HttpSink`.
//!
//! # Driving to completetion
//!
//! Each sink utility provided here strictly follows the patterns described in
//! the `futures01::Sink` docs. Each sink utility must be polled from a valid
//! tokio context wether that may be an actual runtime or using any of the
//! `tokio01-test` utilities.
//!
//! For service based sinks like `BatchSink` and `PartitionBatchSink` they also
//! must be polled within a valid tokio executor context or passed a valid executor.
//! This is due to the fact that they will spawn service requests to allow them to be
//! driven independently from the sink. A oneshot channel is used to tie them back into
//! the sink to allow it to notify the consumer that the request has succeeded.
use super::batch::{Batch, PushResult, StatefulBatch};
use super::buffer::partition::Partition;
use crate::buffers::Acker;
use futures01::{
future::Either,
stream::FuturesUnordered,
sync::oneshot::{self, Receiver},
try_ready, Async, AsyncSink, Future, Poll, Sink, StartSend, Stream,
};
use std::{
collections::{HashMap, VecDeque},
fmt,
hash::Hash,
marker::PhantomData,
time::{Duration, Instant},
};
use tokio01::{
executor::{DefaultExecutor, Executor},
timer::Delay,
};
use tower::Service;
use tracing_futures::Instrument;
// === StreamSink ===
const STREAM_SINK_MAX: usize = 10_000;
/// Simple stream based sink adapter.
///
/// This will wrap any inner sink acking all events
/// as soon as poll_complete returns ready. `start_send`
/// will also attempt to fully flush if the amount of
/// in flight acks is larger than `STREAM_SINK_MAX`.
#[derive(Debug)]
pub struct StreamSink<T> {
inner: T,
acker: Acker,
pending: usize,
}
impl<T> StreamSink<T> {
pub fn new(inner: T, acker: Acker) -> Self {
Self {
inner,
acker,
pending: 0,
}
}
}
impl<T: Sink> Sink for StreamSink<T> {
type SinkItem = T::SinkItem;
type SinkError = T::SinkError;
fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, Self::SinkError> {
trace!("sending item.");
match self.inner.start_send(item)? {
AsyncSink::Ready => {
self.pending += 1;
trace!(message = "submit successful.", pending_acks = self.pending);
if self.pending >= STREAM_SINK_MAX {
self.poll_complete()?;
}
Ok(AsyncSink::Ready)
}
AsyncSink::NotReady(item) => {
trace!("Inner sink applying back pressure.");
Ok(AsyncSink::NotReady(item))
}
}
}
fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
try_ready!(self.inner.poll_complete());
trace!(message = "Acking events.", acking_num = self.pending);
self.acker.ack(self.pending);
self.pending = 0;
Ok(().into())
}
}
// === BatchSink ===
/// A `Sink` interface that wraps a `Service` and a
/// `Batch`.
///
/// Provided a batching scheme, a service and batch settings
/// this type will handle buffering events via the batching scheme
/// and dispatching requests via the service based on either the size
/// of the batch or a batch linger timeout.
///
/// # Acking
///
/// Service based acking will only ack events when all prior request
/// batches have been acked. This means if sequential requests r1, r2,
/// and r3 are dispatched and r2 and r3 complete, all events contained
/// in all requests will not be acked until r1 has completed.
pub struct BatchSink<S, B, Request, E = DefaultExecutor> {
service: ServiceSink<S, Request>,
batch: StatefulBatch<B>,
timeout: Duration,
linger: Option<Delay>,
closing: bool,
exec: E,
_pd: PhantomData<Request>,
}
impl<S, B, Request> BatchSink<S, B, Request, DefaultExecutor>
where
S: Service<Request>,
S::Future: Send + 'static,
S::Error: Into<crate::Error> + Send + 'static,
S::Response: Response,
B: Batch<Output = Request>,
{
pub fn new(service: S, batch: B, timeout: Duration, acker: Acker) -> Self {
BatchSink::with_executor(service, batch, timeout, acker, DefaultExecutor::current())
}
}
impl<S, B, Request, E> BatchSink<S, B, Request, E>
where
S: Service<Request>,
S::Future: Send + 'static,
S::Error: Into<crate::Error> + Send + 'static,
S::Response: Response,
B: Batch<Output = Request>,
E: Executor,
{
pub fn with_executor(service: S, batch: B, timeout: Duration, acker: Acker, exec: E) -> Self {
let service = ServiceSink::new(service, acker);
Self {
service,
batch: batch.into(),
timeout,
linger: None,
closing: false,
exec,
_pd: PhantomData,
}
}
fn should_send(&mut self) -> bool {
self.closing || self.batch.was_full() || self.linger_elapsed()
}
fn linger_elapsed(&mut self) -> bool {
match &mut self.linger {
Some(delay) => delay.poll().expect("timer error").is_ready(),
None => false,
}
}
}
impl<S, B, Request, E> Sink for BatchSink<S, B, Request, E>
where
S: Service<Request>,
S::Future: Send + 'static,
S::Error: Into<crate::Error> + Send + 'static,
S::Response: Response,
B: Batch<Output = Request>,
E: Executor,
{
type SinkItem = B::Input;
type SinkError = crate::Error;
fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, Self::SinkError> {
if self.batch.was_full() {
trace!("batch full.");
self.poll_complete()?;
if !self.batch.is_empty() {
debug!(
message = "Batch buffer full; applying back pressure.",
rate_limit_secs = 10
);
return Ok(AsyncSink::NotReady(item));
}
}
if self.linger.is_none() {
trace!("Starting new batch timer.");
// We just inserted the first item of a new batch, so set our delay to the longest time
// we want to allow that item to linger in the batch before being flushed.
let deadline = Instant::now() + self.timeout;
self.linger = Some(Delay::new(deadline));
}
match self.batch.push(item) {
PushResult::Ok(false) => Ok(AsyncSink::Ready),
PushResult::Ok(true) => {
self.poll_complete()?;
Ok(AsyncSink::Ready)
}
PushResult::Overflow(item) => self.start_send(item),
}
}
fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
loop {
if self.batch.is_empty() {
trace!("no batches; driving service to completion.");
return self.service.poll_complete();
} else {
// We have data to send, so check if we should send it and either attempt the send
// or return that we're not ready to send. If we send and it works, loop to poll or
// close inner instead of prematurely returning Ready
if self.should_send() {
try_ready!(self.service.poll_ready());
trace!("Service ready; Sending batch.");
let batch = self.batch.fresh_replace();
let batch_size = batch.num_items();
let request = batch.finish();
let fut = self.service.call(request, batch_size);
self.exec.spawn(fut).expect("Spawn service future");
// Disable linger timeout
self.linger.take();
} else {
// We have a batch but we can't send any items
// most likely because we have not hit either
// our batch size or the timeout. Here we want
// to poll the inner futures but still return
// NotReady if the linger timeout is not complete yet.
if let Some(linger) = &mut self.linger {
trace!("polling batch linger.");
self.service.poll_complete()?;
try_ready!(linger.poll());
} else {
try_ready!(self.service.poll_complete());
}
}
}
}
}
fn close(&mut self) -> Poll<(), Self::SinkError> {
trace!("closing batch sink.");
self.closing = true;
self.poll_complete()
}
}
impl<S, B, Request> fmt::Debug for BatchSink<S, B, Request>
where
S: fmt::Debug,
B: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BatchSink")
.field("service", &self.service)
.field("batch", &self.batch)
.field("timeout", &self.timeout)
.finish()
}
}
// === PartitionBatchSink ===
type LingerDelay<K> = Box<dyn Future<Item = LingerState<K>, Error = ()> + Send + 'static>;
/// A partition based batcher, given some `Service` and `Batch` where the
/// input is partitionable via the `Partition` trait, it will hold many
/// in flight batches.
///
/// This type is similar to `BatchSink` with the added benefit that it has
/// more fine grained partitioning ability. It will hold many different batches
/// of events and contain linger timeouts for each.
///
/// # Acking
///
/// Service based acking will only ack events when all prior request
/// batches have been acked. This means if sequential requests r1, r2,
/// and r3 are dispatched and r2 and r3 complete, all events contained
/// in all requests will not be acked until r1 has completed.
pub struct PartitionBatchSink<B, S, K, Request, E = DefaultExecutor> {
batch: StatefulBatch<B>,
service: ServiceSink<S, Request>,
exec: E,
partitions: HashMap<K, StatefulBatch<B>>,
timeout: Duration,
closing: bool,
sending: VecDeque<B>,
lingers: FuturesUnordered<LingerDelay<K>>,
linger_handles: HashMap<K, oneshot::Sender<K>>,
}
enum LingerState<K> {
Elapsed(K),
Canceled,
}
impl<B, S, K, Request> PartitionBatchSink<B, S, K, Request, DefaultExecutor>
where
B: Batch<Output = Request>,
B::Input: Partition<K>,
K: Hash + Eq + Clone + Send + 'static,
S: Service<Request>,
S::Future: Send + 'static,
S::Error: Into<crate::Error> + Send + 'static,
S::Response: Response,
{
pub fn new(service: S, batch: B, timeout: Duration, acker: Acker) -> Self {
PartitionBatchSink::with_executor(
service,
batch,
timeout,
acker,
DefaultExecutor::current(),
)
}
}
impl<B, S, K, Request, E> PartitionBatchSink<B, S, K, Request, E>
where
B: Batch<Output = Request>,
B::Input: Partition<K>,
K: Hash + Eq + Clone + Send + 'static,
S: Service<Request>,
S::Future: Send + 'static,
S::Error: Into<crate::Error> + Send + 'static,
S::Response: Response,
E: Executor,
{
pub fn with_executor(service: S, batch: B, timeout: Duration, acker: Acker, exec: E) -> Self {
let service = ServiceSink::new(service, acker);
Self {
batch: batch.into(),
service,
exec,
partitions: HashMap::new(),
timeout,
closing: false,
sending: VecDeque::new(),
lingers: FuturesUnordered::new(),
linger_handles: HashMap::new(),
}
}
fn set_linger(&mut self, partition: K) {
let (tx, rx) = oneshot::channel();
let partition_clone = partition.clone();
let deadline = Instant::now() + self.timeout;
let delay = Delay::new(deadline)
.map(move |_| LingerState::Elapsed(partition_clone))
.map_err(|_| ());
let cancel = rx.map(|_| LingerState::Canceled).map_err(|_| ());
let fut = cancel
.select2(delay)
.map(|state| match state {
Either::A((state, _)) => state,
Either::B((state, _)) => state,
})
.map_err(|_| ());
self.linger_handles.insert(partition, tx);
self.lingers.push(Box::new(fut));
}
fn poll_send(&mut self, batch: B) -> Poll<(), crate::Error> {
if let Async::NotReady = self.service.poll_ready()? {
self.sending.push_front(batch);
Ok(Async::NotReady)
} else {
let batch_size = batch.num_items();
let batch = batch.finish();
let fut = self.service.call(batch, batch_size);
self.exec.spawn(fut).expect("Spawn service future");
self.service.poll_complete()
}
}
fn handle_full_batch(&mut self, item: B::Input, partition: &K) -> FullBatchResult<B::Input> {
trace!("Batch full; driving service to completion.");
if let Err(error) = self.poll_complete() {
return FullBatchResult::Result(Err(error));
}
match self.partitions.get_mut(partition) {
Some(batch) => {
if !batch.is_empty() {
debug!(
message = "Send buffer full; applying back pressure.",
rate_limit_secs = 10
);
FullBatchResult::Result(Ok(AsyncSink::NotReady(item)))
} else {
match batch.push(item) {
PushResult::Ok(full) => {
if full {
if let Err(error) = self.poll_complete() {
return FullBatchResult::Result(Err(error));
}
}
FullBatchResult::Result(Ok(AsyncSink::Ready))
}
PushResult::Overflow(_) => unreachable!("Empty buffer overflowed"),
}
}
}
None => FullBatchResult::Continue(item),
}
}
}
enum FullBatchResult<T> {
Continue(T),
Result(StartSend<T, crate::Error>),
}
impl<B, S, K, Request, E> Sink for PartitionBatchSink<B, S, K, Request, E>
where
B: Batch<Output = Request>,
B::Input: Partition<K>,
K: Hash + Eq + Clone + Send + 'static,
S: Service<Request>,
S::Future: Send + 'static,
S::Error: Into<crate::Error> + Send + 'static,
S::Response: Response,
E: Executor,
{
type SinkItem = B::Input;
type SinkError = crate::Error;
fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, Self::SinkError> {
// Apply back pressure if we are buffering more than
// 5 batches, this should only happen if the inner sink
// is apply back pressure.
if self.sending.len() > 5 {
trace!(
message = "too many sending batches.",
amount = self.sending.len()
);
self.poll_complete()?;
if self.sending.len() > 5 {
debug!(
message = "Too many open batches; applying back pressure.",
max_batch_size = 5,
rate_limit_secs = 10
);
return Ok(AsyncSink::NotReady(item));
}
}
let partition = item.partition();
let item = match self.partitions.get_mut(&partition) {
Some(batch) => {
if batch.was_full() {
match self.handle_full_batch(item, &partition) {
FullBatchResult::Result(result) => return result,
FullBatchResult::Continue(item) => item,
}
} else {
trace!("adding event to batch.");
match batch.push(item) {
PushResult::Ok(full) => {
if full {
self.poll_complete()?;
}
return Ok(AsyncSink::Ready);
}
PushResult::Overflow(item) => {
match self.handle_full_batch(item, &partition) {
FullBatchResult::Result(result) => return result,
FullBatchResult::Continue(item) => item,
}
}
}
}
}
None => item,
};
trace!("replacing batch.");
// We fall through to this case, when there is no batch already
// or the batch got submitted by polling_complete above.
let mut batch = self.batch.fresh();
match batch.push(item) {
PushResult::Overflow(_) => unreachable!("Empty buffer overflowed"),
PushResult::Ok(full) => {
self.set_linger(partition.clone());
self.partitions.insert(partition, batch);
if full {
self.poll_complete()?;
}
Ok(AsyncSink::Ready)
}
}
}
fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
self.service.poll_complete()?;
while let Some(batch) = self.sending.pop_front() {
self.poll_send(batch)?;
}
let closing = self.closing;
let mut partitions = Vec::new();
while let Ok(Async::Ready(Some(linger))) = self.lingers.poll() {
// Only if the linger has elapsed trigger the removal
if let LingerState::Elapsed(partition) = linger {
trace!("batch linger expired.");
self.linger_handles.remove(&partition);
if let Some(batch) = self.partitions.remove(&partition) {
partitions.push(batch);
}
}
}
let ready = self
.partitions
.iter()
.filter(|(_, b)| closing || b.was_full())
.map(|(p, _)| p.clone())
.collect::<Vec<_>>();
let mut ready_batches = Vec::new();
for partition in ready {
if let Some(batch) = self.partitions.remove(&partition) {
if let Some(linger_cancel) = self.linger_handles.remove(&partition) {
// XXX: had to remove the expect here, a cancaellation should
// always be a best effort.
let _ = linger_cancel.send(partition.clone());
}
ready_batches.push(batch);
}
}
for batch in ready_batches.into_iter().chain(partitions) {
self.poll_send(batch.into_inner())?;
}
// If we still have an inflight partition then
// we should have a linger associated with it that
// will wake up this task when it is ready to be flushed.
if !self.partitions.is_empty() {
assert!(
!self.lingers.is_empty(),
"If partitions are not empty, then there must be a linger"
);
self.service.poll_complete()?;
Ok(Async::NotReady)
} else {
self.service.poll_complete()
}
}
fn close(&mut self) -> Poll<(), Self::SinkError> {
trace!("closing partition batch sink.");
self.closing = true;
self.poll_complete()
}
}
impl<B, S, K, Request> fmt::Debug for PartitionBatchSink<B, S, K, Request>
where
B: fmt::Debug,
S: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PartitionedBatchSink")
.field("batch", &self.batch)
.field("service", &self.service)
.field("timeout", &self.timeout)
.finish()
}
}
// === ServiceSink ===
struct ServiceSink<S, Request> {
service: S,
in_flight: FuturesUnordered<Receiver<(usize, usize)>>,
acker: Acker,
seq_head: usize,
seq_tail: usize,
pending_acks: HashMap<usize, usize>,
next_request_id: usize,
_pd: PhantomData<Request>,
}
impl<S, Request> ServiceSink<S, Request>
where
S: Service<Request>,
S::Future: Send + 'static,
S::Error: Into<crate::Error> + Send + 'static,
S::Response: Response,
{
fn new(service: S, acker: Acker) -> Self {
Self {
service,
in_flight: FuturesUnordered::new(),
acker,
seq_head: 0,
seq_tail: 0,
pending_acks: HashMap::new(),
next_request_id: 0,
_pd: PhantomData,
}
}
fn poll_ready(&mut self) -> Poll<(), crate::Error> {
self.service.poll_ready().map_err(Into::into)
}
fn call(
&mut self,
req: Request,
batch_size: usize,
) -> Box<dyn Future<Item = (), Error = ()> + Send + 'static> {
let seqno = self.seq_head;
self.seq_head += 1;
let (tx, rx) = oneshot::channel();
self.in_flight.push(rx);
let request_id = self.next_request_id;
self.next_request_id = request_id.wrapping_add(1);
trace!(
message = "submitting service request.",
in_flight_requests = self.in_flight.len()
);
let response = self
.service
.call(req)
.map_err(Into::into)
.then(move |result| {
match result {
Ok(response) if response.is_successful() => {
trace!(message = "Response successful.", ?response);
}
Ok(response) => {
error!(message = "Response wasn't successful.", ?response);
}
Err(error) => {
error!(
message = "Request failed.",
%error,
);
}
}
// If the rx end is dropped we still completed
// the request so this is a weird case that we can
// ignore for now.
let _ = tx.send((seqno, batch_size));
Ok::<_, ()>(())
})
.instrument(info_span!("request", %request_id));
Box::new(response)
}
fn poll_complete(&mut self) -> Poll<(), crate::Error> {
loop {
match self.in_flight.poll() {
Ok(Async::NotReady) => return Ok(Async::NotReady),
Ok(Async::Ready(None)) => return Ok(Async::Ready(())),
Ok(Async::Ready(Some((seqno, batch_size)))) => {
self.pending_acks.insert(seqno, batch_size);
let mut num_to_ack = 0;
while let Some(ack_size) = self.pending_acks.remove(&self.seq_tail) {
num_to_ack += ack_size;
self.seq_tail += 1
}
trace!(message = "acking events.", acking_num = num_to_ack);
self.acker.ack(num_to_ack);
}
Err(_) => panic!("ServiceSink service sender dropped"),
}
}
}
}
impl<S, Request> fmt::Debug for ServiceSink<S, Request>
where
S: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ServiceSink")
.field("service", &self.service)
.field("acker", &self.acker)
.field("seq_head", &self.seq_head)
.field("seq_tail", &self.seq_tail)
.field("pending_acks", &self.pending_acks)
.finish()
}
}
// === Response ===
pub trait Response: fmt::Debug {
fn is_successful(&self) -> bool {
true
}
}
impl Response for () {}
impl<'a> Response for &'a str {}
#[cfg(test)]
mod tests {
use super::*;
use crate::buffers::Acker;
use crate::sinks::util::{buffer::partition::Partition, BatchSize, VecBuffer};
use crate::test_util::runtime;
use bytes::Bytes;
use futures01::{future, Sink};
use std::{
sync::{atomic::Ordering::Relaxed, Arc, Mutex},
time::Duration,
};
use tokio01_test::clock::MockClock;
const BATCH_SIZE: BatchSize = BatchSize {
events: 10,
bytes: 9999,
};
const TIMEOUT: Duration = Duration::from_secs(10);
#[test]
fn batch_sink_acking_sequential() {
let rt = runtime();
let mut clock = MockClock::new();
let (acker, ack_counter) = Acker::new_for_testing();
let svc = tower::service_fn(|_| future::ok::<_, std::io::Error>(()));
let buffered = BatchSink::with_executor(
svc,
VecBuffer::new(BATCH_SIZE),
TIMEOUT,
acker,
rt.executor(),
);
let _ = clock.enter(|_| {
buffered
.sink_map_err(drop)
.send_all(futures01::stream::iter_ok(0..22))
.wait()
.unwrap()
});
assert_eq!(ack_counter.load(Relaxed), 22);
}
#[test]
fn batch_sink_acking_unordered() {
// We need a mock executor here because we need to ensure
// that we poll the service futures within the mock clock
// context. This allows us to manually advance the time on the
// "spawned" futures.
let mut exec = MockExec::default();
let mut clock = MockClock::new();
let (acker, ack_counter) = Acker::new_for_testing();
let svc = tower::service_fn(|req: Vec<usize>| {
let dur = match req[0] {
0 => Duration::from_secs(1),
1 => Duration::from_secs(1),
2 => Duration::from_secs(1),
// The 4th request will introduce some sort of
// latency spike to ensure later events don't
// get acked.
3 => Duration::from_secs(5),
4 => Duration::from_secs(1),
5 => Duration::from_secs(1),
_ => unreachable!(),
};
let deadline = Instant::now() + dur;
Delay::new(deadline).map(drop)
});
let batch_size = BatchSize {
events: 1,
..BATCH_SIZE
};
let mut sink = BatchSink::with_executor(
svc,
VecBuffer::new(batch_size),
TIMEOUT,
acker,
exec.clone(),
);
let _ = clock.enter(|handle| {
assert!(sink.start_send(0).unwrap().is_ready());
assert!(sink.start_send(1).unwrap().is_ready());
assert_eq!(ack_counter.load(Relaxed), 0);
handle.advance(Duration::from_secs(2));
// We must first poll so that we send the messages
// then we must pull the mock executor to set the timers
// then poll again to ack.
sink.poll_complete().unwrap();
exec.poll().unwrap();
sink.poll_complete().unwrap();
assert_eq!(ack_counter.load(Relaxed), 2);
assert!(sink.start_send(2).unwrap().is_ready());
sink.poll_complete().unwrap();
exec.poll().unwrap();
sink.poll_complete().unwrap();
assert_eq!(ack_counter.load(Relaxed), 3);
assert!(sink.start_send(3).unwrap().is_ready());
assert!(sink.start_send(4).unwrap().is_ready());
assert!(sink.start_send(5).unwrap().is_ready());
handle.advance(Duration::from_secs(2));
sink.poll_complete().unwrap();
exec.poll().unwrap();
sink.poll_complete().unwrap();
// Check that events 3,4,6 have not been acked yet
// only the three previous should be acked.
assert_eq!(ack_counter.load(Relaxed), 3);
handle.advance(Duration::from_secs(5));
exec.poll().unwrap();
sink.flush().wait().unwrap();
assert_eq!(ack_counter.load(Relaxed), 6);
});
}
#[test]
fn batch_sink_buffers_messages_until_limit() {
let rt = runtime();
let mut clock = MockClock::new();
let (acker, _) = Acker::new_for_testing();
let sent_requests = Arc::new(Mutex::new(Vec::new()));
let svc = tower::service_fn(|req| {
let sent_requests = sent_requests.clone();
sent_requests.lock().unwrap().push(req);
future::ok::<_, std::io::Error>(())
});
let buffered = BatchSink::with_executor(
svc,
VecBuffer::new(BATCH_SIZE),
TIMEOUT,
acker,
rt.executor(),
);
let _ = clock.enter(|_| {
buffered
.sink_map_err(drop)
.send_all(futures01::stream::iter_ok(0..22))
.wait()
.unwrap()
});
let output = sent_requests.lock().unwrap();
assert_eq!(
&*output,
&vec![
vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
vec![10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
vec![20, 21]
]
);
}
#[test]
fn batch_sink_flushes_below_min_on_close() {
let rt = runtime();
let mut clock = MockClock::new();
let (acker, _) = Acker::new_for_testing();
let sent_requests = Arc::new(Mutex::new(Vec::new()));
let svc = tower::service_fn(|req| {
let sent_requests = sent_requests.clone();
sent_requests.lock().unwrap().push(req);
future::ok::<_, std::io::Error>(())
});
let mut buffered = BatchSink::with_executor(
svc,
VecBuffer::new(BATCH_SIZE),
TIMEOUT,
acker,
rt.executor(),
);
clock.enter(|_| {
assert!(buffered.start_send(0).unwrap().is_ready());
assert!(buffered.start_send(1).unwrap().is_ready());
future::poll_fn(|| buffered.close()).wait().unwrap()
});
let output = sent_requests.lock().unwrap();
assert_eq!(&*output, &vec![vec![0, 1]]);
}
#[test]
fn batch_sink_expired_linger() {
let rt = runtime();
let mut clock = MockClock::new();
let (acker, _) = Acker::new_for_testing();
let sent_requests = Arc::new(Mutex::new(Vec::new()));
let svc = tower::service_fn(|req| {
let sent_requests = sent_requests.clone();
sent_requests.lock().unwrap().push(req);
future::ok::<_, std::io::Error>(())
});
let mut buffered = BatchSink::with_executor(
svc,
VecBuffer::new(BATCH_SIZE),
TIMEOUT,