legit-streams 0.1.4

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
//! Stream entries as the [`Streams`](crate::Streams) commands return them.

use std::fmt;
use std::str::FromStr;
use std::time::Duration;

use crate::error::{Error, Result};

/// The id Redis gives a stream entry, `<milliseconds>-<sequence>`. Ids order entries by when they
/// were added.
///
/// ```
/// use legit_streams::EntryId;
///
/// let id: EntryId = "1700000000000-3".parse()?;
/// assert_eq!(id, EntryId::new(1_700_000_000_000, 3));
/// assert_eq!(id.to_string(), "1700000000000-3");
/// assert!(EntryId::ZERO < id);
/// # Ok::<(), legit_streams::Error>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct EntryId {
    ms: u64,
    seq: u64,
}

impl EntryId {
    /// `0-0`, the id before every entry, and the start of an `XAUTOCLAIM` scan.
    ///
    /// ```
    /// use legit_streams::EntryId;
    ///
    /// assert_eq!(EntryId::ZERO.to_string(), "0-0");
    /// ```
    pub const ZERO: Self = Self { ms: 0, seq: 0 };

    /// The id with these parts.
    ///
    /// ```
    /// use legit_streams::EntryId;
    ///
    /// assert_eq!(EntryId::new(5, 1).to_string(), "5-1");
    /// ```
    #[must_use]
    pub const fn new(ms: u64, seq: u64) -> Self {
        Self { ms, seq }
    }

    /// The milliseconds part: when the entry was added, by the server's clock.
    ///
    /// ```
    /// use legit_streams::EntryId;
    ///
    /// assert_eq!(EntryId::new(5, 1).ms(), 5);
    /// ```
    #[must_use]
    pub const fn ms(&self) -> u64 {
        self.ms
    }

    /// The sequence part, which orders entries added in the same millisecond.
    ///
    /// ```
    /// use legit_streams::EntryId;
    ///
    /// assert_eq!(EntryId::new(5, 1).seq(), 1);
    /// ```
    #[must_use]
    pub const fn seq(&self) -> u64 {
        self.seq
    }
}

impl fmt::Display for EntryId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}-{}", self.ms, self.seq)
    }
}

impl FromStr for EntryId {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        let invalid = || Error::InvalidEntryId(s.chars().take(64).collect());
        let (ms, seq) = s.split_once('-').ok_or_else(invalid)?;
        let digits = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
        if !digits(ms) || !digits(seq) {
            return Err(invalid());
        }
        Ok(Self {
            ms: ms.parse().map_err(|_| invalid())?,
            seq: seq.parse().map_err(|_| invalid())?,
        })
    }
}

/// The raw fields of a stream entry, in the order they were added, as bytes: Redis stores bytes,
/// and the envelopes check that they're UTF-8.
///
/// ```
/// let fields: legit_streams::RawFields = vec![(b"v".to_vec(), b"1".to_vec())];
/// assert_eq!(fields.len(), 1);
/// ```
pub type RawFields = Vec<(Vec<u8>, Vec<u8>)>;

/// A stream entry: its id and its raw fields.
///
/// ```
/// use legit_streams::{Entry, EntryId};
///
/// let entry = Entry::new(EntryId::new(1, 0), vec![(b"task_id".to_vec(), b"app_1".to_vec())]);
/// assert_eq!(entry.field("task_id"), Some(&b"app_1"[..]));
/// assert_eq!(entry.field("v"), None);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
    /// The entry's id.
    pub id: EntryId,
    /// The entry's fields, in order.
    pub fields: RawFields,
}

impl Entry {
    /// An entry with this id and these fields.
    ///
    /// ```
    /// use legit_streams::{Entry, EntryId};
    ///
    /// assert!(Entry::new(EntryId::ZERO, Vec::new()).fields.is_empty());
    /// ```
    #[must_use]
    pub const fn new(id: EntryId, fields: RawFields) -> Self {
        Self { id, fields }
    }

    /// The value of the first field with this name.
    ///
    /// ```
    /// use legit_streams::{Entry, EntryId};
    ///
    /// let entry = Entry::new(EntryId::ZERO, vec![(b"v".to_vec(), b"1".to_vec())]);
    /// assert_eq!(entry.field("v"), Some(&b"1"[..]));
    /// ```
    #[must_use]
    pub fn field(&self, name: &str) -> Option<&[u8]> {
        self.fields
            .iter()
            .find(|(key, _)| key == name.as_bytes())
            .map(|(_, value)| value.as_slice())
    }
}

