1use std::fmt::Display;
4
5use thiserror::Error;
6use tokio::sync::{mpsc::error::SendError, oneshot::error::RecvError};
7
8#[derive(Error, Debug, Clone)]
10#[non_exhaustive]
11pub enum BatchError<E: Display> {
12 #[error("Unable to send item to the worker for batching: channel closed")]
16 Tx,
17
18 #[error("Error while waiting for batch results: channel closed. {0}")]
22 Rx(#[from] RecvError),
23
24 #[error("Batch item rejected: {0}")]
28 Rejected(RejectionReason),
29
30 #[error("The entire batch failed")]
32 BatchFailed(#[source] E),
33
34 #[error("The processor violated its invariants")]
36 ProcessorInvariantViolation(#[source] ProcessorInvariantViolation),
37
38 #[error("Resource acquisition failed")]
40 ResourceAcquisitionFailed(#[source] E),
41
42 #[error("The batch was cancelled")]
44 Cancelled,
45
46 #[error("The batch processing panicked")]
48 Panic,
49}
50
51#[derive(Error, Debug, Clone)]
53#[non_exhaustive]
54pub enum ProcessorInvariantViolation {
55 #[error("The processor returned the wrong number of outputs: expected {expected}, got {actual}")]
57 WrongNumberOfOutputs {
58 expected: usize,
60 actual: usize,
62 },
63}
64
65#[derive(Debug, Clone, Copy)]
67#[non_exhaustive]
68pub enum RejectionReason {
69 BatchQueueFull(ConcurrencyStatus),
71}
72
73#[derive(Debug, Clone, Copy)]
75#[non_exhaustive]
76pub enum ConcurrencyStatus {
77 Available,
81 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
98pub 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 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}