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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! An in-memory double of the stream commands, for tests.

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fmt;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;

use crate::clock::{Clock, Signal};
use crate::entry::{AutoClaim, Entry, EntryId, GroupBacklog, LostLease, Pending, RawFields, Renewal};
use crate::error::{Error, Result};
use crate::streams::{Streams, expire_seconds};

/// The stream commands of [`Streams`] run in memory, with the semantics Redis 7 gives them, on a
/// [`Clock`] the test controls: entry ids, idle times and blocking reads follow its time, so lease
/// expiry, idle claims and delivery counts can be tested to the millisecond.
///
/// It implements exactly the commands the trait names, and keeps no trimming or persistence. A key
/// given an expiry with `EXPIRE` goes once the clock passes it, as Redis expires keys: every
/// command and inspection sees it gone. `XAUTOCLAIM` reports deleted entries the Redis 7 way. A
/// blocking read on a manual clock waits until an entry arrives or the test advances the clock
/// past its timeout.
///
/// The double is a cheap handle; clones share one set of streams.
///
/// ```
/// use std::time::Duration;
/// use legit_streams::{Clock, EntryId, MemoryStreams, Streams};
///
/// let clock = Clock::manual(1_000);
/// let streams = MemoryStreams::with_clock(clock.clone());
/// streams.xgroup_create("hash_tasks", "hash_workers")?;
/// let id = streams.xadd("hash_tasks", &[(b"task_id".as_slice(), b"app_1".as_slice())])?;
/// streams.xreadgroup("hash_tasks", "hash_workers", "a", 1, None)?;
///
/// clock.advance(Duration::from_secs(300));
/// let claim = streams.xautoclaim("hash_tasks", "hash_workers", "b", Duration::from_secs(300), EntryId::ZERO, 1)?;
/// assert_eq!(claim.claimed[0].id, id);
/// assert_eq!(streams.xpending_entry("hash_tasks", "hash_workers", id)?.map(|p| p.deliveries), Some(2));
/// # Ok::<(), legit_streams::Error>(())
/// ```
#[derive(Clone)]
pub struct MemoryStreams {
    inner: Arc<Inner>,
}

struct Inner {
    clock: Clock,
    state: Mutex<HashMap<String, Stream>>,
    added: Signal,
}

#[derive(Default)]
struct Stream {
    entries: BTreeMap<EntryId, RawFields>,
    last_id: EntryId,
    groups: HashMap<String, Group>,
    /// When the key goes, in milliseconds since the epoch on the double's clock.
    expires_at: Option<u64>,
}

#[derive(Default)]
struct Group {
    last_delivered: EntryId,
    pending: BTreeMap<EntryId, Nack>,
    consumers: BTreeSet<String>,
}

struct Nack {
    consumer: String,
    delivered_ms: u64,
    deliveries: u64,
}

