Skip to main content

protocontract/
code.rs

1//! Error codes: the classes of failure a caller branches on.
2
3use std::any::TypeId;
4use std::fmt;
5use std::hash::{Hash, Hasher};
6
7/// A type whose values are error codes.
8///
9/// A contract declares the codes its callers may branch on as a protobuf
10/// `enum` next to its `service`. Every enum that `protoc-gen-buffa`
11/// generates is an `ErrorCode` already, through `buffa::Enumeration`. A
12/// Rust enum implements the three methods by hand.
13///
14/// ```
15/// use protocontract::{Error, ErrorCode};
16///
17/// #[derive(Clone, Copy, Debug, PartialEq)]
18/// enum StoreCode {
19///     Full = 1,
20/// }
21///
22/// impl ErrorCode for StoreCode {
23///     fn to_i32(self) -> i32 {
24///         self as i32
25///     }
26///     fn from_i32(value: i32) -> Option<StoreCode> {
27///         (value == 1).then_some(StoreCode::Full)
28///     }
29///     fn name(self) -> &'static str {
30///         "STORE_FULL"
31///     }
32/// }
33///
34/// let error = Error::new(StoreCode::Full, "no room for the record");
35/// assert_eq!(error.code_as::<StoreCode>(), Some(StoreCode::Full));
36/// ```
37pub trait ErrorCode: Copy + Send + Sync + 'static {
38    /// The number of this code, unique within its type.
39    fn to_i32(self) -> i32;
40
41    /// The code of this type with the number `value`, or `None` when the
42    /// type has no such code.
43    fn from_i32(value: i32) -> Option<Self>;
44
45    /// The name of this code, as a developer reads it in a message.
46    fn name(self) -> &'static str;
47}
48
49impl<T: buffa::Enumeration + Send + Sync + 'static> ErrorCode for T {
50    fn to_i32(self) -> i32 {
51        buffa::Enumeration::to_i32(&self)
52    }
53
54    fn from_i32(value: i32) -> Option<T> {
55        <T as buffa::Enumeration>::from_i32(value)
56    }
57
58    fn name(self) -> &'static str {
59        buffa::Enumeration::proto_name(&self)
60    }
61}
62
63/// An error code of any [`ErrorCode`] type, with that type erased.
64///
65/// Two codes are equal when they are the same value of the same type: code
66/// 1 of one enum never equals code 1 of another. [`Code::get`] gives the
67/// typed code back.
68///
69/// ```
70/// use protocontract::{Code, RuntimeCode};
71///
72/// let code = Code::of(RuntimeCode::Panicked);
73/// assert!(code.is(RuntimeCode::Panicked));
74/// assert_eq!(code.get::<RuntimeCode>(), Some(RuntimeCode::Panicked));
75/// assert_eq!(code.to_string(), "PANICKED");
76/// ```
77#[derive(Clone, Copy)]
78pub struct Code {
79    kind: TypeId,
80    value: i32,
81    name: &'static str,
82}
83
84impl Code {
85    /// The erased form of `code`.
86    #[must_use]
87    pub fn of<C: ErrorCode>(code: C) -> Code {
88        Code {
89            kind: TypeId::of::<C>(),
90            value: code.to_i32(),
91            name: code.name(),
92        }
93    }
94
95    /// This code as a `C`, or `None` when it is a code of another type.
96    #[must_use]
97    pub fn get<C: ErrorCode>(self) -> Option<C> {
98        if self.kind == TypeId::of::<C>() {
99            C::from_i32(self.value)
100        } else {
101            None
102        }
103    }
104
105    /// Whether this code is `code`.
106    #[must_use]
107    pub fn is<C: ErrorCode>(self, code: C) -> bool {
108        self == Code::of(code)
109    }
110
111    /// The number of this code within its type.
112    #[must_use]
113    pub fn value(self) -> i32 {
114        self.value
115    }
116
117    /// The name of this code.
118    #[must_use]
119    pub fn name(self) -> &'static str {
120        self.name
121    }
122}
123
124impl<C: ErrorCode> From<C> for Code {
125    fn from(code: C) -> Code {
126        Code::of(code)
127    }
128}
129
130impl PartialEq for Code {
131    fn eq(&self, other: &Code) -> bool {
132        self.kind == other.kind && self.value == other.value
133    }
134}
135
136impl Eq for Code {}
137
138impl Hash for Code {
139    fn hash<H: Hasher>(&self, state: &mut H) {
140        self.kind.hash(state);
141        self.value.hash(state);
142    }
143}
144
145impl fmt::Debug for Code {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        write!(f, "Code({}={})", self.name, self.value)
148    }
149}
150
151impl fmt::Display for Code {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        f.write_str(self.name)
154    }
155}
156
157/// The failures the runtime itself reports, outside any contract.
158#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
159pub enum RuntimeCode {
160    /// The implementation panicked on another thread (`Offload`); the
161    /// message carries the panic's message when it has one.
162    Panicked = 1,
163    /// A sync call through `Blocking` was made inside a current-thread tokio
164    /// runtime, where waiting would stop the runtime the call needs.
165    CannotBlock = 2,
166    /// The runtime dropped the call before it finished, typically because
167    /// it is shutting down.
168    Cancelled = 3,
169    /// A reference to a service holds no implementation: it was never
170    /// given one, or it was decoded (a reference does not survive
171    /// encoding).
172    Unbound = 4,
173    /// An async implementation was asked for in the blocking form where no
174    /// tokio runtime could run it: outside a runtime, or in a build without
175    /// the `tokio` feature.
176    NoRuntime = 5,
177}
178
179impl ErrorCode for RuntimeCode {
180    fn to_i32(self) -> i32 {
181        self as i32
182    }
183
184    fn from_i32(value: i32) -> Option<RuntimeCode> {
185        match value {
186            1 => Some(RuntimeCode::Panicked),
187            2 => Some(RuntimeCode::CannotBlock),
188            3 => Some(RuntimeCode::Cancelled),
189            4 => Some(RuntimeCode::Unbound),
190            5 => Some(RuntimeCode::NoRuntime),
191            _ => None,
192        }
193    }
194
195    fn name(self) -> &'static str {
196        match self {
197            RuntimeCode::Panicked => "PANICKED",
198            RuntimeCode::CannotBlock => "CANNOT_BLOCK",
199            RuntimeCode::Cancelled => "CANCELLED",
200            RuntimeCode::Unbound => "UNBOUND",
201            RuntimeCode::NoRuntime => "NO_RUNTIME",
202        }
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    use std::collections::HashSet;
209
210    use super::{Code, ErrorCode, RuntimeCode};
211
212    #[derive(Clone, Copy, Debug, PartialEq)]
213    enum Other {
214        One = 1,
215    }
216
217    impl ErrorCode for Other {
218        fn to_i32(self) -> i32 {
219            self as i32
220        }
221        fn from_i32(value: i32) -> Option<Other> {
222            (value == 1).then_some(Other::One)
223        }
224        fn name(self) -> &'static str {
225            "ONE"
226        }
227    }
228
229    #[test]
230    fn runtime_codes_round_trip() {
231        for code in [
232            RuntimeCode::Panicked,
233            RuntimeCode::CannotBlock,
234            RuntimeCode::Cancelled,
235            RuntimeCode::Unbound,
236            RuntimeCode::NoRuntime,
237        ] {
238            assert_eq!(RuntimeCode::from_i32(code.to_i32()), Some(code));
239            assert_eq!(Code::of(code).get::<RuntimeCode>(), Some(code));
240        }
241        assert_eq!(RuntimeCode::from_i32(0), None);
242    }
243
244    #[test]
245    fn same_number_of_another_type_is_another_code() {
246        let runtime = Code::of(RuntimeCode::Panicked);
247        let other = Code::of(Other::One);
248        assert_eq!(runtime.value(), other.value());
249        assert_ne!(runtime, other);
250        assert_eq!(other.get::<RuntimeCode>(), None);
251        assert!(!other.is(RuntimeCode::Panicked));
252        let set: HashSet<Code> = [runtime, other, Code::of(Other::One)].into();
253        assert_eq!(set.len(), 2);
254    }
255
256    #[test]
257    fn display_and_debug_show_the_name() {
258        let code = Code::from(RuntimeCode::CannotBlock);
259        assert_eq!(code.to_string(), "CANNOT_BLOCK");
260        assert_eq!(format!("{code:?}"), "Code(CANNOT_BLOCK=2)");
261    }
262}