legit-streams 0.1.3

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.
///
/// ```
/// use legit_streams::GroupBacklog;
///
/// let backlog = GroupBacklog::new(64, Some(1_203));
/// assert_eq!((backlog.pending, backlog.lag), (64, Some(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. `None` when the server doesn't
    /// report it: Redis before 7.0 has no `lag`, and Redis 7 and newer answer nil once entries
    /// the group hasn't read have been deleted.
    pub lag: Option<u64>,
}

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

/// 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",
        })
    }
}