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
//! The client side of the contract: send tasks, read their results.

use std::fmt;
use std::sync::Arc;
use std::time::Duration;

use crate::entry::{Entry, EntryId};
use crate::error::{Error, Result};
use crate::fields::{self, Limits};
use crate::result::TaskResult;
use crate::streams::Streams;
use crate::task::Task;
use crate::worker::check_task_stream;

/// The target depth a [`Producer`] starts with, the contract's reference value; a deployment may
/// choose another with [`Producer::target_depth`].
///
/// ```
/// assert_eq!(legit_streams::DEFAULT_TARGET_DEPTH, 300);
/// ```
pub const DEFAULT_TARGET_DEPTH: u64 = 300;

/// Sends tasks to a task stream, checking its depth first: a stream at or over the target depth
/// takes no more until workers drain it, because inline payloads make the stream's depth its
/// memory use.
///
/// Only [`TaskBuilder::build`](crate::TaskBuilder::build) enforces the producer's rules. A task
/// read from a stream rather than built, such as one an application passes on, is sent with the
/// fields it has, reserved names included, as a reader passes through the fields it doesn't know.
///
/// ```
/// use legit_streams::{Error, MemoryStreams, Producer, Task};
///
/// let streams = MemoryStreams::new();
/// let producer = Producer::new(streams.clone(), "hash_tasks").target_depth(1);
///
/// producer.send(&Task::builder("app", "post", "1").field("text_data", "one").build()?)?;
/// let full = producer.send(&Task::builder("app", "post", "2").field("text_data", "two").build()?);
/// assert!(matches!(full, Err(Error::StreamFull { depth: 1, .. })));
/// # Ok::<(), legit_streams::Error>(())
/// ```
#[derive(Clone)]
pub struct Producer {
    streams: Arc<dyn Streams>,
    stream: String,
    target_depth: Option<u64>,
}

impl Producer {
    /// A producer for `stream`, such as `hash_tasks`, with a target depth of
    /// [`DEFAULT_TARGET_DEPTH`]. The stream name is checked on each send, not here.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, Producer};
    ///
    /// let producer = Producer::new(MemoryStreams::new(), "hash_tasks");
    /// assert_eq!(producer.depth()?, 0);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn new(streams: impl Streams + 'static, stream: impl Into<String>) -> Self {
        Self {
            streams: Arc::new(streams),
            stream: stream.into(),
            target_depth: Some(DEFAULT_TARGET_DEPTH),
        }
    }

    /// Set the depth at which the stream counts as full.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, Producer};
    ///
    /// let producer = Producer::new(MemoryStreams::new(), "hash_tasks").target_depth(1_000);
    /// # let _ = producer;
    /// ```
    #[must_use]
    pub const fn target_depth(mut self, target_depth: u64) -> Self {
        self.target_depth = Some(target_depth);
        self
    }

    /// Send without checking the depth, for a caller that paces itself, and save the `XLEN` per
    /// task.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, Producer};
    ///
    /// let producer = Producer::new(MemoryStreams::new(), "hash_tasks").unbounded();
    /// # let _ = producer;
    /// ```
    #[must_use]
    pub const fn unbounded(mut self) -> Self {
        self.target_depth = None;
        self
    }

    /// How many entries the stream holds, those being worked on included.
    ///
    /// # Errors
    ///
    /// [`Error::Redis`] when the server can't be reached.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, Producer};
    ///
    /// assert_eq!(Producer::new(MemoryStreams::new(), "hash_tasks").depth()?, 0);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    pub fn depth(&self) -> Result<u64> {
        self.streams.xlen(&self.stream)
    }

    /// Check the depth and add the task to the stream, returning its entry id. The task is sent
    /// as version 1: one read from an older producer without `v` gets `v` = `1` after `source`.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidConfig`] when the producer's stream begins with `results:` or `dead:`,
    /// which no task stream may; nothing is sent. [`Error::StreamFull`] when the stream is at or
    /// over the target depth, which isn't a failure: send again once it drains.
    /// [`Error::TooLarge`] when the fields it would send are over the default [`Limits`], which a
    /// worker would refuse: a task read without `v` is sent with `v` = `1`, one field more.
    /// [`Error::Redis`] when the server can't be reached.
    ///
    /// ```
    /// use legit_streams::{Error, MemoryStreams, Producer, Task};
    ///
    /// let producer = Producer::new(MemoryStreams::new(), "hash_tasks");
    /// let id = producer.send(&Task::builder("app", "post", "1").build()?)?;
    /// assert_eq!(producer.depth()?, 1);
    /// # let _ = id;
    ///
    /// let producer = Producer::new(MemoryStreams::new(), "dead:hash_tasks");
    /// let refused = producer.send(&Task::builder("app", "post", "1").build()?);
    /// assert!(matches!(refused, Err(Error::InvalidConfig(_))));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    pub fn send(&self, task: &Task) -> Result<EntryId> {
        check_task_stream(&self.stream)?;
        // A task read from an older producer goes out with `v`, which may take it over a bound...
        let fields = task.wire_fields();
        fields::check_strings(&fields, &Limits::default())?;
        if let Some(target_depth) = self.target_depth {
            let depth = self.depth()?;
            if depth >= target_depth {
                return Err(Error::StreamFull {
                    stream: self.stream.clone(),
                    depth,
                    target_depth,
                });
            }
        }
        self.streams.xadd(&self.stream, &fields::as_bytes(&fields))
    }
}

