Skip to main content

legit_streams/
task.rs

1//! The v1 task envelope.
2
3use std::fmt;
4
5use crate::entry::Entry;
6use crate::error::{Error, Result};
7use crate::fields::{self, Limits};
8
9/// The envelope version this crate reads and writes, the value of every task's `v` field.
10///
11/// ```
12/// assert_eq!(legit_streams::VERSION, "1");
13/// ```
14pub const VERSION: &str = "1";
15
16/// The longest payload field name a producer sends, in bytes. A name is lowercase ASCII letters,
17/// digits and `_`, not starting with a digit; a reader accepts any name within its [`Limits`].
18///
19/// ```
20/// assert_eq!(legit_streams::FIELD_NAME_MAX_LEN, 64);
21/// ```
22pub const FIELD_NAME_MAX_LEN: usize = 64;
23
24/// The envelope's own fields, in the order this crate's builder writes them. A reader takes a task
25/// with no `v`, or an empty one, as version 1.
26const REQUIRED: [&str; 7] = [
27    "task_id",
28    "model_type",
29    "model_id",
30    "task_name",
31    "model_name",
32    "source",
33    "v",
34];
35
36/// The longest `task_id`, in bytes. A task id is 1 to 64 ASCII letters, digits, `_` and `-`.
37///
38/// ```
39/// assert_eq!(legit_streams::TASK_ID_MAX_LEN, 64);
40/// ```
41pub const TASK_ID_MAX_LEN: usize = 64;
42
43/// The longest application name a producer sends, the task's `source` and the `{app}` of its reply
44/// streams, in bytes. A worker reading a task takes any non-empty `source`.
45///
46/// ```
47/// assert_eq!(legit_streams::APP_MAX_LEN, 32);
48/// ```
49pub const APP_MAX_LEN: usize = 32;
50
51/// The longest `model_type`, `model_id` and `task_name` a producer sends, in bytes. A worker that
52/// reads a longer one still runs the task, and answers with [`UNKNOWN`] in its place.
53///
54/// ```
55/// use legit_streams::{IDENTITY_MAX_LEN, Task};
56///
57/// assert_eq!(IDENTITY_MAX_LEN, 256);
58/// assert!(Task::builder("app", "a".repeat(256), "42").build().is_ok());
59/// assert!(Task::builder("app", "a".repeat(257), "42").build().is_err());
60/// ```
61pub const IDENTITY_MAX_LEN: usize = 256;
62
63/// What a worker writes in a result's `model_type`, `model_id` or `task_name` when the task's was
64/// missing, empty, or longer than [`IDENTITY_MAX_LEN`]. A result's `model_name` is never replaced.
65///
66/// ```
67/// assert_eq!(legit_streams::UNKNOWN, "unknown");
68/// ```
69pub const UNKNOWN: &str = "unknown";
70
71/// The longest `reply_to`, in bytes: a bulk reply stream and a fast-lane reply key alike.
72///
73/// ```
74/// assert_eq!(legit_streams::REPLY_TO_MAX_LEN, 128);
75/// assert!(legit_streams::is_valid_reply_to(&format!("results:{}:text", "a".repeat(115))));
76/// assert!(!legit_streams::is_valid_reply_to(&format!("results:{}:text", "a".repeat(116))));
77/// ```
78pub const REPLY_TO_MAX_LEN: usize = 128;
79
80/// The payload field names a producer may not use: any name starting with `_`, and these two.
81/// Names starting with `_` are reserved for whoever operates the Redis instance, and
82/// `requeue_count` and `requeued_at` for workers that put a task back. A worker passes them
83/// through untouched.
84///
85/// ```
86/// assert_eq!(legit_streams::RESERVED_FIELDS, ["requeue_count", "requeued_at"]);
87/// ```
88pub const RESERVED_FIELDS: [&str; 2] = ["requeue_count", "requeued_at"];
89
90/// Generate a task id in the form the crate gives every task it builds, `{app}_{ULID}`: unique
91/// across applications, and the key a result carries back. Other ids a worker accepts are any
92/// that pass [`is_valid_task_id`].
93///
94/// ```
95/// let id = legit_streams::task_id("app");
96/// assert!(id.starts_with("app_"));
97/// assert_eq!(id.len(), "app_".len() + 26);
98/// assert!(legit_streams::is_valid_task_id(&id));
99/// ```
100#[must_use]
101pub fn task_id(app: &str) -> String {
102    format!("{app}_{}", ulid::Ulid::new())
103}
104
105/// Whether a `task_id` keeps to the contract: 1 to [`TASK_ID_MAX_LEN`] ASCII letters, digits, `_`
106/// and `-`. A producer sends no other, and a worker refuses any other.
107///
108/// ```
109/// use legit_streams::is_valid_task_id;
110///
111/// assert!(is_valid_task_id("app_01JDV3XK6T9Q4M8R2B7C5N1P0W"));
112/// assert!(is_valid_task_id("Job-42"));
113/// assert!(!is_valid_task_id(""));
114/// assert!(!is_valid_task_id("app:1"));
115/// assert!(!is_valid_task_id(&"a".repeat(65)));
116/// ```
117#[must_use]
118pub fn is_valid_task_id(task_id: &str) -> bool {
119    is_name(task_id, TASK_ID_MAX_LEN, true)
120}
121
122/// Whether an application name is one this crate sends: 1 to [`APP_MAX_LEN`] lowercase ASCII
123/// letters, digits, `_` and `-`. It is the form a task's `source` takes from this crate's builder,
124/// and the only one a fast-lane reply key admits. A worker reading a task requires only that its
125/// `source` isn't empty.
126///
127/// ```
128/// use legit_streams::is_valid_app;
129///
130/// assert!(is_valid_app("my-app_2"));
131/// assert!(!is_valid_app("App"));
132/// assert!(!is_valid_app(""));
133/// assert!(!is_valid_app(&"a".repeat(33)));
134/// ```
135#[must_use]
136pub fn is_valid_app(app: &str) -> bool {
137    is_name(app, APP_MAX_LEN, false)
138}
139
140/// Whether `name` is 1 to `max` ASCII digits, `_`, `-` and lowercase letters, and upper case ones
141/// when `upper` is set.
142pub(crate) fn is_name(name: &str, max: usize, upper: bool) -> bool {
143    (1..=max).contains(&name.len())
144        && name.bytes().all(|b| {
145            b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-' || (upper && b.is_ascii_uppercase())
146        })
147}
148
149/// Whether a payload field name is reserved: it starts with `_`, or it is one of
150/// [`RESERVED_FIELDS`].
151fn is_reserved_payload(name: &str) -> bool {
152    name.starts_with('_') || RESERVED_FIELDS.contains(&name)
153}
154
155/// The reply stream the contract names for an application's results of one kind,
156/// `results:{app}:{modality}`.
157///
158/// ```
159/// assert_eq!(legit_streams::reply_to("app", "hash"), "results:app:hash");
160/// ```
161#[must_use]
162pub fn reply_to(app: &str, modality: &str) -> String {
163    format!("results:{app}:{modality}")
164}
165
166/// Whether a bulk task's `reply_to` keeps to the contract: it must match
167/// `^results:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+$` and be at most [`REPLY_TO_MAX_LEN`] bytes. A
168/// producer sends no other. A task's `reply_to` names a Redis key and comes off a queue, so a
169/// worker checks it rather than trusting it: a task whose `reply_to` fails still runs, and its
170/// result, success or error, goes to the worker's default result stream, since a result in the
171/// wrong place can be found and a dropped one can't.
172///
173/// ```
174/// use legit_streams::is_valid_reply_to;
175///
176/// assert!(is_valid_reply_to("results:app:hash"));
177/// assert!(is_valid_reply_to("results:App:text"));
178/// assert!(!is_valid_reply_to("results:app"));
179/// assert!(!is_valid_reply_to("results:app:hash:rpc:app_1"));
180/// assert!(!is_valid_reply_to("hash_tasks"));
181/// ```
182#[must_use]
183pub fn is_valid_reply_to(stream: &str) -> bool {
184    let segment = |part: &str| is_name(part, REPLY_TO_MAX_LEN, true);
185    let mut parts = stream.split(':');
186    stream.len() <= REPLY_TO_MAX_LEN
187        && parts.next() == Some("results")
188        && parts.next().is_some_and(segment)
189        && parts.next().is_some_and(segment)
190        && parts.next().is_none()
191}
192
193/// A v1 task envelope: the flat map of string fields a producer adds to a task stream.
194///
195/// Every task carries `task_id`, `model_type`, `model_id`, `task_name`, `model_name`, `source` and
196/// `v`, and `reply_to` when the producer names its reply stream. Every other field, the payload
197/// and the optional settings alike, is the caller's: this crate keeps them in order and never
198/// reads them. A task parsed from a stream and written back gives the same fields in the same
199/// order.
200///
201/// `Debug` shows the identity fields and the names of the others, never their values: a payload
202/// can be large, or a credential such as a presigned URL.
203///
204/// ```
205/// use legit_streams::Task;
206///
207/// let task = Task::builder("app", "post", "42")
208///     .task_id("app_01J0000000000000000000000A")
209///     .field("text_data", "Hello")
210///     .build()?;
211///
212/// assert_eq!(task.get("text_data"), Some("Hello"));
213/// assert_eq!(task.task_name(), "default");
214/// assert_eq!(Task::from_fields(task.fields().to_vec())?, task);
215/// # Ok::<(), legit_streams::Error>(())
216/// ```
217#[derive(Clone, PartialEq, Eq)]
218pub struct Task {
219    fields: Vec<(String, String)>,
220}
221
222impl Task {
223    /// Start a task for the application `source`, about the caller's record `model_id` of type
224    /// `model_type`. The worker echoes both back untouched.
225    ///
226    /// ```
227    /// use legit_streams::Task;
228    ///
229    /// let task = Task::builder("app", "post", "42").build()?;
230    /// assert!(task.task_id().starts_with("app_"));
231    /// # Ok::<(), legit_streams::Error>(())
232    /// ```
233    #[must_use]
234    pub fn builder(
235        source: impl Into<String>,
236        model_type: impl Into<String>,
237        model_id: impl Into<String>,
238    ) -> TaskBuilder {
239        TaskBuilder {
240            source: source.into(),
241            model_type: model_type.into(),
242            model_id: model_id.into(),
243            task_id: None,
244            task_name: "default".to_owned(),
245            model_name: String::new(),
246            reply_to: None,
247            extra: Vec::new(),
248        }
249    }
250
251    /// Read a task from a stream entry, within the default [`Limits`].
252    ///
253    /// # Errors
254    ///
255    /// The errors of [`Task::from_raw`].
256    ///
257    /// ```
258    /// use legit_streams::{Entry, EntryId, Task};
259    ///
260    /// let entry = Entry::new(EntryId::ZERO, vec![(b"v".to_vec(), b"2".to_vec())]);
261    /// assert!(Task::from_entry(&entry).is_err());
262    /// ```
263    pub fn from_entry(entry: &Entry) -> Result<Self> {
264        Self::from_raw(&entry.fields, &Limits::default())
265    }
266
267    /// Read a task from raw stream fields.
268    ///
269    /// # Errors
270    ///
271    /// [`Error::TooLarge`] for an entry over `limits`, [`Error::InvalidUtf8`] for a name or value
272    /// that isn't UTF-8, [`Error::DuplicateField`] for a name given twice,
273    /// [`Error::UnsupportedVersion`] when `v` is present and isn't `1` (a task without `v`, or
274    /// with an empty one, is version 1), [`Error::MissingField`] when another of the envelope's
275    /// own fields is absent, [`Error::EmptyField`] when one of them but `model_name` is empty, and
276    /// [`Error::InvalidValue`] when `task_id` fails [`is_valid_task_id`]. Any non-empty `source` is
277    /// taken: only a producer keeps to [`is_valid_app`], and only a fast reply key's `{app}` is
278    /// checked against it. A `model_type`, `model_id` or `task_name` longer than
279    /// [`IDENTITY_MAX_LEN`] is taken too; a worker's result carries [`UNKNOWN`] in its place.
280    /// Fields the envelope doesn't name,
281    /// reserved names among them, are kept as they are, and so is a missing or empty `v`: a
282    /// [`Producer`](crate::Producer) or [`FastCaller`](crate::FastCaller) that sends the task on
283    /// writes `v` = `1`.
284    ///
285    /// ```
286    /// use legit_streams::{Error, Limits, Task};
287    ///
288    /// let raw = vec![(b"task_id".to_vec(), vec![0xff])];
289    /// assert!(matches!(Task::from_raw(&raw, &Limits::default()), Err(Error::InvalidUtf8 { .. })));
290    /// ```
291    pub fn from_raw(raw: &[(Vec<u8>, Vec<u8>)], limits: &Limits) -> Result<Self> {
292        let fields = fields::decode(raw, limits)?;
293        validate(&fields)?;
294        Ok(Self { fields })
295    }
296
297    /// Read a task from decoded fields, within the default [`Limits`].
298    ///
299    /// # Errors
300    ///
301    /// The errors of [`Task::from_raw`] that apply to strings.
302    ///
303    /// ```
304    /// use legit_streams::{Error, Task};
305    ///
306    /// let fields = vec![("v".to_owned(), "1".to_owned())];
307    /// assert_eq!(Task::from_fields(fields), Err(Error::MissingField("task_id")));
308    /// ```
309    pub fn from_fields(fields: Vec<(String, String)>) -> Result<Self> {
310        fields::check_strings(&fields, &Limits::default())?;
311        validate(&fields)?;
312        Ok(Self { fields })
313    }
314
315    /// The task id: `{app}_{ULID}` when this crate's builder generated it.
316    ///
317    /// ```
318    /// use legit_streams::Task;
319    ///
320    /// let task = Task::builder("app", "post", "42").task_id("app_1").build()?;
321    /// assert_eq!(task.task_id(), "app_1");
322    /// # Ok::<(), legit_streams::Error>(())
323    /// ```
324    #[must_use]
325    pub fn task_id(&self) -> &str {
326        self.required("task_id")
327    }
328
329    /// The type of the caller's record, echoed in the result.
330    ///
331    /// ```
332    /// use legit_streams::Task;
333    ///
334    /// let task = Task::builder("app", "post", "42").build()?;
335    /// assert_eq!(task.model_type(), "post");
336    /// # Ok::<(), legit_streams::Error>(())
337    /// ```
338    #[must_use]
339    pub fn model_type(&self) -> &str {
340        self.required("model_type")
341    }
342
343    /// The id of the caller's record, echoed in the result.
344    ///
345    /// ```
346    /// use legit_streams::Task;
347    ///
348    /// let task = Task::builder("app", "post", "42").build()?;
349    /// assert_eq!(task.model_id(), "42");
350    /// # Ok::<(), legit_streams::Error>(())
351    /// ```
352    #[must_use]
353    pub fn model_id(&self) -> &str {
354        self.required("model_id")
355    }
356
357    /// A free-form label for logs; `default` unless the producer set one.
358    ///
359    /// ```
360    /// use legit_streams::Task;
361    ///
362    /// let task = Task::builder("app", "post", "42").build()?;
363    /// assert_eq!(task.task_name(), "default");
364    /// # Ok::<(), legit_streams::Error>(())
365    /// ```
366    #[must_use]
367    pub fn task_name(&self) -> &str {
368        self.required("task_name")
369    }
370
371    /// Which model the task asks for; empty means the worker's default.
372    ///
373    /// ```
374    /// use legit_streams::Task;
375    ///
376    /// let task = Task::builder("app", "post", "42").build()?;
377    /// assert_eq!(task.model_name(), "");
378    /// # Ok::<(), legit_streams::Error>(())
379    /// ```
380    #[must_use]
381    pub fn model_name(&self) -> &str {
382        self.required("model_name")
383    }
384
385    /// The producing application.
386    ///
387    /// ```
388    /// use legit_streams::Task;
389    ///
390    /// let task = Task::builder("app", "post", "42").build()?;
391    /// assert_eq!(task.source(), "app");
392    /// # Ok::<(), legit_streams::Error>(())
393    /// ```
394    #[must_use]
395    pub fn source(&self) -> &str {
396        self.required("source")
397    }
398
399    /// Where the producer wants the result, when it named a stream. An empty `reply_to` is an
400    /// absent one.
401    ///
402    /// ```
403    /// use legit_streams::Task;
404    ///
405    /// let task = Task::builder("app", "post", "42").reply_to("results:app:hash").build()?;
406    /// assert_eq!(task.reply_to(), Some("results:app:hash"));
407    ///
408    /// let mut fields = Task::builder("app", "post", "42").build()?.into_fields();
409    /// fields.push(("reply_to".to_owned(), String::new()));
410    /// assert_eq!(Task::from_fields(fields)?.reply_to(), None);
411    /// # Ok::<(), legit_streams::Error>(())
412    /// ```
413    #[must_use]
414    pub fn reply_to(&self) -> Option<&str> {
415        self.get("reply_to").filter(|reply_to| !reply_to.is_empty())
416    }
417
418    /// The value of a field, the envelope's own or the caller's.
419    ///
420    /// ```
421    /// use legit_streams::Task;
422    ///
423    /// let task = Task::builder("app", "post", "42").field("prefix", "").build()?;
424    /// assert_eq!(task.get("prefix"), Some(""));
425    /// assert_eq!(task.get("embed_role"), None);
426    /// assert_eq!(task.get("v"), Some("1"));
427    /// # Ok::<(), legit_streams::Error>(())
428    /// ```
429    #[must_use]
430    pub fn get(&self, name: &str) -> Option<&str> {
431        fields::get(&self.fields, name)
432    }
433
434    /// Every field, in order.
435    ///
436    /// ```
437    /// use legit_streams::Task;
438    ///
439    /// let task = Task::builder("app", "post", "42").build()?;
440    /// assert_eq!(task.fields()[6], ("v".to_owned(), "1".to_owned()));
441    /// # Ok::<(), legit_streams::Error>(())
442    /// ```
443    #[must_use]
444    pub fn fields(&self) -> &[(String, String)] {
445        &self.fields
446    }
447
448    /// The fields that aren't the envelope's own: the payload and the optional settings, in order.
449    ///
450    /// ```
451    /// use legit_streams::Task;
452    ///
453    /// let task = Task::builder("app", "post", "42").reply_to("results:app:hash").field("text_data", "Hi").build()?;
454    /// let extra: Vec<_> = task.extra().collect();
455    /// assert_eq!(extra, [("text_data", "Hi")]);
456    /// # Ok::<(), legit_streams::Error>(())
457    /// ```
458    pub fn extra(&self) -> impl Iterator<Item = (&str, &str)> {
459        self.fields
460            .iter()
461            .filter(|(name, _)| !is_reserved(name))
462            .map(|(name, value)| (name.as_str(), value.as_str()))
463    }
464
465    /// The fields, in order, consuming the task.
466    ///
467    /// ```
468    /// use legit_streams::Task;
469    ///
470    /// let task = Task::builder("app", "post", "42").build()?;
471    /// assert_eq!(task.into_fields().len(), 7);
472    /// # Ok::<(), legit_streams::Error>(())
473    /// ```
474    #[must_use]
475    pub fn into_fields(self) -> Vec<(String, String)> {
476        self.fields
477    }
478
479    /// The fields a producer sends for this task: its own, with `v` = `1` where a task read from
480    /// an older producer had none or an empty one. The sender checks them against the [`Limits`]
481    /// again, since an added `v` can take a task at a bound over it.
482    pub(crate) fn wire_fields(&self) -> Vec<(String, String)> {
483        with_version(self.fields.clone())
484    }
485
486    fn required(&self, name: &str) -> &str {
487        // Construction checked every required field...
488        self.get(name).unwrap_or_default()
489    }
490}
491
492impl fmt::Debug for Task {
493    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
494        f.debug_struct("Task")
495            .field("task_id", &self.task_id())
496            .field("task_name", &self.task_name())
497            .field("source", &self.source())
498            .field(
499                "fields",
500                &self.fields.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(),
501            )
502            .finish_non_exhaustive()
503    }
504}
505
506/// Whether the envelope sets this field itself.
507fn is_reserved(name: &str) -> bool {
508    REQUIRED.contains(&name) || name == "reply_to"
509}
510
511fn validate(fields: &[(String, String)]) -> Result<()> {
512    // Older producers send no `v`; an empty value is an absent one...
513    match fields::get(fields, "v") {
514        None | Some("" | VERSION) => {}
515        Some(other) => return Err(Error::UnsupportedVersion(other.chars().take(32).collect())),
516    }
517    for name in REQUIRED {
518        if name != "v" && fields::get(fields, name).is_none() {
519            return Err(Error::MissingField(name));
520        }
521    }
522    for name in NON_EMPTY {
523        if fields::get(fields, name).is_some_and(str::is_empty) {
524            return Err(Error::EmptyField(name));
525        }
526    }
527    if !fields::get(fields, "task_id").is_some_and(is_valid_task_id) {
528        return Err(invalid("task_id", TASK_ID_EXPECTED));
529    }
530    Ok(())
531}
532
533/// The fields of a task that passed [`validate`], with `v` = `1` where it was absent or empty:
534/// a task read from an older producer is sent on as a version 1 task. An absent `v` goes right
535/// after `source`, where the builder writes it.
536fn with_version(mut fields: Vec<(String, String)>) -> Vec<(String, String)> {
537    if let Some((_, value)) = fields.iter_mut().find(|(name, _)| name == "v") {
538        if value.is_empty() {
539            VERSION.clone_into(value);
540        }
541        return fields;
542    }
543    let at = fields
544        .iter()
545        .position(|(name, _)| name == "source")
546        .map_or(fields.len(), |source| source + 1);
547    fields.insert(at, ("v".to_owned(), VERSION.to_owned()));
548    fields
549}
550
551/// The fields a task must not leave empty: every one of the envelope's own but `model_name`, which
552/// may be, and `v`, which may be absent.
553const NON_EMPTY: [&str; 5] = ["task_id", "model_type", "model_id", "task_name", "source"];
554
555/// Whether a payload field name is one a producer may send: 1 to [`FIELD_NAME_MAX_LEN`] lowercase
556/// ASCII letters, digits and `_`, not starting with a digit.
557fn is_field_name(name: &str) -> bool {
558    is_name(name, FIELD_NAME_MAX_LEN, false) && !name.contains('-') && !name.starts_with(|c: char| c.is_ascii_digit())
559}
560
561const TASK_ID_EXPECTED: &str = "1 to 64 ASCII letters, digits, `_` and `-`";
562
563fn invalid(field: &str, expected: &'static str) -> Error {
564    Error::InvalidValue {
565        field: field.to_owned(),
566        expected,
567    }
568}
569
570/// A task being built; [`TaskBuilder::build`] writes the fields in this order, which is the
571/// crate's (a reader takes the fields as a map):
572/// `task_id`, `model_type`, `model_id`, `task_name`, `model_name`, `source`, `v`, `reply_to` when
573/// set, then the extra fields in the order they were added.
574///
575/// ```
576/// use legit_streams::Task;
577///
578/// let task = Task::builder("app", "post", "42")
579///     .task_id("app_01J0000000000000000000000A")
580///     .model_name("example-model")
581///     .field("embed_role", "query")
582///     .field("text_data", "Where is it?")
583///     .build()?;
584///
585/// let names: Vec<&str> = task.fields().iter().map(|(name, _)| name.as_str()).collect();
586/// assert_eq!(
587///     names,
588///     ["task_id", "model_type", "model_id", "task_name", "model_name", "source", "v", "embed_role", "text_data"]
589/// );
590/// # Ok::<(), legit_streams::Error>(())
591/// ```
592#[derive(Clone)]
593pub struct TaskBuilder {
594    source: String,
595    model_type: String,
596    model_id: String,
597    task_id: Option<String>,
598    task_name: String,
599    model_name: String,
600    reply_to: Option<String>,
601    extra: Vec<(String, String)>,
602}
603
604impl TaskBuilder {
605    /// Use this task id rather than generating one. An empty id is ignored, and one is generated.
606    /// An id set here is the caller's to make unguessable: a fast-lane task's id must carry at
607    /// least 64 random bits, as the generated `{app}_{ULID}` does.
608    ///
609    /// ```
610    /// use legit_streams::Task;
611    ///
612    /// let task = Task::builder("app", "post", "42").task_id("app_1").build()?;
613    /// assert_eq!(task.task_id(), "app_1");
614    /// # Ok::<(), legit_streams::Error>(())
615    /// ```
616    #[must_use]
617    pub fn task_id(mut self, task_id: impl Into<String>) -> Self {
618        self.task_id = Some(task_id.into());
619        self
620    }
621
622    /// Set the label for logs; `default` when unset.
623    ///
624    /// ```
625    /// use legit_streams::Task;
626    ///
627    /// let task = Task::builder("app", "post", "42").task_name("embed").build()?;
628    /// assert_eq!(task.task_name(), "embed");
629    /// # Ok::<(), legit_streams::Error>(())
630    /// ```
631    #[must_use]
632    pub fn task_name(mut self, task_name: impl Into<String>) -> Self {
633        self.task_name = task_name.into();
634        self
635    }
636
637    /// Ask for a model; empty, the default, means the worker's default.
638    ///
639    /// ```
640    /// use legit_streams::Task;
641    ///
642    /// let task = Task::builder("app", "post", "42").model_name("example-model").build()?;
643    /// assert_eq!(task.model_name(), "example-model");
644    /// # Ok::<(), legit_streams::Error>(())
645    /// ```
646    #[must_use]
647    pub fn model_name(mut self, model_name: impl Into<String>) -> Self {
648        self.model_name = model_name.into();
649        self
650    }
651
652    /// Name the stream the result should go to, such as [`reply_to`](crate::reply_to)`("app",
653    /// "hash")`. Without it the envelope has no `reply_to` field. An empty name is ignored.
654    ///
655    /// ```
656    /// use legit_streams::Task;
657    ///
658    /// let task = Task::builder("app", "post", "42").reply_to("").build()?;
659    /// assert_eq!(task.reply_to(), None);
660    /// # Ok::<(), legit_streams::Error>(())
661    /// ```
662    #[must_use]
663    pub fn reply_to(mut self, reply_to: impl Into<String>) -> Self {
664        let reply_to = reply_to.into();
665        self.reply_to = (!reply_to.is_empty()).then_some(reply_to);
666        self
667    }
668
669    /// Add a field of the caller's: the payload, such as `text_data`, or an optional setting,
670    /// such as `embed_role`. Fields keep the order they're added in.
671    ///
672    /// ```
673    /// use legit_streams::Task;
674    ///
675    /// let task = Task::builder("app", "post", "42").field("embed_role", "query").build()?;
676    /// assert_eq!(task.get("embed_role"), Some("query"));
677    /// # Ok::<(), legit_streams::Error>(())
678    /// ```
679    #[must_use]
680    pub fn field(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
681        self.extra.push((name.into(), value.into()));
682        self
683    }
684
685    /// Build the task.
686    ///
687    /// # Errors
688    ///
689    /// - [`Error::EmptyField`] for an empty `source`, `model_type`, `model_id` or `task_name`.
690    /// - [`Error::InvalidValue`] for a `model_type`, `model_id` or `task_name` longer than
691    ///   [`IDENTITY_MAX_LEN`], a `source` that fails [`is_valid_app`], a `task_id` that
692    ///   fails [`is_valid_task_id`], a `reply_to` that fails [`is_valid_reply_to`], or an extra
693    ///   field whose name isn't 1 to [`FIELD_NAME_MAX_LEN`] lowercase ASCII letters, digits and
694    ///   `_`, not starting with a digit.
695    /// - [`Error::ReservedField`] for an extra field named like one of the envelope's own, or with
696    ///   a reserved name: one starting with `_`, or one of [`RESERVED_FIELDS`].
697    /// - [`Error::DuplicateField`] for an extra field added twice.
698    /// - [`Error::TooLarge`] for a task over the default [`Limits`].
699    ///
700    /// ```
701    /// use legit_streams::{Error, Task};
702    ///
703    /// let built = Task::builder("app", "post", "42").field("task_id", "other").build();
704    /// assert_eq!(built, Err(Error::ReservedField("task_id".into())));
705    /// let built = Task::builder("app", "post", "42").field("_trace", "x").build();
706    /// assert_eq!(built, Err(Error::ReservedField("_trace".into())));
707    /// let built = Task::builder("App", "post", "42").build();
708    /// assert!(matches!(built, Err(Error::InvalidValue { .. })));
709    /// ```
710    pub fn build(self) -> Result<Task> {
711        for (name, value) in [
712            ("source", &self.source),
713            ("model_type", &self.model_type),
714            ("model_id", &self.model_id),
715            ("task_name", &self.task_name),
716        ] {
717            if value.is_empty() {
718                return Err(Error::EmptyField(name));
719            }
720        }
721        for (name, value) in [
722            ("model_type", &self.model_type),
723            ("model_id", &self.model_id),
724            ("task_name", &self.task_name),
725        ] {
726            if value.len() > IDENTITY_MAX_LEN {
727                return Err(invalid(name, "at most 256 bytes"));
728            }
729        }
730        if !is_valid_app(&self.source) {
731            return Err(invalid(
732                "source",
733                "1 to 32 lowercase ASCII letters, digits, `_` and `-`",
734            ));
735        }
736        if let Some((name, _)) = self
737            .extra
738            .iter()
739            .find(|(name, _)| is_reserved(name) || is_reserved_payload(name))
740        {
741            return Err(Error::ReservedField(name.clone()));
742        }
743        if let Some((name, _)) = self.extra.iter().find(|(name, _)| !is_field_name(name)) {
744            return Err(Error::InvalidValue {
745                field: name.clone(),
746                expected: "a field name of 1 to 64 lowercase ASCII letters, digits and `_`, not starting with a digit",
747            });
748        }
749        let task_id = match self.task_id {
750            Some(id) if !id.is_empty() => id,
751            _ => task_id(&self.source),
752        };
753        if !is_valid_task_id(&task_id) {
754            return Err(invalid("task_id", TASK_ID_EXPECTED));
755        }
756        if self
757            .reply_to
758            .as_deref()
759            .is_some_and(|reply_to| !is_valid_reply_to(reply_to))
760        {
761            return Err(invalid(
762                "reply_to",
763                "`results:<app>:<kind>` of at most 128 bytes, each part ASCII letters, digits, `_` and `-`",
764            ));
765        }
766        let mut fields = vec![
767            ("task_id".to_owned(), task_id),
768            ("model_type".to_owned(), self.model_type),
769            ("model_id".to_owned(), self.model_id),
770            ("task_name".to_owned(), self.task_name),
771            ("model_name".to_owned(), self.model_name),
772            ("source".to_owned(), self.source),
773            ("v".to_owned(), VERSION.to_owned()),
774        ];
775        if let Some(reply_to) = self.reply_to {
776            fields.push(("reply_to".to_owned(), reply_to));
777        }
778        fields.extend(self.extra);
779        fields::check_strings(&fields, &Limits::default())?;
780        Ok(Task { fields })
781    }
782}
783
784impl fmt::Debug for TaskBuilder {
785    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
786        f.debug_struct("TaskBuilder")
787            .field("source", &self.source)
788            .field("task_id", &self.task_id)
789            .field(
790                "extra",
791                &self.extra.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(),
792            )
793            .finish_non_exhaustive()
794    }
795}