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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
//! The result envelope a worker adds to a reply stream.

use std::fmt;

use crate::entry::Entry;
use crate::error::{Error, Result};
use crate::fields::{self, Limits};
use crate::task::{IDENTITY_MAX_LEN, Task, UNKNOWN};

/// The fields a result builder sets itself.
const RESERVED: [&str; 10] = [
    "task_id",
    "model_type",
    "model_id",
    "task_name",
    "model_name",
    "status",
    "error_type",
    "error",
    "worker_id",
    "processing_ms",
];

/// The optional task fields the contract says a worker echoes into the result untouched.
pub(crate) const ECHOED: [&str; 2] = ["embedder_key", "metadata"];

/// Whether a task succeeded, the result's `status` field.
///
/// ```
/// use legit_streams::Status;
///
/// assert_eq!(Status::Error.as_str(), "error");
/// assert_eq!("success".parse::<Status>(), Ok(Status::Success));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Status {
    /// `success`: the task ran, and the result carries its output.
    Success,
    /// `error`: the task failed, and the result carries `error` and usually `error_type`.
    Error,
}

impl Status {
    /// The field's value: `success` or `error`.
    ///
    /// ```
    /// assert_eq!(legit_streams::Status::Success.as_str(), "success");
    /// ```
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Success => "success",
            Self::Error => "error",
        }
    }
}

impl fmt::Display for Status {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::str::FromStr for Status {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        match s {
            "success" => Ok(Self::Success),
            "error" => Ok(Self::Error),
            _ => Err(Error::InvalidValue {
                field: "status".to_owned(),
                expected: "`success` or `error`",
            }),
        }
    }
}

/// A result envelope: the flat map of string fields a worker adds to a reply stream.
///
/// A result carries `task_id` and `status`, exactly `success` or `error`; an entry without them
/// isn't a result. A worker also writes `model_type`, `model_id`, `task_name` and `model_name`,
/// echoed from the task, and on an error `error`, a message, and `error_type`, a code in lowercase
/// snake case such as `unsupported_model`; it should write `worker_id` and `processing_ms`, who ran
/// the task and for how long, and may write `requested_model_name`. A reader requires none of
/// those: error types are an open set, and a reader treats an unknown or missing one as a failure
/// that won't pass on a retry. Every other field, such as `embedding` or `result`, is the output,
/// which this crate keeps in order and never reads. A result parsed from a stream and written back
/// gives the same fields in the same order.
///
/// `Debug` shows the identity and status fields and the names of the others, never their values.
///
/// ```
/// use legit_streams::{Status, TaskResult};
///
/// let result = TaskResult::success("app_01J0000000000000000000000A")
///     .worker_id("worker-1")
///     .processing_ms(12)
///     .field("result", "{}")
///     .build()?;
///
/// assert_eq!(result.status(), Status::Success);
/// assert_eq!(result.processing_ms(), Some(12));
/// assert_eq!(TaskResult::from_fields(result.fields().to_vec())?, result);
/// # Ok::<(), legit_streams::Error>(())
/// ```
#[derive(Clone, PartialEq, Eq)]
pub struct TaskResult {
    fields: Vec<(String, String)>,
}

impl TaskResult {
    /// Start a success result for a task.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// assert!(TaskResult::success("app_1").build()?.is_success());
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn success(task_id: impl Into<String>) -> ResultBuilder {
        ResultBuilder::new(Some(task_id.into()), Status::Success, None)
    }

