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
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
583
584
585
586
587
588
589
590
591
//! The stream commands the crate uses, behind a trait.

use std::fmt;
use std::time::Duration;

#[cfg(doc)]
use crate::entry::LostLease;
use crate::entry::{AutoClaim, Entry, EntryId, GroupBacklog, Pending, Renewal};
use crate::error::Result;

/// The Redis stream commands this crate sends, and nothing else. [`RedisStreams`](crate::RedisStreams)
/// sends them to a server; [`MemoryStreams`](crate::MemoryStreams) runs them in memory for tests.
///
/// Every method takes `&self` and may be called from many threads at once. Each is one command
/// with the Redis semantics its name gives, except [`Streams::xack_xdel`] and
/// [`Streams::xadd_expire`], which send two, and [`Streams::renew_lease`] and
/// [`Streams::release_lease`], which check an entry's owner and claim it in one atomic step. An
/// implementation must keep those two atomic: a worker's lease depends on it.
///
/// The fast lane's commands, [`Streams::xread`], [`Streams::expire`], [`Streams::del`] and
/// [`Streams::xadd_expire`], came after the others. An implementation written before them still
/// compiles: their default answers [`Error::Redis`](crate::Error::Redis) for the first three, so
/// such an implementation serves the bulk lane only. So did [`Streams::group_backlog`], which no
/// worker, producer or reader of this crate calls; by default it answers `None`.
///
/// ```
/// use legit_streams::{MemoryStreams, Streams};
///
/// let streams = MemoryStreams::new();
/// streams.xadd("hash_tasks", &[(b"task_id".as_slice(), b"app_1".as_slice())])?;
/// assert_eq!(streams.xlen("hash_tasks")?, 1);
/// # Ok::<(), legit_streams::Error>(())
/// ```
pub trait Streams: Send + Sync + fmt::Debug {
    /// `XADD stream * field value ...`: append an entry and return its id.
    ///
    /// # Errors
    ///
    /// [`Error::Redis`](crate::Error::Redis) when the server refuses it or can't be reached.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, Streams};
    ///
    /// let streams = MemoryStreams::new();
    /// let first = streams.xadd("s", &[(b"k".as_slice(), b"v".as_slice())])?;
    /// let second = streams.xadd("s", &[(b"k".as_slice(), b"v".as_slice())])?;
    /// assert!(first < second);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    fn xadd(&self, stream: &str, fields: &[(&[u8], &[u8])]) -> Result<EntryId>;

    /// `XLEN stream`: how many entries the stream holds, 0 when it doesn't exist.
    ///
    /// # Errors
    ///
    /// [`Error::Redis`](crate::Error::Redis) when the server refuses it or can't be reached.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, Streams};
    ///
    /// assert_eq!(MemoryStreams::new().xlen("missing")?, 0);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    fn xlen(&self, stream: &str) -> Result<u64>;

    /// `XGROUP CREATE stream group 0 MKSTREAM`: create the group, reading from the start of the
    /// stream, and the stream when it doesn't exist. Returns `false` when the group already
    /// existed (`BUSYGROUP`), which isn't an error.
    ///
    /// # Errors
    ///
    /// [`Error::Redis`](crate::Error::Redis) when the server refuses it or can't be reached.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, Streams};
    ///
    /// let streams = MemoryStreams::new();
    /// assert!(streams.xgroup_create("s", "g")?);
    /// assert!(!streams.xgroup_create("s", "g")?);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    fn xgroup_create(&self, stream: &str, group: &str) -> Result<bool>;

    /// `XREADGROUP GROUP group consumer COUNT count [BLOCK ms] STREAMS stream >`: deliver up to
    /// `count` entries no consumer of the group has seen, adding each to the group's pending list
    /// under `consumer`. With `block`, wait up to that long for one when there are none; `None`
    /// returns at once. A `block` under a millisecond waits a millisecond: Redis reads `BLOCK 0`
    /// as forever.
    ///
    /// # Errors
    ///
    /// [`Error::NoGroup`](crate::Error::NoGroup) when the group doesn't exist, and
    /// [`Error::Redis`](crate::Error::Redis) when the server refuses it or can't be reached.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, Streams};
    ///
    /// let streams = MemoryStreams::new();
    /// streams.xgroup_create("s", "g")?;
    /// streams.xadd("s", &[(b"k".as_slice(), b"v".as_slice())])?;
    /// assert_eq!(streams.xreadgroup("s", "g", "c", 10, None)?.len(), 1);
    /// assert!(streams.xreadgroup("s", "g", "c", 10, None)?.is_empty());
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    fn xreadgroup(
        &self,
        stream: &str,
        group: &str,
        consumer: &str,
        count: usize,
        block: Option<Duration>,
    ) -> Result<Vec<Entry>>;

