Skip to main content

legit_streams/
result.rs

1//! The result envelope a worker adds to a reply stream.
2
3use std::fmt;
4
5use crate::entry::Entry;
6use crate::error::{Error, Result};
7use crate::fields::{self, Limits};
8use crate::task::{IDENTITY_MAX_LEN, Task, UNKNOWN};
9
10/// The fields a result builder sets itself.
11const RESERVED: [&str; 10] = [
12    "task_id",
13    "model_type",
14    "model_id",
15    "task_name",
16    "model_name",
17    "status",
18    "error_type",
19    "error",
20    "worker_id",
21    "processing_ms",
22];
23
24/// The optional task fields the contract says a worker echoes into the result untouched.
25pub(crate) const ECHOED: [&str; 2] = ["embedder_key", "metadata"];
26
27/// Whether a task succeeded, the result's `status` field.
28///
29/// ```
30/// use legit_streams::Status;
31///
32/// assert_eq!(Status::Error.as_str(), "error");
33/// assert_eq!("success".parse::<Status>(), Ok(Status::Success));
34/// ```
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36pub enum Status {
37    /// `success`: the task ran, and the result carries its output.
38    Success,
39    /// `error`: the task failed, and the result carries `error` and usually `error_type`.
40    Error,
41}
42
43impl Status {
44    /// The field's value: `success` or `error`.
45    ///
46    /// ```
47    /// assert_eq!(legit_streams::Status::Success.as_str(), "success");
48    /// ```
49    #[must_use]
50    pub const fn as_str(self) -> &'static str {
51        match self {
52            Self::Success => "success",
53            Self::Error => "error",
54        }
55    }
56}
57
58impl fmt::Display for Status {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        f.write_str(self.as_str())
61    }
62}
63
64impl std::str::FromStr for Status {
65    type Err = Error;
66
67    fn from_str(s: &str) -> Result<Self> {
68        match s {
69            "success" => Ok(Self::Success),
70            "error" => Ok(Self::Error),
71            _ => Err(Error::InvalidValue {
72                field: "status".to_owned(),
73                expected: "`success` or `error`",
74            }),
75        }
76    }
77}
78
79/// A result envelope: the flat map of string fields a worker adds to a reply stream.
80///
81/// A result carries `task_id` and `status`, exactly `success` or `error`; an entry without them
82/// isn't a result. A worker also writes `model_type`, `model_id`, `task_name` and `model_name`,
83/// echoed from the task, and on an error `error`, a message, and `error_type`, a code in lowercase
84/// snake case such as `unsupported_model`; it should write `worker_id` and `processing_ms`, who ran
85/// the task and for how long, and may write `requested_model_name`. A reader requires none of
86/// those: error types are an open set, and a reader treats an unknown or missing one as a failure
87/// that won't pass on a retry. Every other field, such as `embedding` or `result`, is the output,
88/// which this crate keeps in order and never reads. A result parsed from a stream and written back
89/// gives the same fields in the same order.
90///
91/// `Debug` shows the identity and status fields and the names of the others, never their values.
92///
93/// ```
94/// use legit_streams::{Status, TaskResult};
95///
96/// let result = TaskResult::success("app_01J0000000000000000000000A")
97///     .worker_id("worker-1")
98///     .processing_ms(12)
99///     .field("result", "{}")
100///     .build()?;
101///
102/// assert_eq!(result.status(), Status::Success);
103/// assert_eq!(result.processing_ms(), Some(12));
104/// assert_eq!(TaskResult::from_fields(result.fields().to_vec())?, result);
105/// # Ok::<(), legit_streams::Error>(())
106/// ```
107#[derive(Clone, PartialEq, Eq)]
108pub struct TaskResult {
109    fields: Vec<(String, String)>,
110}
111
112impl TaskResult {
113    /// Start a success result for a task.
114    ///
115    /// ```
116    /// use legit_streams::TaskResult;
117    ///
118    /// assert!(TaskResult::success("app_1").build()?.is_success());
119    /// # Ok::<(), legit_streams::Error>(())
120    /// ```
121    #[must_use]
122    pub fn success(task_id: impl Into<String>) -> ResultBuilder {
123        ResultBuilder::new(Some(task_id.into()), Status::Success, None)
124    }
125
126    /// Start an error result for a task, with the message for its `error` field.
127    ///
128    /// A worker must set [`ResultBuilder::error_type`] on every error it writes, as this crate's
129    /// workers do. The builder still builds an error without one: a reader must accept such a
130    /// result, from an older worker, and its tests need one to read.
131    ///
132    /// ```
133    /// use legit_streams::TaskResult;
134    ///
135    /// let result = TaskResult::failure("app_1", "no such model").error_type("unsupported_model").build()?;
136    /// assert_eq!(result.error(), Some("no such model"));
137    /// assert_eq!(result.error_type(), Some("unsupported_model"));
138    /// # Ok::<(), legit_streams::Error>(())
139    /// ```
140    #[must_use]
141    pub fn failure(task_id: impl Into<String>, message: impl Into<String>) -> ResultBuilder {
142        ResultBuilder::new(Some(task_id.into()), Status::Error, Some(message.into()))
143    }
144
145    /// Read a result from a stream entry, within the default [`Limits`].
146    ///
147    /// # Errors
148    ///
149    /// The errors of [`TaskResult::from_raw`].
150    ///
151    /// ```
152    /// use legit_streams::{Entry, EntryId, TaskResult};
153    ///
154    /// let entry = Entry::new(EntryId::ZERO, vec![(b"task_id".to_vec(), b"app_1".to_vec())]);
155    /// assert!(TaskResult::from_entry(&entry).is_err());
156    /// ```
157    pub fn from_entry(entry: &Entry) -> Result<Self> {
158        Self::from_raw(&entry.fields, &Limits::default())
159    }
160
161    /// Read a result from raw stream fields.
162    ///
163    /// # Errors
164    ///
165    /// [`Error::TooLarge`] for an entry over `limits`, [`Error::InvalidUtf8`] for a name or value
166    /// that isn't UTF-8, [`Error::DuplicateField`] for a name given twice,
167    /// [`Error::MissingField`] without `task_id` or `status`, [`Error::EmptyField`] for an empty
168    /// `task_id`, and [`Error::InvalidValue`] for a `status` other than exactly `success` or
169    /// `error`. Nothing else is required: not `error` or `error_type` on an error, nor
170    /// `worker_id` or `processing_ms`.
171    ///
172    /// ```
173    /// use legit_streams::{Error, Limits, TaskResult};
174    ///
175    /// let raw = vec![(b"task_id".to_vec(), b"app_1".to_vec()), (b"status".to_vec(), b"done".to_vec())];
176    /// assert!(matches!(TaskResult::from_raw(&raw, &Limits::default()), Err(Error::InvalidValue { .. })));
177    /// ```
178    pub fn from_raw(raw: &[(Vec<u8>, Vec<u8>)], limits: &Limits) -> Result<Self> {
179        let fields = fields::decode(raw, limits)?;
180        validate(&fields)?;
181        Ok(Self { fields })
182    }
183
184    /// Read a result from decoded fields, within the default [`Limits`].
185    ///
186    /// # Errors
187    ///
188    /// The errors of [`TaskResult::from_raw`] that apply to strings.
189    ///
190    /// ```
191    /// use legit_streams::{Error, TaskResult};
192    ///
193    /// let fields = vec![("task_id".to_owned(), "app_1".to_owned()), ("status".to_owned(), "Error".to_owned())];
194    /// assert!(matches!(TaskResult::from_fields(fields), Err(Error::InvalidValue { .. })));
195    /// let fields = vec![("task_id".to_owned(), "app_1".to_owned()), ("status".to_owned(), "error".to_owned())];
196    /// assert_eq!(TaskResult::from_fields(fields)?.error_type(), None);
197    /// # Ok::<(), legit_streams::Error>(())
198    /// ```
199    pub fn from_fields(fields: Vec<(String, String)>) -> Result<Self> {
200        fields::check_strings(&fields, &Limits::default())?;
201        validate(&fields)?;
202        Ok(Self { fields })
203    }
204
205    /// The id of the task this is the result of.
206    ///
207    /// ```
208    /// use legit_streams::TaskResult;
209    ///
210    /// assert_eq!(TaskResult::success("app_1").build()?.task_id(), "app_1");
211    /// # Ok::<(), legit_streams::Error>(())
212    /// ```
213    #[must_use]
214    pub fn task_id(&self) -> &str {
215        self.get("task_id").unwrap_or_default()
216    }
217
218    /// Whether the task succeeded.
219    ///
220    /// ```
221    /// use legit_streams::{Status, TaskResult};
222    ///
223    /// assert_eq!(TaskResult::failure("app_1", "failed").build()?.status(), Status::Error);
224    /// # Ok::<(), legit_streams::Error>(())
225    /// ```
226    #[must_use]
227    pub fn status(&self) -> Status {
228        if self.get("status") == Some("error") {
229            Status::Error
230        } else {
231            Status::Success
232        }
233    }
234
235    /// Whether the status is `success`.
236    ///
237    /// ```
238    /// use legit_streams::TaskResult;
239    ///
240    /// assert!(!TaskResult::failure("app_1", "failed").build()?.is_success());
241    /// # Ok::<(), legit_streams::Error>(())
242    /// ```
243    #[must_use]
244    pub fn is_success(&self) -> bool {
245        self.status() == Status::Success
246    }
247
248    /// The error message, on an error.
249    ///
250    /// ```
251    /// use legit_streams::TaskResult;
252    ///
253    /// assert_eq!(TaskResult::success("app_1").build()?.error(), None);
254    /// # Ok::<(), legit_streams::Error>(())
255    /// ```
256    #[must_use]
257    pub fn error(&self) -> Option<&str> {
258        self.get("error")
259    }
260
261    /// The error code, such as `unsupported_model`, when the worker gave one.
262    ///
263    /// ```
264    /// use legit_streams::TaskResult;
265    ///
266    /// assert_eq!(TaskResult::failure("app_1", "failed").build()?.error_type(), None);
267    /// # Ok::<(), legit_streams::Error>(())
268    /// ```
269    #[must_use]
270    pub fn error_type(&self) -> Option<&str> {
271        self.get("error_type")
272    }
273
274    /// The task's `model_type`, echoed.
275    ///
276    /// ```
277    /// use legit_streams::TaskResult;
278    ///
279    /// assert_eq!(TaskResult::success("app_1").model_type("post").build()?.model_type(), Some("post"));
280    /// # Ok::<(), legit_streams::Error>(())
281    /// ```
282    #[must_use]
283    pub fn model_type(&self) -> Option<&str> {
284        self.get("model_type")
285    }
286
287    /// The task's `model_id`, echoed.
288    ///
289    /// ```
290    /// use legit_streams::TaskResult;
291    ///
292    /// assert_eq!(TaskResult::success("app_1").model_id("42").build()?.model_id(), Some("42"));
293    /// # Ok::<(), legit_streams::Error>(())
294    /// ```
295    #[must_use]
296    pub fn model_id(&self) -> Option<&str> {
297        self.get("model_id")
298    }
299
300    /// The task's `task_name`, echoed.
301    ///
302    /// ```
303    /// use legit_streams::TaskResult;
304    ///
305    /// assert_eq!(TaskResult::success("app_1").build()?.task_name(), None);
306    /// # Ok::<(), legit_streams::Error>(())
307    /// ```
308    #[must_use]
309    pub fn task_name(&self) -> Option<&str> {
310        self.get("task_name")
311    }
312
313    /// The model the worker names: the task's `model_name` echoed, or the worker's own name for
314    /// what ran.
315    ///
316    /// ```
317    /// use legit_streams::TaskResult;
318    ///
319    /// let result = TaskResult::success("app_1").model_name("example-model").build()?;
320    /// assert_eq!(result.model_name(), Some("example-model"));
321    /// # Ok::<(), legit_streams::Error>(())
322    /// ```
323    #[must_use]
324    pub fn model_name(&self) -> Option<&str> {
325        self.get("model_name")
326    }
327
328    /// The consumer name of the worker that ran the task.
329    ///
330    /// ```
331    /// use legit_streams::TaskResult;
332    ///
333    /// assert_eq!(TaskResult::success("app_1").worker_id("w-1").build()?.worker_id(), Some("w-1"));
334    /// # Ok::<(), legit_streams::Error>(())
335    /// ```
336    #[must_use]
337    pub fn worker_id(&self) -> Option<&str> {
338        self.get("worker_id")
339    }
340
341    /// How long the worker spent on the task, in milliseconds, from taking the entry to writing
342    /// the result; `None` when the result doesn't say, or says it with something other than a
343    /// whole number.
344    ///
345    /// ```
346    /// use legit_streams::TaskResult;
347    ///
348    /// assert_eq!(TaskResult::success("app_1").build()?.processing_ms(), None);
349    /// # Ok::<(), legit_streams::Error>(())
350    /// ```
351    #[must_use]
352    pub fn processing_ms(&self) -> Option<u64> {
353        self.get("processing_ms").and_then(|ms| ms.parse().ok())
354    }
355
356    /// The value of a field, the envelope's own or the worker's output.
357    ///
358    /// ```
359    /// use legit_streams::TaskResult;
360    ///
361    /// let result = TaskResult::success("app_1").field("embedding_format", "base64_fp32").build()?;
362    /// assert_eq!(result.get("embedding_format"), Some("base64_fp32"));
363    /// # Ok::<(), legit_streams::Error>(())
364    /// ```
365    #[must_use]
366    pub fn get(&self, name: &str) -> Option<&str> {
367        fields::get(&self.fields, name)
368    }
369
370    /// Every field, in order.
371    ///
372    /// ```
373    /// use legit_streams::TaskResult;
374    ///
375    /// assert_eq!(TaskResult::success("app_1").build()?.fields().len(), 2);
376    /// # Ok::<(), legit_streams::Error>(())
377    /// ```
378    #[must_use]
379    pub fn fields(&self) -> &[(String, String)] {
380        &self.fields
381    }
382
383    /// The fields, in order, consuming the result.
384    ///
385    /// ```
386    /// use legit_streams::TaskResult;
387    ///
388    /// let fields = TaskResult::success("app_1").build()?.into_fields();
389    /// assert_eq!(fields[0], ("task_id".to_owned(), "app_1".to_owned()));
390    /// # Ok::<(), legit_streams::Error>(())
391    /// ```
392    #[must_use]
393    pub fn into_fields(self) -> Vec<(String, String)> {
394        self.fields
395    }
396}
397
398impl fmt::Debug for TaskResult {
399    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
400        f.debug_struct("TaskResult")
401            .field("task_id", &self.task_id())
402            .field("status", &self.status())
403            .field("error_type", &self.error_type())
404            .field(
405                "fields",
406                &self.fields.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(),
407            )
408            .finish_non_exhaustive()
409    }
410}
411
412fn validate(fields: &[(String, String)]) -> Result<()> {
413    match fields::get(fields, "task_id") {
414        None => return Err(Error::MissingField("task_id")),
415        Some("") => return Err(Error::EmptyField("task_id")),
416        Some(_) => {}
417    }
418    // Compared exactly: anything but `success` or `error` isn't a result...
419    fields::get(fields, "status")
420        .ok_or(Error::MissingField("status"))?
421        .parse::<Status>()?;
422    Ok(())
423}
424
425/// Whether an error type is lowercase snake case, as a worker writes it: a lowercase ASCII letter,
426/// then lowercase letters, digits and `_`. A reader takes any code, or none.
427fn is_error_type(error_type: &str) -> bool {
428    error_type.starts_with(|c: char| c.is_ascii_lowercase())
429        && error_type
430            .bytes()
431            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
432}
433
434/// A result being built. [`ResultBuilder::build`] writes the fields in this order: `task_id`,
435/// `model_type`, `model_id`, `task_name`, `model_name`, `status`, `error_type`, `error`,
436/// `worker_id` and `processing_ms`, each when set, then the extra fields in the order they were
437/// added. The contract doesn't fix an order; this one is the crate's.
438///
439/// ```
440/// use legit_streams::{Task, TaskResult};
441///
442/// let task = Task::builder("app", "post", "42").task_id("app_1").field("metadata", "{\"k\":1}").build()?;
443/// let result = TaskResult::success(task.task_id()).echo(&task).build()?;
444///
445/// assert_eq!(result.model_id(), Some("42"));
446/// assert_eq!(result.get("metadata"), Some("{\"k\":1}"));
447/// # Ok::<(), legit_streams::Error>(())
448/// ```
449#[derive(Clone)]
450pub struct ResultBuilder {
451    task_id: Option<String>,
452    model_type: Option<String>,
453    model_id: Option<String>,
454    task_name: Option<String>,
455    model_name: Option<String>,
456    status: Status,
457    error_type: Option<String>,
458    error: Option<String>,
459    worker_id: Option<String>,
460    processing_ms: Option<u64>,
461    echoed: Vec<(String, String)>,
462    extra: Vec<(String, String)>,
463}
464
465impl ResultBuilder {
466    const fn new(task_id: Option<String>, status: Status, error: Option<String>) -> Self {
467        Self {
468            task_id,
469            model_type: None,
470            model_id: None,
471            task_name: None,
472            model_name: None,
473            status,
474            error_type: None,
475            error,
476            worker_id: None,
477            processing_ms: None,
478            echoed: Vec::new(),
479            extra: Vec::new(),
480        }
481    }
482
483    /// Echo what the contract echoes from a task: `model_type`, `model_id`, `task_name` and
484    /// `model_name`, and `embedder_key` and `metadata` when the task has them. A `model_type`,
485    /// `model_id` or `task_name` longer than [`IDENTITY_MAX_LEN`] is echoed as
486    /// [`UNKNOWN`](crate::UNKNOWN); `model_name` is echoed as it is.
487    ///
488    /// ```
489    /// use legit_streams::{Task, TaskResult};
490    ///
491    /// let task = Task::builder("app", "post", "42").task_name("embed").build()?;
492    /// let result = TaskResult::failure(task.task_id(), "failed").echo(&task).build()?;
493    /// assert_eq!(result.task_name(), Some("embed"));
494    /// # Ok::<(), legit_streams::Error>(())
495    /// ```
496    #[must_use]
497    pub fn echo(mut self, task: &Task) -> Self {
498        self.model_type = Some(identity(Some(task.model_type())));
499        self.model_id = Some(identity(Some(task.model_id())));
500        self.task_name = Some(identity(Some(task.task_name())));
501        self.model_name = Some(task.model_name().to_owned());
502        for name in ECHOED {
503            if let Some(value) = task.get(name) {
504                self.echoed.push((name.to_owned(), value.to_owned()));
505            }
506        }
507        self
508    }
509
510    /// Set `model_type`.
511    ///
512    /// ```
513    /// use legit_streams::TaskResult;
514    ///
515    /// assert_eq!(TaskResult::success("app_1").model_type("post").build()?.model_type(), Some("post"));
516    /// # Ok::<(), legit_streams::Error>(())
517    /// ```
518    #[must_use]
519    pub fn model_type(mut self, model_type: impl Into<String>) -> Self {
520        self.model_type = Some(model_type.into());
521        self
522    }
523
524    /// Set `model_id`.
525    ///
526    /// ```
527    /// use legit_streams::TaskResult;
528    ///
529    /// assert_eq!(TaskResult::success("app_1").model_id("7").build()?.model_id(), Some("7"));
530    /// # Ok::<(), legit_streams::Error>(())
531    /// ```
532    #[must_use]
533    pub fn model_id(mut self, model_id: impl Into<String>) -> Self {
534        self.model_id = Some(model_id.into());
535        self
536    }
537
538    /// Set `task_name`.
539    ///
540    /// ```
541    /// use legit_streams::TaskResult;
542    ///
543    /// assert_eq!(TaskResult::success("app_1").task_name("embed").build()?.task_name(), Some("embed"));
544    /// # Ok::<(), legit_streams::Error>(())
545    /// ```
546    #[must_use]
547    pub fn task_name(mut self, task_name: impl Into<String>) -> Self {
548        self.task_name = Some(task_name.into());
549        self
550    }
551
552    /// Set `model_name`, replacing the echoed one: a worker may name what actually ran.
553    ///
554    /// ```
555    /// use legit_streams::TaskResult;
556    ///
557    /// let result = TaskResult::success("app_1").model_name("example-model").build()?;
558    /// assert_eq!(result.model_name(), Some("example-model"));
559    /// # Ok::<(), legit_streams::Error>(())
560    /// ```
561    #[must_use]
562    pub fn model_name(mut self, model_name: impl Into<String>) -> Self {
563        self.model_name = Some(model_name.into());
564        self
565    }
566
567    /// Set `error_type`, the error's code. Ignored on a success.
568    ///
569    /// ```
570    /// use legit_streams::TaskResult;
571    ///
572    /// let result = TaskResult::failure("app_1", "too big").error_type("result_too_large").build()?;
573    /// assert_eq!(result.error_type(), Some("result_too_large"));
574    /// # Ok::<(), legit_streams::Error>(())
575    /// ```
576    #[must_use]
577    pub fn error_type(mut self, error_type: impl Into<String>) -> Self {
578        self.error_type = Some(error_type.into());
579        self
580    }
581
582    /// Set `worker_id`, the consumer name of the worker that ran the task.
583    ///
584    /// ```
585    /// use legit_streams::TaskResult;
586    ///
587    /// assert_eq!(TaskResult::success("app_1").worker_id("w-1").build()?.worker_id(), Some("w-1"));
588    /// # Ok::<(), legit_streams::Error>(())
589    /// ```
590    #[must_use]
591    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
592        self.worker_id = Some(worker_id.into());
593        self
594    }
595
596    /// Set `processing_ms`.
597    ///
598    /// ```
599    /// use legit_streams::TaskResult;
600    ///
601    /// assert_eq!(TaskResult::success("app_1").processing_ms(5).build()?.processing_ms(), Some(5));
602    /// # Ok::<(), legit_streams::Error>(())
603    /// ```
604    #[must_use]
605    pub const fn processing_ms(mut self, processing_ms: u64) -> Self {
606        self.processing_ms = Some(processing_ms);
607        self
608    }
609
610    /// Add a field of the worker's, such as `result` or `supported_models`. Fields keep the
611    /// order they're added in.
612    ///
613    /// ```
614    /// use legit_streams::TaskResult;
615    ///
616    /// let result = TaskResult::success("app_1").field("result", "{}").build()?;
617    /// assert_eq!(result.get("result"), Some("{}"));
618    /// # Ok::<(), legit_streams::Error>(())
619    /// ```
620    #[must_use]
621    pub fn field(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
622        self.extra.push((name.into(), value.into()));
623        self
624    }
625
626    /// Build the result.
627    ///
628    /// # Errors
629    ///
630    /// [`Error::EmptyField`] for an empty task id, [`Error::InvalidValue`] for an `error_type` that
631    /// isn't lowercase snake case, [`Error::ReservedField`] for an extra field
632    /// named like one of the envelope's own, [`Error::DuplicateField`] for a field given twice,
633    /// such as an extra `metadata` beside the echoed one, and [`Error::TooLarge`] for a result
634    /// over the default [`Limits`].
635    ///
636    /// ```
637    /// use legit_streams::{Error, TaskResult};
638    ///
639    /// assert_eq!(TaskResult::success("").build(), Err(Error::EmptyField("task_id")));
640    /// ```
641    pub fn build(self) -> Result<TaskResult> {
642        self.build_within(&Limits::default())
643    }
644
645    /// Build the result within `limits`.
646    pub(crate) fn build_within(self, limits: &Limits) -> Result<TaskResult> {
647        if let Some((name, _)) = self.extra.iter().find(|(name, _)| RESERVED.contains(&name.as_str())) {
648            return Err(Error::ReservedField(name.clone()));
649        }
650        if self.status == Status::Error
651            && let Some(error_type) = &self.error_type
652            && !is_error_type(error_type)
653        {
654            return Err(Error::InvalidValue {
655                field: "error_type".to_owned(),
656                expected: "lowercase snake case, such as `unsupported_model`",
657            });
658        }
659        let fields = self.into_fields();
660        fields::check_strings(&fields, limits)?;
661        validate(&fields)?;
662        Ok(TaskResult { fields })
663    }
664
665    /// The fields without the checks of [`ResultBuilder::build`], for a worker answering an entry
666    /// it couldn't read, which may lack a task id.
667    pub(crate) fn into_fields(self) -> Vec<(String, String)> {
668        let mut fields = Vec::with_capacity(10 + self.echoed.len() + self.extra.len());
669        let mut push = |name: &str, value: Option<String>| {
670            if let Some(value) = value {
671                fields.push((name.to_owned(), value));
672            }
673        };
674        push("task_id", self.task_id);
675        push("model_type", self.model_type);
676        push("model_id", self.model_id);
677        push("task_name", self.task_name);
678        push("model_name", self.model_name);
679        push("status", Some(self.status.as_str().to_owned()));
680        if self.status == Status::Error {
681            push("error_type", self.error_type);
682            push("error", self.error);
683        }
684        push("worker_id", self.worker_id);
685        push("processing_ms", self.processing_ms.map(|ms| ms.to_string()));
686        fields.extend(self.echoed);
687        fields.extend(self.extra);
688        fields
689    }
690
691    /// Turn the result into an error with this message and type, keeping what it echoes of the
692    /// task and dropping the worker's output.
693    pub(crate) fn into_error(mut self, message: String, error_type: &str) -> Self {
694        self.status = Status::Error;
695        self.error = Some(message);
696        self.error_type = Some(error_type.to_owned());
697        self.extra.clear();
698        self
699    }
700
701    /// A builder echoing what can be read from an entry that isn't a valid task: the last of each
702    /// field, as a reader that takes repeated names takes them. Of the four echoes a result always
703    /// carries, `model_type`, `model_id` and `task_name` are [`UNKNOWN`] when the entry's is
704    /// missing, empty, not UTF-8 or longer than [`IDENTITY_MAX_LEN`]; `model_name` is the entry's,
705    /// and empty when it has none. The `task_id` is `task_id` as it was sent.
706    pub(crate) fn for_raw(raw: &[(Vec<u8>, Vec<u8>)], task_id: Option<&str>, status: Status, error: String) -> Self {
707        let text = |name: &str| {
708            raw.iter()
709                .rev()
710                .find(|(key, _)| key == name.as_bytes())
711                .and_then(|(_, value)| std::str::from_utf8(value).ok())
712        };
713        let mut builder = Self::new(task_id.map(str::to_owned), status, Some(error));
714        builder.model_type = Some(identity(text("model_type")));
715        builder.model_id = Some(identity(text("model_id")));
716        builder.task_name = Some(identity(text("task_name")));
717        builder.model_name = Some(text("model_name").unwrap_or_default().to_owned());
718        for name in ECHOED {
719            if let Some(value) = text(name) {
720                builder.echoed.push((name.to_owned(), value.to_owned()));
721            }
722        }
723        builder
724    }
725
726    /// Whether the result is an error.
727    pub(crate) fn is_error(&self) -> bool {
728        self.status == Status::Error
729    }
730
731    /// The result without the optional fields it echoes of the task, such as `metadata`.
732    pub(crate) fn without_echoes(mut self) -> Self {
733        self.echoed.clear();
734        self
735    }
736
737    /// The bare error a worker sends when even the echoed fields would put the result over its
738    /// limits: the task id when it's short, the four echoes a result always carries when they're
739    /// short, the status, the error and who ran it.
740    pub(crate) fn bare(self) -> Self {
741        self.cut(1024, 1024)
742    }
743
744    /// The bare error with `model_type`, `model_id` and `task_name` kept only when each is at most
745    /// `echo` bytes, and [`UNKNOWN`] past that or when missing, and `model_name` kept only when it's
746    /// at most `model_name` bytes, and empty past that. The task id is kept when it's at most 1,024
747    /// bytes.
748    pub(crate) fn cut(self, echo: usize, model_name: usize) -> Self {
749        let short = |value: Option<String>| value.filter(|value| !value.is_empty() && value.len() <= echo);
750        let task_id = self.task_id.filter(|id| id.len() <= 1024);
751        let mut bare = Self::new(task_id, self.status, self.error);
752        bare.model_type = Some(short(self.model_type).unwrap_or_else(|| UNKNOWN.to_owned()));
753        bare.model_id = Some(short(self.model_id).unwrap_or_else(|| UNKNOWN.to_owned()));
754        bare.task_name = Some(short(self.task_name).unwrap_or_else(|| UNKNOWN.to_owned()));
755        bare.model_name = Some(
756            self.model_name
757                .filter(|value| value.len() <= model_name)
758                .unwrap_or_default(),
759        );
760        bare.error_type = self.error_type;
761        bare.worker_id = self.worker_id;
762        bare.processing_ms = self.processing_ms;
763        bare
764    }
765}
766
767/// The echo of a `model_type`, `model_id` or `task_name`: the value, or [`UNKNOWN`] when it's
768/// missing, empty or longer than [`IDENTITY_MAX_LEN`].
769fn identity(value: Option<&str>) -> String {
770    value
771        .filter(|value| !value.is_empty() && value.len() <= IDENTITY_MAX_LEN)
772        .unwrap_or(UNKNOWN)
773        .to_owned()
774}
775
776impl fmt::Debug for ResultBuilder {
777    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
778        f.debug_struct("ResultBuilder")
779            .field("task_id", &self.task_id)
780            .field("status", &self.status)
781            .field(
782                "extra",
783                &self.extra.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(),
784            )
785            .finish_non_exhaustive()
786    }
787}