    /// Start an error result for a task, with the message for its `error` field.
    ///
    /// A worker must set [`ResultBuilder::error_type`] on every error it writes, as this crate's
    /// workers do. The builder still builds an error without one: a reader must accept such a
    /// result, from an older worker, and its tests need one to read.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// let result = TaskResult::failure("app_1", "no such model").error_type("unsupported_model").build()?;
    /// assert_eq!(result.error(), Some("no such model"));
    /// assert_eq!(result.error_type(), Some("unsupported_model"));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn failure(task_id: impl Into<String>, message: impl Into<String>) -> ResultBuilder {
        ResultBuilder::new(Some(task_id.into()), Status::Error, Some(message.into()))
    }

    /// Read a result from a stream entry, within the default [`Limits`].
    ///
    /// # Errors
    ///
    /// The errors of [`TaskResult::from_raw`].
    ///
    /// ```
    /// use legit_streams::{Entry, EntryId, TaskResult};
    ///
    /// let entry = Entry::new(EntryId::ZERO, vec![(b"task_id".to_vec(), b"app_1".to_vec())]);
    /// assert!(TaskResult::from_entry(&entry).is_err());
    /// ```
    pub fn from_entry(entry: &Entry) -> Result<Self> {
        Self::from_raw(&entry.fields, &Limits::default())
    }

    /// Read a result from raw stream fields.
    ///
    /// # Errors
    ///
    /// [`Error::TooLarge`] for an entry over `limits`, [`Error::InvalidUtf8`] for a name or value
    /// that isn't UTF-8, [`Error::DuplicateField`] for a name given twice,
    /// [`Error::MissingField`] without `task_id` or `status`, [`Error::EmptyField`] for an empty
    /// `task_id`, and [`Error::InvalidValue`] for a `status` other than exactly `success` or
    /// `error`. Nothing else is required: not `error` or `error_type` on an error, nor
    /// `worker_id` or `processing_ms`.
    ///
    /// ```
    /// use legit_streams::{Error, Limits, TaskResult};
    ///
    /// let raw = vec![(b"task_id".to_vec(), b"app_1".to_vec()), (b"status".to_vec(), b"done".to_vec())];
    /// assert!(matches!(TaskResult::from_raw(&raw, &Limits::default()), Err(Error::InvalidValue { .. })));
    /// ```
    pub fn from_raw(raw: &[(Vec<u8>, Vec<u8>)], limits: &Limits) -> Result<Self> {
        let fields = fields::decode(raw, limits)?;
        validate(&fields)?;
        Ok(Self { fields })
    }

    /// Read a result from decoded fields, within the default [`Limits`].
    ///
    /// # Errors
    ///
    /// The errors of [`TaskResult::from_raw`] that apply to strings.
    ///
    /// ```
    /// use legit_streams::{Error, TaskResult};
    ///
    /// let fields = vec![("task_id".to_owned(), "app_1".to_owned()), ("status".to_owned(), "Error".to_owned())];
    /// assert!(matches!(TaskResult::from_fields(fields), Err(Error::InvalidValue { .. })));
    /// let fields = vec![("task_id".to_owned(), "app_1".to_owned()), ("status".to_owned(), "error".to_owned())];
    /// assert_eq!(TaskResult::from_fields(fields)?.error_type(), None);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    pub fn from_fields(fields: Vec<(String, String)>) -> Result<Self> {
        fields::check_strings(&fields, &Limits::default())?;
        validate(&fields)?;
        Ok(Self { fields })
    }

    /// The id of the task this is the result of.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// assert_eq!(TaskResult::success("app_1").build()?.task_id(), "app_1");
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn task_id(&self) -> &str {
        self.get("task_id").unwrap_or_default()
    }

    /// Whether the task succeeded.
    ///
    /// ```
    /// use legit_streams::{Status, TaskResult};
    ///
    /// assert_eq!(TaskResult::failure("app_1", "failed").build()?.status(), Status::Error);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn status(&self) -> Status {
        if self.get("status") == Some("error") {
            Status::Error
        } else {
            Status::Success
        }
    }

    /// Whether the status is `success`.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// assert!(!TaskResult::failure("app_1", "failed").build()?.is_success());
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn is_success(&self) -> bool {
        self.status() == Status::Success
    }

    /// The error message, on an error.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// assert_eq!(TaskResult::success("app_1").build()?.error(), None);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn error(&self) -> Option<&str> {
        self.get("error")
    }

    /// The error code, such as `unsupported_model`, when the worker gave one.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// assert_eq!(TaskResult::failure("app_1", "failed").build()?.error_type(), None);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn error_type(&self) -> Option<&str> {
        self.get("error_type")
    }

    /// The task's `model_type`, echoed.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// assert_eq!(TaskResult::success("app_1").model_type("post").build()?.model_type(), Some("post"));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn model_type(&self) -> Option<&str> {
        self.get("model_type")
    }

    /// The task's `model_id`, echoed.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// assert_eq!(TaskResult::success("app_1").model_id("42").build()?.model_id(), Some("42"));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn model_id(&self) -> Option<&str> {
        self.get("model_id")
    }

    /// The task's `task_name`, echoed.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// assert_eq!(TaskResult::success("app_1").build()?.task_name(), None);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn task_name(&self) -> Option<&str> {
        self.get("task_name")
    }

    /// The model the worker names: the task's `model_name` echoed, or the worker's own name for
    /// what ran.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// let result = TaskResult::success("app_1").model_name("example-model").build()?;
    /// assert_eq!(result.model_name(), Some("example-model"));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn model_name(&self) -> Option<&str> {
        self.get("model_name")
    }

    /// The consumer name of the worker that ran the task.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// assert_eq!(TaskResult::success("app_1").worker_id("w-1").build()?.worker_id(), Some("w-1"));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn worker_id(&self) -> Option<&str> {
        self.get("worker_id")
    }

    /// How long the worker spent on the task, in milliseconds, from taking the entry to writing
    /// the result; `None` when the result doesn't say, or says it with something other than a
    /// whole number.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// assert_eq!(TaskResult::success("app_1").build()?.processing_ms(), None);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn processing_ms(&self) -> Option<u64> {
        self.get("processing_ms").and_then(|ms| ms.parse().ok())
    }

    /// The value of a field, the envelope's own or the worker's output.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// let result = TaskResult::success("app_1").field("embedding_format", "base64_fp32").build()?;
    /// assert_eq!(result.get("embedding_format"), Some("base64_fp32"));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&str> {
        fields::get(&self.fields, name)
    }

    /// Every field, in order.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// assert_eq!(TaskResult::success("app_1").build()?.fields().len(), 2);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn fields(&self) -> &[(String, String)] {
        &self.fields
    }

    /// The fields, in order, consuming the result.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// let fields = TaskResult::success("app_1").build()?.into_fields();
    /// assert_eq!(fields[0], ("task_id".to_owned(), "app_1".to_owned()));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn into_fields(self) -> Vec<(String, String)> {
        self.fields
    }
}

