use std::{fmt, marker::PhantomData};
use tower::layer::Layer;
use tower::Service;
use super::{service::Batch, BatchControl};
pub struct BatchLayer<Request> {
max_items_in_batch: usize,
max_batches: Option<usize>,
max_latency: std::time::Duration,
_handles_requests: PhantomData<fn(Request)>,
}
impl<Request> BatchLayer<Request> {
pub fn new(
max_items_in_batch: usize,
max_batches: impl Into<Option<usize>>,
max_latency: std::time::Duration,
) -> Self {
BatchLayer {
max_items_in_batch,
max_batches: max_batches.into(),
max_latency,
_handles_requests: PhantomData,
}
}
}
impl<S, Request> Layer<S> for BatchLayer<Request>
where
S: Service<BatchControl<Request>> + Send + 'static,
S::Future: Send,
S::Response: Send,
S::Error: Into<crate::BoxError> + Send + Sync,
Request: Send + 'static,
{
type Service = Batch<S, Request>;
fn layer(&self, service: S) -> Self::Service {
Batch::new(
service,
self.max_items_in_batch,
self.max_batches,
self.max_latency,
)
}
}
impl<Request> fmt::Debug for BatchLayer<Request> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("BufferLayer")
.field("max_items_in_batch", &self.max_items_in_batch)
.field("max_batches", &self.max_batches)
.field("max_latency", &self.max_latency)
.finish()
}
}