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
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
788
789
790
791
792
793
794
795
//! The v1 task envelope.

use std::fmt;

use crate::entry::Entry;
use crate::error::{Error, Result};
use crate::fields::{self, Limits};

/// The envelope version this crate reads and writes, the value of every task's `v` field.
///
/// ```
/// assert_eq!(legit_streams::VERSION, "1");
/// ```
pub const VERSION: &str = "1";

/// The longest payload field name a producer sends, in bytes. A name is lowercase ASCII letters,
/// digits and `_`, not starting with a digit; a reader accepts any name within its [`Limits`].
///
/// ```
/// assert_eq!(legit_streams::FIELD_NAME_MAX_LEN, 64);
/// ```
pub const FIELD_NAME_MAX_LEN: usize = 64;

/// The envelope's own fields, in the order this crate's builder writes them. A reader takes a task
/// with no `v`, or an empty one, as version 1.
const REQUIRED: [&str; 7] = [
    "task_id",
    "model_type",
    "model_id",
    "task_name",
    "model_name",
    "source",
    "v",
];

/// The longest `task_id`, in bytes. A task id is 1 to 64 ASCII letters, digits, `_` and `-`.
///
/// ```
/// assert_eq!(legit_streams::TASK_ID_MAX_LEN, 64);
/// ```
pub const TASK_ID_MAX_LEN: usize = 64;

/// The longest application name a producer sends, the task's `source` and the `{app}` of its reply
/// streams, in bytes. A worker reading a task takes any non-empty `source`.
///
/// ```
/// assert_eq!(legit_streams::APP_MAX_LEN, 32);
/// ```
pub const APP_MAX_LEN: usize = 32;

/// The longest `model_type`, `model_id` and `task_name` a producer sends, in bytes. A worker that
/// reads a longer one still runs the task, and answers with [`UNKNOWN`] in its place.
///
/// ```
/// use legit_streams::{IDENTITY_MAX_LEN, Task};
///
/// assert_eq!(IDENTITY_MAX_LEN, 256);
/// assert!(Task::builder("app", "a".repeat(256), "42").build().is_ok());
/// assert!(Task::builder("app", "a".repeat(257), "42").build().is_err());
/// ```
pub const IDENTITY_MAX_LEN: usize = 256;

/// What a worker writes in a result's `model_type`, `model_id` or `task_name` when the task's was
/// missing, empty, or longer than [`IDENTITY_MAX_LEN`]. A result's `model_name` is never replaced.
///
/// ```
/// assert_eq!(legit_streams::UNKNOWN, "unknown");
/// ```
pub const UNKNOWN: &str = "unknown";

/// The longest `reply_to`, in bytes: a bulk reply stream and a fast-lane reply key alike.
///
/// ```
/// assert_eq!(legit_streams::REPLY_TO_MAX_LEN, 128);
/// assert!(legit_streams::is_valid_reply_to(&format!("results:{}:text", "a".repeat(115))));
/// assert!(!legit_streams::is_valid_reply_to(&format!("results:{}:text", "a".repeat(116))));
/// ```
pub const REPLY_TO_MAX_LEN: usize = 128;

/// The payload field names a producer may not use: any name starting with `_`, and these two.
/// Names starting with `_` are reserved for whoever operates the Redis instance, and
/// `requeue_count` and `requeued_at` for workers that put a task back. A worker passes them
/// through untouched.
///
/// ```
/// assert_eq!(legit_streams::RESERVED_FIELDS, ["requeue_count", "requeued_at"]);
/// ```
pub const RESERVED_FIELDS: [&str; 2] = ["requeue_count", "requeued_at"];

/// Generate a task id in the form the crate gives every task it builds, `{app}_{ULID}`: unique
/// across applications, and the key a result carries back. Other ids a worker accepts are any
/// that pass [`is_valid_task_id`].
///
/// ```
/// let id = legit_streams::task_id("app");
/// assert!(id.starts_with("app_"));
/// assert_eq!(id.len(), "app_".len() + 26);
/// assert!(legit_streams::is_valid_task_id(&id));
/// ```
#[must_use]
pub fn task_id(app: &str) -> String {
    format!("{app}_{}", ulid::Ulid::new())
}

