Skip to main content

wa_wire_contract/
error.rs

1//! Decode failures.
2//!
3//! Every variant names what was expected and what was found. An envelope comes
4//! from another process or another language runtime, so a malformed one is an
5//! ordinary input, not a bug — it must be reportable, never a panic.
6
7use core::fmt;
8
9use crate::status::PlaintextStatus;
10
11/// Why an envelope could not be decoded.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum DecodeError {
15    /// The buffer ended before a field could be read in full.
16    UnexpectedEof {
17        /// Bytes the field required.
18        needed: usize,
19        /// Bytes actually left in the buffer.
20        available: usize,
21        /// Which field ran out.
22        field: Field,
23    },
24    /// A reserved flag bit was set. Reserved bits must be zero so that a future
25    /// contract version can assign meaning to them without silently changing
26    /// how an older decoder behaves.
27    ReservedFlags(u16),
28    /// The status byte of a plaintext entry is not a value this contract
29    /// version defines.
30    InvalidStatus(u8),
31    /// A plaintext entry carries a payload under a status that defines none.
32    ///
33    /// Only [`PlaintextStatus::Ok`] describes usable bytes. Bytes under any
34    /// other status have no defined meaning, and reading them as plaintext
35    /// would be reading whatever the producer happened to leave there.
36    ///
37    /// [`PlaintextStatus::Ok`]: crate::status::PlaintextStatus::Ok
38    PayloadOnFailedStatus {
39        /// The status the entry declared.
40        status: PlaintextStatus,
41        /// How many bytes it carried anyway.
42        len: usize,
43    },
44    /// The envelope decoded correctly but bytes remain. A trailing tail means
45    /// the producer and consumer disagree about the layout, which is a fault
46    /// even though the prefix parsed.
47    TrailingBytes(usize),
48}
49
50/// The envelope field a decode failure refers to.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52#[non_exhaustive]
53pub enum Field {
54    /// The contract version.
55    Version,
56    /// The flag word.
57    Flags,
58    /// The frame length prefix.
59    FrameLen,
60    /// The frame payload.
61    Frame,
62    /// The plaintext entry count.
63    PlaintextCount,
64    /// A plaintext entry's path length prefix.
65    PathLen,
66    /// A plaintext entry's path.
67    Path,
68    /// A plaintext entry's status byte.
69    Status,
70    /// A plaintext entry's payload length prefix.
71    PayloadLen,
72    /// A plaintext entry's payload.
73    Payload,
74}
75
76impl Field {
77    /// A stable, human-readable name for this field.
78    #[must_use]
79    pub const fn name(self) -> &'static str {
80        match self {
81            Self::Version => "version",
82            Self::Flags => "flags",
83            Self::FrameLen => "frame_len",
84            Self::Frame => "frame",
85            Self::PlaintextCount => "pt_count",
86            Self::PathLen => "path_len",
87            Self::Path => "path",
88            Self::Status => "status",
89            Self::PayloadLen => "payload_len",
90            Self::Payload => "payload",
91        }
92    }
93}
94
95impl fmt::Display for Field {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        f.write_str(self.name())
98    }
99}
100
101impl fmt::Display for DecodeError {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        match self {
104            Self::UnexpectedEof {
105                needed,
106                available,
107                field,
108            } => write!(
109                f,
110                "unexpected end of input reading {field}: needed {needed} byte(s), {available} available"
111            ),
112            Self::ReservedFlags(bits) => {
113                write!(f, "reserved flag bits set: {bits:#06x}")
114            }
115            Self::InvalidStatus(byte) => write!(f, "invalid plaintext status: {byte}"),
116            Self::PayloadOnFailedStatus { status, len } => write!(
117                f,
118                "status {status} carries {len} payload byte(s); only ok may carry any"
119            ),
120            Self::TrailingBytes(count) => {
121                write!(f, "{count} trailing byte(s) after the envelope")
122            }
123        }
124    }
125}
126
127impl core::error::Error for DecodeError {}
128
129/// Why an envelope could not be encoded.
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131#[non_exhaustive]
132pub enum EncodeError {
133    /// The frame is longer than the `u32` length prefix can describe.
134    FrameTooLong(usize),
135    /// A plaintext payload is longer than the `u32` length prefix can describe.
136    PayloadTooLong(usize),
137    /// A node path has more components than the `u8` length prefix can
138    /// describe. Real stanzas nest to depth 9 at the extreme, so hitting this
139    /// means the path is wrong, not that the limit is tight.
140    PathTooLong(usize),
141    /// More plaintext entries than the `u16` count can describe.
142    TooManyEntries(usize),
143    /// A plaintext entry carries a payload under a status that defines none.
144    ///
145    /// Refused at the producer rather than tolerated, so an envelope whose
146    /// status and payload contradict each other never reaches a consumer that
147    /// has to guess which of the two to believe.
148    PayloadOnFailedStatus {
149        /// The status the entry declared.
150        status: PlaintextStatus,
151        /// How many bytes it carried anyway.
152        len: usize,
153    },
154    /// The destination slice is smaller than [`encoded_len`] reported.
155    ///
156    /// [`encoded_len`]: crate::envelope::EnvelopeBuilder::encoded_len
157    BufferTooSmall {
158        /// Bytes the envelope needs.
159        needed: usize,
160        /// Bytes the destination offers.
161        available: usize,
162    },
163    /// The envelope's total size does not fit in `usize` on this target.
164    LengthOverflow,
165}
166
167impl fmt::Display for EncodeError {
168    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169        match self {
170            Self::FrameTooLong(len) => write!(f, "frame of {len} byte(s) exceeds u32"),
171            Self::PayloadTooLong(len) => write!(f, "payload of {len} byte(s) exceeds u32"),
172            Self::PathTooLong(len) => write!(f, "path of {len} component(s) exceeds u8"),
173            Self::TooManyEntries(count) => write!(f, "{count} plaintext entries exceed u16"),
174            Self::PayloadOnFailedStatus { status, len } => write!(
175                f,
176                "status {status} carries {len} payload byte(s); only ok may carry any"
177            ),
178            Self::BufferTooSmall { needed, available } => write!(
179                f,
180                "destination too small: needed {needed} byte(s), {available} available"
181            ),
182            Self::LengthOverflow => {
183                f.write_str("encoded length exceeds this target's address space")
184            }
185        }
186    }
187}
188
189impl core::error::Error for EncodeError {}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194    extern crate alloc;
195    use alloc::string::ToString;
196
197    #[test]
198    fn field_names_are_stable_and_unique() {
199        let all = [
200            Field::Version,
201            Field::Flags,
202            Field::FrameLen,
203            Field::Frame,
204            Field::PlaintextCount,
205            Field::PathLen,
206            Field::Path,
207            Field::Status,
208            Field::PayloadLen,
209            Field::Payload,
210        ];
211        for (i, a) in all.iter().enumerate() {
212            assert!(!a.name().is_empty());
213            assert_eq!(a.to_string(), a.name());
214            for b in all.iter().skip(i.saturating_add(1)) {
215                assert_ne!(a.name(), b.name(), "field names must be unique");
216            }
217        }
218    }
219
220    #[test]
221    fn decode_errors_render_their_detail() {
222        let eof = DecodeError::UnexpectedEof {
223            needed: 4,
224            available: 1,
225            field: Field::FrameLen,
226        };
227        let text = eof.to_string();
228        assert!(text.contains("frame_len"), "{text}");
229        assert!(text.contains('4') && text.contains('1'), "{text}");
230
231        assert!(
232            DecodeError::ReservedFlags(0xFFFC)
233                .to_string()
234                .contains("0xfffc")
235        );
236        assert!(DecodeError::InvalidStatus(9).to_string().contains('9'));
237        assert!(DecodeError::TrailingBytes(3).to_string().contains('3'));
238
239        let paired = DecodeError::PayloadOnFailedStatus {
240            status: PlaintextStatus::Unobserved,
241            len: 12,
242        }
243        .to_string();
244        assert!(
245            paired.contains("unobserved") && paired.contains("12"),
246            "{paired}"
247        );
248    }
249
250    #[test]
251    fn encode_errors_render_their_detail() {
252        assert!(EncodeError::FrameTooLong(5).to_string().contains('5'));
253        assert!(EncodeError::PayloadTooLong(6).to_string().contains('6'));
254        assert!(EncodeError::PathTooLong(7).to_string().contains('7'));
255        assert!(EncodeError::TooManyEntries(8).to_string().contains('8'));
256        let paired = EncodeError::PayloadOnFailedStatus {
257            status: PlaintextStatus::DecryptFailed,
258            len: 9,
259        }
260        .to_string();
261        assert!(
262            paired.contains("decrypt-failed") && paired.contains('9'),
263            "{paired}"
264        );
265        let small = EncodeError::BufferTooSmall {
266            needed: 10,
267            available: 2,
268        };
269        assert!(small.to_string().contains("10") && small.to_string().contains('2'));
270        assert!(
271            EncodeError::LengthOverflow
272                .to_string()
273                .contains("address space")
274        );
275    }
276
277    #[test]
278    fn errors_are_std_errors() {
279        fn assert_error<E: core::error::Error>(_: &E) {}
280        assert_error(&DecodeError::TrailingBytes(1));
281        assert_error(&EncodeError::LengthOverflow);
282    }
283
284    #[test]
285    fn errors_are_debug_and_comparable() {
286        assert_eq!(DecodeError::InvalidStatus(1), DecodeError::InvalidStatus(1));
287        assert_ne!(DecodeError::InvalidStatus(1), DecodeError::InvalidStatus(2));
288        assert_eq!(EncodeError::PathTooLong(1), EncodeError::PathTooLong(1));
289        assert_ne!(EncodeError::PathTooLong(1), EncodeError::FrameTooLong(1));
290        assert!(!alloc::format!("{:?}", Field::Path).is_empty());
291    }
292}