impl MemoryStreams {
    /// An empty double on the system clock.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, Streams};
    ///
    /// assert_eq!(MemoryStreams::new().xlen("hash_tasks")?, 0);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self::with_clock(Clock::system())
    }

    /// An empty double on `clock`.
    ///
    /// ```
    /// use legit_streams::{Clock, MemoryStreams};
    ///
    /// let streams = MemoryStreams::with_clock(Clock::manual(0));
    /// assert!(streams.clock().is_manual());
    /// ```
    #[must_use]
    pub fn with_clock(clock: Clock) -> Self {
        let added = Signal::new(&clock);
        Self {
            inner: Arc::new(Inner {
                clock,
                state: Mutex::new(HashMap::new()),
                added,
            }),
        }
    }

    /// The clock the double runs on.
    ///
    /// ```
    /// use legit_streams::MemoryStreams;
    ///
    /// assert!(!MemoryStreams::new().clock().is_manual());
    /// ```
    #[must_use]
    pub fn clock(&self) -> &Clock {
        &self.inner.clock
    }

    /// Every entry of a stream, oldest first, as `XRANGE stream - +` gives them.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, Streams};
    ///
    /// let streams = MemoryStreams::new();
    /// streams.xadd("hash_tasks", &[(b"k".as_slice(), b"v".as_slice())])?;
    /// assert_eq!(streams.entries("hash_tasks")[0].field("k"), Some(&b"v"[..]));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn entries(&self, stream: &str) -> Vec<Entry> {
        self.lock().get(stream).map_or_else(Vec::new, |stream| {
            stream
                .entries
                .iter()
                .map(|(id, fields)| Entry::new(*id, fields.clone()))
                .collect()
        })
    }

    /// A group's whole pending list, oldest first, as `XPENDING stream group - + <all>` gives it;
    /// empty when the group doesn't exist.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, Streams};
    ///
    /// let streams = MemoryStreams::new();
    /// streams.xgroup_create("hash_tasks", "hash_workers")?;
    /// streams.xadd("hash_tasks", &[(b"k".as_slice(), b"v".as_slice())])?;
    /// streams.xreadgroup("hash_tasks", "hash_workers", "c", 1, None)?;
    /// assert_eq!(streams.pending("hash_tasks", "hash_workers")[0].consumer, "c");
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn pending(&self, stream: &str, group: &str) -> Vec<Pending> {
        let now = self.inner.clock.now_ms();
        self.lock()
            .get(stream)
            .and_then(|stream| stream.groups.get(group))
            .map_or_else(Vec::new, |group| {
                group.pending.iter().map(|(id, nack)| pending(*id, nack, now)).collect()
            })
    }

    /// A group's consumers, in name order; empty when the group doesn't exist.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, Streams};
    ///
    /// let streams = MemoryStreams::new();
    /// streams.xgroup_create("hash_tasks", "hash_workers")?;
    /// streams.xreadgroup("hash_tasks", "hash_workers", "c", 1, None)?;
    /// assert_eq!(streams.consumers("hash_tasks", "hash_workers"), ["c"]);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn consumers(&self, stream: &str, group: &str) -> Vec<String> {
        self.lock()
            .get(stream)
            .and_then(|stream| stream.groups.get(group))
            .map_or_else(Vec::new, |group| group.consumers.iter().cloned().collect())
    }

    /// How long until a key's expiry, or `None` when the key doesn't exist or has none, as `PTTL`
    /// tells it.
    ///
    /// ```
    /// use std::time::Duration;
    /// use legit_streams::{Clock, MemoryStreams, Streams};
    ///
    /// let clock = Clock::manual(0);
    /// let streams = MemoryStreams::with_clock(clock.clone());
    /// streams.xadd("results:app:hash:rpc:app_1", &[(b"k".as_slice(), b"v".as_slice())])?;
    /// assert_eq!(streams.ttl("results:app:hash:rpc:app_1"), None);
    /// streams.expire("results:app:hash:rpc:app_1", Duration::from_secs(60))?;
    /// clock.advance(Duration::from_secs(15));
    /// assert_eq!(streams.ttl("results:app:hash:rpc:app_1"), Some(Duration::from_secs(45)));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn ttl(&self, key: &str) -> Option<Duration> {
        let now = self.inner.clock.now_ms();
        self.lock()
            .get(key)
            .and_then(|stream| stream.expires_at)
            .map(|at| Duration::from_millis(at.saturating_sub(now)))
    }

    /// The streams, without any key whose expiry the clock has passed.
    fn lock(&self) -> MutexGuard<'_, HashMap<String, Stream>> {
        // Read before the lock: the clock's own lock is never taken inside this one...
        let now = self.inner.clock.now_ms();
        let mut streams = self.inner.state.lock().unwrap_or_else(PoisonError::into_inner);
        // Redis keeps a key until the time is past its expiry...
        streams.retain(|_, stream| stream.expires_at.is_none_or(|at| now <= at));
        streams
    }

    fn try_read_after(&self, stream: &str, after: EntryId, count: usize) -> Vec<Entry> {
        let limit = if count == 0 { usize::MAX } else { count };
        self.lock().get(stream).map_or_else(Vec::new, |stream| {
            stream
                .entries
                .range(next_after(after)..)
                .take(limit)
                .map(|(id, fields)| Entry::new(*id, fields.clone()))
                .collect()
        })
    }

    /// The atomic step behind [`Streams::renew_lease`] and [`Streams::release_lease`]: under one
    /// hold of the lock, as Redis runs a script with no other command in between, check that the
    /// entry is pending for `consumer` and set the time it was last delivered.
    fn claim_if_owned(
        &self,
        stream: &str,
        group: &str,
        consumer: &str,
        id: EntryId,
        delivered_ms: u64,
    ) -> Result<Renewal> {
        let mut streams = self.lock();
        let (entries, group) = group_mut(&mut streams, stream, group)?;
        let Some(nack) = group.pending.get_mut(&id) else {
            return Ok(Renewal::Lost(LostLease::NotPending));
        };
        if nack.consumer != consumer {
            return Ok(Renewal::Lost(LostLease::OtherConsumer));
        }
        // `XCLAIM` of an entry deleted from the stream drops it from the pending list...
        if !entries.contains_key(&id) {
            group.pending.remove(&id);
            return Ok(Renewal::Lost(LostLease::NotPending));
        }
        nack.delivered_ms = delivered_ms;
        Ok(Renewal::Renewed)
    }

    fn try_read(&self, stream: &str, group: &str, consumer: &str, count: usize) -> Result<Vec<Entry>> {
        let now = self.inner.clock.now_ms();
        let mut streams = self.lock();
        let (entries, group) = group_mut(&mut streams, stream, group)?;
        group.consumers.insert(consumer.to_owned());
        let limit = if count == 0 { usize::MAX } else { count };
        let delivered: Vec<Entry> = entries
            .range(next_after(group.last_delivered)..)
            .take(limit)
            .map(|(id, fields)| Entry::new(*id, fields.clone()))
            .collect();
        for entry in &delivered {
            group.last_delivered = entry.id;
            group.pending.insert(
                entry.id,
                Nack {
                    consumer: consumer.to_owned(),
                    delivered_ms: now,
                    deliveries: 1,
                },
            );
        }
        Ok(delivered)
    }
}