/// Whether a `task_id` keeps to the contract: 1 to [`TASK_ID_MAX_LEN`] ASCII letters, digits, `_`
/// and `-`. A producer sends no other, and a worker refuses any other.
///
/// ```
/// use legit_streams::is_valid_task_id;
///
/// assert!(is_valid_task_id("app_01JDV3XK6T9Q4M8R2B7C5N1P0W"));
/// assert!(is_valid_task_id("Job-42"));
/// assert!(!is_valid_task_id(""));
/// assert!(!is_valid_task_id("app:1"));
/// assert!(!is_valid_task_id(&"a".repeat(65)));
/// ```
#[must_use]
pub fn is_valid_task_id(task_id: &str) -> bool {
    is_name(task_id, TASK_ID_MAX_LEN, true)
}

/// Whether an application name is one this crate sends: 1 to [`APP_MAX_LEN`] lowercase ASCII
/// letters, digits, `_` and `-`. It is the form a task's `source` takes from this crate's builder,
/// and the only one a fast-lane reply key admits. A worker reading a task requires only that its
/// `source` isn't empty.
///
/// ```
/// use legit_streams::is_valid_app;
///
/// assert!(is_valid_app("my-app_2"));
/// assert!(!is_valid_app("App"));
/// assert!(!is_valid_app(""));
/// assert!(!is_valid_app(&"a".repeat(33)));
/// ```
#[must_use]
pub fn is_valid_app(app: &str) -> bool {
    is_name(app, APP_MAX_LEN, false)
}

/// Whether `name` is 1 to `max` ASCII digits, `_`, `-` and lowercase letters, and upper case ones
/// when `upper` is set.
pub(crate) fn is_name(name: &str, max: usize, upper: bool) -> bool {
    (1..=max).contains(&name.len())
        && name.bytes().all(|b| {
            b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-' || (upper && b.is_ascii_uppercase())
        })
}

/// Whether a payload field name is reserved: it starts with `_`, or it is one of
/// [`RESERVED_FIELDS`].
fn is_reserved_payload(name: &str) -> bool {
    name.starts_with('_') || RESERVED_FIELDS.contains(&name)
}

/// The reply stream the contract names for an application's results of one kind,
/// `results:{app}:{modality}`.
///
/// ```
/// assert_eq!(legit_streams::reply_to("app", "hash"), "results:app:hash");
/// ```
#[must_use]
pub fn reply_to(app: &str, modality: &str) -> String {
    format!("results:{app}:{modality}")
}

/// Whether a bulk task's `reply_to` keeps to the contract: it must match
/// `^results:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+$` and be at most [`REPLY_TO_MAX_LEN`] bytes. A
/// producer sends no other. A task's `reply_to` names a Redis key and comes off a queue, so a
/// worker checks it rather than trusting it: a task whose `reply_to` fails still runs, and its
/// result, success or error, goes to the worker's default result stream, since a result in the
/// wrong place can be found and a dropped one can't.
///
/// ```
/// use legit_streams::is_valid_reply_to;
///
/// assert!(is_valid_reply_to("results:app:hash"));
/// assert!(is_valid_reply_to("results:App:text"));
/// assert!(!is_valid_reply_to("results:app"));
/// assert!(!is_valid_reply_to("results:app:hash:rpc:app_1"));
/// assert!(!is_valid_reply_to("hash_tasks"));
/// ```
#[must_use]
pub fn is_valid_reply_to(stream: &str) -> bool {
    let segment = |part: &str| is_name(part, REPLY_TO_MAX_LEN, true);
    let mut parts = stream.split(':');
    stream.len() <= REPLY_TO_MAX_LEN
        && parts.next() == Some("results")
        && parts.next().is_some_and(segment)
        && parts.next().is_some_and(segment)
        && parts.next().is_none()
}

/// A v1 task envelope: the flat map of string fields a producer adds to a task stream.
///
/// Every task carries `task_id`, `model_type`, `model_id`, `task_name`, `model_name`, `source` and
/// `v`, and `reply_to` when the producer names its reply stream. Every other field, the payload
/// and the optional settings alike, is the caller's: this crate keeps them in order and never
/// reads them. A task parsed from a stream and written back gives the same fields in the same
/// order.
///
/// `Debug` shows the identity fields and the names of the others, never their values: a payload
/// can be large, or a credential such as a presigned URL.
///
/// ```
/// use legit_streams::Task;
///
/// let task = Task::builder("app", "post", "42")
///     .task_id("app_01J0000000000000000000000A")
///     .field("text_data", "Hello")
///     .build()?;
///
/// assert_eq!(task.get("text_data"), Some("Hello"));
/// assert_eq!(task.task_name(), "default");
/// assert_eq!(Task::from_fields(task.fields().to_vec())?, task);
/// # Ok::<(), legit_streams::Error>(())
/// ```
#[derive(Clone, PartialEq, Eq)]
pub struct Task {
    fields: Vec<(String, String)>,
}