/// One entry of a consumer group's pending entries list, as `XPENDING` reports it.
///
/// ```
/// use std::time::Duration;
/// use legit_streams::{EntryId, Pending};
///
/// let pending = Pending { id: EntryId::new(1, 0), consumer: "worker-1".into(), idle: Duration::ZERO, deliveries: 1 };
/// assert_eq!(pending.deliveries, 1);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pending {
    /// The entry.
    pub id: EntryId,
    /// The consumer that owns it.
    pub consumer: String,
    /// How long since it was last delivered or claimed.
    pub idle: Duration,
    /// How many times it has been delivered: once by `XREADGROUP`, and once more by each claim
    /// that doesn't pass `JUSTID`.
    pub deliveries: u64,
}

/// What `XAUTOCLAIM` returns.
///
/// ```
/// use legit_streams::{AutoClaim, EntryId};
///
/// let claim = AutoClaim { next: EntryId::ZERO, claimed: Vec::new(), deleted: Vec::new() };
/// assert!(claim.claimed.is_empty());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct AutoClaim {
    /// Where the next scan starts; [`EntryId::ZERO`] once the scan has covered the whole list.
    pub next: EntryId,
    /// The entries claimed, with their fields.
    pub claimed: Vec<Entry>,
    /// Pending entries whose stream entry is gone. Redis 7 drops them from the pending list and
    /// lists them here; Redis 6.2 claims them with no fields, and they're listed here too, still
    /// pending, so the caller acknowledges them either way.
    pub deleted: Vec<EntryId>,
}

/// How much work a consumer group hasn't finished, as `XINFO GROUPS` reports it: what
/// [`Streams::group_backlog`](crate::Streams::group_backlog) returns.
///
/// [`GroupBacklog::waiting`] is the figure to read for "how many tasks wait": the server's own
/// count when it gives one, otherwise an estimate from the stream's length, marked as such.
///
/// ```
/// use legit_streams::{GroupBacklog, Waiting};
///
/// let backlog = GroupBacklog::new(64, Some(1_203));
/// assert_eq!((backlog.pending, backlog.lag, backlog.length), (64, Some(1_203), None));
/// assert_eq!(backlog.waiting(), Some(Waiting::Exact(1_203)));
///
/// // The server gave no lag; the stream held 1,267 entries, 64 of them pending.
/// let backlog = GroupBacklog::new(64, None).with_length(1_267);
/// assert_eq!(backlog.waiting(), Some(Waiting::Estimate(1_203)));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct GroupBacklog {
    /// Entries delivered to a consumer of the group and not acknowledged: the length of the
    /// group's pending list.
    pub pending: u64,
    /// Entries in the stream not yet delivered to the group, as the server counts them. `None`
    /// when the server doesn't report it: Redis before 7.0 has no `lag`, and Redis 7 and newer
    /// answer nil once an `XDEL` has left the group's count of entries read unknown (the crate's
    /// README says when, as measured).
    pub lag: Option<u64>,
    /// The stream's length, when the implementation read it. [`RedisStreams`](crate::RedisStreams)
    /// reads it only when the server gives no lag; [`MemoryStreams`](crate::MemoryStreams)
    /// always does.
    pub length: Option<u64>,
}

impl GroupBacklog {
    /// A backlog of these counts, with no length, for an implementation of
    /// [`Streams`](crate::Streams) outside this crate.
    ///
    /// ```
    /// let backlog = legit_streams::GroupBacklog::new(0, None);
    /// assert_eq!((backlog.lag, backlog.length), (None, None));
    /// ```
    #[must_use]
    pub const fn new(pending: u64, lag: Option<u64>) -> Self {
        Self {
            pending,
            lag,
            length: None,
        }
    }

    /// The same backlog with the stream's length.
    ///
    /// ```
    /// let backlog = legit_streams::GroupBacklog::new(2, None).with_length(5);
    /// assert_eq!(backlog.length, Some(5));
    /// ```
    #[must_use]
    pub const fn with_length(mut self, length: u64) -> Self {
        self.length = Some(length);
        self
    }