    /// `XAUTOCLAIM stream group consumer min-idle start COUNT count`: scan the pending list from
    /// `start` and claim for `consumer` up to `count` entries idle at least `min_idle`, adding one
    /// to each one's delivery count.
    ///
    /// # Errors
    ///
    /// [`Error::NoGroup`](crate::Error::NoGroup) when the group doesn't exist, and
    /// [`Error::Redis`](crate::Error::Redis) when the server refuses it or can't be reached.
    ///
    /// ```
    /// use std::time::Duration;
    /// use legit_streams::{EntryId, MemoryStreams, Streams};
    ///
    /// let streams = MemoryStreams::new();
    /// streams.xgroup_create("s", "g")?;
    /// let claim = streams.xautoclaim("s", "g", "c", Duration::from_secs(60), EntryId::ZERO, 10)?;
    /// assert!(claim.claimed.is_empty());
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    fn xautoclaim(
        &self,
        stream: &str,
        group: &str,
        consumer: &str,
        min_idle: Duration,
        start: EntryId,
        count: usize,
    ) -> Result<AutoClaim>;

    /// `XCLAIM stream group consumer 0 id ... [IDLE ms] JUSTID`: give pending entries to
    /// `consumer` without counting a delivery, and return the ids claimed. Without `idle` their
    /// idle time restarts at 0, which renews a lease; with it, it's set to `idle`, which can make
    /// an entry claimable by another worker at once. Ids no longer pending are skipped.
    ///
    /// # Errors
    ///
    /// [`Error::NoGroup`](crate::Error::NoGroup) when the group doesn't exist, and
    /// [`Error::Redis`](crate::Error::Redis) when the server refuses it or can't be reached.
    ///
    /// ```
    /// use legit_streams::{EntryId, MemoryStreams, Streams};
    ///
    /// let streams = MemoryStreams::new();
    /// streams.xgroup_create("s", "g")?;
    /// assert!(streams.xclaim_justid("s", "g", "c", &[EntryId::new(1, 0)], None)?.is_empty());
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    fn xclaim_justid(
        &self,
        stream: &str,
        group: &str,
        consumer: &str,
        ids: &[EntryId],
        idle: Option<Duration>,
    ) -> Result<Vec<EntryId>>;

    /// `XPENDING stream group id id 1`: the pending list's record of one entry, or `None` when
    /// it isn't pending.
    ///
    /// # Errors
    ///
    /// [`Error::NoGroup`](crate::Error::NoGroup) when the group doesn't exist, and
    /// [`Error::Redis`](crate::Error::Redis) when the server refuses it or can't be reached.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, Streams};
    ///
    /// let streams = MemoryStreams::new();
    /// streams.xgroup_create("s", "g")?;
    /// let id = streams.xadd("s", &[(b"k".as_slice(), b"v".as_slice())])?;
    /// streams.xreadgroup("s", "g", "c", 1, None)?;
    /// assert_eq!(streams.xpending_entry("s", "g", id)?.map(|p| p.deliveries), Some(1));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    fn xpending_entry(&self, stream: &str, group: &str, id: EntryId) -> Result<Option<Pending>>;

    /// `XPENDING stream group - + count consumer`: up to `count` of the entries `consumer` owns,
    /// oldest first.
    ///
    /// # Errors
    ///
    /// [`Error::NoGroup`](crate::Error::NoGroup) when the group doesn't exist, and
    /// [`Error::Redis`](crate::Error::Redis) when the server refuses it or can't be reached.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, Streams};
    ///
    /// let streams = MemoryStreams::new();
    /// streams.xgroup_create("s", "g")?;
    /// assert!(streams.xpending_consumer("s", "g", "c", 10)?.is_empty());
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    fn xpending_consumer(&self, stream: &str, group: &str, consumer: &str, count: usize) -> Result<Vec<Pending>>;