impl Task {
    /// Start a task for the application `source`, about the caller's record `model_id` of type
    /// `model_type`. The worker echoes both back untouched.
    ///
    /// ```
    /// use legit_streams::Task;
    ///
    /// let task = Task::builder("app", "post", "42").build()?;
    /// assert!(task.task_id().starts_with("app_"));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn builder(
        source: impl Into<String>,
        model_type: impl Into<String>,
        model_id: impl Into<String>,
    ) -> TaskBuilder {
        TaskBuilder {
            source: source.into(),
            model_type: model_type.into(),
            model_id: model_id.into(),
            task_id: None,
            task_name: "default".to_owned(),
            model_name: String::new(),
            reply_to: None,
            extra: Vec::new(),
        }
    }

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

    /// Read a task 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::UnsupportedVersion`] when `v` is present and isn't `1` (a task without `v`, or
    /// with an empty one, is version 1), [`Error::MissingField`] when another of the envelope's
    /// own fields is absent, [`Error::EmptyField`] when one of them but `model_name` is empty, and
    /// [`Error::InvalidValue`] when `task_id` fails [`is_valid_task_id`]. Any non-empty `source` is
    /// taken: only a producer keeps to [`is_valid_app`], and only a fast reply key's `{app}` is
    /// checked against it. A `model_type`, `model_id` or `task_name` longer than
    /// [`IDENTITY_MAX_LEN`] is taken too; a worker's result carries [`UNKNOWN`] in its place.
    /// Fields the envelope doesn't name,
    /// reserved names among them, are kept as they are, and so is a missing or empty `v`: a
    /// [`Producer`](crate::Producer) or [`FastCaller`](crate::FastCaller) that sends the task on
    /// writes `v` = `1`.
    ///
    /// ```
    /// use legit_streams::{Error, Limits, Task};
    ///
    /// let raw = vec![(b"task_id".to_vec(), vec![0xff])];
    /// assert!(matches!(Task::from_raw(&raw, &Limits::default()), Err(Error::InvalidUtf8 { .. })));
    /// ```
    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 task from decoded fields, within the default [`Limits`].
    ///
    /// # Errors
    ///
    /// The errors of [`Task::from_raw`] that apply to strings.
    ///
    /// ```
    /// use legit_streams::{Error, Task};
    ///
    /// let fields = vec![("v".to_owned(), "1".to_owned())];
    /// assert_eq!(Task::from_fields(fields), Err(Error::MissingField("task_id")));
    /// ```
    pub fn from_fields(fields: Vec<(String, String)>) -> Result<Self> {
        fields::check_strings(&fields, &Limits::default())?;
        validate(&fields)?;
        Ok(Self { fields })
    }

    /// The task id: `{app}_{ULID}` when this crate's builder generated it.
    ///
    /// ```
    /// use legit_streams::Task;
    ///
    /// let task = Task::builder("app", "post", "42").task_id("app_1").build()?;
    /// assert_eq!(task.task_id(), "app_1");
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn task_id(&self) -> &str {
        self.required("task_id")
    }

    /// The type of the caller's record, echoed in the result.
    ///
    /// ```
    /// use legit_streams::Task;
    ///
    /// let task = Task::builder("app", "post", "42").build()?;
    /// assert_eq!(task.model_type(), "post");
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn model_type(&self) -> &str {
        self.required("model_type")
    }

    /// The id of the caller's record, echoed in the result.
    ///
    /// ```
    /// use legit_streams::Task;
    ///
    /// let task = Task::builder("app", "post", "42").build()?;
    /// assert_eq!(task.model_id(), "42");
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn model_id(&self) -> &str {
        self.required("model_id")
    }

    /// A free-form label for logs; `default` unless the producer set one.
    ///
    /// ```
    /// use legit_streams::Task;
    ///
    /// let task = Task::builder("app", "post", "42").build()?;
    /// assert_eq!(task.task_name(), "default");
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn task_name(&self) -> &str {
        self.required("task_name")
    }

    /// Which model the task asks for; empty means the worker's default.
    ///
    /// ```
    /// use legit_streams::Task;
    ///
    /// let task = Task::builder("app", "post", "42").build()?;
    /// assert_eq!(task.model_name(), "");
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn model_name(&self) -> &str {
        self.required("model_name")
    }

    /// The producing application.
    ///
    /// ```
    /// use legit_streams::Task;
    ///
    /// let task = Task::builder("app", "post", "42").build()?;
    /// assert_eq!(task.source(), "app");
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn source(&self) -> &str {
        self.required("source")
    }

    /// Where the producer wants the result, when it named a stream. An empty `reply_to` is an
    /// absent one.
    ///
    /// ```
    /// use legit_streams::Task;
    ///
    /// let task = Task::builder("app", "post", "42").reply_to("results:app:hash").build()?;
    /// assert_eq!(task.reply_to(), Some("results:app:hash"));
    ///
    /// let mut fields = Task::builder("app", "post", "42").build()?.into_fields();
    /// fields.push(("reply_to".to_owned(), String::new()));
    /// assert_eq!(Task::from_fields(fields)?.reply_to(), None);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn reply_to(&self) -> Option<&str> {
        self.get("reply_to").filter(|reply_to| !reply_to.is_empty())
    }

    /// The value of a field, the envelope's own or the caller's.
    ///
    /// ```
    /// use legit_streams::Task;
    ///
    /// let task = Task::builder("app", "post", "42").field("prefix", "").build()?;
    /// assert_eq!(task.get("prefix"), Some(""));
    /// assert_eq!(task.get("embed_role"), None);
    /// assert_eq!(task.get("v"), Some("1"));
    /// # 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::Task;
    ///
    /// let task = Task::builder("app", "post", "42").build()?;
    /// assert_eq!(task.fields()[6], ("v".to_owned(), "1".to_owned()));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn fields(&self) -> &[(String, String)] {
        &self.fields
    }

    /// The fields that aren't the envelope's own: the payload and the optional settings, in order.
    ///
    /// ```
    /// use legit_streams::Task;
    ///
    /// let task = Task::builder("app", "post", "42").reply_to("results:app:hash").field("text_data", "Hi").build()?;
    /// let extra: Vec<_> = task.extra().collect();
    /// assert_eq!(extra, [("text_data", "Hi")]);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    pub fn extra(&self) -> impl Iterator<Item = (&str, &str)> {
        self.fields
            .iter()
            .filter(|(name, _)| !is_reserved(name))
            .map(|(name, value)| (name.as_str(), value.as_str()))
    }

    /// The fields, in order, consuming the task.
    ///
    /// ```
    /// use legit_streams::Task;
    ///
    /// let task = Task::builder("app", "post", "42").build()?;
    /// assert_eq!(task.into_fields().len(), 7);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn into_fields(self) -> Vec<(String, String)> {
        self.fields
    }

    /// The fields a producer sends for this task: its own, with `v` = `1` where a task read from
    /// an older producer had none or an empty one. The sender checks them against the [`Limits`]
    /// again, since an added `v` can take a task at a bound over it.
    pub(crate) fn wire_fields(&self) -> Vec<(String, String)> {
        with_version(self.fields.clone())
    }

    fn required(&self, name: &str) -> &str {
        // Construction checked every required field...
        self.get(name).unwrap_or_default()
    }
}

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

