batch_aint_one/
error.rs

1use std::fmt::Display;
2
3use thiserror::Error;
4use tokio::sync::{mpsc::error::SendError, oneshot::error::RecvError};
5
6/// An error that occurred while trying to batch.
7#[derive(Error, Debug, Clone)]
8#[non_exhaustive]
9pub enum BatchError<E: Display> {
10    /// Something went wrong while submitting an input for processing.
11    ///
12    /// Unrecoverable.
13    #[error("Unable to send item to the worker for batching: channel closed")]
14    Tx,
15
16    /// Something went wrong while waiting for the output of a batch.
17    ///
18    /// Unrecoverable.
19    #[error("Error while waiting for batch results: channel closed. {0}")]
20    Rx(RecvError),
21
22    /// The current batch is full so the item was rejected.
23    ///
24    /// Recoverable.
25    #[error("Batch item rejected: {0}")]
26    Rejected(RejectionReason),
27
28    /// Something went wrong while processing a batch.
29    #[error("The entire batch failed: {0}")]
30    BatchFailed(E),
31
32    /// Something went wrong while acquiring resources for processing.
33    #[error("Resource acquisition failed: {0}")]
34    ResourceAcquisitionFailed(E),
35
36    /// The batch was cancelled before completion.
37    #[error("The batch was cancelled")]
38    Cancelled,
39
40    /// The batch processing (or resource acquisition) panicked.
41    #[error("The batch processing panicked")]
42    Panic,
43}
44
45#[derive(Debug, Clone, Copy)]
46#[non_exhaustive]
47pub enum RejectionReason {
48    /// The batch is full and still waiting to be processed.
49    BatchFull,
50    /// The batch is full and no more batches can be processed concurrently.
51    MaxConcurrency,
52}
53
54impl Display for RejectionReason {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        f.write_str(match self {
57            RejectionReason::BatchFull => "the batch is full",
58            RejectionReason::MaxConcurrency => "the key has reached maximum concurrency",
59        })
60    }
61}
62
63pub type BatchResult<T, E> = std::result::Result<T, BatchError<E>>;
64
65impl<E: Display> From<RecvError> for BatchError<E> {
66    fn from(rx_err: RecvError) -> Self {
67        BatchError::Rx(rx_err)
68    }
69}
70
71impl<T, E: Display> From<SendError<T>> for BatchError<E> {
72    fn from(_tx_err: SendError<T>) -> Self {
73        BatchError::Tx
74    }
75}
76
77impl<E> BatchError<E>
78where
79    E: Display,
80{
81    /// Get the inner error for general batch failures, otherwise self.
82    pub fn inner(self) -> BatchResult<E, E> {
83        match self {
84            BatchError::BatchFailed(source) => Ok(source),
85            _ => Err(self),
86        }
87    }
88}