    /// `XACK stream group id ...`: drop entries from the group's pending list, returning how many
    /// were pending.
    ///
    /// # Errors
    ///
    /// [`Error::Redis`](crate::Error::Redis) when the server refuses it or can't be reached.
    ///
    /// ```
    /// use legit_streams::{EntryId, MemoryStreams, Streams};
    ///
    /// assert_eq!(MemoryStreams::new().xack("s", "g", &[EntryId::new(1, 0)])?, 0);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    fn xack(&self, stream: &str, group: &str, ids: &[EntryId]) -> Result<u64>;

    /// `XDEL stream id ...`: delete entries from the stream, returning how many existed.
    ///
    /// # Errors
    ///
    /// [`Error::Redis`](crate::Error::Redis) when the server refuses it or can't be reached.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, Streams};
    ///
    /// let streams = MemoryStreams::new();
    /// let id = streams.xadd("s", &[(b"k".as_slice(), b"v".as_slice())])?;
    /// assert_eq!(streams.xdel("s", &[id])?, 1);
    /// assert_eq!(streams.xlen("s")?, 0);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    fn xdel(&self, stream: &str, ids: &[EntryId]) -> Result<u64>;

    /// `XACK` then `XDEL`: how the contract finishes with an entry, so streams don't grow.
    /// [`RedisStreams`](crate::RedisStreams) sends both in one round trip.
    ///
    /// # Errors
    ///
    /// [`Error::Redis`](crate::Error::Redis) when the server refuses either or can't be reached;
    /// the acknowledgement may have happened.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, Streams};
    ///
    /// let streams = MemoryStreams::new();
    /// streams.xgroup_create("s", "g")?;
    /// streams.xadd("s", &[(b"k".as_slice(), b"v".as_slice())])?;
    /// let entries = streams.xreadgroup("s", "g", "c", 1, None)?;
    /// streams.xack_xdel("s", "g", &[entries[0].id])?;
    /// assert_eq!(streams.xlen("s")?, 0);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    fn xack_xdel(&self, stream: &str, group: &str, ids: &[EntryId]) -> Result<()> {
        self.xack(stream, group, ids)?;
        self.xdel(stream, ids)?;
        Ok(())
    }

    /// `XGROUP DELCONSUMER stream group consumer`: remove a consumer, and with it any entries it
    /// still owns; returns how many it owned.
    ///
    /// # Errors
    ///
    /// [`Error::NoGroup`](crate::Error::NoGroup) when the group doesn't exist, and
    /// [`Error::Redis`](crate::Error::Redis) when the server refuses it or can't be reached.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, Streams};
    ///
    /// let streams = MemoryStreams::new();
    /// streams.xgroup_create("s", "g")?;
    /// assert_eq!(streams.xgroup_delconsumer("s", "g", "c")?, 0);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    fn xgroup_delconsumer(&self, stream: &str, group: &str, consumer: &str) -> Result<u64>;

    /// Renew `consumer`'s lease on a pending entry, as one atomic step on the server: if, at the
    /// instant it runs, the entry is pending in the group for `consumer`, its idle time becomes 0
    /// and nothing else changes, neither its owner nor its delivery count; otherwise nothing
    /// changes and the answer is [`Renewal::Lost`]. An entry still pending but deleted from the
    /// stream is dropped from the pending list and answers [`LostLease::NotPending`].
    ///
    /// The check and the renewal must be one step. A check followed by a separate `XCLAIM` lets
    /// another worker's `XAUTOCLAIM` land between the two, and the `XCLAIM` then takes the entry
    /// straight back: two workers run the task, each holding what it believes is the lease.
    /// [`RedisStreams`](crate::RedisStreams) runs both in one server-side script, which Redis runs
    /// with no other command in between.
    ///
    /// # Errors
    ///
    /// [`Error::NoGroup`](crate::Error::NoGroup) when the group doesn't exist, which a worker
    /// treats as a lost lease, and [`Error::Redis`](crate::Error::Redis) when the server refuses it
    /// or can't be reached, which says nothing about the lease.
    ///
    /// ```
    /// use legit_streams::{LostLease, MemoryStreams, Renewal, Streams};
    ///
    /// let streams = MemoryStreams::new();
    /// streams.xgroup_create("s", "g")?;
    /// let id = streams.xadd("s", &[(b"k".as_slice(), b"v".as_slice())])?;
    /// streams.xreadgroup("s", "g", "a", 1, None)?;
    /// assert_eq!(streams.renew_lease("s", "g", "a", id)?, Renewal::Renewed);
    /// assert_eq!(streams.renew_lease("s", "g", "b", id)?, Renewal::Lost(LostLease::OtherConsumer));
    /// streams.xack("s", "g", &[id])?;
    /// assert_eq!(streams.renew_lease("s", "g", "a", id)?, Renewal::Lost(LostLease::NotPending));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    fn renew_lease(&self, stream: &str, group: &str, consumer: &str, id: EntryId) -> Result<Renewal>;

    /// Release `consumer`'s lease on a pending entry, as one atomic step on the server: if the
    /// entry is pending in the group for `consumer`, its idle time is set to `idle`, so a worker
    /// that claims entries idle that long takes it at once; otherwise nothing changes. The owner
    /// and the delivery count don't change. Returns whether the entry was released. As with
    /// [`Streams::renew_lease`], a separate check and `XCLAIM` could take back an entry another
    /// worker has just claimed.
    ///
    /// # Errors
    ///
    /// [`Error::NoGroup`](crate::Error::NoGroup) when the group doesn't exist, and
    /// [`Error::Redis`](crate::Error::Redis) when the server refuses it or can't be reached.
    ///
    /// ```
    /// use std::time::Duration;
    /// use legit_streams::{Clock, MemoryStreams, Streams};
    ///
    /// let streams = MemoryStreams::with_clock(Clock::manual(1_000_000));
    /// streams.xgroup_create("s", "g")?;
    /// let id = streams.xadd("s", &[(b"k".as_slice(), b"v".as_slice())])?;
    /// streams.xreadgroup("s", "g", "a", 1, None)?;
    /// assert!(!streams.release_lease("s", "g", "b", id, Duration::from_secs(300))?);
    /// assert!(streams.release_lease("s", "g", "a", id, Duration::from_secs(300))?);
    /// assert_eq!(streams.pending("s", "g")[0].idle, Duration::from_secs(300));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    fn release_lease(&self, stream: &str, group: &str, consumer: &str, id: EntryId, idle: Duration) -> Result<bool>;

    /// `XREAD COUNT count [BLOCK ms] STREAMS stream after`: up to `count` entries added after
    /// `after`, without a consumer group, so nothing is delivered or pending. With `block`, wait
    /// up to that long for one when there are none; `None` returns at once. A `block` under a
    /// millisecond waits a millisecond, as for [`Streams::xreadgroup`]. A stream that doesn't
    /// exist reads as empty. `count` 0 means no limit.
    ///
    /// Reading from [`EntryId::ZERO`] gives the entries already there, so a fast-lane caller that
    /// reads its own reply key from `0` sees a reply that arrived before its read began.
    ///
    /// # Errors
    ///
    /// [`Error::Redis`](crate::Error::Redis) when the server refuses it or can't be reached, and
    /// by default, for an implementation that doesn't send it.
    ///
    /// ```
    /// use legit_streams::{EntryId, MemoryStreams, Streams};
    ///
    /// let streams = MemoryStreams::new();
    /// let id = streams.xadd("reply", &[(b"k".as_slice(), b"v".as_slice())])?;
    /// assert_eq!(streams.xread("reply", EntryId::ZERO, 1, None)?[0].id, id);
    /// assert!(streams.xread("reply", id, 1, None)?.is_empty());
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    fn xread(&self, stream: &str, after: EntryId, count: usize, block: Option<Duration>) -> Result<Vec<Entry>> {
        let _ = (stream, after, count, block);
        Err(unsupported("XREAD"))
    }

    /// `EXPIRE key seconds`: delete the key once `ttl` has passed, replacing any expiry it had.
    /// The time is rounded up to whole seconds, so the key never goes sooner than asked; a `ttl` of
    /// zero deletes it now, as Redis does. Returns whether the key existed.
    ///
    /// # Errors
    ///
    /// [`Error::Redis`](crate::Error::Redis) when the server refuses it or can't be reached, and
    /// by default, for an implementation that doesn't send 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("reply", &[(b"k".as_slice(), b"v".as_slice())])?;
    /// assert!(streams.expire("reply", Duration::from_secs(60))?);
    /// clock.advance(Duration::from_secs(61));
    /// assert_eq!(streams.xlen("reply")?, 0);
    /// assert!(!streams.expire("reply", Duration::from_secs(60))?);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    fn expire(&self, key: &str, ttl: Duration) -> Result<bool> {
        let _ = (key, ttl);
        Err(unsupported("EXPIRE"))
    }

    /// `DEL key ...`: delete keys, returning how many existed.
    ///
    /// # Errors
    ///
    /// [`Error::Redis`](crate::Error::Redis) when the server refuses it or can't be reached, and
    /// by default, for an implementation that doesn't send it.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, Streams};
    ///
    /// let streams = MemoryStreams::new();
    /// streams.xadd("reply", &[(b"k".as_slice(), b"v".as_slice())])?;
    /// assert_eq!(streams.del(&["reply", "missing"])?, 1);
    /// assert_eq!(streams.xlen("reply")?, 0);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    fn del(&self, keys: &[&str]) -> Result<u64> {
        let _ = keys;
        Err(unsupported("DEL"))
    }

    /// `XADD` then `EXPIRE`: how a fast-lane worker writes a reply, so a reply nobody reads goes
    /// away on its own. The expiry is set again on every add. [`RedisStreams`](crate::RedisStreams)
    /// sends both in one round trip.
    ///
    /// # Errors
    ///
    /// [`Error::Redis`](crate::Error::Redis) when the server refuses either or can't be reached;
    /// the entry may have been added.
    ///
    /// ```
    /// use std::time::Duration;
    /// use legit_streams::{Clock, MemoryStreams, Streams};
    ///
    /// let streams = MemoryStreams::with_clock(Clock::manual(0));
    /// streams.xadd_expire("reply", &[(b"k".as_slice(), b"v".as_slice())], Duration::from_secs(60))?;
    /// assert_eq!(streams.ttl("reply"), Some(Duration::from_secs(60)));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    fn xadd_expire(&self, stream: &str, fields: &[(&[u8], &[u8])], ttl: Duration) -> Result<EntryId> {
        let id = self.xadd(stream, fields)?;
        self.expire(stream, ttl)?;
        Ok(id)
    }

    /// `XINFO GROUPS stream`: how much work a group has not finished. `None` when this
    /// implementation can't tell, which is the default for an implementation written before this
    /// method.
    ///
    /// When the server gives no lag, [`RedisStreams`](crate::RedisStreams) also sends
    /// `XLEN stream` and sets [`GroupBacklog::length`], so that [`GroupBacklog::waiting`] can give
    /// an estimate, marked as one; when the server gives a lag, it sends nothing more. A refused
    /// or failed `XLEN` leaves the length `None`, never an error.
    ///
    /// Nothing in this crate calls it: it's for a caller that reports on a group, such as a
    /// worker's status page, and it should be called off the path that runs tasks.
    ///
    /// # Errors
    ///
    /// [`Error::NoGroup`](crate::Error::NoGroup) when the stream or the group doesn't exist, and
    /// [`Error::Redis`](crate::Error::Redis) when the server refuses `XINFO GROUPS` or can't be
    /// reached.
    ///
    /// ```
    /// use legit_streams::{GroupBacklog, MemoryStreams, Streams, Waiting};
    ///
    /// let streams = MemoryStreams::new();
    /// streams.xgroup_create("s", "g")?;
    /// for _ in 0..3 {
    ///     streams.xadd("s", &[(b"k".as_slice(), b"v".as_slice())])?;
    /// }
    /// streams.xreadgroup("s", "g", "c", 1, None)?;
    /// let backlog = streams.group_backlog("s", "g")?.expect("the double always tells");
    /// assert_eq!(backlog, GroupBacklog::new(1, Some(2)).with_length(3));
    /// assert_eq!(backlog.waiting(), Some(Waiting::Exact(2)));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    fn group_backlog(&self, stream: &str, group: &str) -> Result<Option<GroupBacklog>> {
        let _ = (stream, group);
        Ok(None)
    }
}