impl fmt::Debug for TaskResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TaskResult")
            .field("task_id", &self.task_id())
            .field("status", &self.status())
            .field("error_type", &self.error_type())
            .field(
                "fields",
                &self.fields.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(),
            )
            .finish_non_exhaustive()
    }
}

fn validate(fields: &[(String, String)]) -> Result<()> {
    match fields::get(fields, "task_id") {
        None => return Err(Error::MissingField("task_id")),
        Some("") => return Err(Error::EmptyField("task_id")),
        Some(_) => {}
    }
    // Compared exactly: anything but `success` or `error` isn't a result...
    fields::get(fields, "status")
        .ok_or(Error::MissingField("status"))?
        .parse::<Status>()?;
    Ok(())
}

/// Whether an error type is lowercase snake case, as a worker writes it: a lowercase ASCII letter,
/// then lowercase letters, digits and `_`. A reader takes any code, or none.
fn is_error_type(error_type: &str) -> bool {
    error_type.starts_with(|c: char| c.is_ascii_lowercase())
        && error_type
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
}

/// A result being built. [`ResultBuilder::build`] writes the fields in this order: `task_id`,
/// `model_type`, `model_id`, `task_name`, `model_name`, `status`, `error_type`, `error`,
/// `worker_id` and `processing_ms`, each when set, then the extra fields in the order they were
/// added. The contract doesn't fix an order; this one is the crate's.
///
/// ```
/// use legit_streams::{Task, TaskResult};
///
/// let task = Task::builder("app", "post", "42").task_id("app_1").field("metadata", "{\"k\":1}").build()?;
/// let result = TaskResult::success(task.task_id()).echo(&task).build()?;
///
/// assert_eq!(result.model_id(), Some("42"));
/// assert_eq!(result.get("metadata"), Some("{\"k\":1}"));
/// # Ok::<(), legit_streams::Error>(())
/// ```
#[derive(Clone)]
pub struct ResultBuilder {
    task_id: Option<String>,
    model_type: Option<String>,
    model_id: Option<String>,
    task_name: Option<String>,
    model_name: Option<String>,
    status: Status,
    error_type: Option<String>,
    error: Option<String>,
    worker_id: Option<String>,
    processing_ms: Option<u64>,
    echoed: Vec<(String, String)>,
    extra: Vec<(String, String)>,
}

