Skip to main content

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 crate::RequestWeight;
9
10use super::{service::Batch, BatchControl};
11
12/// Adds a layer performing batch processing of requests.
13///
14/// The default Tokio executor is used to run the given service,
15/// which means that this layer can only be used on the Tokio runtime.
16///
17/// See the module documentation for more details.
18pub struct BatchLayer<Request> {
19    max_items_weight_in_batch: usize,
20    max_batches: Option<usize>,
21    max_latency: std::time::Duration,
22    max_idle: std::time::Duration,
23
24    // TODO: is the variance correct here?
25    // https://doc.rust-lang.org/1.33.0/nomicon/subtyping.html#variance
26    // https://doc.rust-lang.org/nomicon/phantom-data.html#table-of-phantomdata-patterns
27    _handles_requests: PhantomData<fn(Request)>,
28}
29
30impl<Request> BatchLayer<Request> {
31    /// Creates a new `BatchLayer`.
32    ///
33    /// The wrapper is responsible for telling the inner service when to flush a
34    /// batch of requests. See [`Batch::new()`] for details.
35    pub fn new(
36        max_items_weight_in_batch: usize,
37        max_batches: impl Into<Option<usize>>,
38        max_latency: std::time::Duration,
39        max_idle: std::time::Duration,
40    ) -> Self {
41        BatchLayer {
42            max_items_weight_in_batch,
43            max_batches: max_batches.into(),
44            max_latency,
45            max_idle,
46            _handles_requests: PhantomData,
47        }
48    }
49}
50
51impl<S, Request: RequestWeight> Layer<S> for BatchLayer<Request>
52where
53    S: Service<BatchControl<Request>> + Send + 'static,
54    S::Future: Send,
55    S::Response: Send,
56    S::Error: Into<crate::BoxError> + Send + Sync,
57    Request: Send + 'static,
58{
59    type Service = Batch<S, Request>;
60
61    fn layer(&self, service: S) -> Self::Service {
62        Batch::new(
63            service,
64            self.max_items_weight_in_batch,
65            self.max_batches,
66            self.max_latency,
67            self.max_idle,
68        )
69    }
70}
71
72impl<Request> fmt::Debug for BatchLayer<Request> {
73    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
74        f.debug_struct("BatchLayer")
75            .field("max_items_weight_in_batch", &self.max_items_weight_in_batch)
76            .field("max_batches", &self.max_batches)
77            .field("max_latency", &self.max_latency)
78            .field("max_idle", &self.max_idle)
79            .finish()
80    }
81}