impl Default for MemoryStreams {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Debug for MemoryStreams {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let streams = self.lock();
        let mut names: Vec<&str> = streams.keys().map(String::as_str).collect();
        names.sort_unstable();
        f.debug_struct("MemoryStreams")
            .field("clock", &self.inner.clock)
            .field("streams", &names)
            .finish()
    }
}

impl Streams for MemoryStreams {
    fn xadd(&self, stream: &str, fields: &[(&[u8], &[u8])]) -> Result<EntryId> {
        if fields.is_empty() {
            return Err(Error::Redis(
                "ERR wrong number of arguments for 'xadd' command".to_owned(),
            ));
        }
        let now = self.inner.clock.now_ms();
        let id = {
            let mut streams = self.lock();
            let stream = streams.entry(stream.to_owned()).or_default();
            let last = stream.last_id;
            let id = if now > last.ms() {
                EntryId::new(now, 0)
            } else {
                EntryId::new(last.ms(), last.seq() + 1)
            };
            stream.last_id = id;
            stream.entries.insert(
                id,
                fields
                    .iter()
                    .map(|(name, value)| (name.to_vec(), value.to_vec()))
                    .collect(),
            );
            id
        };
        self.inner.added.raise();
        Ok(id)
    }

    fn xlen(&self, stream: &str) -> Result<u64> {
        Ok(self.lock().get(stream).map_or(0, |stream| stream.entries.len() as u64))
    }

    fn xgroup_create(&self, stream: &str, group: &str) -> Result<bool> {
        let mut streams = self.lock();
        let stream = streams.entry(stream.to_owned()).or_default();
        if stream.groups.contains_key(group) {
            return Ok(false);
        }
        stream.groups.insert(group.to_owned(), Group::default());
        Ok(true)
    }

    fn xreadgroup(
        &self,
        stream: &str,
        group: &str,
        consumer: &str,
        count: usize,
        block: Option<Duration>,
    ) -> Result<Vec<Entry>> {
        let clock = &self.inner.clock;
        let deadline = block.map(|block| clock.monotonic().saturating_add(block.max(Duration::from_millis(1))));
        loop {
            let seen = self.inner.added.seen();
            let entries = self.try_read(stream, group, consumer, count)?;
            let Some(deadline) = deadline else { return Ok(entries) };
            if !entries.is_empty() || clock.monotonic() >= deadline {
                return Ok(entries);
            }
            clock.wait(Some((&self.inner.added, seen)), Some(deadline));
        }
    }

