tower_batch_control/
layer.rs1use std::{fmt, marker::PhantomData};
4
5use tower::layer::Layer;
6use tower::Service;
7
8use crate::RequestWeight;
9
10use super::{service::Batch, BatchControl};
11
12pub 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 _handles_requests: PhantomData<fn(Request)>,
28}
29
30impl<Request> BatchLayer<Request> {
31 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}