/// The error of a command an implementation doesn't send.
fn unsupported(command: &str) -> crate::Error {
    crate::Error::Redis(format!("ERR this `Streams` implementation doesn't send {command}"))
}

/// A shared handle runs the commands of what it points to, so one [`RedisStreams`](crate::RedisStreams)
/// or a `dyn Streams` can serve many workers and readers.
impl<S: Streams + ?Sized> Streams for std::sync::Arc<S> {
    fn xadd(&self, stream: &str, fields: &[(&[u8], &[u8])]) -> Result<EntryId> {
        (**self).xadd(stream, fields)
    }

    fn xlen(&self, stream: &str) -> Result<u64> {
        (**self).xlen(stream)
    }

    fn xgroup_create(&self, stream: &str, group: &str) -> Result<bool> {
        (**self).xgroup_create(stream, group)
    }

    fn xreadgroup(
        &self,
        stream: &str,
        group: &str,
        consumer: &str,
        count: usize,
        block: Option<Duration>,
    ) -> Result<Vec<Entry>> {
        (**self).xreadgroup(stream, group, consumer, count, block)
    }

    fn xautoclaim(
        &self,
        stream: &str,
        group: &str,
        consumer: &str,
        min_idle: Duration,
        start: EntryId,
        count: usize,
    ) -> Result<AutoClaim> {
        (**self).xautoclaim(stream, group, consumer, min_idle, start, count)
    }