    /// How many entries wait for the group: [`Waiting::Exact`] with the server's lag when it
    /// gives one; otherwise [`Waiting::Estimate`], the stream's length less the pending entries,
    /// at least 0; `None` when neither the lag nor the length is known. The lag always wins: the
    /// estimate never overrides it.
    ///
    /// The estimate is right for a stream that one consumer group reads and whose workers delete
    /// what they acknowledge, as this crate's [`Worker`](crate::Worker) and
    /// [`FastWorker`](crate::FastWorker) do. It is off when:
    ///
    /// - entries are acknowledged and not yet deleted: they are counted, so it runs high by at
    ///   most the tasks finishing at that instant, and corrects itself;
    /// - a worker died between the acknowledgement and the delete: the entry stays in the stream
    ///   for good, never delivered again, and the estimate is one too high from then on. So an
    ///   estimate never says that a stream is drained: a drained group's lag is an exact 0;
    /// - entries were trimmed (`MAXLEN`, `MINID`) or deleted while pending: they stay in the
    ///   pending list until acknowledged, so pending can exceed the length, hence the floor at 0,
    ///   and the estimate can run low;
    /// - a second consumer group reads the stream: the length then counts that group's work too,
    ///   and the estimate means nothing.
    ///
    /// ```
    /// use legit_streams::{GroupBacklog, Waiting};
    ///
    /// assert_eq!(GroupBacklog::new(3, Some(0)).with_length(9).waiting(), Some(Waiting::Exact(0)));
    /// assert_eq!(GroupBacklog::new(3, None).with_length(9).waiting(), Some(Waiting::Estimate(6)));
    /// // More pending than the stream holds, after a trim: never below 0.
    /// assert_eq!(GroupBacklog::new(64, None).with_length(9).waiting(), Some(Waiting::Estimate(0)));
    /// assert_eq!(GroupBacklog::new(3, None).waiting(), None);
    /// ```
    #[must_use]
    pub const fn waiting(&self) -> Option<Waiting> {
        match (self.lag, self.length) {
            (Some(lag), _) => Some(Waiting::Exact(lag)),
            (None, Some(length)) => Some(Waiting::Estimate(length.saturating_sub(self.pending))),
            (None, None) => None,
        }
    }
}

/// How many entries wait for a consumer group, and whether the server counted them: what
/// [`GroupBacklog::waiting`] returns.
///
/// ```
/// use legit_streams::Waiting;
///
/// assert_eq!((Waiting::Exact(7).count(), Waiting::Exact(7).is_exact()), (7, true));
/// assert_eq!((Waiting::Estimate(7).count(), Waiting::Estimate(7).is_exact()), (7, false));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Waiting {
    /// The server's own count, the group's `lag`. An exact 0 is the only sign that a group is
    /// drained.
    Exact(u64),
    /// The stream's length less the group's pending entries, at least 0, when the server gave no
    /// lag. See [`GroupBacklog::waiting`] for when it is off.
    Estimate(u64),
}

impl Waiting {
    /// The number of entries, exact or estimated.
    ///
    /// ```
    /// assert_eq!(legit_streams::Waiting::Estimate(3).count(), 3);
    /// ```
    #[must_use]
    pub const fn count(self) -> u64 {
        match self {
            Self::Exact(count) | Self::Estimate(count) => count,
        }
    }

    /// Whether the count is the server's own.
    ///
    /// ```
    /// assert!(legit_streams::Waiting::Exact(0).is_exact());
    /// ```
    #[must_use]
    pub const fn is_exact(self) -> bool {
        matches!(self, Self::Exact(_))
    }
}

/// What [`Streams::renew_lease`](crate::Streams::renew_lease) found.
///
/// ```
/// use legit_streams::{LostLease, Renewal};
///
/// assert!(Renewal::Renewed.is_renewed());
/// assert!(!Renewal::Lost(LostLease::OtherConsumer).is_renewed());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Renewal {
    /// The entry was pending for this consumer; its idle time is now 0.
    Renewed,
    /// The entry wasn't this consumer's: nothing changed, and the lease is lost.
    Lost(LostLease),
}

impl Renewal {
    /// Whether the lease was renewed.
    ///
    /// ```
    /// assert!(legit_streams::Renewal::Renewed.is_renewed());
    /// ```
    #[must_use]
    pub const fn is_renewed(self) -> bool {
        matches!(self, Self::Renewed)
    }
}

/// Why a lease was lost. A worker treats both the same: it writes no result and leaves the entry
/// alone. The two are kept apart for log lines.
///
/// ```
/// use legit_streams::LostLease;
///
/// assert_ne!(LostLease::NotPending, LostLease::OtherConsumer);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LostLease {
    /// The entry isn't in the group's pending list: it was acknowledged, or it was deleted from
    /// the stream (the renewal then drops it from the pending list).
    NotPending,
    /// Another consumer owns the entry, such as a worker that claimed it once it sat idle.
    OtherConsumer,
}

impl fmt::Display for LostLease {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::NotPending => "the entry is no longer pending",
            Self::OtherConsumer => "another consumer owns the entry",
        })
    }
}