Skip to main content

khive_wire_protocol/
error.rs

1//! The wire error taxonomy from ADR-137's "Wire error taxonomy" section.
2//!
3//! Wire-level errors are distinct from verb-level DSL errors (ADR-016): a
4//! wire error is returned before or instead of DSL dispatch, while a
5//! DSL-level per-operation error is a separate failure mode carried inside a
6//! successful [`crate::frame::Frame::Response`] frame's payload.
7
8use serde::{Deserialize, Serialize};
9
10/// Where a wire error terminates: the whole connection, or just the
11/// operation id it echoes.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum TerminalScope {
14    /// The error is followed by connection close. It carries no operation
15    /// id.
16    Connection,
17    /// The error terminates only the operation id it echoes (a request,
18    /// subscribe, or unsubscribe id); the connection stays usable.
19    Request,
20}
21
22/// The closed set of wire-level error codes for protocol version 1
23/// (ADR-137, "Wire error taxonomy").
24///
25/// The set is closed within a protocol version: adding a code requires a
26/// protocol version bump ([`crate::version`]). Serialized names are
27/// `snake_case` and match the ADR exactly.
28///
29/// A decoder that encounters a code string it does not recognize falls back
30/// to [`WireErrorCode::Internal`] per the ADR: *"a client that receives a
31/// code it does not recognize must treat it as `internal` — request-terminal,
32/// retriable only under the caller's own policy — rather than inventing
33/// semantics for it."* This is implemented with `#[serde(other)]`, so an
34/// older client talking to a server that has gained a new code under a later
35/// protocol version degrades to this documented behavior instead of a decode
36/// failure.
37/// The wire (`snake_case`) names of every code in the closed set for
38/// protocol version 1, in ADR-137's "Wire error taxonomy" table order.
39///
40/// The codec enforces the id/scope pairing when decoding an error frame.
41/// Under ADR-137 Amendment 1 Decision 5, an unknown code is accepted only
42/// with a non-empty operation id. It becomes request-terminal
43/// [`WireErrorCode::Internal`], retains its raw string for diagnostics, and
44/// cannot be re-encoded. An unknown code without an operation id is malformed
45/// and connection-terminal. Names are case-sensitive: `"Cancelled"` is an
46/// unknown spelling and follows the same rule.
47pub const WIRE_ERROR_CODES: &[&str] = &[
48    "unsupported_version",
49    "identity_rejected",
50    "malformed_frame",
51    "frame_too_large",
52    "subscriber_overflow",
53    "subscription_revoked",
54    "context_rejected",
55    "peer_class_denied",
56    "subscription_denied",
57    "already_subscribed",
58    "cursor_expired",
59    "in_flight_limit_exceeded",
60    "deadline_exceeded",
61    "cancelled",
62    "shutting_down",
63    "internal",
64];
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(rename_all = "snake_case")]
68pub enum WireErrorCode {
69    /// Handshake named no mutually supported protocol version. Connection.
70    UnsupportedVersion,
71    /// Whois lookup failed, no or invalid node mapping, or native-frame
72    /// ingress attempted by a class without native access. Connection.
73    IdentityRejected,
74    /// A frame cannot be decoded or violates the frame grammar. Connection.
75    MalformedFrame,
76    /// A frame exceeds the configured maximum size. Connection.
77    FrameTooLarge,
78    /// The connection's bounded outbound event queue reached its limit.
79    /// Connection.
80    SubscriberOverflow,
81    /// A live mapping or peer-class change short of mapping deletion removed
82    /// authorization for a topic with an active subscription on this
83    /// connection. Connection.
84    SubscriptionRevoked,
85    /// A frame-level attempt to supply `namespace`, `actor_id`, or
86    /// `visible_namespaces` on a mapped transport. Request.
87    ContextRejected,
88    /// A parsed operation names a verb outside the mapped class allowlist.
89    /// Request.
90    PeerClassDenied,
91    /// A `subscribe` names a topic outside the mapped class's allowed-topic
92    /// set. Request.
93    SubscriptionDenied,
94    /// A `subscribe` names a topic that already has an active subscription
95    /// on this connection. Request.
96    AlreadySubscribed,
97    /// A `subscribe` resume cursor is older than the topic's retention
98    /// window. Request.
99    CursorExpired,
100    /// A `request` arrives while the per-connection in-flight limit is
101    /// reached. Request.
102    InFlightLimitExceeded,
103    /// The server abandoned the request at its deadline. Request.
104    DeadlineExceeded,
105    /// The request was terminated by a `cancel` frame before its normal
106    /// completion. Request.
107    Cancelled,
108    /// The server is draining and refuses new work. Request.
109    ShuttingDown,
110    /// An unclassified server-side transport failure. Request. Also the
111    /// fallback for an error code this client does not recognize.
112    #[serde(other)]
113    Internal,
114}
115
116impl WireErrorCode {
117    /// The terminal scope defined for this code in ADR-137's error table.
118    pub const fn terminal_scope(self) -> TerminalScope {
119        use WireErrorCode::*;
120        match self {
121            UnsupportedVersion | IdentityRejected | MalformedFrame | FrameTooLarge
122            | SubscriberOverflow | SubscriptionRevoked => TerminalScope::Connection,
123            ContextRejected
124            | PeerClassDenied
125            | SubscriptionDenied
126            | AlreadySubscribed
127            | CursorExpired
128            | InFlightLimitExceeded
129            | DeadlineExceeded
130            | Cancelled
131            | ShuttingDown
132            | Internal => TerminalScope::Request,
133        }
134    }
135
136    /// The wire (`snake_case`) name of this code, as it appears on the wire
137    /// and in ADR-137's table.
138    pub const fn as_str(self) -> &'static str {
139        use WireErrorCode::*;
140        match self {
141            UnsupportedVersion => "unsupported_version",
142            IdentityRejected => "identity_rejected",
143            MalformedFrame => "malformed_frame",
144            FrameTooLarge => "frame_too_large",
145            SubscriberOverflow => "subscriber_overflow",
146            SubscriptionRevoked => "subscription_revoked",
147            ContextRejected => "context_rejected",
148            PeerClassDenied => "peer_class_denied",
149            SubscriptionDenied => "subscription_denied",
150            AlreadySubscribed => "already_subscribed",
151            CursorExpired => "cursor_expired",
152            InFlightLimitExceeded => "in_flight_limit_exceeded",
153            DeadlineExceeded => "deadline_exceeded",
154            Cancelled => "cancelled",
155            ShuttingDown => "shutting_down",
156            Internal => "internal",
157        }
158    }
159}
160
161impl std::fmt::Display for WireErrorCode {
162    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
163        f.write_str(self.as_str())
164    }
165}
166
167#[cfg(test)]
168#[path = "error_tests.rs"]
169mod tests;