    fn xclaim_justid(
        &self,
        stream: &str,
        group: &str,
        consumer: &str,
        ids: &[EntryId],
        idle: Option<Duration>,
    ) -> Result<Vec<EntryId>> {
        (**self).xclaim_justid(stream, group, consumer, ids, idle)
    }

    fn xpending_entry(&self, stream: &str, group: &str, id: EntryId) -> Result<Option<Pending>> {
        (**self).xpending_entry(stream, group, id)
    }

    fn xpending_consumer(&self, stream: &str, group: &str, consumer: &str, count: usize) -> Result<Vec<Pending>> {
        (**self).xpending_consumer(stream, group, consumer, count)
    }

    fn xack(&self, stream: &str, group: &str, ids: &[EntryId]) -> Result<u64> {
        (**self).xack(stream, group, ids)
    }

    fn xdel(&self, stream: &str, ids: &[EntryId]) -> Result<u64> {
        (**self).xdel(stream, ids)
    }

    fn xack_xdel(&self, stream: &str, group: &str, ids: &[EntryId]) -> Result<()> {
        (**self).xack_xdel(stream, group, ids)
    }

    fn xgroup_delconsumer(&self, stream: &str, group: &str, consumer: &str) -> Result<u64> {
        (**self).xgroup_delconsumer(stream, group, consumer)
    }