    fn xautoclaim(
        &self,
        stream: &str,
        group: &str,
        consumer: &str,
        min_idle: Duration,
        start: EntryId,
        count: usize,
    ) -> Result<AutoClaim> {
        let now = self.inner.clock.now_ms();
        let min_idle = u64::try_from(min_idle.as_millis()).unwrap_or(u64::MAX);
        let mut streams = self.lock();
        let (entries, group) = group_mut(&mut streams, stream, group)?;
        group.consumers.insert(consumer.to_owned());
        let ids: Vec<EntryId> = group.pending.range(start..).map(|(id, _)| *id).collect();
        let mut claim = AutoClaim::default();
        let mut left = count.max(1);
        let mut attempts = left.saturating_mul(10);
        let mut examined = 0;
        for id in &ids {
            if attempts == 0 || left == 0 {
                break;
            }
            attempts -= 1;
            examined += 1;
            let Some(fields) = entries.get(id) else {
                group.pending.remove(id);
                claim.deleted.push(*id);
                left -= 1;
                continue;
            };
            let Some(nack) = group.pending.get_mut(id) else {
                continue;
            };
            if now.saturating_sub(nack.delivered_ms) < min_idle {
                continue;
            }
            consumer.clone_into(&mut nack.consumer);
            nack.delivered_ms = now;
            nack.deliveries += 1;
            claim.claimed.push(Entry::new(*id, fields.clone()));
            left -= 1;
        }
        claim.next = ids.get(examined).copied().unwrap_or(EntryId::ZERO);
        Ok(claim)
    }

    fn xclaim_justid(
        &self,
        stream: &str,
        group: &str,
        consumer: &str,
        ids: &[EntryId],
        idle: Option<Duration>,
    ) -> Result<Vec<EntryId>> {
        let now = self.inner.clock.now_ms();
        let delivered_ms =
            now.saturating_sub(idle.map_or(0, |idle| u64::try_from(idle.as_millis()).unwrap_or(u64::MAX)));
        let mut streams = self.lock();
        let (entries, group) = group_mut(&mut streams, stream, group)?;
        group.consumers.insert(consumer.to_owned());
        let mut claimed = Vec::new();
        for id in ids {
            if !group.pending.contains_key(id) {
                continue;
            }
            if !entries.contains_key(id) {
                group.pending.remove(id);
                continue;
            }
            if let Some(nack) = group.pending.get_mut(id) {
                consumer.clone_into(&mut nack.consumer);
                nack.delivered_ms = delivered_ms;
                claimed.push(*id);
            }
        }
        Ok(claimed)
    }

    fn xpending_entry(&self, stream: &str, group: &str, id: EntryId) -> Result<Option<Pending>> {
        let now = self.inner.clock.now_ms();
        let mut streams = self.lock();
        let (_, group) = group_mut(&mut streams, stream, group)?;
        Ok(group.pending.get(&id).map(|nack| pending(id, nack, now)))
    }

    fn xpending_consumer(&self, stream: &str, group: &str, consumer: &str, count: usize) -> Result<Vec<Pending>> {
        let now = self.inner.clock.now_ms();
        let mut streams = self.lock();
        let (_, group) = group_mut(&mut streams, stream, group)?;
        Ok(group
            .pending
            .iter()
            .filter(|(_, nack)| nack.consumer == consumer)
            .take(count)
            .map(|(id, nack)| pending(*id, nack, now))
            .collect())
    }

    fn xack(&self, stream: &str, group: &str, ids: &[EntryId]) -> Result<u64> {
        let mut streams = self.lock();
        let Some(group) = streams.get_mut(stream).and_then(|stream| stream.groups.get_mut(group)) else {
            return Ok(0);
        };
        Ok(ids.iter().filter(|id| group.pending.remove(id).is_some()).count() as u64)
    }

    fn xdel(&self, stream: &str, ids: &[EntryId]) -> Result<u64> {
        let mut streams = self.lock();
        let Some(stream) = streams.get_mut(stream) else {
            return Ok(0);
        };
        Ok(ids.iter().filter(|id| stream.entries.remove(id).is_some()).count() as u64)
    }

