legit-streams 0.1.2

A Redis Streams work contract for task and result envelopes, with a worker loop that leases, reclaims and replies, a producer and a result reader
Documentation
//! The crate's error type.

use std::fmt;

/// The result of a fallible operation in this crate.
///
/// ```
/// fn version(task: &legit_streams::Task) -> legit_streams::Result<&str> {
///     task.get("v").ok_or(legit_streams::Error::MissingField("v"))
/// }
/// # let _ = version;
/// ```
pub type Result<T, E = Error> = std::result::Result<T, E>;

/// What went wrong. Every failure in this crate, hostile input included, is one of these; nothing
/// panics on what a stream holds.
///
/// ```
/// use legit_streams::{Error, Task};
///
/// let error = Task::from_fields(vec![("v".to_owned(), "2".to_owned())]).unwrap_err();
/// assert_eq!(error, Error::UnsupportedVersion("2".to_owned()));
/// assert_eq!(error.to_string(), "the envelope is version `2`; this crate reads version `1`");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
    /// The Redis server refused a command, or the connection to it failed. The message is the
    /// server's or the client's and never holds the URL's password.
    Redis(String),
    /// The server answered with a reply this crate can't read, such as a stream entry whose fields
    /// don't come in pairs.
    UnexpectedReply(String),
    /// The consumer group doesn't exist on the stream: the server answered `NOGROUP`, as the
    /// error's code or inside a script error's message.
    NoGroup {
        /// The stream.
        stream: String,
        /// The group.
        group: String,
    },
    /// An envelope without a field the contract requires.
    MissingField(&'static str),
    /// A field the contract requires to be non-empty, given empty.
    EmptyField(&'static str),
    /// An envelope that names a field twice. Redis keeps both, and a reader that takes the fields
    /// as a map would silently keep one, so this crate refuses the entry.
    DuplicateField(String),
    /// A field name or value that isn't UTF-8. The contract's values are strings.
    InvalidUtf8 {
        /// The field's name, with any invalid bytes replaced.
        field: String,
    },
    /// A task envelope whose `v` isn't `1`, the only version this crate speaks.
    UnsupportedVersion(String),
    /// A field whose value the contract doesn't allow, such as a result `status` other than
    /// `success` or `error`.
    InvalidValue {
        /// The field.
        field: String,
        /// What the contract allows.
        expected: &'static str,
    },
    /// An extra field given to a builder under a name the envelope sets itself, such as
    /// `task_id`.
    ReservedField(String),
    /// An entry over one of the bounds in [`Limits`](crate::Limits).
    TooLarge {
        /// What is over its bound: `fields`, `field name` or `entry bytes`.
        what: &'static str,
        /// The bound.
        limit: usize,
        /// The size found.
        actual: usize,
    },
    /// A stream entry id that isn't `<milliseconds>-<sequence>`.
    InvalidEntryId(String),
    /// A task left unsent because its stream is at or over the producer's target depth.
    StreamFull {
        /// The stream.
        stream: String,
        /// Its length when checked.
        depth: u64,
        /// The producer's target depth.
        target_depth: u64,
    },
    /// A setting that can't work, such as a lease heartbeat no shorter than the idle time after
    /// which another worker claims the entry.
    InvalidConfig(String),
    /// The worker couldn't start a thread it needs.
    Thread(String),
    /// A fast-lane call got no reply within its timeout. The caller has taken its task back and
    /// deleted its reply key, and the worker skips the task once its deadline passes, so nothing
    /// is left to wait for: fall back, such as to a slower path or an error for the user.
    Timeout {
        /// The task's id.
        task_id: String,
        /// How long the call waited.
        timeout: std::time::Duration,
    },
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Redis(message) => write!(f, "redis: {message}"),
            Self::UnexpectedReply(message) => write!(f, "unexpected reply from redis: {message}"),
            Self::NoGroup { stream, group } => {
                write!(f, "the `{group}` group doesn't exist on the `{stream}` stream")
            }
            Self::MissingField(field) => write!(f, "the envelope has no `{field}` field"),
            Self::EmptyField(field) => write!(f, "the envelope's `{field}` field is empty"),
            Self::DuplicateField(field) => write!(f, "the envelope names the `{field}` field twice"),
            Self::InvalidUtf8 { field } => write!(f, "the envelope's `{field}` field isn't UTF-8"),
            Self::UnsupportedVersion(version) => {
                write!(f, "the envelope is version `{version}`; this crate reads version `1`")
            }
            Self::InvalidValue { field, expected } => {
                write!(f, "the envelope's `{field}` field isn't {expected}")
            }
            Self::ReservedField(field) => {
                write!(
                    f,
                    "the envelope sets `{field}` itself; it can't be given as an extra field"
                )
            }
            Self::TooLarge { what, limit, actual } => {
                write!(f, "the entry's {what} is {actual}, over the limit of {limit}")
            }
            Self::InvalidEntryId(id) => write!(f, "`{id}` isn't a stream entry id"),
            Self::StreamFull {
                stream,
                depth,
                target_depth,
            } => write!(
                f,
                "the `{stream}` stream holds {depth} entries, at or over its target depth of {target_depth}; \
                 send again once it drains"
            ),
            Self::InvalidConfig(message) => write!(f, "invalid configuration: {message}"),
            Self::Thread(message) => write!(f, "couldn't start a worker thread: {message}"),
            Self::Timeout { task_id, timeout } => {
                write!(f, "no reply to task `{task_id}` within {} ms", timeout.as_millis())
            }
        }
    }
}

impl std::error::Error for Error {}