tower_batch_control/
layer.rs

1//! Tower service layer for batch processing.
2
3use std::{fmt, marker::PhantomData};
4
5use tower::layer::Layer;
6use tower::Service;
7
8use super::{service::Batch, BatchControl};
9
10/// Adds a layer performing batch processing of requests.
11///
12/// The default Tokio executor is used to run the given service,
13/// which means that this layer can only be used on the Tokio runtime.
14///
15/// See the module documentation for more details.
16pub struct BatchLayer<Request> {
17    max_items_in_batch: usize,
18    max_batches: Option<usize>,
19    max_latency: std::time::Duration,
20
21    // TODO: is the variance correct here?
22    // https://doc.rust-lang.org/1.33.0/nomicon/subtyping.html#variance
23    // https://doc.rust-lang.org/nomicon/phantom-data.html#table-of-phantomdata-patterns
24    _handles_requests: PhantomData<fn(Request)>,
25}
26
27impl<Request> BatchLayer<Request> {
28    /// Creates a new `BatchLayer`.
29    ///
30    /// The wrapper is responsible for telling the inner service when to flush a
31    /// batch of requests. See [`Batch::new()`] for details.
32    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}