/// Whether the envelope sets this field itself.
fn is_reserved(name: &str) -> bool {
    REQUIRED.contains(&name) || name == "reply_to"
}

fn validate(fields: &[(String, String)]) -> Result<()> {
    // Older producers send no `v`; an empty value is an absent one...
    match fields::get(fields, "v") {
        None | Some("" | VERSION) => {}
        Some(other) => return Err(Error::UnsupportedVersion(other.chars().take(32).collect())),
    }
    for name in REQUIRED {
        if name != "v" && fields::get(fields, name).is_none() {
            return Err(Error::MissingField(name));
        }
    }
    for name in NON_EMPTY {
        if fields::get(fields, name).is_some_and(str::is_empty) {
            return Err(Error::EmptyField(name));
        }
    }
    if !fields::get(fields, "task_id").is_some_and(is_valid_task_id) {
        return Err(invalid("task_id", TASK_ID_EXPECTED));
    }
    Ok(())
}

/// The fields of a task that passed [`validate`], with `v` = `1` where it was absent or empty:
/// a task read from an older producer is sent on as a version 1 task. An absent `v` goes right
/// after `source`, where the builder writes it.
fn with_version(mut fields: Vec<(String, String)>) -> Vec<(String, String)> {
    if let Some((_, value)) = fields.iter_mut().find(|(name, _)| name == "v") {
        if value.is_empty() {
            VERSION.clone_into(value);
        }
        return fields;
    }
    let at = fields
        .iter()
        .position(|(name, _)| name == "source")
        .map_or(fields.len(), |source| source + 1);
    fields.insert(at, ("v".to_owned(), VERSION.to_owned()));
    fields
}

