batch_aint_one/processor.rs
1use std::{
2 fmt::{Debug, Display},
3 future::Future,
4 hash::Hash,
5};
6
7/// Process a batch of inputs for a given key.
8///
9/// Should be cheap to clone.
10pub trait Processor: 'static + Send + Clone {
11 /// The key used to group inputs.
12 type Key: 'static + Debug + Eq + Hash + Clone + Send + Sync;
13 /// The input type for each item.
14 type Input: Send;
15 /// The output type for each item.
16 type Output: Send;
17 /// The error type that can be returned when processing a batch.
18 type Error: Send + Clone + Display + Debug;
19 /// The resources that will be acquired before processing each batch, and can be used during
20 /// processing.
21 type Resources: Send;
22
23 /// Acquire resources to be used for processing the next batch with the given key.
24 ///
25 /// This method is called before processing each batch.
26 ///
27 /// For the `Immediate` and `Balanced` batching policies, resources can be acquired before the
28 /// batch is processed, and the batch will keep accumulating items until the resources are
29 /// acquired.
30 ///
31 /// Can be used to e.g. acquire a database connection from a pool.
32 fn acquire_resources(
33 &self,
34 key: Self::Key,
35 ) -> impl Future<Output = Result<Self::Resources, Self::Error>> + Send;
36
37 /// Process the batch.
38 ///
39 /// Must return exactly one output per input, in the same order as the inputs in the given
40 /// iterator. If the number of outputs is wrong, every item in the batch receives a
41 /// `BatchError::ProcessorInvariantViolation` error.
42 fn process(
43 &self,
44 key: Self::Key,
45 inputs: impl Iterator<Item = Self::Input> + Send,
46 resources: Self::Resources,
47 ) -> impl Future<Output = Result<Vec<Self::Output>, Self::Error>> + Send;
48}