Skip to main content

zenkey_model/
envelope.rs

1//! The error of a failed operation call (spec `core.md` §5.2, r3 §3.7
2//! O3) in its error form (core §7.5, #980's C4a).
3//!
4//! **The error form** ([`ErrorForm`], §5.2 "The error form") carries the
5//! error's fields in bytes under `zenoh/bytes`, after a value's CH and
6//! stamp:
7//!
8//! ```text
9//! error, a reply error's payload   CH · run · seq · byte · message? · detail?
10//! byte                             code (bits 7–5) · cause (4–3) · detail (2) · message (1) · extension (0)
11//! message                          a length byte, 0 to 255 · that many bytes of UTF-8
12//! detail                           every byte after the message, or after the byte without one
13//! ```
14//!
15//! The code is §5.2's ([`Code`], numbered in its table's order), the cause
16//! 0 for none or one of `unavailable`'s three ([`Cause`]), and the
17//! extension bit 0. [`ErrorByte::read`] reads the byte alone,
18//! [`crate::wire::read_reply_err`] a payload, [`ErrorForm::read`] a payload
19//! by its `Encoding` first, and [`ErrorForm::write`] writes one, its
20//! message [`cut`] to 255 bytes. Every owner answers in it since core 0.94
21//! (#985's C4c). `spec/conformance/errors/forms.json` pins it.
22//!
23//! **Reading a reply error** (core §5.2, "Reading an error"): [`read_error`]
24//! reads one by its `Encoding` first, as an owner's error form or the
25//! transport's ([`ErrorReading`]), and [`crate::wire::read_value`] a reply
26//! as a value form. Core 0.99 (#985's C4d) removed the bare wire, a call
27//! with no form whose error travelled in a JSON, CBOR or protobuf
28//! envelope: a reply error under any `Encoding` but `zenoh/bytes`, one of
29//! those three included, is the transport's, and nothing here decodes an
30//! envelope.
31
32use serde_json::Value;
33use thiserror::Error;
34
35use crate::wire::{self, Form, Header, Refusal, Stamp, Tag};
36
37/// The core error codes.
38pub const CODES: [&str; 8] = [
39    "invalid_request",
40    "not_found",
41    "unavailable",
42    "forbidden",
43    "fanout_forbidden",
44    "busy",
45    "internal",
46    "app",
47];
48
49/// The causes `unavailable` carries (r3.3 D4).
50pub const CAUSES: [&str; 3] = ["build", "config", "capability"];
51
52/// A core error code (§5.2), numbered in its table's order: the number is
53/// the error form's bits 7–5 (§7.5), and three bits hold eight, so no
54/// code of the form is unknown.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
56pub enum Code {
57    InvalidRequest,
58    NotFound,
59    Unavailable,
60    Forbidden,
61    FanoutForbidden,
62    Busy,
63    Internal,
64    App,
65}
66
67impl Code {
68    /// Every code, in §5.2's order.
69    pub const ALL: [Code; 8] = [
70        Code::InvalidRequest,
71        Code::NotFound,
72        Code::Unavailable,
73        Code::Forbidden,
74        Code::FanoutForbidden,
75        Code::Busy,
76        Code::Internal,
77        Code::App,
78    ];
79
80    /// Its number, from 0 to 7.
81    #[must_use]
82    pub const fn number(self) -> u8 {
83        self as u8
84    }
85
86    /// The code of a number, `None` above 7.
87    #[must_use]
88    pub const fn from_number(n: u8) -> Option<Code> {
89        if n < 8 {
90            Some(Code::ALL[n as usize])
91        } else {
92            None
93        }
94    }
95
96    /// Its name, as [`CODES`] spells it.
97    #[must_use]
98    pub const fn as_str(self) -> &'static str {
99        CODES[self as usize]
100    }
101
102    /// The code a name spells, `None` for any other text.
103    #[must_use]
104    pub fn from_name(name: &str) -> Option<Code> {
105        Code::ALL.into_iter().find(|c| c.as_str() == name)
106    }
107}
108
109impl std::fmt::Display for Code {
110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        f.write_str(self.as_str())
112    }
113}
114
115/// A cause `unavailable` carries (§5.2), numbered from 1 in the error
116/// form's bits 4–3 (§7.5), 0 being none.
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
118pub enum Cause {
119    Build,
120    Config,
121    Capability,
122}
123
124impl Cause {
125    /// Every cause, in §5.2's order.
126    pub const ALL: [Cause; 3] = [Cause::Build, Cause::Config, Cause::Capability];
127
128    /// Its number, from 1 to 3.
129    #[must_use]
130    pub const fn number(self) -> u8 {
131        self as u8 + 1
132    }
133
134    /// Its name, as [`CAUSES`] spells it.
135    #[must_use]
136    pub const fn as_str(self) -> &'static str {
137        CAUSES[self as usize]
138    }
139
140    /// The cause a name spells, `None` for any other text.
141    #[must_use]
142    pub fn from_name(name: &str) -> Option<Cause> {
143        Cause::ALL.into_iter().find(|c| c.as_str() == name)
144    }
145}
146
147impl std::fmt::Display for Cause {
148    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149        f.write_str(self.as_str())
150    }
151}
152
153/// An error form's first byte after its stamp (core 0.92 §7.5), its bits
154/// numbered from 7: the code (7–5), the cause (4–3), whether a detail
155/// follows (2), whether a message follows (1), and the extension bit (0),
156/// which this version leaves 0. So `0xa0` is `busy`, `0x50` is
157/// `unavailable` for `config`, and `0xe4` is `app` with a detail.
158#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
159pub struct ErrorByte {
160    pub code: Code,
161    pub cause: Option<Cause>,
162    pub detail: bool,
163    pub message: bool,
164}
165
166impl ErrorByte {
167    /// The byte read alone, or the first of §7.5's checks on it that
168    /// refuses.
169    ///
170    /// # Errors
171    ///
172    /// [`Refusal::Cause`], [`Refusal::Detail`] ([`ErrorByte::check`]) or
173    /// [`Refusal::Extension`], in that order.
174    pub fn read(byte: u8) -> Result<ErrorByte, Refusal> {
175        let b = ErrorByte {
176            code: Code::ALL[usize::from(byte >> 5)],
177            cause: match (byte >> 3) & 0b11 {
178                0 => None,
179                n => Some(Cause::ALL[usize::from(n - 1)]),
180            },
181            detail: byte & 0b100 != 0,
182            message: byte & 0b10 != 0,
183        };
184        b.check()?;
185        if byte & 1 != 0 {
186            return Err(Refusal::Extension);
187        }
188        Ok(b)
189    }
190
191    /// What §7.5's parse refuses, and its writer MUST NOT write: a cause
192    /// on a code other than `unavailable`, `unavailable` without one, then
193    /// a detail on a code other than `app`.
194    ///
195    /// # Errors
196    ///
197    /// [`Refusal::Cause`] or [`Refusal::Detail`], in that order.
198    pub fn check(self) -> Result<(), Refusal> {
199        if self.cause.is_some() != (self.code == Code::Unavailable) {
200            return Err(Refusal::Cause {
201                code: self.code,
202                cause: self.cause,
203            });
204        }
205        if self.detail && self.code != Code::App {
206            return Err(Refusal::Detail(self.code));
207        }
208        Ok(())
209    }
210
211    /// The byte, its extension bit 0.
212    #[must_use]
213    pub const fn byte(self) -> u8 {
214        let cause = match self.cause {
215            Some(c) => c.number(),
216            None => 0,
217        };
218        (self.code.number() << 5)
219            | (cause << 3)
220            | ((self.detail as u8) << 2)
221            | ((self.message as u8) << 1)
222    }
223}
224
225/// The longest message the error form holds, in bytes (§7.5).
226pub const MESSAGE_MAX: usize = 255;
227
228/// A message as a writer puts it in an error form (§7.5's MUST): its
229/// longest prefix of whole characters within [`MESSAGE_MAX`] bytes, the
230/// message itself when it fits.
231#[must_use]
232pub fn cut(message: &str) -> &str {
233    &message[..message.floor_char_boundary(MESSAGE_MAX)]
234}
235
236/// §5.2's error in bytes (core 0.92, §5.2 "The error form", §7.5): a
237/// `reply_err`'s payload, `CH · run · seq · error`, under `zenoh/bytes`.
238/// [`crate::wire::read_reply_err`] parses one, and every one it accepts
239/// writes back to its bytes.
240#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
241pub struct ErrorForm<'a> {
242    /// The operation's `error` type's tag, whether a detail follows or
243    /// not; 0 for an operation that declares none. Reported, never checked.
244    pub tag: Tag,
245    /// The replying instance's as-of mark (§5.1). It attributes nothing: a
246    /// reply error carries no key.
247    pub stamp: Stamp,
248    pub code: Code,
249    /// `unavailable`'s, and no other code's.
250    pub cause: Option<Cause>,
251    /// For a human, never parsed (§5.2). `Some("")` is a message present
252    /// and empty, apart from an absent one.
253    pub message: Option<&'a str>,
254    /// `app`'s alone: a value of the operation's `error` type, as that type
255    /// encodes it, taken unread. It can be empty, as a protobuf message with
256    /// no field written is.
257    pub detail: Option<&'a [u8]>,
258}
259
260impl<'a> ErrorForm<'a> {
261    /// An error with no message and no detail.
262    #[must_use]
263    pub const fn new(tag: Tag, stamp: Stamp, code: Code, cause: Option<Cause>) -> ErrorForm<'a> {
264        ErrorForm {
265            tag,
266            stamp,
267            code,
268            cause,
269            message: None,
270            detail: None,
271        }
272    }
273
274    /// Its CH: an error, the width its run takes, and its tag.
275    #[must_use]
276    pub const fn header(&self) -> Header {
277        Header {
278            form: Form::Error,
279            wide: self.stamp.run.is_wide(),
280            tag: self.tag,
281        }
282    }
283
284    /// Its error byte.
285    #[must_use]
286    pub const fn error_byte(&self) -> ErrorByte {
287        ErrorByte {
288            code: self.code,
289            cause: self.cause,
290            detail: self.detail.is_some(),
291            message: self.message.is_some(),
292        }
293    }
294
295    /// What follows the stamp, read in §7.5's order: the byte, the
296    /// message, then the detail.
297    pub(crate) fn after_stamp(
298        tag: Tag,
299        stamp: Stamp,
300        rest: &'a [u8],
301    ) -> Result<ErrorForm<'a>, Refusal> {
302        let (&byte, rest) = rest
303            .split_first()
304            .ok_or(Refusal::Short { need: 1, have: 0 })?;
305        let b = ErrorByte::read(byte)?;
306        let (message, rest) = if b.message {
307            let (&len, rest) = rest
308                .split_first()
309                .ok_or(Refusal::MessageShort { need: 1, have: 0 })?;
310            let len = usize::from(len);
311            if rest.len() < len {
312                return Err(Refusal::MessageShort {
313                    need: len,
314                    have: rest.len(),
315                });
316            }
317            let (text, rest) = rest.split_at(len);
318            let text = std::str::from_utf8(text).map_err(|_| Refusal::Utf8)?;
319            (Some(text), rest)
320        } else {
321            (None, rest)
322        };
323        let detail = if b.detail {
324            Some(rest)
325        } else if rest.is_empty() {
326            None
327        } else {
328            return Err(Refusal::Trailing(rest.len()));
329        };
330        Ok(ErrorForm {
331            tag,
332            stamp,
333            code: b.code,
334            cause: b.cause,
335            message,
336            detail,
337        })
338    }
339
340    /// A reply error read as an error form, by its `Encoding` first (§5.2,
341    /// §7.5): only `zenoh/bytes`, exactly ([`wire::ENCODING`]), carries one,
342    /// and a reply error under any other is the transport's.
343    ///
344    /// # Errors
345    ///
346    /// [`FormRefusal::Encoding`] for any other `Encoding`, a schema suffix
347    /// included, else [`wire::read_reply_err`]'s refusal.
348    pub fn read(encoding: &str, payload: &'a [u8]) -> Result<ErrorForm<'a>, FormRefusal> {
349        if encoding != wire::ENCODING {
350            return Err(FormRefusal::Encoding(encoding.to_owned()));
351        }
352        wire::read_reply_err(payload).map_err(FormRefusal::Form)
353    }
354
355    /// Its bytes: 7 with a 16-bit run, or 9 with a 32-bit one, then the
356    /// message's length and bytes, and the detail's. A message over 255
357    /// bytes is [`cut`] at a character boundary, so it reads back cut.
358    ///
359    /// # Errors
360    ///
361    /// What the parse refuses, which §7.5's writer MUST NOT write
362    /// ([`ErrorByte::check`]): [`Refusal::Cause`], then [`Refusal::Detail`].
363    pub fn write(&self) -> Result<Vec<u8>, Refusal> {
364        let b = self.error_byte();
365        b.check()?;
366        let message = self.message.map(cut);
367        let detail = self.detail.unwrap_or_default();
368        let mut out = Vec::with_capacity(
369            self.stamp.envelope_bytes() + 2 + message.map_or(0, str::len) + detail.len(),
370        );
371        out.push(self.header().byte());
372        self.stamp.write_to(&mut out);
373        out.push(b.byte());
374        if let Some(m) = message {
375            out.push(u8::try_from(m.len()).expect("a cut message fits a byte"));
376            out.extend_from_slice(m.as_bytes());
377        }
378        out.extend_from_slice(detail);
379        Ok(out)
380    }
381}
382
383/// Why a call's sample is not read as one of its forms: a reply error as
384/// an error form ([`ErrorForm::read`]), or a reply as a value form
385/// ([`crate::wire::read_value`]).
386#[derive(Debug, Clone, PartialEq, Eq, Error)]
387pub enum FormRefusal {
388    /// An `Encoding` other than `zenoh/bytes`, which carries no form (core
389    /// §5.1, "Reading a value"; §5.2, "Reading an error").
390    #[error("under {0:?}, which carries no form")]
391    Encoding(String),
392    /// §7.5's first refusal for the sample.
393    #[error(transparent)]
394    Form(Refusal),
395}
396
397impl FormRefusal {
398    /// `encoding`, or the refusal's token ([`Refusal::token`]), as
399    /// `spec/conformance/errors/forms.json` spells it.
400    #[must_use]
401    pub const fn token(&self) -> &'static str {
402        match self {
403            FormRefusal::Encoding(_) => "encoding",
404            FormRefusal::Form(r) => r.token(),
405        }
406    }
407
408    /// Why the sample has no reading, as a rendering names it: the parse's
409    /// refusal as [`Refusal::reason`] spells it, or the `Encoding` that
410    /// carries no form.
411    #[must_use]
412    pub fn reason(&self) -> String {
413        match self {
414            FormRefusal::Encoding(e) => {
415                format!("no call form under {e}: only zenoh/bytes carries one (core §5.1)")
416            }
417            FormRefusal::Form(r) => r.reason(),
418        }
419    }
420}
421
422/// What a call's reply error reads as, by its `Encoding` first (core §5.2,
423/// "Reading an error"): [`read_error`].
424#[derive(Debug, Clone, PartialEq)]
425pub enum ErrorReading<'a> {
426    /// Under `zenoh/bytes`, an error form the parse accepts: the owner's.
427    Form(ErrorForm<'a>),
428    /// The transport's: under `zenoh/bytes`, bytes the parse refuses (its
429    /// refusal), such as a router's `Timeout` (`sample_kind`); under any
430    /// other `Encoding`, `None`, such as a querier's own `Timeout` under
431    /// `zenoh/string`, or an earlier core's envelope under
432    /// `application/json`. A caller reads either as silence (§5.1,
433    /// "Retries").
434    Transport(Option<Refusal>),
435}
436
437/// A call's `reply_err` read by its `Encoding` (core §5.2): under
438/// `zenoh/bytes`, exactly, as the error form ([`ErrorForm::read`]), the
439/// transport's when the parse refuses it; under any other as the
440/// transport's. No contract is read: only a detail needs the `error`
441/// type, and it is taken unread.
442#[must_use]
443pub fn read_error<'a>(encoding: &str, payload: &'a [u8]) -> ErrorReading<'a> {
444    match ErrorForm::read(encoding, payload) {
445        Ok(form) => ErrorReading::Form(form),
446        Err(FormRefusal::Form(r)) => ErrorReading::Transport(Some(r)),
447        Err(FormRefusal::Encoding(_)) => ErrorReading::Transport(None),
448    }
449}
450
451/// An `app` error's detail as its owner gives it, before the error form
452/// carries it (core §5.2, "`app`"): a value of the operation's `error`
453/// type for the runtime to encode (a JSON Schema value, or a packed
454/// record's JSON reading), or that type's own bytes. A caller reads an
455/// error form's detail as its bytes.
456#[derive(Debug, Clone, PartialEq)]
457pub enum Detail {
458    Value(Value),
459    Bytes(Vec<u8>),
460}
461
462#[cfg(test)]
463mod tests {
464    use super::*;
465
466    fn hex(h: &str) -> Vec<u8> {
467        (0..h.len())
468            .step_by(2)
469            .map(|i| u8::from_str_radix(&h[i..i + 2], 16).unwrap())
470            .collect()
471    }
472
473    /// Core 0.92 §7.5's worked bytes: `0xa0` is `busy`, `0x50` is
474    /// `unavailable` for `config`, and `0xe4` is `app` with a detail.
475    #[test]
476    fn the_error_bytes_worked_in_the_text() {
477        let read = |b| ErrorByte::read(b).map(|e| (e.code, e.cause, e.detail, e.message));
478        assert_eq!(read(0xa0), Ok((Code::Busy, None, false, false)));
479        assert_eq!(
480            read(0x50),
481            Ok((Code::Unavailable, Some(Cause::Config), false, false))
482        );
483        assert_eq!(read(0xe4), Ok((Code::App, None, true, false)));
484        for code in Code::ALL {
485            assert_eq!(Code::from_number(code.number()), Some(code));
486            assert_eq!(Code::from_name(code.as_str()), Some(code));
487        }
488        assert_eq!(Code::from_number(8), None);
489    }
490
491    /// A message is cut to whole characters within 255 bytes.
492    #[test]
493    fn a_long_message_is_cut_at_a_character() {
494        let fits = "a".repeat(MESSAGE_MAX);
495        assert_eq!(cut(&fits), fits);
496        let over = format!("{}é", "a".repeat(254));
497        assert_eq!(cut(&over), &over[..254]);
498        assert_eq!(cut(""), "");
499    }
500
501    /// Core §5.2, "Reading an error": the error form under `zenoh/bytes`
502    /// alone; a router's `Timeout` and a form refused by its byte the
503    /// transport's; any other `Encoding` the transport's, an error form's
504    /// bytes and an earlier core's JSON envelope included (`operations.md`
505    /// §9 steps 5 and 7).
506    #[test]
507    fn a_reply_error_is_read_by_its_encoding_first() {
508        let busy = hex("600001000007a0");
509        let ErrorReading::Form(f) = read_error(wire::ENCODING, &busy) else {
510            panic!("an error form")
511        };
512        assert_eq!(
513            (f.code, f.cause, f.message, f.detail),
514            (Code::Busy, None, None, None)
515        );
516        assert_eq!(f.stamp.seq.get(), 7);
517        assert_eq!(
518            read_error(wire::ENCODING, b"Timeout"),
519            ErrorReading::Transport(Some(Refusal::WrongSample {
520                form: Form::Value,
521                sample: wire::SampleKind::ReplyErr
522            }))
523        );
524        let ErrorReading::Transport(Some(r)) = read_error(wire::ENCODING, &hex("600001000007a8"))
525        else {
526            panic!("a cause on busy")
527        };
528        assert_eq!(r.token(), "cause");
529        for (encoding, bytes) in [
530            ("application/json", &br#"{"code":"busy","message":""}"#[..]),
531            ("application/json", br#"{"code":"busy"}"#),
532            ("application/cbor", &hex("a164636f64656462757379")),
533            (
534                "application/protobuf;zk2.core.v1.Error",
535                &hex("0a0462757379"),
536            ),
537        ] {
538            assert_eq!(
539                read_error(encoding, bytes),
540                ErrorReading::Transport(None),
541                "{encoding}"
542            );
543        }
544        for other in ["zenoh/string", "zenoh/bytes;x", "text/plain"] {
545            assert_eq!(
546                read_error(other, &busy),
547                ErrorReading::Transport(None),
548                "{other}"
549            );
550        }
551    }
552}