Skip to main content

batch_aint_one/
error.rs

1//! Errors.
2
3use std::fmt::Display;
4
5use thiserror::Error;
6use tokio::sync::{mpsc::error::SendError, oneshot::error::RecvError};
7
8/// An error that occurred while trying to batch.
9#[derive(Error, Debug, Clone)]
10#[non_exhaustive]
11pub enum BatchError<E: Display> {
12    /// Something went wrong while submitting an input for processing.
13    ///
14    /// Unrecoverable.
15    #[error("Unable to send item to the worker for batching: channel closed")]
16    Tx,
17
18    /// Something went wrong while waiting for the output of a batch.
19    ///
20    /// Unrecoverable.
21    #[error("Error while waiting for batch results: channel closed. {0}")]
22    Rx(#[from] RecvError),
23
24    /// The current batch is full so the item was rejected.
25    ///
26    /// Recoverable.
27    #[error("Batch item rejected: {0}")]
28    Rejected(RejectionReason),
29
30    /// Something went wrong while processing a batch.
31    #[error("The entire batch failed")]
32    BatchFailed(#[source] E),
33
34    /// The processor violated its invariants.
35    #[error("The processor violated its invariants")]
36    ProcessorInvariantViolation(#[source] ProcessorInvariantViolation),
37
38    /// Something went wrong while acquiring resources for processing.
39    #[error("Resource acquisition failed")]
40    ResourceAcquisitionFailed(#[source] E),
41
42    /// The batch was cancelled before completion.
43    #[error("The batch was cancelled")]
44    Cancelled,
45
46    /// The batch processing (or resource acquisition) panicked.
47    #[error("The batch processing panicked")]
48    Panic,
49}
50
51/// A processor implementation violated its invariants.
52#[derive(Error, Debug, Clone)]
53#[non_exhaustive]
54pub enum ProcessorInvariantViolation {
55    /// The processor returned the wrong number of outputs for the inputs given.
56    #[error("The processor returned the wrong number of outputs: expected {expected}, got {actual}")]
57    WrongNumberOfOutputs {
58        /// The number of inputs given.
59        expected: usize,
60        /// The number of outputs returned.
61        actual: usize,
62    },
63}
64
65/// Reason for rejecting a batch item.
66#[derive(Debug, Clone, Copy)]
67#[non_exhaustive]
68pub enum RejectionReason {
69    /// The batch queue is full.
70    BatchQueueFull(ConcurrencyStatus),
71}
72
73/// Status of concurrency when rejecting a batch item.
74#[derive(Debug, Clone, Copy)]
75#[non_exhaustive]
76pub enum ConcurrencyStatus {
77    /// There is available concurrency to process another batch.
78    ///
79    /// It might be being used because batches are waiting to be processed.
80    Available,
81    /// The maximum concurrency for this key has been reached.
82    MaxedOut,
83}
84
85impl Display for RejectionReason {
86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87        f.write_str(match self {
88            RejectionReason::BatchQueueFull(concurrency) => match concurrency {
89                ConcurrencyStatus::Available => "the batch queue is full",
90                ConcurrencyStatus::MaxedOut => {
91                    "the batch queue is full and maximum concurrency reached"
92                }
93            },
94        })
95    }
96}
97
98/// Result type for batch operations.
99pub type BatchResult<T, E> = std::result::Result<T, BatchError<E>>;
100
101impl<T, E: Display> From<SendError<T>> for BatchError<E> {
102    fn from(_tx_err: SendError<T>) -> Self {
103        BatchError::Tx
104    }
105}
106
107impl<E> BatchError<E>
108where
109    E: Display,
110{
111    /// Get the inner error for general batch failures, otherwise self.
112    pub fn inner(self) -> BatchResult<E, E> {
113        match self {
114            BatchError::BatchFailed(source) => Ok(source),
115            BatchError::ResourceAcquisitionFailed(source) => Ok(source),
116            _ => Err(self),
117        }
118    }
119}