/// The fields a task must not leave empty: every one of the envelope's own but `model_name`, which
/// may be, and `v`, which may be absent.
const NON_EMPTY: [&str; 5] = ["task_id", "model_type", "model_id", "task_name", "source"];

/// Whether a payload field name is one a producer may send: 1 to [`FIELD_NAME_MAX_LEN`] lowercase
/// ASCII letters, digits and `_`, not starting with a digit.
fn is_field_name(name: &str) -> bool {
    is_name(name, FIELD_NAME_MAX_LEN, false) && !name.contains('-') && !name.starts_with(|c: char| c.is_ascii_digit())
}

const TASK_ID_EXPECTED: &str = "1 to 64 ASCII letters, digits, `_` and `-`";

fn invalid(field: &str, expected: &'static str) -> Error {
    Error::InvalidValue {
        field: field.to_owned(),
        expected,
    }
}

/// A task being built; [`TaskBuilder::build`] writes the fields in this order, which is the
/// crate's (a reader takes the fields as a map):
/// `task_id`, `model_type`, `model_id`, `task_name`, `model_name`, `source`, `v`, `reply_to` when
/// set, then the extra fields in the order they were added.
///
/// ```
/// use legit_streams::Task;
///
/// let task = Task::builder("app", "post", "42")
///     .task_id("app_01J0000000000000000000000A")
///     .model_name("example-model")
///     .field("embed_role", "query")
///     .field("text_data", "Where is it?")
///     .build()?;
///
/// let names: Vec<&str> = task.fields().iter().map(|(name, _)| name.as_str()).collect();
/// assert_eq!(
///     names,
///     ["task_id", "model_type", "model_id", "task_name", "model_name", "source", "v", "embed_role", "text_data"]
/// );
/// # Ok::<(), legit_streams::Error>(())
/// ```
#[derive(Clone)]
pub struct TaskBuilder {
    source: String,
    model_type: String,
    model_id: String,
    task_id: Option<String>,
    task_name: String,
    model_name: String,
    reply_to: Option<String>,
    extra: Vec<(String, String)>,
}

impl TaskBuilder {
    /// Use this task id rather than generating one. An empty id is ignored, and one is generated.
    /// An id set here is the caller's to make unguessable: a fast-lane task's id must carry at
    /// least 64 random bits, as the generated `{app}_{ULID}` does.
    ///
    /// ```
    /// use legit_streams::Task;
    ///
    /// let task = Task::builder("app", "post", "42").task_id("app_1").build()?;
    /// assert_eq!(task.task_id(), "app_1");
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn task_id(mut self, task_id: impl Into<String>) -> Self {
        self.task_id = Some(task_id.into());
        self
    }

    /// Set the label for logs; `default` when unset.
    ///
    /// ```
    /// use legit_streams::Task;
    ///
    /// let task = Task::builder("app", "post", "42").task_name("embed").build()?;
    /// assert_eq!(task.task_name(), "embed");
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn task_name(mut self, task_name: impl Into<String>) -> Self {
        self.task_name = task_name.into();
        self
    }

    /// Ask for a model; empty, the default, means the worker's default.
    ///
    /// ```
    /// use legit_streams::Task;
    ///
    /// let task = Task::builder("app", "post", "42").model_name("example-model").build()?;
    /// assert_eq!(task.model_name(), "example-model");
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn model_name(mut self, model_name: impl Into<String>) -> Self {
        self.model_name = model_name.into();
        self
    }

