Skip to main content

legit_streams/
memory.rs

1//! An in-memory double of the stream commands, for tests.
2
3use std::collections::{BTreeMap, BTreeSet, HashMap};
4use std::fmt;
5use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
6use std::time::Duration;
7
8use crate::clock::{Clock, Signal};
9use crate::entry::{AutoClaim, Entry, EntryId, GroupBacklog, LostLease, Pending, RawFields, Renewal};
10use crate::error::{Error, Result};
11use crate::streams::{Streams, expire_seconds};
12
13/// The stream commands of [`Streams`] run in memory, with the semantics Redis 7 gives them, on a
14/// [`Clock`] the test controls: entry ids, idle times and blocking reads follow its time, so lease
15/// expiry, idle claims and delivery counts can be tested to the millisecond.
16///
17/// It implements exactly the commands the trait names, and keeps no trimming or persistence. A key
18/// given an expiry with `EXPIRE` goes once the clock passes it, as Redis expires keys: every
19/// command and inspection sees it gone. `XAUTOCLAIM` reports deleted entries the Redis 7 way. A
20/// blocking read on a manual clock waits until an entry arrives or the test advances the clock
21/// past its timeout.
22///
23/// The double is a cheap handle; clones share one set of streams.
24///
25/// ```
26/// use std::time::Duration;
27/// use legit_streams::{Clock, EntryId, MemoryStreams, Streams};
28///
29/// let clock = Clock::manual(1_000);
30/// let streams = MemoryStreams::with_clock(clock.clone());
31/// streams.xgroup_create("hash_tasks", "hash_workers")?;
32/// let id = streams.xadd("hash_tasks", &[(b"task_id".as_slice(), b"app_1".as_slice())])?;
33/// streams.xreadgroup("hash_tasks", "hash_workers", "a", 1, None)?;
34///
35/// clock.advance(Duration::from_secs(300));
36/// let claim = streams.xautoclaim("hash_tasks", "hash_workers", "b", Duration::from_secs(300), EntryId::ZERO, 1)?;
37/// assert_eq!(claim.claimed[0].id, id);
38/// assert_eq!(streams.xpending_entry("hash_tasks", "hash_workers", id)?.map(|p| p.deliveries), Some(2));
39/// # Ok::<(), legit_streams::Error>(())
40/// ```
41#[derive(Clone)]
42pub struct MemoryStreams {
43    inner: Arc<Inner>,
44}
45
46struct Inner {
47    clock: Clock,
48    state: Mutex<HashMap<String, Stream>>,
49    added: Signal,
50}
51
52#[derive(Default)]
53struct Stream {
54    entries: BTreeMap<EntryId, RawFields>,
55    last_id: EntryId,
56    groups: HashMap<String, Group>,
57    /// When the key goes, in milliseconds since the epoch on the double's clock.
58    expires_at: Option<u64>,
59}
60
61#[derive(Default)]
62struct Group {
63    last_delivered: EntryId,
64    pending: BTreeMap<EntryId, Nack>,
65    consumers: BTreeSet<String>,
66}
67
68struct Nack {
69    consumer: String,
70    delivered_ms: u64,
71    deliveries: u64,
72}
73
74impl MemoryStreams {
75    /// An empty double on the system clock.
76    ///
77    /// ```
78    /// use legit_streams::{MemoryStreams, Streams};
79    ///
80    /// assert_eq!(MemoryStreams::new().xlen("hash_tasks")?, 0);
81    /// # Ok::<(), legit_streams::Error>(())
82    /// ```
83    #[must_use]
84    pub fn new() -> Self {
85        Self::with_clock(Clock::system())
86    }
87
88    /// An empty double on `clock`.
89    ///
90    /// ```
91    /// use legit_streams::{Clock, MemoryStreams};
92    ///
93    /// let streams = MemoryStreams::with_clock(Clock::manual(0));
94    /// assert!(streams.clock().is_manual());
95    /// ```
96    #[must_use]
97    pub fn with_clock(clock: Clock) -> Self {
98        let added = Signal::new(&clock);
99        Self {
100            inner: Arc::new(Inner {
101                clock,
102                state: Mutex::new(HashMap::new()),
103                added,
104            }),
105        }
106    }
107
108    /// The clock the double runs on.
109    ///
110    /// ```
111    /// use legit_streams::MemoryStreams;
112    ///
113    /// assert!(!MemoryStreams::new().clock().is_manual());
114    /// ```
115    #[must_use]
116    pub fn clock(&self) -> &Clock {
117        &self.inner.clock
118    }
119
120    /// Every entry of a stream, oldest first, as `XRANGE stream - +` gives them.
121    ///
122    /// ```
123    /// use legit_streams::{MemoryStreams, Streams};
124    ///
125    /// let streams = MemoryStreams::new();
126    /// streams.xadd("hash_tasks", &[(b"k".as_slice(), b"v".as_slice())])?;
127    /// assert_eq!(streams.entries("hash_tasks")[0].field("k"), Some(&b"v"[..]));
128    /// # Ok::<(), legit_streams::Error>(())
129    /// ```
130    #[must_use]
131    pub fn entries(&self, stream: &str) -> Vec<Entry> {
132        self.lock().get(stream).map_or_else(Vec::new, |stream| {
133            stream
134                .entries
135                .iter()
136                .map(|(id, fields)| Entry::new(*id, fields.clone()))
137                .collect()
138        })
139    }
140
141    /// A group's whole pending list, oldest first, as `XPENDING stream group - + <all>` gives it;
142    /// empty when the group doesn't exist.
143    ///
144    /// ```
145    /// use legit_streams::{MemoryStreams, Streams};
146    ///
147    /// let streams = MemoryStreams::new();
148    /// streams.xgroup_create("hash_tasks", "hash_workers")?;
149    /// streams.xadd("hash_tasks", &[(b"k".as_slice(), b"v".as_slice())])?;
150    /// streams.xreadgroup("hash_tasks", "hash_workers", "c", 1, None)?;
151    /// assert_eq!(streams.pending("hash_tasks", "hash_workers")[0].consumer, "c");
152    /// # Ok::<(), legit_streams::Error>(())
153    /// ```
154    #[must_use]
155    pub fn pending(&self, stream: &str, group: &str) -> Vec<Pending> {
156        let now = self.inner.clock.now_ms();
157        self.lock()
158            .get(stream)
159            .and_then(|stream| stream.groups.get(group))
160            .map_or_else(Vec::new, |group| {
161                group.pending.iter().map(|(id, nack)| pending(*id, nack, now)).collect()
162            })
163    }
164
165    /// A group's consumers, in name order; empty when the group doesn't exist.
166    ///
167    /// ```
168    /// use legit_streams::{MemoryStreams, Streams};
169    ///
170    /// let streams = MemoryStreams::new();
171    /// streams.xgroup_create("hash_tasks", "hash_workers")?;
172    /// streams.xreadgroup("hash_tasks", "hash_workers", "c", 1, None)?;
173    /// assert_eq!(streams.consumers("hash_tasks", "hash_workers"), ["c"]);
174    /// # Ok::<(), legit_streams::Error>(())
175    /// ```
176    #[must_use]
177    pub fn consumers(&self, stream: &str, group: &str) -> Vec<String> {
178        self.lock()
179            .get(stream)
180            .and_then(|stream| stream.groups.get(group))
181            .map_or_else(Vec::new, |group| group.consumers.iter().cloned().collect())
182    }
183
184    /// How long until a key's expiry, or `None` when the key doesn't exist or has none, as `PTTL`
185    /// tells it.
186    ///
187    /// ```
188    /// use std::time::Duration;
189    /// use legit_streams::{Clock, MemoryStreams, Streams};
190    ///
191    /// let clock = Clock::manual(0);
192    /// let streams = MemoryStreams::with_clock(clock.clone());
193    /// streams.xadd("results:app:hash:rpc:app_1", &[(b"k".as_slice(), b"v".as_slice())])?;
194    /// assert_eq!(streams.ttl("results:app:hash:rpc:app_1"), None);
195    /// streams.expire("results:app:hash:rpc:app_1", Duration::from_secs(60))?;
196    /// clock.advance(Duration::from_secs(15));
197    /// assert_eq!(streams.ttl("results:app:hash:rpc:app_1"), Some(Duration::from_secs(45)));
198    /// # Ok::<(), legit_streams::Error>(())
199    /// ```
200    #[must_use]
201    pub fn ttl(&self, key: &str) -> Option<Duration> {
202        let now = self.inner.clock.now_ms();
203        self.lock()
204            .get(key)
205            .and_then(|stream| stream.expires_at)
206            .map(|at| Duration::from_millis(at.saturating_sub(now)))
207    }
208
209    /// The streams, without any key whose expiry the clock has passed.
210    fn lock(&self) -> MutexGuard<'_, HashMap<String, Stream>> {
211        // Read before the lock: the clock's own lock is never taken inside this one...
212        let now = self.inner.clock.now_ms();
213        let mut streams = self.inner.state.lock().unwrap_or_else(PoisonError::into_inner);
214        // Redis keeps a key until the time is past its expiry...
215        streams.retain(|_, stream| stream.expires_at.is_none_or(|at| now <= at));
216        streams
217    }
218
219    fn try_read_after(&self, stream: &str, after: EntryId, count: usize) -> Vec<Entry> {
220        let limit = if count == 0 { usize::MAX } else { count };
221        self.lock().get(stream).map_or_else(Vec::new, |stream| {
222            stream
223                .entries
224                .range(next_after(after)..)
225                .take(limit)
226                .map(|(id, fields)| Entry::new(*id, fields.clone()))
227                .collect()
228        })
229    }
230
231    /// The atomic step behind [`Streams::renew_lease`] and [`Streams::release_lease`]: under one
232    /// hold of the lock, as Redis runs a script with no other command in between, check that the
233    /// entry is pending for `consumer` and set the time it was last delivered.
234    fn claim_if_owned(
235        &self,
236        stream: &str,
237        group: &str,
238        consumer: &str,
239        id: EntryId,
240        delivered_ms: u64,
241    ) -> Result<Renewal> {
242        let mut streams = self.lock();
243        let (entries, group) = group_mut(&mut streams, stream, group)?;
244        let Some(nack) = group.pending.get_mut(&id) else {
245            return Ok(Renewal::Lost(LostLease::NotPending));
246        };
247        if nack.consumer != consumer {
248            return Ok(Renewal::Lost(LostLease::OtherConsumer));
249        }
250        // `XCLAIM` of an entry deleted from the stream drops it from the pending list...
251        if !entries.contains_key(&id) {
252            group.pending.remove(&id);
253            return Ok(Renewal::Lost(LostLease::NotPending));
254        }
255        nack.delivered_ms = delivered_ms;
256        Ok(Renewal::Renewed)
257    }
258
259    fn try_read(&self, stream: &str, group: &str, consumer: &str, count: usize) -> Result<Vec<Entry>> {
260        let now = self.inner.clock.now_ms();
261        let mut streams = self.lock();
262        let (entries, group) = group_mut(&mut streams, stream, group)?;
263        group.consumers.insert(consumer.to_owned());
264        let limit = if count == 0 { usize::MAX } else { count };
265        let delivered: Vec<Entry> = entries
266            .range(next_after(group.last_delivered)..)
267            .take(limit)
268            .map(|(id, fields)| Entry::new(*id, fields.clone()))
269            .collect();
270        for entry in &delivered {
271            group.last_delivered = entry.id;
272            group.pending.insert(
273                entry.id,
274                Nack {
275                    consumer: consumer.to_owned(),
276                    delivered_ms: now,
277                    deliveries: 1,
278                },
279            );
280        }
281        Ok(delivered)
282    }
283}
284
285impl Default for MemoryStreams {
286    fn default() -> Self {
287        Self::new()
288    }
289}
290
291impl fmt::Debug for MemoryStreams {
292    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293        let streams = self.lock();
294        let mut names: Vec<&str> = streams.keys().map(String::as_str).collect();
295        names.sort_unstable();
296        f.debug_struct("MemoryStreams")
297            .field("clock", &self.inner.clock)
298            .field("streams", &names)
299            .finish()
300    }
301}
302
303impl Streams for MemoryStreams {
304    fn xadd(&self, stream: &str, fields: &[(&[u8], &[u8])]) -> Result<EntryId> {
305        if fields.is_empty() {
306            return Err(Error::Redis(
307                "ERR wrong number of arguments for 'xadd' command".to_owned(),
308            ));
309        }
310        let now = self.inner.clock.now_ms();
311        let id = {
312            let mut streams = self.lock();
313            let stream = streams.entry(stream.to_owned()).or_default();
314            let last = stream.last_id;
315            let id = if now > last.ms() {
316                EntryId::new(now, 0)
317            } else {
318                EntryId::new(last.ms(), last.seq() + 1)
319            };
320            stream.last_id = id;
321            stream.entries.insert(
322                id,
323                fields
324                    .iter()
325                    .map(|(name, value)| (name.to_vec(), value.to_vec()))
326                    .collect(),
327            );
328            id
329        };
330        self.inner.added.raise();
331        Ok(id)
332    }
333
334    fn xlen(&self, stream: &str) -> Result<u64> {
335        Ok(self.lock().get(stream).map_or(0, |stream| stream.entries.len() as u64))
336    }
337
338    fn xgroup_create(&self, stream: &str, group: &str) -> Result<bool> {
339        let mut streams = self.lock();
340        let stream = streams.entry(stream.to_owned()).or_default();
341        if stream.groups.contains_key(group) {
342            return Ok(false);
343        }
344        stream.groups.insert(group.to_owned(), Group::default());
345        Ok(true)
346    }
347
348    fn xreadgroup(
349        &self,
350        stream: &str,
351        group: &str,
352        consumer: &str,
353        count: usize,
354        block: Option<Duration>,
355    ) -> Result<Vec<Entry>> {
356        let clock = &self.inner.clock;
357        let deadline = block.map(|block| clock.monotonic().saturating_add(block.max(Duration::from_millis(1))));
358        loop {
359            let seen = self.inner.added.seen();
360            let entries = self.try_read(stream, group, consumer, count)?;
361            let Some(deadline) = deadline else { return Ok(entries) };
362            if !entries.is_empty() || clock.monotonic() >= deadline {
363                return Ok(entries);
364            }
365            clock.wait(Some((&self.inner.added, seen)), Some(deadline));
366        }
367    }
368
369    fn xautoclaim(
370        &self,
371        stream: &str,
372        group: &str,
373        consumer: &str,
374        min_idle: Duration,
375        start: EntryId,
376        count: usize,
377    ) -> Result<AutoClaim> {
378        let now = self.inner.clock.now_ms();
379        let min_idle = u64::try_from(min_idle.as_millis()).unwrap_or(u64::MAX);
380        let mut streams = self.lock();
381        let (entries, group) = group_mut(&mut streams, stream, group)?;
382        group.consumers.insert(consumer.to_owned());
383        let ids: Vec<EntryId> = group.pending.range(start..).map(|(id, _)| *id).collect();
384        let mut claim = AutoClaim::default();
385        let mut left = count.max(1);
386        let mut attempts = left.saturating_mul(10);
387        let mut examined = 0;
388        for id in &ids {
389            if attempts == 0 || left == 0 {
390                break;
391            }
392            attempts -= 1;
393            examined += 1;
394            let Some(fields) = entries.get(id) else {
395                group.pending.remove(id);
396                claim.deleted.push(*id);
397                left -= 1;
398                continue;
399            };
400            let Some(nack) = group.pending.get_mut(id) else {
401                continue;
402            };
403            if now.saturating_sub(nack.delivered_ms) < min_idle {
404                continue;
405            }
406            consumer.clone_into(&mut nack.consumer);
407            nack.delivered_ms = now;
408            nack.deliveries += 1;
409            claim.claimed.push(Entry::new(*id, fields.clone()));
410            left -= 1;
411        }
412        claim.next = ids.get(examined).copied().unwrap_or(EntryId::ZERO);
413        Ok(claim)
414    }
415
416    fn xclaim_justid(
417        &self,
418        stream: &str,
419        group: &str,
420        consumer: &str,
421        ids: &[EntryId],
422        idle: Option<Duration>,
423    ) -> Result<Vec<EntryId>> {
424        let now = self.inner.clock.now_ms();
425        let delivered_ms =
426            now.saturating_sub(idle.map_or(0, |idle| u64::try_from(idle.as_millis()).unwrap_or(u64::MAX)));
427        let mut streams = self.lock();
428        let (entries, group) = group_mut(&mut streams, stream, group)?;
429        group.consumers.insert(consumer.to_owned());
430        let mut claimed = Vec::new();
431        for id in ids {
432            if !group.pending.contains_key(id) {
433                continue;
434            }
435            if !entries.contains_key(id) {
436                group.pending.remove(id);
437                continue;
438            }
439            if let Some(nack) = group.pending.get_mut(id) {
440                consumer.clone_into(&mut nack.consumer);
441                nack.delivered_ms = delivered_ms;
442                claimed.push(*id);
443            }
444        }
445        Ok(claimed)
446    }
447
448    fn xpending_entry(&self, stream: &str, group: &str, id: EntryId) -> Result<Option<Pending>> {
449        let now = self.inner.clock.now_ms();
450        let mut streams = self.lock();
451        let (_, group) = group_mut(&mut streams, stream, group)?;
452        Ok(group.pending.get(&id).map(|nack| pending(id, nack, now)))
453    }
454
455    fn xpending_consumer(&self, stream: &str, group: &str, consumer: &str, count: usize) -> Result<Vec<Pending>> {
456        let now = self.inner.clock.now_ms();
457        let mut streams = self.lock();
458        let (_, group) = group_mut(&mut streams, stream, group)?;
459        Ok(group
460            .pending
461            .iter()
462            .filter(|(_, nack)| nack.consumer == consumer)
463            .take(count)
464            .map(|(id, nack)| pending(*id, nack, now))
465            .collect())
466    }
467
468    fn xack(&self, stream: &str, group: &str, ids: &[EntryId]) -> Result<u64> {
469        let mut streams = self.lock();
470        let Some(group) = streams.get_mut(stream).and_then(|stream| stream.groups.get_mut(group)) else {
471            return Ok(0);
472        };
473        Ok(ids.iter().filter(|id| group.pending.remove(id).is_some()).count() as u64)
474    }
475
476    fn xdel(&self, stream: &str, ids: &[EntryId]) -> Result<u64> {
477        let mut streams = self.lock();
478        let Some(stream) = streams.get_mut(stream) else {
479            return Ok(0);
480        };
481        Ok(ids.iter().filter(|id| stream.entries.remove(id).is_some()).count() as u64)
482    }
483
484    fn xgroup_delconsumer(&self, stream: &str, group: &str, consumer: &str) -> Result<u64> {
485        let mut streams = self.lock();
486        let (_, group) = group_mut(&mut streams, stream, group)?;
487        if !group.consumers.remove(consumer) {
488            return Ok(0);
489        }
490        let before = group.pending.len();
491        group.pending.retain(|_, nack| nack.consumer != consumer);
492        Ok((before - group.pending.len()) as u64)
493    }
494
495    fn renew_lease(&self, stream: &str, group: &str, consumer: &str, id: EntryId) -> Result<Renewal> {
496        let now = self.inner.clock.now_ms();
497        self.claim_if_owned(stream, group, consumer, id, now)
498    }
499
500    fn release_lease(&self, stream: &str, group: &str, consumer: &str, id: EntryId, idle: Duration) -> Result<bool> {
501        let idle = u64::try_from(idle.as_millis()).unwrap_or(u64::MAX);
502        let delivered_ms = self.inner.clock.now_ms().saturating_sub(idle);
503        Ok(self
504            .claim_if_owned(stream, group, consumer, id, delivered_ms)?
505            .is_renewed())
506    }
507
508    fn xread(&self, stream: &str, after: EntryId, count: usize, block: Option<Duration>) -> Result<Vec<Entry>> {
509        let clock = &self.inner.clock;
510        let deadline = block.map(|block| clock.monotonic().saturating_add(block.max(Duration::from_millis(1))));
511        loop {
512            let seen = self.inner.added.seen();
513            let entries = self.try_read_after(stream, after, count);
514            let Some(deadline) = deadline else { return Ok(entries) };
515            if !entries.is_empty() || clock.monotonic() >= deadline {
516                return Ok(entries);
517            }
518            clock.wait(Some((&self.inner.added, seen)), Some(deadline));
519        }
520    }
521
522    fn expire(&self, key: &str, ttl: Duration) -> Result<bool> {
523        let seconds = expire_seconds(ttl);
524        let now = self.inner.clock.now_ms();
525        let mut streams = self.lock();
526        if seconds == 0 {
527            return Ok(streams.remove(key).is_some());
528        }
529        let Some(stream) = streams.get_mut(key) else {
530            return Ok(false);
531        };
532        stream.expires_at = Some(now.saturating_add(seconds.saturating_mul(1_000)));
533        Ok(true)
534    }
535
536    fn del(&self, keys: &[&str]) -> Result<u64> {
537        let mut streams = self.lock();
538        Ok(keys.iter().filter(|key| streams.remove(**key).is_some()).count() as u64)
539    }
540
541    /// Exact, where a server may not be: the lag is always known, as the number of entries after
542    /// the group's last-delivered id. Redis 7 and newer give the same count until entries the group
543    /// hasn't read are deleted, and then answer nil.
544    fn group_backlog(&self, stream: &str, group: &str) -> Result<Option<GroupBacklog>> {
545        let mut streams = self.lock();
546        let (entries, group) = group_mut(&mut streams, stream, group)?;
547        let lag = entries.range(next_after(group.last_delivered)..).count() as u64;
548        Ok(Some(GroupBacklog::new(group.pending.len() as u64, Some(lag))))
549    }
550}
551
552fn group_mut<'a>(
553    streams: &'a mut HashMap<String, Stream>,
554    stream: &str,
555    group: &str,
556) -> Result<(&'a BTreeMap<EntryId, RawFields>, &'a mut Group)> {
557    let no_group = || Error::NoGroup {
558        stream: stream.to_owned(),
559        group: group.to_owned(),
560    };
561    let found = streams.get_mut(stream).ok_or_else(no_group)?;
562    let group = found.groups.get_mut(group).ok_or_else(no_group)?;
563    Ok((&found.entries, group))
564}
565
566fn pending(id: EntryId, nack: &Nack, now: u64) -> Pending {
567    Pending {
568        id,
569        consumer: nack.consumer.clone(),
570        idle: Duration::from_millis(now.saturating_sub(nack.delivered_ms)),
571        deliveries: nack.deliveries,
572    }
573}
574
575/// The smallest id after `id`.
576const fn next_after(id: EntryId) -> EntryId {
577    if id.seq() == u64::MAX {
578        EntryId::new(id.ms() + 1, 0)
579    } else {
580        EntryId::new(id.ms(), id.seq() + 1)
581    }
582}