    fn xgroup_delconsumer(&self, stream: &str, group: &str, consumer: &str) -> Result<u64> {
        let mut streams = self.lock();
        let (_, group) = group_mut(&mut streams, stream, group)?;
        if !group.consumers.remove(consumer) {
            return Ok(0);
        }
        let before = group.pending.len();
        group.pending.retain(|_, nack| nack.consumer != consumer);
        Ok((before - group.pending.len()) as u64)
    }

    fn renew_lease(&self, stream: &str, group: &str, consumer: &str, id: EntryId) -> Result<Renewal> {
        let now = self.inner.clock.now_ms();
        self.claim_if_owned(stream, group, consumer, id, now)
    }

    fn release_lease(&self, stream: &str, group: &str, consumer: &str, id: EntryId, idle: Duration) -> Result<bool> {
        let idle = u64::try_from(idle.as_millis()).unwrap_or(u64::MAX);
        let delivered_ms = self.inner.clock.now_ms().saturating_sub(idle);
        Ok(self
            .claim_if_owned(stream, group, consumer, id, delivered_ms)?
            .is_renewed())
    }

    fn xread(&self, stream: &str, after: EntryId, count: usize, block: Option<Duration>) -> Result<Vec<Entry>> {
        let clock = &self.inner.clock;
        let deadline = block.map(|block| clock.monotonic().saturating_add(block.max(Duration::from_millis(1))));
        loop {
            let seen = self.inner.added.seen();
            let entries = self.try_read_after(stream, after, count);
            let Some(deadline) = deadline else { return Ok(entries) };
            if !entries.is_empty() || clock.monotonic() >= deadline {
                return Ok(entries);
            }
            clock.wait(Some((&self.inner.added, seen)), Some(deadline));
        }
    }

    fn expire(&self, key: &str, ttl: Duration) -> Result<bool> {
        let seconds = expire_seconds(ttl);
        let now = self.inner.clock.now_ms();
        let mut streams = self.lock();
        if seconds == 0 {
            return Ok(streams.remove(key).is_some());
        }
        let Some(stream) = streams.get_mut(key) else {
            return Ok(false);
        };
        stream.expires_at = Some(now.saturating_add(seconds.saturating_mul(1_000)));
        Ok(true)
    }

    fn del(&self, keys: &[&str]) -> Result<u64> {
        let mut streams = self.lock();
        Ok(keys.iter().filter(|key| streams.remove(**key).is_some()).count() as u64)
    }

    /// Exact, where a server may not be: the lag is always known, as the number of entries after
    /// the group's last-delivered id. Redis 7 and newer give the same count until entries the group
    /// hasn't read are deleted, and then answer nil.
    fn group_backlog(&self, stream: &str, group: &str) -> Result<Option<GroupBacklog>> {
        let mut streams = self.lock();
        let (entries, group) = group_mut(&mut streams, stream, group)?;
        let lag = entries.range(next_after(group.last_delivered)..).count() as u64;
        Ok(Some(GroupBacklog::new(group.pending.len() as u64, Some(lag))))
    }
}

fn group_mut<'a>(
    streams: &'a mut HashMap<String, Stream>,
    stream: &str,
    group: &str,
) -> Result<(&'a BTreeMap<EntryId, RawFields>, &'a mut Group)> {
    let no_group = || Error::NoGroup {
        stream: stream.to_owned(),
        group: group.to_owned(),
    };
    let found = streams.get_mut(stream).ok_or_else(no_group)?;
    let group = found.groups.get_mut(group).ok_or_else(no_group)?;
    Ok((&found.entries, group))
}

fn pending(id: EntryId, nack: &Nack, now: u64) -> Pending {
    Pending {
        id,
        consumer: nack.consumer.clone(),
        idle: Duration::from_millis(now.saturating_sub(nack.delivered_ms)),
        deliveries: nack.deliveries,
    }
}

/// The smallest id after `id`.
const fn next_after(id: EntryId) -> EntryId {
    if id.seq() == u64::MAX {
        EntryId::new(id.ms() + 1, 0)
    } else {
        EntryId::new(id.ms(), id.seq() + 1)
    }
}