impl ResultBuilder {
    const fn new(task_id: Option<String>, status: Status, error: Option<String>) -> Self {
        Self {
            task_id,
            model_type: None,
            model_id: None,
            task_name: None,
            model_name: None,
            status,
            error_type: None,
            error,
            worker_id: None,
            processing_ms: None,
            echoed: Vec::new(),
            extra: Vec::new(),
        }
    }

    /// Echo what the contract echoes from a task: `model_type`, `model_id`, `task_name` and
    /// `model_name`, and `embedder_key` and `metadata` when the task has them. A `model_type`,
    /// `model_id` or `task_name` longer than [`IDENTITY_MAX_LEN`] is echoed as
    /// [`UNKNOWN`](crate::UNKNOWN); `model_name` is echoed as it is.
    ///
    /// ```
    /// use legit_streams::{Task, TaskResult};
    ///
    /// let task = Task::builder("app", "post", "42").task_name("embed").build()?;
    /// let result = TaskResult::failure(task.task_id(), "failed").echo(&task).build()?;
    /// assert_eq!(result.task_name(), Some("embed"));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn echo(mut self, task: &Task) -> Self {
        self.model_type = Some(identity(Some(task.model_type())));
        self.model_id = Some(identity(Some(task.model_id())));
        self.task_name = Some(identity(Some(task.task_name())));
        self.model_name = Some(task.model_name().to_owned());
        for name in ECHOED {
            if let Some(value) = task.get(name) {
                self.echoed.push((name.to_owned(), value.to_owned()));
            }
        }
        self
    }

    /// Set `model_type`.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// assert_eq!(TaskResult::success("app_1").model_type("post").build()?.model_type(), Some("post"));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn model_type(mut self, model_type: impl Into<String>) -> Self {
        self.model_type = Some(model_type.into());
        self
    }

    /// Set `model_id`.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// assert_eq!(TaskResult::success("app_1").model_id("7").build()?.model_id(), Some("7"));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn model_id(mut self, model_id: impl Into<String>) -> Self {
        self.model_id = Some(model_id.into());
        self
    }

    /// Set `task_name`.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// assert_eq!(TaskResult::success("app_1").task_name("embed").build()?.task_name(), Some("embed"));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn task_name(mut self, task_name: impl Into<String>) -> Self {
        self.task_name = Some(task_name.into());
        self
    }

    /// Set `model_name`, replacing the echoed one: a worker may name what actually ran.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// let result = TaskResult::success("app_1").model_name("example-model").build()?;
    /// assert_eq!(result.model_name(), Some("example-model"));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn model_name(mut self, model_name: impl Into<String>) -> Self {
        self.model_name = Some(model_name.into());
        self
    }

    /// Set `error_type`, the error's code. Ignored on a success.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// let result = TaskResult::failure("app_1", "too big").error_type("result_too_large").build()?;
    /// assert_eq!(result.error_type(), Some("result_too_large"));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn error_type(mut self, error_type: impl Into<String>) -> Self {
        self.error_type = Some(error_type.into());
        self
    }

    /// Set `worker_id`, the consumer name of the worker that ran the task.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// assert_eq!(TaskResult::success("app_1").worker_id("w-1").build()?.worker_id(), Some("w-1"));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
        self.worker_id = Some(worker_id.into());
        self
    }

    /// Set `processing_ms`.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// assert_eq!(TaskResult::success("app_1").processing_ms(5).build()?.processing_ms(), Some(5));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub const fn processing_ms(mut self, processing_ms: u64) -> Self {
        self.processing_ms = Some(processing_ms);
        self
    }

    /// Add a field of the worker's, such as `result` or `supported_models`. Fields keep the
    /// order they're added in.
    ///
    /// ```
    /// use legit_streams::TaskResult;
    ///
    /// let result = TaskResult::success("app_1").field("result", "{}").build()?;
    /// assert_eq!(result.get("result"), Some("{}"));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn field(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.extra.push((name.into(), value.into()));
        self
    }

    /// Build the result.
    ///
    /// # Errors
    ///
    /// [`Error::EmptyField`] for an empty task id, [`Error::InvalidValue`] for an `error_type` that
    /// isn't lowercase snake case, [`Error::ReservedField`] for an extra field
    /// named like one of the envelope's own, [`Error::DuplicateField`] for a field given twice,
    /// such as an extra `metadata` beside the echoed one, and [`Error::TooLarge`] for a result
    /// over the default [`Limits`].
    ///
    /// ```
    /// use legit_streams::{Error, TaskResult};
    ///
    /// assert_eq!(TaskResult::success("").build(), Err(Error::EmptyField("task_id")));
    /// ```
    pub fn build(self) -> Result<TaskResult> {
        self.build_within(&Limits::default())
    }

    /// Build the result within `limits`.
    pub(crate) fn build_within(self, limits: &Limits) -> Result<TaskResult> {
        if let Some((name, _)) = self.extra.iter().find(|(name, _)| RESERVED.contains(&name.as_str())) {
            return Err(Error::ReservedField(name.clone()));
        }
        if self.status == Status::Error
            && let Some(error_type) = &self.error_type
            && !is_error_type(error_type)
        {
            return Err(Error::InvalidValue {
                field: "error_type".to_owned(),
                expected: "lowercase snake case, such as `unsupported_model`",
            });
        }
        let fields = self.into_fields();
        fields::check_strings(&fields, limits)?;
        validate(&fields)?;
        Ok(TaskResult { fields })
    }

    /// The fields without the checks of [`ResultBuilder::build`], for a worker answering an entry
    /// it couldn't read, which may lack a task id.
    pub(crate) fn into_fields(self) -> Vec<(String, String)> {
        let mut fields = Vec::with_capacity(10 + self.echoed.len() + self.extra.len());
        let mut push = |name: &str, value: Option<String>| {
            if let Some(value) = value {
                fields.push((name.to_owned(), value));
            }
        };
        push("task_id", self.task_id);
        push("model_type", self.model_type);
        push("model_id", self.model_id);
        push("task_name", self.task_name);
        push("model_name", self.model_name);
        push("status", Some(self.status.as_str().to_owned()));
        if self.status == Status::Error {
            push("error_type", self.error_type);
            push("error", self.error);
        }
        push("worker_id", self.worker_id);
        push("processing_ms", self.processing_ms.map(|ms| ms.to_string()));
        fields.extend(self.echoed);
        fields.extend(self.extra);
        fields
    }

    /// Turn the result into an error with this message and type, keeping what it echoes of the
    /// task and dropping the worker's output.
    pub(crate) fn into_error(mut self, message: String, error_type: &str) -> Self {
        self.status = Status::Error;
        self.error = Some(message);
        self.error_type = Some(error_type.to_owned());
        self.extra.clear();
        self
    }

    /// A builder echoing what can be read from an entry that isn't a valid task: the last of each
    /// field, as a reader that takes repeated names takes them. Of the four echoes a result always
    /// carries, `model_type`, `model_id` and `task_name` are [`UNKNOWN`] when the entry's is
    /// missing, empty, not UTF-8 or longer than [`IDENTITY_MAX_LEN`]; `model_name` is the entry's,
    /// and empty when it has none. The `task_id` is `task_id` as it was sent.
    pub(crate) fn for_raw(raw: &[(Vec<u8>, Vec<u8>)], task_id: Option<&str>, status: Status, error: String) -> Self {
        let text = |name: &str| {
            raw.iter()
                .rev()
                .find(|(key, _)| key == name.as_bytes())
                .and_then(|(_, value)| std::str::from_utf8(value).ok())
        };
        let mut builder = Self::new(task_id.map(str::to_owned), status, Some(error));
        builder.model_type = Some(identity(text("model_type")));
        builder.model_id = Some(identity(text("model_id")));
        builder.task_name = Some(identity(text("task_name")));
        builder.model_name = Some(text("model_name").unwrap_or_default().to_owned());
        for name in ECHOED {
            if let Some(value) = text(name) {
                builder.echoed.push((name.to_owned(), value.to_owned()));
            }
        }
        builder
    }

    /// Whether the result is an error.
    pub(crate) fn is_error(&self) -> bool {
        self.status == Status::Error
    }

    /// The result without the optional fields it echoes of the task, such as `metadata`.
    pub(crate) fn without_echoes(mut self) -> Self {
        self.echoed.clear();
        self
    }

    /// The bare error a worker sends when even the echoed fields would put the result over its
    /// limits: the task id when it's short, the four echoes a result always carries when they're
    /// short, the status, the error and who ran it.
    pub(crate) fn bare(self) -> Self {
        self.cut(1024, 1024)
    }

    /// The bare error with `model_type`, `model_id` and `task_name` kept only when each is at most
    /// `echo` bytes, and [`UNKNOWN`] past that or when missing, and `model_name` kept only when it's
    /// at most `model_name` bytes, and empty past that. The task id is kept when it's at most 1,024
    /// bytes.
    pub(crate) fn cut(self, echo: usize, model_name: usize) -> Self {
        let short = |value: Option<String>| value.filter(|value| !value.is_empty() && value.len() <= echo);
        let task_id = self.task_id.filter(|id| id.len() <= 1024);
        let mut bare = Self::new(task_id, self.status, self.error);
        bare.model_type = Some(short(self.model_type).unwrap_or_else(|| UNKNOWN.to_owned()));
        bare.model_id = Some(short(self.model_id).unwrap_or_else(|| UNKNOWN.to_owned()));
        bare.task_name = Some(short(self.task_name).unwrap_or_else(|| UNKNOWN.to_owned()));
        bare.model_name = Some(
            self.model_name
                .filter(|value| value.len() <= model_name)
                .unwrap_or_default(),
        );
        bare.error_type = self.error_type;
        bare.worker_id = self.worker_id;
        bare.processing_ms = self.processing_ms;
        bare
    }
}

/// The echo of a `model_type`, `model_id` or `task_name`: the value, or [`UNKNOWN`] when it's
/// missing, empty or longer than [`IDENTITY_MAX_LEN`].
fn identity(value: Option<&str>) -> String {
    value
        .filter(|value| !value.is_empty() && value.len() <= IDENTITY_MAX_LEN)
        .unwrap_or(UNKNOWN)
        .to_owned()
}

impl fmt::Debug for ResultBuilder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ResultBuilder")
            .field("task_id", &self.task_id)
            .field("status", &self.status)
            .field(
                "extra",
                &self.extra.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(),
            )
            .finish_non_exhaustive()
    }
}