Skip to main content

laser_wire/
result.rs

1// The unified result-code space. Each managed surface keeps its own typed error
2// for the detail a caller needs, but every one of those errors also projects
3// onto one logical `ResultCode` here, so a generic client, the HTTP status
4// mapper, and a cross-language port all dispatch on one small dictionary
5// instead of parsing per-surface strings. The codes are a pinned cross-repo
6// contract, and an unknown code from a newer peer rides through as
7// `Unrecognized` rather than failing, the same forward-compat shape the growable
8// u8 dictionaries use.
9
10use crate::authz::AuthzError;
11use crate::fork::ForkError;
12use crate::graph::GraphError;
13use crate::kv::KvError;
14use crate::query::QueryError;
15use crate::session::SessionError;
16use serde::{Deserialize, Serialize};
17
18/// One logical outcome code spanning query, key-value, fork, and browse. Built
19/// from a surface's typed error via the `From` impls below. The typed error
20/// keeps the detail, this is the shared classification.
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
22#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
23#[serde(rename_all = "snake_case")]
24#[non_exhaustive]
25pub enum ResultCode {
26    /// The operation succeeded (no error to classify).
27    Ok,
28    /// The operation, or the managed surface, is not available here.
29    Unsupported,
30    /// A named entity (index, fork, key) does not exist.
31    NotFound,
32    /// The request was malformed or a field was out of range.
33    InvalidArgument,
34    /// A result or value exceeded a size cap.
35    TooLarge,
36    /// A precondition lost a race (a compare-and-swap version mismatch, a fork
37    /// promote/squash conflict).
38    Conflict,
39    /// A consistency level could not be met within the deadline (the read model
40    /// is still catching up).
41    Stale,
42    /// The wire op version is not accepted by this peer.
43    VersionSkew,
44    /// No credential, or an invalid one: the caller is not authenticated.
45    Unauthenticated,
46    /// The managed backend failed or was unreachable.
47    Backend,
48    /// Authenticated, but the grant needed for the operation is missing.
49    Forbidden,
50    /// Authenticated, but the operation needs a stronger authentication (a
51    /// step-up) than the caller currently holds.
52    StepUpRequired,
53    /// The request could not be served right now, and the same request may
54    /// succeed on a later attempt: the store was momentarily out of reach, a
55    /// connection was refused or dropped, a concurrency conflict was aborted, or
56    /// a resource limit was hit. Distinct from [`Backend`](Self::Backend), which
57    /// is a fault the caller cannot retry away. This is the one code a generic
58    /// client may safely retry with backoff, so it never has to parse a message
59    /// to decide (see [`is_retryable`](Self::is_retryable)).
60    Unavailable,
61    /// The query exceeded a server-enforced resource budget.
62    ResourceLimit,
63    /// The query was cancelled through its execution identity.
64    Cancelled,
65    /// The query did not finish before its absolute deadline.
66    DeadlineExceeded,
67    /// The requested historical snapshot is no longer retained.
68    ExpiredSnapshot,
69    /// The requested destination or backend generation is no longer current.
70    StaleGeneration,
71    /// The resolved target is not ready to serve queries.
72    TargetUnavailable,
73    /// The mutation was accepted into the log, but its outcome is not known
74    /// yet. Only a retry with the same operation identity may follow: it
75    /// returns the recorded outcome once the mutation has applied. A new
76    /// identity could apply the change a second time.
77    Pending,
78    /// The node could not reach its managed backend, or the backend did not
79    /// answer in time. The request may still apply, so a mutation repeats
80    /// only under the same operation identity, on this node or another one.
81    BackendUnavailable,
82    /// A code from a newer peer this build does not name. Decodes and re-encodes
83    /// byte-for-byte so an old build relays it rather than failing. Only a value
84    /// outside the named range (21 and up) should ever appear here: `from_code`
85    /// never produces `Unrecognized` for `0..=20`, which map to the named
86    /// variants.
87    Unrecognized(u16),
88}
89
90impl ResultCode {
91    /// The pinned numeric code, stable across repos and language ports.
92    pub const fn code(self) -> u16 {
93        match self {
94            ResultCode::Ok => 0,
95            ResultCode::Unsupported => 1,
96            ResultCode::NotFound => 2,
97            ResultCode::InvalidArgument => 3,
98            ResultCode::TooLarge => 4,
99            ResultCode::Conflict => 5,
100            ResultCode::Stale => 6,
101            ResultCode::VersionSkew => 7,
102            ResultCode::Unauthenticated => 8,
103            ResultCode::Backend => 9,
104            ResultCode::Forbidden => 10,
105            ResultCode::StepUpRequired => 11,
106            ResultCode::Unavailable => 12,
107            ResultCode::ResourceLimit => 13,
108            ResultCode::Cancelled => 14,
109            ResultCode::DeadlineExceeded => 15,
110            ResultCode::ExpiredSnapshot => 16,
111            ResultCode::StaleGeneration => 17,
112            ResultCode::TargetUnavailable => 18,
113            ResultCode::Pending => 19,
114            ResultCode::BackendUnavailable => 20,
115            ResultCode::Unrecognized(code) => code,
116        }
117    }
118
119    /// The code for a pinned numeric value, where an unknown value becomes
120    /// `Unrecognized` rather than an error.
121    pub const fn from_code(code: u16) -> Self {
122        match code {
123            0 => ResultCode::Ok,
124            1 => ResultCode::Unsupported,
125            2 => ResultCode::NotFound,
126            3 => ResultCode::InvalidArgument,
127            4 => ResultCode::TooLarge,
128            5 => ResultCode::Conflict,
129            6 => ResultCode::Stale,
130            7 => ResultCode::VersionSkew,
131            8 => ResultCode::Unauthenticated,
132            9 => ResultCode::Backend,
133            10 => ResultCode::Forbidden,
134            11 => ResultCode::StepUpRequired,
135            12 => ResultCode::Unavailable,
136            13 => ResultCode::ResourceLimit,
137            14 => ResultCode::Cancelled,
138            15 => ResultCode::DeadlineExceeded,
139            16 => ResultCode::ExpiredSnapshot,
140            17 => ResultCode::StaleGeneration,
141            18 => ResultCode::TargetUnavailable,
142            19 => ResultCode::Pending,
143            20 => ResultCode::BackendUnavailable,
144            other => ResultCode::Unrecognized(other),
145        }
146    }
147
148    /// The HTTP status this code maps to, the one mapping every surface shares,
149    /// so a status need not be decided per surface or per route.
150    pub const fn http_status(self) -> u16 {
151        match self {
152            ResultCode::Ok => 200,
153            ResultCode::Unsupported => 501,
154            ResultCode::NotFound => 404,
155            ResultCode::InvalidArgument => 400,
156            ResultCode::TooLarge => 413,
157            ResultCode::Conflict => 409,
158            ResultCode::Stale => 503,
159            ResultCode::VersionSkew => 400,
160            ResultCode::Unauthenticated => 401,
161            ResultCode::Backend => 502,
162            // Authenticated-but-forbidden is 403, distinct from the 401 an
163            // unauthenticated caller gets. Step-up also lands on 403 unless the
164            // HTTP layer has a better challenge status for the chosen scheme.
165            ResultCode::Forbidden => 403,
166            ResultCode::StepUpRequired => 403,
167            // Retry-after territory, the same status a lagging read model gets.
168            ResultCode::Unavailable => 503,
169            ResultCode::ResourceLimit => 429,
170            ResultCode::Cancelled => 409,
171            ResultCode::DeadlineExceeded => 408,
172            ResultCode::ExpiredSnapshot => 410,
173            ResultCode::StaleGeneration => 409,
174            ResultCode::TargetUnavailable => 503,
175            // The outcome is still being decided, so the same request comes
176            // back later. It is not generically retryable, see `is_retryable`.
177            ResultCode::Pending => 503,
178            ResultCode::BackendUnavailable => 503,
179            ResultCode::Unrecognized(_) => 500,
180        }
181    }
182
183    /// Whether a caller may retry the identical request and reasonably expect a
184    /// different outcome. True only for the two transient classes: the store was
185    /// momentarily unreachable, or the read model had not caught up yet. Every
186    /// other code needs the request, the credential, or the data to change first,
187    /// so retrying it unchanged only wastes the attempt. [`Pending`](Self::Pending)
188    /// is not in this set: only the original operation identity may be
189    /// retried, see [`is_pending`](Self::is_pending).
190    pub const fn is_retryable(self) -> bool {
191        matches!(
192            self,
193            ResultCode::Unavailable
194                | ResultCode::Stale
195                | ResultCode::TargetUnavailable
196                | ResultCode::BackendUnavailable
197        )
198    }
199
200    /// Whether the request could not be served right now: the retryable codes
201    /// other than a lagging read model. The broad `is_unavailable` classifier
202    /// of every client reads this.
203    pub const fn is_unavailable(self) -> bool {
204        matches!(
205            self,
206            ResultCode::Unavailable
207                | ResultCode::TargetUnavailable
208                | ResultCode::BackendUnavailable
209        )
210    }
211
212    /// Whether the caller's credential or grant was refused: no credential or
213    /// an unverified one, or a missing grant. The fix is a credential or a
214    /// grant, never a retry.
215    pub const fn is_permission_denied(self) -> bool {
216        matches!(self, ResultCode::Forbidden | ResultCode::Unauthenticated)
217    }
218
219    /// Whether the mutation was accepted and its outcome is still unknown. The
220    /// caller repeats the exact request with the same operation identity.
221    pub const fn is_pending(self) -> bool {
222        matches!(self, ResultCode::Pending)
223    }
224
225    /// Whether the node could not reach its managed backend, or the backend
226    /// did not answer in time. The request may still apply. A client
227    /// repeats a mutation under the same operation identity, and may send it
228    /// to another node. Unlike [`Unavailable`](Self::Unavailable), which a
229    /// busy node or an unreachable destination answers, this one names the
230    /// node itself as the problem.
231    pub const fn is_backend_unavailable(self) -> bool {
232        matches!(self, ResultCode::BackendUnavailable)
233    }
234}
235
236/// The canonical surface-agnostic error reply. Every managed surface has its own
237/// typed reply enum (`QueryReply`, `KvReply`, `ForkReply`, `BrowseReply`), but a
238/// server that receives a command code it does not handle (a forwarded
239/// `AGDX_KV_CAS` on a build without compare-and-swap, or any future additive
240/// code) has no one surface to answer in: a query-shaped error reply fails to
241/// decode in a client awaiting a key-value reply, and surfaces as an opaque
242/// transport error instead of a clean classification. This is that fallback. A
243/// server answers an unhandled or unsupported code with a `CommandError`, and a
244/// client that fails to decode the surface's typed reply tries `CommandError`
245/// next, turning the wrong-surface reply into a typed [`ResultCode`].
246#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
247#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
248pub struct CommandError {
249    pub code: ResultCode,
250    pub message: String,
251}
252
253impl CommandError {
254    /// A command error from a classified code and a human message.
255    pub fn new(code: ResultCode, message: impl Into<String>) -> Self {
256        Self {
257            code,
258            message: message.into(),
259        }
260    }
261
262    /// The reply for a command code this server does not handle.
263    pub fn unsupported(message: impl Into<String>) -> Self {
264        Self::new(ResultCode::Unsupported, message)
265    }
266}
267
268impl From<&QueryError> for ResultCode {
269    fn from(error: &QueryError) -> Self {
270        match error {
271            QueryError::Unsupported(_) => ResultCode::Unsupported,
272            QueryError::Invalid(_) => ResultCode::InvalidArgument,
273            // The per-source DSL check refused the query: the caller authenticated
274            // but lacks the grant for the named resource, so forbidden not 401.
275            QueryError::Unauthorized(_) => ResultCode::Forbidden,
276            QueryError::IndexNotFound(_)
277            | QueryError::ForkNotFound(_)
278            | QueryError::SchemaNotFound(_) => ResultCode::NotFound,
279            QueryError::Backend(_) => ResultCode::Backend,
280            QueryError::Unavailable(_) => ResultCode::Unavailable,
281            QueryError::TooLarge { .. } => ResultCode::TooLarge,
282            QueryError::Version { .. } => ResultCode::VersionSkew,
283            QueryError::Stale { .. } => ResultCode::Stale,
284            QueryError::DeadlineExceeded { .. } => ResultCode::DeadlineExceeded,
285            QueryError::StaleGeneration { .. } => ResultCode::StaleGeneration,
286        }
287    }
288}
289
290impl From<&KvError> for ResultCode {
291    fn from(error: &KvError) -> Self {
292        match error {
293            KvError::Unsupported(_) => ResultCode::Unsupported,
294            KvError::InvalidKey(_) => ResultCode::InvalidArgument,
295            KvError::InvalidNamespace(_) => ResultCode::InvalidArgument,
296            KvError::TooLarge { .. } => ResultCode::TooLarge,
297            KvError::Backend(_) => ResultCode::Backend,
298            KvError::Unavailable(_) => ResultCode::Unavailable,
299            KvError::Version { .. } => ResultCode::VersionSkew,
300            KvError::VersionConflict { .. } => ResultCode::Conflict,
301            KvError::LeaseLost => ResultCode::Conflict,
302            KvError::LeaseHeld { .. } => ResultCode::Conflict,
303            KvError::BarrierUnreachable { .. } => ResultCode::StaleGeneration,
304            KvError::NotFound => ResultCode::NotFound,
305            KvError::NotLeader => ResultCode::Unavailable,
306            KvError::Stale { .. } => ResultCode::Stale,
307            KvError::Forbidden(_) => ResultCode::Forbidden,
308            KvError::InvalidExpiry(_) => ResultCode::InvalidArgument,
309        }
310    }
311}
312
313impl From<&ForkError> for ResultCode {
314    fn from(error: &ForkError) -> Self {
315        match error {
316            ForkError::Unsupported(_) => ResultCode::Unsupported,
317            ForkError::NotFound(_) => ResultCode::NotFound,
318            ForkError::InvalidFork(_) => ResultCode::InvalidArgument,
319            ForkError::Conflict(_) => ResultCode::Conflict,
320            ForkError::Backend(_) => ResultCode::Backend,
321            ForkError::Unavailable(_) => ResultCode::Unavailable,
322            ForkError::Version { .. } => ResultCode::VersionSkew,
323            ForkError::NotLeader => ResultCode::Unavailable,
324        }
325    }
326}
327
328impl From<&GraphError> for ResultCode {
329    fn from(error: &GraphError) -> Self {
330        match error {
331            GraphError::Unsupported(_) => ResultCode::Unsupported,
332            GraphError::Unauthorized(_) => ResultCode::Forbidden,
333            GraphError::InvalidName(_) => ResultCode::InvalidArgument,
334            GraphError::NotFound(_) => ResultCode::NotFound,
335            GraphError::TooLarge { .. } => ResultCode::TooLarge,
336            GraphError::Backend(_) => ResultCode::Backend,
337            GraphError::Unavailable(_) => ResultCode::Unavailable,
338            GraphError::Version { .. } => ResultCode::VersionSkew,
339        }
340    }
341}
342
343impl From<&AuthzError> for ResultCode {
344    fn from(error: &AuthzError) -> Self {
345        match error {
346            AuthzError::Unsupported(_) => ResultCode::Unsupported,
347            AuthzError::Unauthorized => ResultCode::Forbidden,
348            AuthzError::UnknownRole(_) => ResultCode::NotFound,
349            AuthzError::InvalidName(_)
350            | AuthzError::InvalidGrant(_)
351            | AuthzError::TenancyViolation(_) => ResultCode::InvalidArgument,
352            AuthzError::Conflict { .. } | AuthzError::MutationConflict(_) => ResultCode::Conflict,
353            AuthzError::Version { .. } => ResultCode::VersionSkew,
354            AuthzError::ResourceLimit(_) => ResultCode::ResourceLimit,
355        }
356    }
357}
358
359impl From<&SessionError> for ResultCode {
360    fn from(error: &SessionError) -> Self {
361        match error {
362            SessionError::Unsupported(_) => ResultCode::Unsupported,
363            SessionError::NotFound(_) | SessionError::NotRegistered(_) => ResultCode::NotFound,
364            SessionError::Invalid(_) => ResultCode::InvalidArgument,
365            SessionError::Unauthorized(_) => ResultCode::Forbidden,
366            SessionError::Stale(_) => ResultCode::StaleGeneration,
367            SessionError::Backend(_) => ResultCode::Backend,
368            SessionError::Unavailable(_) => ResultCode::Unavailable,
369        }
370    }
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376
377    #[test]
378    fn given_result_codes_when_mapped_then_should_round_trip_through_the_numeric_value() {
379        for code in [
380            ResultCode::Ok,
381            ResultCode::Unsupported,
382            ResultCode::NotFound,
383            ResultCode::InvalidArgument,
384            ResultCode::TooLarge,
385            ResultCode::Conflict,
386            ResultCode::Stale,
387            ResultCode::VersionSkew,
388            ResultCode::Unauthenticated,
389            ResultCode::Backend,
390            ResultCode::Forbidden,
391            ResultCode::StepUpRequired,
392            ResultCode::Unavailable,
393            ResultCode::TargetUnavailable,
394            ResultCode::Pending,
395            ResultCode::BackendUnavailable,
396        ] {
397            assert_eq!(ResultCode::from_code(code.code()), code);
398        }
399        assert_eq!(ResultCode::Pending.code(), 19);
400        assert_eq!(ResultCode::BackendUnavailable.code(), 20);
401        assert!(ResultCode::BackendUnavailable.is_retryable());
402        assert!(ResultCode::BackendUnavailable.is_backend_unavailable());
403        assert!(!ResultCode::Unavailable.is_backend_unavailable());
404        assert_eq!(ResultCode::from_code(21), ResultCode::Unrecognized(21));
405        // An unknown numeric code rides through as Unrecognized.
406        assert_eq!(ResultCode::from_code(900), ResultCode::Unrecognized(900));
407        assert_eq!(ResultCode::Unrecognized(900).code(), 900);
408    }
409
410    #[test]
411    fn given_surface_errors_when_classified_then_should_map_to_the_shared_code() {
412        assert_eq!(
413            ResultCode::from(&QueryError::IndexNotFound("readings".to_owned())),
414            ResultCode::NotFound
415        );
416        assert_eq!(
417            ResultCode::from(&QueryError::Stale {
418                what: "readings".to_owned(),
419                applied: 4,
420                required: 9,
421            }),
422            ResultCode::Stale
423        );
424        assert_eq!(
425            ResultCode::from(&KvError::VersionConflict { current: Some(3) }),
426            ResultCode::Conflict
427        );
428        assert_eq!(
429            ResultCode::from(&ForkError::Conflict("open".to_owned())),
430            ResultCode::Conflict
431        );
432        assert_eq!(
433            ResultCode::from(&KvError::NotLeader),
434            ResultCode::Unavailable
435        );
436        assert_eq!(
437            ResultCode::from(&ForkError::NotLeader),
438            ResultCode::Unavailable
439        );
440        assert_eq!(
441            ResultCode::from(&AuthzError::TenancyViolation("prefix acme".to_owned())),
442            ResultCode::InvalidArgument
443        );
444        assert_eq!(
445            ResultCode::from(&AuthzError::Unauthorized),
446            ResultCode::Forbidden
447        );
448    }
449
450    // One code per condition on every surface. A surface without its own
451    // variant for a condition answers the surface-neutral `CommandError`.
452    #[test]
453    fn given_one_condition_on_every_surface_when_classified_then_should_share_one_code() {
454        let text = || "x".to_owned();
455        let table: [(ResultCode, Vec<ResultCode>); 6] = [
456            (
457                ResultCode::InvalidArgument,
458                vec![
459                    ResultCode::from(&KvError::InvalidKey(text())),
460                    ResultCode::from(&KvError::InvalidNamespace(text())),
461                    ResultCode::from(&ForkError::InvalidFork(text())),
462                    ResultCode::from(&GraphError::InvalidName(text())),
463                    ResultCode::from(&AuthzError::InvalidName(text())),
464                    ResultCode::from(&AuthzError::InvalidGrant(text())),
465                    ResultCode::from(&SessionError::Invalid(text())),
466                    ResultCode::from(&QueryError::Invalid(text())),
467                ],
468            ),
469            (
470                ResultCode::Forbidden,
471                vec![
472                    ResultCode::from(&QueryError::Unauthorized(text())),
473                    ResultCode::from(&GraphError::Unauthorized(text())),
474                    ResultCode::from(&AuthzError::Unauthorized),
475                    ResultCode::from(&SessionError::Unauthorized(text())),
476                ],
477            ),
478            (
479                ResultCode::NotFound,
480                vec![
481                    ResultCode::from(&QueryError::IndexNotFound(text())),
482                    ResultCode::from(&KvError::NotFound),
483                    ResultCode::from(&ForkError::NotFound(text())),
484                    ResultCode::from(&GraphError::NotFound(text())),
485                    ResultCode::from(&AuthzError::UnknownRole(text())),
486                    ResultCode::from(&SessionError::NotFound(text())),
487                ],
488            ),
489            (
490                ResultCode::Unavailable,
491                vec![
492                    ResultCode::from(&QueryError::Unavailable(text())),
493                    ResultCode::from(&KvError::Unavailable(text())),
494                    ResultCode::from(&ForkError::Unavailable(text())),
495                    ResultCode::from(&GraphError::Unavailable(text())),
496                    ResultCode::from(&SessionError::Unavailable(text())),
497                ],
498            ),
499            (
500                ResultCode::Unsupported,
501                vec![
502                    ResultCode::from(&QueryError::Unsupported(text())),
503                    ResultCode::from(&KvError::Unsupported(text())),
504                    ResultCode::from(&ForkError::Unsupported(text())),
505                    ResultCode::from(&GraphError::Unsupported(text())),
506                    ResultCode::from(&AuthzError::Unsupported(text())),
507                    ResultCode::from(&SessionError::Unsupported(text())),
508                ],
509            ),
510            (
511                ResultCode::Backend,
512                vec![
513                    ResultCode::from(&QueryError::Backend(text())),
514                    ResultCode::from(&KvError::Backend(text())),
515                    ResultCode::from(&ForkError::Backend(text())),
516                    ResultCode::from(&GraphError::Backend(text())),
517                    ResultCode::from(&SessionError::Backend(text())),
518                ],
519            ),
520        ];
521        for (expected, codes) in table {
522            for (surface, code) in codes.into_iter().enumerate() {
523                assert_eq!(code, expected, "surface {surface} of {expected:?}");
524            }
525            assert!(
526                !expected.is_retryable() || expected == ResultCode::Unavailable,
527                "only unavailable is retryable among these"
528            );
529        }
530    }
531
532    // A transient outcome must be distinguishable from a fault without parsing
533    // the message, so a generic client can back off and retry exactly these.
534    #[test]
535    fn given_transient_outcomes_when_classified_then_should_be_the_only_retryable_codes() {
536        for surface in [
537            ResultCode::from(&QueryError::Unavailable("dropped".to_owned())),
538            ResultCode::from(&KvError::Unavailable("dropped".to_owned())),
539            ResultCode::from(&ForkError::Unavailable("dropped".to_owned())),
540        ] {
541            assert_eq!(surface, ResultCode::Unavailable);
542        }
543        assert_eq!(ResultCode::Unavailable.http_status(), 503);
544        assert!(ResultCode::Unavailable.is_retryable());
545        assert!(ResultCode::Stale.is_retryable());
546        for code in [
547            ResultCode::Ok,
548            ResultCode::Unsupported,
549            ResultCode::NotFound,
550            ResultCode::InvalidArgument,
551            ResultCode::TooLarge,
552            ResultCode::Conflict,
553            ResultCode::VersionSkew,
554            ResultCode::Unauthenticated,
555            ResultCode::Backend,
556            ResultCode::Forbidden,
557            ResultCode::StepUpRequired,
558            ResultCode::Pending,
559            ResultCode::Unrecognized(900),
560        ] {
561            assert!(
562                !code.is_retryable(),
563                "{code:?} must not invite a blind retry"
564            );
565        }
566    }
567
568    #[test]
569    fn given_result_codes_when_mapped_to_http_then_should_match_the_binding_table() {
570        assert_eq!(ResultCode::NotFound.http_status(), 404);
571        assert_eq!(ResultCode::Unsupported.http_status(), 501);
572        assert_eq!(ResultCode::TooLarge.http_status(), 413);
573        assert_eq!(ResultCode::Conflict.http_status(), 409);
574        assert_eq!(ResultCode::Stale.http_status(), 503);
575        assert_eq!(ResultCode::Unauthenticated.http_status(), 401);
576        assert_eq!(ResultCode::Forbidden.http_status(), 403);
577        assert_eq!(ResultCode::StepUpRequired.http_status(), 403);
578        assert_eq!(ResultCode::Backend.http_status(), 502);
579        // An unrecognized code from a newer peer maps to a generic 500 rather
580        // than panicking, and keeps its raw numeric.
581        assert_eq!(ResultCode::Unrecognized(777).http_status(), 500);
582        assert_eq!(ResultCode::Unrecognized(777).code(), 777);
583    }
584
585    #[cfg(feature = "cbor")]
586    #[test]
587    fn given_a_result_code_when_round_tripped_through_cbor_then_should_preserve_the_variant() {
588        use crate::framing::{decode_named, encode_named};
589        for code in [
590            ResultCode::Ok,
591            ResultCode::Conflict,
592            ResultCode::Stale,
593            ResultCode::Unrecognized(4242),
594        ] {
595            let bytes = encode_named(&code).expect("serializes");
596            let back: ResultCode = decode_named(&bytes).expect("deserializes");
597            assert_eq!(back, code);
598        }
599    }
600
601    #[test]
602    fn given_backend_unavailable_when_serialized_then_should_use_the_backend_unavailable_string() {
603        let json = serde_json::to_string(&ResultCode::BackendUnavailable).expect("serializes");
604        assert_eq!(json, "\"backend_unavailable\"");
605        let back: ResultCode =
606            serde_json::from_str("\"backend_unavailable\"").expect("deserializes");
607        assert_eq!(back, ResultCode::BackendUnavailable);
608    }
609
610    #[cfg(feature = "cbor")]
611    #[test]
612    fn given_a_command_error_when_round_tripped_then_should_preserve_code_and_message() {
613        use crate::framing::{decode_named, encode_named};
614        let error = CommandError::unsupported("AGDX_KV_CAS not served on this build");
615        assert_eq!(error.code, ResultCode::Unsupported);
616        let bytes = encode_named(&error).expect("serializes");
617        let back: CommandError = decode_named(&bytes).expect("deserializes");
618        assert_eq!(back, error);
619    }
620}