tower_batch_control/
layer.rs
1use std::{fmt, marker::PhantomData};
4
5use tower::layer::Layer;
6use tower::Service;
7
8use super::{service::Batch, BatchControl};
9
10pub struct BatchLayer<Request> {
17 max_items_in_batch: usize,
18 max_batches: Option<usize>,
19 max_latency: std::time::Duration,
20
21 _handles_requests: PhantomData<fn(Request)>,
25}
26
27impl<Request> BatchLayer<Request> {
28 pub fn new(
33 max_items_in_batch: usize,
34 max_batches: impl Into<Option<usize>>,
35 max_latency: std::time::Duration,
36 ) -> Self {
37 BatchLayer {
38 max_items_in_batch,
39 max_batches: max_batches.into(),
40 max_latency,
41 _handles_requests: PhantomData,
42 }
43 }
44}
45
46impl<S, Request> Layer<S> for BatchLayer<Request>
47where
48 S: Service<BatchControl<Request>> + Send + 'static,
49 S::Future: Send,
50 S::Response: Send,
51 S::Error: Into<crate::BoxError> + Send + Sync,
52 Request: Send + 'static,
53{
54 type Service = Batch<S, Request>;
55
56 fn layer(&self, service: S) -> Self::Service {
57 Batch::new(
58 service,
59 self.max_items_in_batch,
60 self.max_batches,
61 self.max_latency,
62 )
63 }
64}
65
66impl<Request> fmt::Debug for BatchLayer<Request> {
67 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
68 f.debug_struct("BufferLayer")
69 .field("max_items_in_batch", &self.max_items_in_batch)
70 .field("max_batches", &self.max_batches)
71 .field("max_latency", &self.max_latency)
72 .finish()
73 }
74}