Skip to main content

legit_streams/
error.rs

1//! The crate's error type.
2
3use std::fmt;
4
5/// The result of a fallible operation in this crate.
6///
7/// ```
8/// fn version(task: &legit_streams::Task) -> legit_streams::Result<&str> {
9///     task.get("v").ok_or(legit_streams::Error::MissingField("v"))
10/// }
11/// # let _ = version;
12/// ```
13pub type Result<T, E = Error> = std::result::Result<T, E>;
14
15/// What went wrong. Every failure in this crate, hostile input included, is one of these; nothing
16/// panics on what a stream holds.
17///
18/// ```
19/// use legit_streams::{Error, Task};
20///
21/// let error = Task::from_fields(vec![("v".to_owned(), "2".to_owned())]).unwrap_err();
22/// assert_eq!(error, Error::UnsupportedVersion("2".to_owned()));
23/// assert_eq!(error.to_string(), "the envelope is version `2`; this crate reads version `1`");
24/// ```
25#[derive(Debug, Clone, PartialEq, Eq)]
26#[non_exhaustive]
27pub enum Error {
28    /// The Redis server refused a command, or the connection to it failed. The message is the
29    /// server's or the client's and never holds the URL's password.
30    Redis(String),
31    /// The server answered with a reply this crate can't read, such as a stream entry whose fields
32    /// don't come in pairs.
33    UnexpectedReply(String),
34    /// The consumer group doesn't exist on the stream: the server answered `NOGROUP`, as the
35    /// error's code or inside a script error's message.
36    NoGroup {
37        /// The stream.
38        stream: String,
39        /// The group.
40        group: String,
41    },
42    /// An envelope without a field the contract requires.
43    MissingField(&'static str),
44    /// A field the contract requires to be non-empty, given empty.
45    EmptyField(&'static str),
46    /// An envelope that names a field twice. Redis keeps both, and a reader that takes the fields
47    /// as a map would silently keep one, so this crate refuses the entry.
48    DuplicateField(String),
49    /// A field name or value that isn't UTF-8. The contract's values are strings.
50    InvalidUtf8 {
51        /// The field's name, with any invalid bytes replaced.
52        field: String,
53    },
54    /// A task envelope whose `v` isn't `1`, the only version this crate speaks.
55    UnsupportedVersion(String),
56    /// A field whose value the contract doesn't allow, such as a result `status` other than
57    /// `success` or `error`.
58    InvalidValue {
59        /// The field.
60        field: String,
61        /// What the contract allows.
62        expected: &'static str,
63    },
64    /// An extra field given to a builder under a name the envelope sets itself, such as
65    /// `task_id`.
66    ReservedField(String),
67    /// An entry over one of the bounds in [`Limits`](crate::Limits).
68    TooLarge {
69        /// What is over its bound: `fields`, `field name` or `entry bytes`.
70        what: &'static str,
71        /// The bound.
72        limit: usize,
73        /// The size found.
74        actual: usize,
75    },
76    /// A stream entry id that isn't `<milliseconds>-<sequence>`.
77    InvalidEntryId(String),
78    /// A task left unsent because its stream is at or over the producer's target depth.
79    StreamFull {
80        /// The stream.
81        stream: String,
82        /// Its length when checked.
83        depth: u64,
84        /// The producer's target depth.
85        target_depth: u64,
86    },
87    /// A setting that can't work, such as a lease heartbeat no shorter than the idle time after
88    /// which another worker claims the entry.
89    InvalidConfig(String),
90    /// The worker couldn't start a thread it needs.
91    Thread(String),
92    /// A fast-lane call got no reply within its timeout. The caller has taken its task back and
93    /// deleted its reply key, and the worker skips the task once its deadline passes, so nothing
94    /// is left to wait for: fall back, such as to a slower path or an error for the user.
95    Timeout {
96        /// The task's id.
97        task_id: String,
98        /// How long the call waited.
99        timeout: std::time::Duration,
100    },
101}
102
103impl fmt::Display for Error {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        match self {
106            Self::Redis(message) => write!(f, "redis: {message}"),
107            Self::UnexpectedReply(message) => write!(f, "unexpected reply from redis: {message}"),
108            Self::NoGroup { stream, group } => {
109                write!(f, "the `{group}` group doesn't exist on the `{stream}` stream")
110            }
111            Self::MissingField(field) => write!(f, "the envelope has no `{field}` field"),
112            Self::EmptyField(field) => write!(f, "the envelope's `{field}` field is empty"),
113            Self::DuplicateField(field) => write!(f, "the envelope names the `{field}` field twice"),
114            Self::InvalidUtf8 { field } => write!(f, "the envelope's `{field}` field isn't UTF-8"),
115            Self::UnsupportedVersion(version) => {
116                write!(f, "the envelope is version `{version}`; this crate reads version `1`")
117            }
118            Self::InvalidValue { field, expected } => {
119                write!(f, "the envelope's `{field}` field isn't {expected}")
120            }
121            Self::ReservedField(field) => {
122                write!(
123                    f,
124                    "the envelope sets `{field}` itself; it can't be given as an extra field"
125                )
126            }
127            Self::TooLarge { what, limit, actual } => {
128                write!(f, "the entry's {what} is {actual}, over the limit of {limit}")
129            }
130            Self::InvalidEntryId(id) => write!(f, "`{id}` isn't a stream entry id"),
131            Self::StreamFull {
132                stream,
133                depth,
134                target_depth,
135            } => write!(
136                f,
137                "the `{stream}` stream holds {depth} entries, at or over its target depth of {target_depth}; \
138                 send again once it drains"
139            ),
140            Self::InvalidConfig(message) => write!(f, "invalid configuration: {message}"),
141            Self::Thread(message) => write!(f, "couldn't start a worker thread: {message}"),
142            Self::Timeout { task_id, timeout } => {
143                write!(f, "no reply to task `{task_id}` within {} ms", timeout.as_millis())
144            }
145        }
146    }
147}
148
149impl std::error::Error for Error {}