    fn renew_lease(&self, stream: &str, group: &str, consumer: &str, id: EntryId) -> Result<Renewal> {
        (**self).renew_lease(stream, group, consumer, id)
    }

    fn release_lease(&self, stream: &str, group: &str, consumer: &str, id: EntryId, idle: Duration) -> Result<bool> {
        (**self).release_lease(stream, group, consumer, id, idle)
    }

    fn xread(&self, stream: &str, after: EntryId, count: usize, block: Option<Duration>) -> Result<Vec<Entry>> {
        (**self).xread(stream, after, count, block)
    }

    fn expire(&self, key: &str, ttl: Duration) -> Result<bool> {
        (**self).expire(key, ttl)
    }

    fn del(&self, keys: &[&str]) -> Result<u64> {
        (**self).del(keys)
    }

    fn xadd_expire(&self, stream: &str, fields: &[(&[u8], &[u8])], ttl: Duration) -> Result<EntryId> {
        (**self).xadd_expire(stream, fields, ttl)
    }

    fn group_backlog(&self, stream: &str, group: &str) -> Result<Option<GroupBacklog>> {
        (**self).group_backlog(stream, group)
    }
}

/// `ttl` in whole seconds, rounded up, as `EXPIRE` takes it.
pub(crate) fn expire_seconds(ttl: Duration) -> u64 {
    ttl.as_secs().saturating_add(u64::from(ttl.subsec_nanos() > 0))
}