impl fmt::Debug for Producer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Producer")
            .field("stream", &self.stream)
            .field("target_depth", &self.target_depth)
            .finish_non_exhaustive()
    }
}

/// A result read from a reply stream: its entry id, the result, or why the entry isn't one, and
/// how many times the entry has been delivered.
///
/// ```
/// use legit_streams::{EntryId, Received, TaskResult};
///
/// let received = Received { id: EntryId::new(1, 0), result: TaskResult::success("app_1").build(), deliveries: Some(1) };
/// assert!(received.result.is_ok());
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Received {
    /// The entry, to pass to [`ResultReader::ack`] once the result is handled.
    pub id: EntryId,
    /// The result, or the error that kept the entry from being read as one; the reader has
    /// already removed such an entry.
    pub result: Result<TaskResult>,
    /// How many times the entry has been delivered to the group, this delivery included: `Some(1)`
    /// from [`ResultReader::read`], which takes only entries never delivered, and the count after
    /// the claim from [`ResultReader::reclaim`]; `None` when the count couldn't be read. A reader
    /// should set aside a result that keeps failing once this passes a bound of its own.
    pub deliveries: Option<u64>,
}

/// Reads an application's results from its reply stream with a consumer group: read, handle, then
/// [`ResultReader::ack`], which acknowledges and deletes. An entry left unacknowledged stays
/// pending, and [`ResultReader::reclaim`] takes it back once idle, so a reader that crashes
/// between storing a result and acknowledging it loses nothing.
///
/// A reader should bound how many times it retries one result, using
/// [`Received::deliveries`], and set aside one that keeps failing; and it should apply a result
/// only to a task it issued, since any writer to the instance can name its stream.
///
/// A process that stops cleanly should delete its consumer from the group, after checking that the
/// consumer owns no pending entries. `ResultReader` has no call for it; do it on the same
/// [`Streams`] with [`Streams::xpending_consumer`] (`count` 1) and, when that returns nothing,
/// [`Streams::xgroup_delconsumer`], as the workers do when they stop.
///
/// ```
/// use legit_streams::{MemoryStreams, ResultReader, Streams, TaskResult};
///
/// let streams = MemoryStreams::new();
/// let reader = ResultReader::new(streams.clone(), "results:app:hash", "app", "app-1");
/// reader.create_group()?;
///
/// let result = TaskResult::success("app_1").field("result", "{}").build()?;
/// let fields: Vec<(&[u8], &[u8])> = result.fields().iter().map(|(k, v)| (k.as_bytes(), v.as_bytes())).collect();
/// streams.xadd("results:app:hash", &fields)?;
///
/// let received = reader.read(10, None)?;
/// assert_eq!(received[0].result.as_ref().map(TaskResult::task_id), Ok("app_1"));
/// reader.ack(&[received[0].id])?;
/// assert_eq!(streams.xlen("results:app:hash")?, 0);
/// # Ok::<(), legit_streams::Error>(())
/// ```
#[derive(Clone)]
pub struct ResultReader {
    streams: Arc<dyn Streams>,
    stream: String,
    group: String,
    consumer: String,
    limits: Limits,
}

impl ResultReader {
    /// A reader of `stream` with `group` as `consumer`.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, ResultReader};
    ///
    /// let reader = ResultReader::new(MemoryStreams::new(), "results:app:hash", "app", "app-1");
    /// # let _ = reader;
    /// ```
    #[must_use]
    pub fn new(
        streams: impl Streams + 'static,
        stream: impl Into<String>,
        group: impl Into<String>,
        consumer: impl Into<String>,
    ) -> Self {
        Self {
            streams: Arc::new(streams),
            stream: stream.into(),
            group: group.into(),
            consumer: consumer.into(),
            limits: Limits::default(),
        }
    }

    /// Set the bounds on a result entry.
    ///
    /// ```
    /// use legit_streams::{Limits, MemoryStreams, ResultReader};
    ///
    /// let limits = Limits { max_entry_bytes: 1024, ..Limits::default() };
    /// let reader = ResultReader::new(MemoryStreams::new(), "results:app:hash", "app", "app-1").limits(limits);
    /// # let _ = reader;
    /// ```
    #[must_use]
    pub const fn limits(mut self, limits: Limits) -> Self {
        self.limits = limits;
        self
    }

