legit_streams/entry.rs
1//! Stream entries as the [`Streams`](crate::Streams) commands return them.
2
3use std::fmt;
4use std::str::FromStr;
5use std::time::Duration;
6
7use crate::error::{Error, Result};
8
9/// The id Redis gives a stream entry, `<milliseconds>-<sequence>`. Ids order entries by when they
10/// were added.
11///
12/// ```
13/// use legit_streams::EntryId;
14///
15/// let id: EntryId = "1700000000000-3".parse()?;
16/// assert_eq!(id, EntryId::new(1_700_000_000_000, 3));
17/// assert_eq!(id.to_string(), "1700000000000-3");
18/// assert!(EntryId::ZERO < id);
19/// # Ok::<(), legit_streams::Error>(())
20/// ```
21#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
22pub struct EntryId {
23 ms: u64,
24 seq: u64,
25}
26
27impl EntryId {
28 /// `0-0`, the id before every entry, and the start of an `XAUTOCLAIM` scan.
29 ///
30 /// ```
31 /// use legit_streams::EntryId;
32 ///
33 /// assert_eq!(EntryId::ZERO.to_string(), "0-0");
34 /// ```
35 pub const ZERO: Self = Self { ms: 0, seq: 0 };
36
37 /// The id with these parts.
38 ///
39 /// ```
40 /// use legit_streams::EntryId;
41 ///
42 /// assert_eq!(EntryId::new(5, 1).to_string(), "5-1");
43 /// ```
44 #[must_use]
45 pub const fn new(ms: u64, seq: u64) -> Self {
46 Self { ms, seq }
47 }
48
49 /// The milliseconds part: when the entry was added, by the server's clock.
50 ///
51 /// ```
52 /// use legit_streams::EntryId;
53 ///
54 /// assert_eq!(EntryId::new(5, 1).ms(), 5);
55 /// ```
56 #[must_use]
57 pub const fn ms(&self) -> u64 {
58 self.ms
59 }
60
61 /// The sequence part, which orders entries added in the same millisecond.
62 ///
63 /// ```
64 /// use legit_streams::EntryId;
65 ///
66 /// assert_eq!(EntryId::new(5, 1).seq(), 1);
67 /// ```
68 #[must_use]
69 pub const fn seq(&self) -> u64 {
70 self.seq
71 }
72}
73
74impl fmt::Display for EntryId {
75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76 write!(f, "{}-{}", self.ms, self.seq)
77 }
78}
79
80impl FromStr for EntryId {
81 type Err = Error;
82
83 fn from_str(s: &str) -> Result<Self> {
84 let invalid = || Error::InvalidEntryId(s.chars().take(64).collect());
85 let (ms, seq) = s.split_once('-').ok_or_else(invalid)?;
86 let digits = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
87 if !digits(ms) || !digits(seq) {
88 return Err(invalid());
89 }
90 Ok(Self {
91 ms: ms.parse().map_err(|_| invalid())?,
92 seq: seq.parse().map_err(|_| invalid())?,
93 })
94 }
95}
96
97/// The raw fields of a stream entry, in the order they were added, as bytes: Redis stores bytes,
98/// and the envelopes check that they're UTF-8.
99///
100/// ```
101/// let fields: legit_streams::RawFields = vec![(b"v".to_vec(), b"1".to_vec())];
102/// assert_eq!(fields.len(), 1);
103/// ```
104pub type RawFields = Vec<(Vec<u8>, Vec<u8>)>;
105
106/// A stream entry: its id and its raw fields.
107///
108/// ```
109/// use legit_streams::{Entry, EntryId};
110///
111/// let entry = Entry::new(EntryId::new(1, 0), vec![(b"task_id".to_vec(), b"app_1".to_vec())]);
112/// assert_eq!(entry.field("task_id"), Some(&b"app_1"[..]));
113/// assert_eq!(entry.field("v"), None);
114/// ```
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct Entry {
117 /// The entry's id.
118 pub id: EntryId,
119 /// The entry's fields, in order.
120 pub fields: RawFields,
121}
122
123impl Entry {
124 /// An entry with this id and these fields.
125 ///
126 /// ```
127 /// use legit_streams::{Entry, EntryId};
128 ///
129 /// assert!(Entry::new(EntryId::ZERO, Vec::new()).fields.is_empty());
130 /// ```
131 #[must_use]
132 pub const fn new(id: EntryId, fields: RawFields) -> Self {
133 Self { id, fields }
134 }
135
136 /// The value of the first field with this name.
137 ///
138 /// ```
139 /// use legit_streams::{Entry, EntryId};
140 ///
141 /// let entry = Entry::new(EntryId::ZERO, vec![(b"v".to_vec(), b"1".to_vec())]);
142 /// assert_eq!(entry.field("v"), Some(&b"1"[..]));
143 /// ```
144 #[must_use]
145 pub fn field(&self, name: &str) -> Option<&[u8]> {
146 self.fields
147 .iter()
148 .find(|(key, _)| key == name.as_bytes())
149 .map(|(_, value)| value.as_slice())
150 }
151}
152
153/// One entry of a consumer group's pending entries list, as `XPENDING` reports it.
154///
155/// ```
156/// use std::time::Duration;
157/// use legit_streams::{EntryId, Pending};
158///
159/// let pending = Pending { id: EntryId::new(1, 0), consumer: "worker-1".into(), idle: Duration::ZERO, deliveries: 1 };
160/// assert_eq!(pending.deliveries, 1);
161/// ```
162#[derive(Debug, Clone, PartialEq, Eq)]
163pub struct Pending {
164 /// The entry.
165 pub id: EntryId,
166 /// The consumer that owns it.
167 pub consumer: String,
168 /// How long since it was last delivered or claimed.
169 pub idle: Duration,
170 /// How many times it has been delivered: once by `XREADGROUP`, and once more by each claim
171 /// that doesn't pass `JUSTID`.
172 pub deliveries: u64,
173}
174
175/// What `XAUTOCLAIM` returns.
176///
177/// ```
178/// use legit_streams::{AutoClaim, EntryId};
179///
180/// let claim = AutoClaim { next: EntryId::ZERO, claimed: Vec::new(), deleted: Vec::new() };
181/// assert!(claim.claimed.is_empty());
182/// ```
183#[derive(Debug, Clone, PartialEq, Eq, Default)]
184pub struct AutoClaim {
185 /// Where the next scan starts; [`EntryId::ZERO`] once the scan has covered the whole list.
186 pub next: EntryId,
187 /// The entries claimed, with their fields.
188 pub claimed: Vec<Entry>,
189 /// Pending entries whose stream entry is gone. Redis 7 drops them from the pending list and
190 /// lists them here; Redis 6.2 claims them with no fields, and they're listed here too, still
191 /// pending, so the caller acknowledges them either way.
192 pub deleted: Vec<EntryId>,
193}
194
195/// How much work a consumer group hasn't finished, as `XINFO GROUPS` reports it: what
196/// [`Streams::group_backlog`](crate::Streams::group_backlog) returns.
197///
198/// ```
199/// use legit_streams::GroupBacklog;
200///
201/// let backlog = GroupBacklog::new(64, Some(1_203));
202/// assert_eq!((backlog.pending, backlog.lag), (64, Some(1_203)));
203/// ```
204#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
205#[non_exhaustive]
206pub struct GroupBacklog {
207 /// Entries delivered to a consumer of the group and not acknowledged: the length of the
208 /// group's pending list.
209 pub pending: u64,
210 /// Entries in the stream not yet delivered to the group. `None` when the server doesn't
211 /// report it: Redis before 7.0 has no `lag`, and Redis 7 and newer answer nil once entries
212 /// the group hasn't read have been deleted.
213 pub lag: Option<u64>,
214}
215
216impl GroupBacklog {
217 /// A backlog of these counts, for an implementation of [`Streams`](crate::Streams) outside
218 /// this crate.
219 ///
220 /// ```
221 /// assert_eq!(legit_streams::GroupBacklog::new(0, None).lag, None);
222 /// ```
223 #[must_use]
224 pub const fn new(pending: u64, lag: Option<u64>) -> Self {
225 Self { pending, lag }
226 }
227}
228
229/// What [`Streams::renew_lease`](crate::Streams::renew_lease) found.
230///
231/// ```
232/// use legit_streams::{LostLease, Renewal};
233///
234/// assert!(Renewal::Renewed.is_renewed());
235/// assert!(!Renewal::Lost(LostLease::OtherConsumer).is_renewed());
236/// ```
237#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238pub enum Renewal {
239 /// The entry was pending for this consumer; its idle time is now 0.
240 Renewed,
241 /// The entry wasn't this consumer's: nothing changed, and the lease is lost.
242 Lost(LostLease),
243}
244
245impl Renewal {
246 /// Whether the lease was renewed.
247 ///
248 /// ```
249 /// assert!(legit_streams::Renewal::Renewed.is_renewed());
250 /// ```
251 #[must_use]
252 pub const fn is_renewed(self) -> bool {
253 matches!(self, Self::Renewed)
254 }
255}
256
257/// Why a lease was lost. A worker treats both the same: it writes no result and leaves the entry
258/// alone. The two are kept apart for log lines.
259///
260/// ```
261/// use legit_streams::LostLease;
262///
263/// assert_ne!(LostLease::NotPending, LostLease::OtherConsumer);
264/// ```
265#[derive(Debug, Clone, Copy, PartialEq, Eq)]
266pub enum LostLease {
267 /// The entry isn't in the group's pending list: it was acknowledged, or it was deleted from
268 /// the stream (the renewal then drops it from the pending list).
269 NotPending,
270 /// Another consumer owns the entry, such as a worker that claimed it once it sat idle.
271 OtherConsumer,
272}
273
274impl fmt::Display for LostLease {
275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276 f.write_str(match self {
277 Self::NotPending => "the entry is no longer pending",
278 Self::OtherConsumer => "another consumer owns the entry",
279 })
280 }
281}