    /// Name the stream the result should go to, such as [`reply_to`](crate::reply_to)`("app",
    /// "hash")`. Without it the envelope has no `reply_to` field. An empty name is ignored.
    ///
    /// ```
    /// use legit_streams::Task;
    ///
    /// let task = Task::builder("app", "post", "42").reply_to("").build()?;
    /// assert_eq!(task.reply_to(), None);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn reply_to(mut self, reply_to: impl Into<String>) -> Self {
        let reply_to = reply_to.into();
        self.reply_to = (!reply_to.is_empty()).then_some(reply_to);
        self
    }

    /// Add a field of the caller's: the payload, such as `text_data`, or an optional setting,
    /// such as `embed_role`. Fields keep the order they're added in.
    ///
    /// ```
    /// use legit_streams::Task;
    ///
    /// let task = Task::builder("app", "post", "42").field("embed_role", "query").build()?;
    /// assert_eq!(task.get("embed_role"), Some("query"));
    /// # 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 task.
    ///
    /// # Errors
    ///
    /// - [`Error::EmptyField`] for an empty `source`, `model_type`, `model_id` or `task_name`.
    /// - [`Error::InvalidValue`] for a `model_type`, `model_id` or `task_name` longer than
    ///   [`IDENTITY_MAX_LEN`], a `source` that fails [`is_valid_app`], a `task_id` that
    ///   fails [`is_valid_task_id`], a `reply_to` that fails [`is_valid_reply_to`], or an extra
    ///   field whose name isn't 1 to [`FIELD_NAME_MAX_LEN`] lowercase ASCII letters, digits and
    ///   `_`, not starting with a digit.
    /// - [`Error::ReservedField`] for an extra field named like one of the envelope's own, or with
    ///   a reserved name: one starting with `_`, or one of [`RESERVED_FIELDS`].
    /// - [`Error::DuplicateField`] for an extra field added twice.
    /// - [`Error::TooLarge`] for a task over the default [`Limits`].
    ///
    /// ```
    /// use legit_streams::{Error, Task};
    ///
    /// let built = Task::builder("app", "post", "42").field("task_id", "other").build();
    /// assert_eq!(built, Err(Error::ReservedField("task_id".into())));
    /// let built = Task::builder("app", "post", "42").field("_trace", "x").build();
    /// assert_eq!(built, Err(Error::ReservedField("_trace".into())));
    /// let built = Task::builder("App", "post", "42").build();
    /// assert!(matches!(built, Err(Error::InvalidValue { .. })));
    /// ```
    pub fn build(self) -> Result<Task> {
        for (name, value) in [
            ("source", &self.source),
            ("model_type", &self.model_type),
            ("model_id", &self.model_id),
            ("task_name", &self.task_name),
        ] {
            if value.is_empty() {
                return Err(Error::EmptyField(name));
            }
        }
        for (name, value) in [
            ("model_type", &self.model_type),
            ("model_id", &self.model_id),
            ("task_name", &self.task_name),
        ] {
            if value.len() > IDENTITY_MAX_LEN {
                return Err(invalid(name, "at most 256 bytes"));
            }
        }
        if !is_valid_app(&self.source) {
            return Err(invalid(
                "source",
                "1 to 32 lowercase ASCII letters, digits, `_` and `-`",
            ));
        }
        if let Some((name, _)) = self
            .extra
            .iter()
            .find(|(name, _)| is_reserved(name) || is_reserved_payload(name))
        {
            return Err(Error::ReservedField(name.clone()));
        }
        if let Some((name, _)) = self.extra.iter().find(|(name, _)| !is_field_name(name)) {
            return Err(Error::InvalidValue {
                field: name.clone(),
                expected: "a field name of 1 to 64 lowercase ASCII letters, digits and `_`, not starting with a digit",
            });
        }
        let task_id = match self.task_id {
            Some(id) if !id.is_empty() => id,
            _ => task_id(&self.source),
        };
        if !is_valid_task_id(&task_id) {
            return Err(invalid("task_id", TASK_ID_EXPECTED));
        }
        if self
            .reply_to
            .as_deref()
            .is_some_and(|reply_to| !is_valid_reply_to(reply_to))
        {
            return Err(invalid(
                "reply_to",
                "`results:<app>:<kind>` of at most 128 bytes, each part ASCII letters, digits, `_` and `-`",
            ));
        }
        let mut fields = vec![
            ("task_id".to_owned(), task_id),
            ("model_type".to_owned(), self.model_type),
            ("model_id".to_owned(), self.model_id),
            ("task_name".to_owned(), self.task_name),
            ("model_name".to_owned(), self.model_name),
            ("source".to_owned(), self.source),
            ("v".to_owned(), VERSION.to_owned()),
        ];
        if let Some(reply_to) = self.reply_to {
            fields.push(("reply_to".to_owned(), reply_to));
        }
        fields.extend(self.extra);
        fields::check_strings(&fields, &Limits::default())?;
        Ok(Task { fields })
    }
}

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