    /// Create the group, and the stream, so results that arrive before the first read are kept.
    /// Returns `false` when it already existed.
    ///
    /// # Errors
    ///
    /// [`Error::Redis`] when the server can't be reached.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, ResultReader};
    ///
    /// let reader = ResultReader::new(MemoryStreams::new(), "results:app:hash", "app", "app-1");
    /// assert!(reader.create_group()?);
    /// assert!(!reader.create_group()?);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    pub fn create_group(&self) -> Result<bool> {
        self.streams.xgroup_create(&self.stream, &self.group)
    }

    /// Read up to `count` results no consumer of the group has seen, waiting up to `block` for
    /// one. Creates the group when it's missing.
    ///
    /// # Errors
    ///
    /// [`Error::Redis`] when the server can't be reached. An entry that isn't a valid result, such
    /// as one without a `task_id` or whose `status` isn't exactly `success` or `error`, is
    /// returned with its error, and already acknowledged and deleted: no retry would make it a
    /// result. Acknowledge each valid one with [`ResultReader::ack`] once it's handled.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, ResultReader};
    ///
    /// let reader = ResultReader::new(MemoryStreams::new(), "results:app:hash", "app", "app-1");
    /// assert!(reader.read(10, None)?.is_empty());
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    pub fn read(&self, count: usize, block: Option<Duration>) -> Result<Vec<Received>> {
        let read = || {
            self.streams
                .xreadgroup(&self.stream, &self.group, &self.consumer, count, block)
        };
        let entries = match read() {
            Err(Error::NoGroup { .. }) => {
                self.create_group()?;
                read()?
            }
            other => other?,
        };
        Ok(self.receive(entries.into_iter().map(|entry| (entry, Some(1))).collect()))
    }

    /// Take back results that this group's consumers read and left unacknowledged for at least
    /// `min_idle`, scanning the whole pending list in batches of `count`; for example every minute,
    /// for entries idle 5 minutes. Each claim counts a delivery, and each result comes back with
    /// its count, [`Received::deliveries`], read with one `XPENDING` per entry after the claim.
    ///
    /// # Errors
    ///
    /// [`Error::NoGroup`] when the group doesn't exist, and [`Error::Redis`] when the server can't
    /// be reached.
    ///
    /// ```
    /// use std::time::Duration;
    /// use legit_streams::{MemoryStreams, ResultReader};
    ///
    /// let reader = ResultReader::new(MemoryStreams::new(), "results:app:hash", "app", "app-1");
    /// reader.create_group()?;
    /// assert!(reader.reclaim(Duration::from_secs(300), 25)?.is_empty());
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    pub fn reclaim(&self, min_idle: Duration, count: usize) -> Result<Vec<Received>> {
        let mut received = Vec::new();
        let mut cursor = EntryId::ZERO;
        loop {
            let claim = self
                .streams
                .xautoclaim(&self.stream, &self.group, &self.consumer, min_idle, cursor, count)?;
            if !claim.deleted.is_empty() {
                self.streams.xack(&self.stream, &self.group, &claim.deleted)?;
            }
            let empty = claim.claimed.is_empty();
            let counted = claim
                .claimed
                .into_iter()
                .map(|entry| {
                    let deliveries = match self.streams.xpending_entry(&self.stream, &self.group, entry.id) {
                        Ok(pending) => pending.map(|pending| pending.deliveries),
                        Err(error) => {
                            tracing::warn!(entry = %entry.id, %error, "Couldn't read a result's delivery count");
                            None
                        }
                    };
                    (entry, deliveries)
                })
                .collect();
            received.extend(self.receive(counted));
            cursor = claim.next;
            if cursor == EntryId::ZERO || empty {
                return Ok(received);
            }
        }
    }

    /// Acknowledge and delete results the caller has handled.
    ///
    /// # Errors
    ///
    /// [`Error::Redis`] when the server can't be reached.
    ///
    /// ```
    /// use legit_streams::{EntryId, MemoryStreams, ResultReader};
    ///
    /// let reader = ResultReader::new(MemoryStreams::new(), "results:app:hash", "app", "app-1");
    /// reader.ack(&[EntryId::new(1, 0)])?;
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    pub fn ack(&self, ids: &[EntryId]) -> Result<()> {
        self.streams.xack_xdel(&self.stream, &self.group, ids)
    }

    /// Read entries as results. One that isn't a result is acknowledged and deleted here, and
    /// returned with its error: no retry would make it one.
    fn receive(&self, entries: Vec<(Entry, Option<u64>)>) -> Vec<Received> {
        let received: Vec<Received> = entries
            .into_iter()
            .map(|(entry, deliveries)| Received {
                id: entry.id,
                result: TaskResult::from_raw(&entry.fields, &self.limits),
                deliveries,
            })
            .collect();
        let malformed: Vec<EntryId> = received
            .iter()
            .filter(|received| received.result.is_err())
            .map(|received| received.id)
            .collect();
        if !malformed.is_empty()
            && let Err(error) = self.ack(&malformed)
        {
            tracing::warn!(%error, "Couldn't remove entries that aren't results; they stay pending");
        }
        received
    }
}

impl fmt::Debug for ResultReader {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ResultReader")
            .field("stream", &self.stream)
            .field("group", &self.group)
            .field("consumer", &self.consumer)
            .finish_non_exhaustive()
    }
}