tower_batch/
layer.rs

1use std::{fmt, marker::PhantomData, time::Duration};
2
3use tower::{layer::Layer, Service};
4
5use super::{service::Batch, BatchControl};
6
7/// Adds a layer performing batch processing of requests.
8///
9/// The default Tokio executor is used to run the given service,
10/// which means that this layer can only be used on the Tokio runtime.
11///
12/// See the module documentation for more details.
13pub struct BatchLayer<Request> {
14    size: usize,
15    time: Duration,
16    _p: PhantomData<fn(Request)>,
17}
18
19impl<Request> BatchLayer<Request> {
20    /// Creates a new [`BatchLayer`].
21    ///
22    /// The wrapper is responsible for telling the inner service when to flush a batch of requests.
23    /// Two parameters control this policy:
24    ///
25    /// * `size` gives the maximum number of items per batch.
26    /// * `time` gives the maximum duration before a batch is flushed.
27    pub fn new(size: usize, time: Duration) -> Self {
28        Self {
29            size,
30            time,
31            _p: PhantomData,
32        }
33    }
34}
35
36impl<S, Request> Layer<S> for BatchLayer<Request>
37where
38    S: Service<BatchControl<Request>> + Send + 'static,
39    S::Future: Send,
40    S::Error: Into<crate::BoxError> + Send + Sync,
41    Request: Send + 'static,
42{
43    type Service = Batch<S, Request>;
44
45    fn layer(&self, service: S) -> Self::Service {
46        Batch::new(service, self.size, self.time)
47    }
48}
49
50impl<Request> fmt::Debug for BatchLayer<Request> {
51    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52        f.debug_struct("BufferLayer")
53            .field("size", &self.size)
54            .field("time", &self.time)
55            .finish()
56    }
57}