dig_rpc_protocol/error.rs
1//! The canonical DIG-node RPC error taxonomy.
2//!
3//! This module is the **single definition point** for every error code the DIG
4//! node RPC surface emits, the canonical [`RpcError`] envelope
5//! (`{code, message, data:{code, origin}}`), and the one constructor helper both
6//! node implementations call so every error carries a machine-branchable
7//! `data.code` and `data.origin`.
8//!
9//! # The code set
10//!
11//! Standard JSON-RPC 2.0 codes plus the DIG protocol-specific codes. The numeric
12//! values are a **published wire contract** and never change once assigned.
13//!
14//! | Code | Variant | Origin | Meaning |
15//! |---|---|---|---|
16//! | `-32700` | [`ParseError`](ErrorCode::ParseError) | Node | request body is not valid JSON |
17//! | `-32600` | [`InvalidRequest`](ErrorCode::InvalidRequest) | Node | not a valid Request object |
18//! | `-32601` | [`MethodNotFound`](ErrorCode::MethodNotFound) | Node | method not implemented |
19//! | `-32602` | [`InvalidParams`](ErrorCode::InvalidParams) | Node | missing/malformed params |
20//! | `-32603` | [`InternalError`](ErrorCode::InternalError) | Node | well-formed call failed |
21//! | `-32000` | [`ServerError`](ErrorCode::ServerError) | Node | generic server error |
22//! | `-32003` | [`ContentMissRateLimited`](ErrorCode::ContentMissRateLimited) | Node | content not held; miss-lookup budget exhausted for this requestor |
23//! | `-32004` | [`ResourceUnavailable`](ErrorCode::ResourceUnavailable) | Node | resource not available at the requested root (genuine infra miss) |
24//! | `-32005` | [`RootNotAnchored`](ErrorCode::RootNotAnchored) | Node | requested/served root is not the chain-anchored root (fail-closed pin) |
25//! | `-32006` | [`PeerUnreachable`](ErrorCode::PeerUnreachable) | Node | no NAT-traversal strategy reached the peer |
26//! | `-32007` | [`RangeNotSatisfiable`](ErrorCode::RangeNotSatisfiable) | Node | byte range lies outside the resource |
27//! | `-32008` | [`ContentRedirect`](ErrorCode::ContentRedirect) | Node | content held elsewhere — `data.redirect` names holders |
28//! | `-32009` | [`RangeMetadataUnrepresentable`](ErrorCode::RangeMetadataUnrepresentable) | Node | the resource's own range metadata cannot fit a conforming frame, so this holder can NEVER serve the range |
29//! | `-32010` | [`UpstreamError`](ErrorCode::UpstreamError) | Upstream | an upstream/proxy fetch failed |
30//! | `-32011` | [`StageInvalidInput`](ErrorCode::StageInvalidInput) | Node | `dig.stage`: dir unreadable / walk budget exceeded |
31//! | `-32012` | [`StageNoFiles`](ErrorCode::StageNoFiles) | Node | `dig.stage`: no files to compile |
32//! | `-32013` | [`StageOverCap`](ErrorCode::StageOverCap) | Node | `dig.stage`: input exceeds the store cap |
33//! | `-32014` | [`StageCompileFailed`](ErrorCode::StageCompileFailed) | Node | `dig.stage`: compile / IO failure |
34//! | `-32020` | [`OnionCircuitUnavailable`](ErrorCode::OnionCircuitUnavailable) | Onion | private read could not build/keep a circuit |
35//! | `-32021` | [`PrivacyRequiresLocalNode`](ErrorCode::PrivacyRequiresLocalNode) | Onion | privacy mode requires the caller be a local originator |
36//! | `-32022` | [`OnionHopsOutOfRange`](ErrorCode::OnionHopsOutOfRange) | Onion | requested hop count outside `[2, 5]` |
37//! | `-32030` | [`Unauthorized`](ErrorCode::Unauthorized) | Control | control-plane call is not authorized |
38//! | `-32031` | [`NotSupported`](ErrorCode::NotSupported) | Control | control-plane method not supported here |
39//! | `-32032` | [`ControlError`](ErrorCode::ControlError) | Control | control-plane runtime error |
40//!
41//! ## The `-32020..-32022` collision, resolved
42//!
43//! The published normative protocol (docs.dig.net) assigns `-32020/-32021/-32022`
44//! to the **onion** (private-retrieval) failures. Those keep their numbers. The
45//! control-plane errors that previously squatted the same values are renumbered
46//! to `-32030/-32031/-32032`.
47
48use serde::{Deserialize, Serialize};
49use serde_repr::{Deserialize_repr, Serialize_repr};
50
51/// A canonical DIG-node RPC error code.
52///
53/// Serializes as a bare integer (via `serde_repr`), spec-compliant for
54/// `error.code`. `#[non_exhaustive]` so adding a code in a minor release is
55/// additive; downstream matches must use `_ => …`.
56#[repr(i32)]
57#[non_exhaustive]
58#[derive(Debug, Clone, Copy, Serialize_repr, Deserialize_repr, PartialEq, Eq, Hash)]
59pub enum ErrorCode {
60 // ---- Standard JSON-RPC 2.0 ----
61 /// Invalid JSON was received by the server.
62 ParseError = -32700,
63 /// The JSON sent is not a valid Request object.
64 InvalidRequest = -32600,
65 /// The method does not exist / is not available.
66 MethodNotFound = -32601,
67 /// Invalid method parameter(s).
68 InvalidParams = -32602,
69 /// The node failed to satisfy a well-formed call (network profile).
70 InternalError = -32603,
71
72 // ---- DIG protocol-specific (implementation-defined server range) ----
73 /// Generic server error (config write failure, file I/O, chain read failure).
74 ServerError = -32000,
75 /// This node does not hold the content, and the requestor has exhausted its
76 /// miss-lookup budget. Unlike an ordinary content miss (an indistinguishable
77 /// decoy that is never an error), this is an explicit rate-limit signal: the
78 /// requestor has spent its budget of miss lookups and should back off rather
79 /// than keep probing.
80 ContentMissRateLimited = -32003,
81 /// Resource not available at the requested root — a genuine infrastructure
82 /// miss (absent module, bad magic, oversize, a trap, an undecodable
83 /// envelope). Distinct from a content miss, which is an indistinguishable
84 /// decoy and is never an error.
85 ResourceUnavailable = -32004,
86 /// The requested or served generation is not the store's current on-chain
87 /// root. The read path pins to the CHIP-0035 singleton's on-chain root and
88 /// fails closed rather than serving an unverified generation.
89 RootNotAnchored = -32005,
90 /// No connection to the named peer could be established — every
91 /// NAT-traversal strategy failed, or the peer is not on this network.
92 PeerUnreachable = -32006,
93 /// The requested byte range lies outside the resource (`offset >=
94 /// total_length`) or is otherwise unsatisfiable.
95 RangeNotSatisfiable = -32007,
96 /// This node does not hold the content but located peers that do.
97 /// `data.redirect` names the holders + the redirect budget.
98 ContentRedirect = -32008,
99 /// `dig.fetchRange`: the resource's own range metadata cannot be represented
100 /// in a conforming frame at all, so this holder can NEVER serve the range.
101 ///
102 /// A resource whose `chunk_lens` layout or `inclusion_proof` exceeds the
103 /// per-frame bounds has no conforming first frame, even with a paged prologue.
104 /// That is a permanent property of the resource, not a transient condition, so
105 /// it needs its own code: a client that could not tell it from an ordinary
106 /// transport failure would keep retrying a holder that cannot succeed, and would
107 /// retry every other holder of the same resource for the same reason.
108 RangeMetadataUnrepresentable = -32009,
109 /// An upstream/proxy fetch (e.g. `rpc.dig.net`) failed. Distinct from the
110 /// generic [`ServerError`](ErrorCode::ServerError) so a client can tell an
111 /// upstream fault from a local one.
112 UpstreamError = -32010,
113 /// `dig.stage`: the input directory is unreadable, or the bounded walk
114 /// exceeded its byte / file-count / depth budget.
115 StageInvalidInput = -32011,
116 /// `dig.stage`: the input directory contained no files to compile.
117 StageNoFiles = -32012,
118 /// `dig.stage`: the input exceeds the per-store size cap.
119 StageOverCap = -32013,
120 /// `dig.stage`: compiling the capsule failed (CLVM/IO error).
121 StageCompileFailed = -32014,
122
123 // ---- Onion / private retrieval (published normative — KEEP) ----
124 /// A `mode:"privacy"` read could not be served privately (no circuit could
125 /// be built, or one died mid-fetch). The node fails closed rather than
126 /// downgrading — a silent downgrade would deanonymize the reader.
127 OnionCircuitUnavailable = -32020,
128 /// `mode:"privacy"` was requested but the caller is not the node's own
129 /// trusted local originator. Privacy requires a local DIG node.
130 PrivacyRequiresLocalNode = -32021,
131 /// The requested `privacy.hops` (circuit length) is outside `[2, 5]`.
132 OnionHopsOutOfRange = -32022,
133
134 // ---- Control plane (loopback-only; renumbered off the onion codes) ----
135 /// The control-plane call is not authorized (loopback / token gate failed).
136 Unauthorized = -32030,
137 /// The control-plane method is recognized but not supported on this node.
138 NotSupported = -32031,
139 /// A control-plane runtime error (pin registry, sync trigger, config write).
140 ControlError = -32032,
141}
142
143impl ErrorCode {
144 /// The raw integer wire code.
145 pub const fn code(self) -> i32 {
146 self as i32
147 }
148
149 /// The stable `UPPER_SNAKE_CASE` machine identifier carried in `data.code`.
150 ///
151 /// This is the branch key an agent keys on; it never changes once assigned.
152 pub const fn machine_code(self) -> &'static str {
153 match self {
154 ErrorCode::ParseError => "PARSE_ERROR",
155 ErrorCode::InvalidRequest => "INVALID_REQUEST",
156 ErrorCode::MethodNotFound => "METHOD_NOT_FOUND",
157 ErrorCode::InvalidParams => "INVALID_PARAMS",
158 ErrorCode::InternalError => "INTERNAL_ERROR",
159 ErrorCode::ServerError => "SERVER_ERROR",
160 ErrorCode::ContentMissRateLimited => "CONTENT_MISS_RATE_LIMITED",
161 ErrorCode::ResourceUnavailable => "RESOURCE_UNAVAILABLE",
162 ErrorCode::RootNotAnchored => "ROOT_NOT_ANCHORED",
163 ErrorCode::PeerUnreachable => "PEER_UNREACHABLE",
164 ErrorCode::RangeNotSatisfiable => "RANGE_NOT_SATISFIABLE",
165 ErrorCode::ContentRedirect => "CONTENT_REDIRECT",
166 ErrorCode::RangeMetadataUnrepresentable => "RANGE_METADATA_UNREPRESENTABLE",
167 ErrorCode::UpstreamError => "UPSTREAM_ERROR",
168 ErrorCode::StageInvalidInput => "STAGE_INVALID_INPUT",
169 ErrorCode::StageNoFiles => "STAGE_NO_FILES",
170 ErrorCode::StageOverCap => "STAGE_OVER_CAP",
171 ErrorCode::StageCompileFailed => "STAGE_COMPILE_FAILED",
172 ErrorCode::OnionCircuitUnavailable => "ONION_CIRCUIT_UNAVAILABLE",
173 ErrorCode::PrivacyRequiresLocalNode => "PRIVACY_REQUIRES_LOCAL_NODE",
174 ErrorCode::OnionHopsOutOfRange => "ONION_HOPS_OUT_OF_RANGE",
175 ErrorCode::Unauthorized => "UNAUTHORIZED",
176 ErrorCode::NotSupported => "NOT_SUPPORTED",
177 ErrorCode::ControlError => "CONTROL_ERROR",
178 }
179 }
180
181 /// The default human-readable summary for this code (used when a caller does
182 /// not supply a more specific message).
183 pub const fn default_message(self) -> &'static str {
184 match self {
185 ErrorCode::ParseError => "Parse error",
186 ErrorCode::InvalidRequest => "Invalid request",
187 ErrorCode::MethodNotFound => "Method not found",
188 ErrorCode::InvalidParams => "Invalid params",
189 ErrorCode::InternalError => "Internal error",
190 ErrorCode::ServerError => "Server error",
191 ErrorCode::ContentMissRateLimited => {
192 "Content not held; miss-lookup budget exhausted for this requestor"
193 }
194 ErrorCode::ResourceUnavailable => "Resource not available at the requested root",
195 ErrorCode::RootNotAnchored => "Root not chain-anchored",
196 ErrorCode::PeerUnreachable => "Peer unreachable",
197 ErrorCode::RangeNotSatisfiable => "Range not satisfiable",
198 ErrorCode::ContentRedirect => "Content held elsewhere — redirect",
199 ErrorCode::RangeMetadataUnrepresentable => {
200 "Range metadata cannot be represented in a conforming frame"
201 }
202 ErrorCode::UpstreamError => "Upstream error",
203 ErrorCode::StageInvalidInput => "Stage input directory not readable",
204 ErrorCode::StageNoFiles => "Stage input contained no files",
205 ErrorCode::StageOverCap => "Stage input over the store cap",
206 ErrorCode::StageCompileFailed => "Stage compile failed",
207 ErrorCode::OnionCircuitUnavailable => "Onion circuit unavailable",
208 ErrorCode::PrivacyRequiresLocalNode => "Privacy requires a local node",
209 ErrorCode::OnionHopsOutOfRange => "Onion hop count out of range",
210 ErrorCode::Unauthorized => "Unauthorized",
211 ErrorCode::NotSupported => "Not supported",
212 ErrorCode::ControlError => "Control-plane error",
213 }
214 }
215
216 /// The natural [`ErrorOrigin`] for this code (which subsystem the failure
217 /// arose in). A caller may override it — a `ResourceUnavailable` bubbled up
218 /// from an upstream proxy can be tagged [`ErrorOrigin::Upstream`].
219 pub const fn default_origin(self) -> ErrorOrigin {
220 match self {
221 ErrorCode::UpstreamError => ErrorOrigin::Upstream,
222 ErrorCode::OnionCircuitUnavailable
223 | ErrorCode::PrivacyRequiresLocalNode
224 | ErrorCode::OnionHopsOutOfRange => ErrorOrigin::Onion,
225 ErrorCode::Unauthorized | ErrorCode::NotSupported | ErrorCode::ControlError => {
226 ErrorOrigin::Control
227 }
228 ErrorCode::PeerUnreachable => ErrorOrigin::Peer,
229 _ => ErrorOrigin::Node,
230 }
231 }
232
233 /// Whether this variant is in the JSON-RPC-reserved range
234 /// (`-32768..=-32000`).
235 pub const fn is_jsonrpc_reserved(self) -> bool {
236 let c = self.code();
237 c >= -32768 && c <= -32000
238 }
239
240 /// Every code, in wire order. Drives the OpenRPC error catalogue and the
241 /// exhaustiveness conformance test — a new variant must be added here.
242 pub const ALL: &'static [ErrorCode] = &[
243 ErrorCode::ParseError,
244 ErrorCode::InvalidRequest,
245 ErrorCode::MethodNotFound,
246 ErrorCode::InvalidParams,
247 ErrorCode::InternalError,
248 ErrorCode::ServerError,
249 ErrorCode::ContentMissRateLimited,
250 ErrorCode::ResourceUnavailable,
251 ErrorCode::RootNotAnchored,
252 ErrorCode::PeerUnreachable,
253 ErrorCode::RangeNotSatisfiable,
254 ErrorCode::ContentRedirect,
255 ErrorCode::RangeMetadataUnrepresentable,
256 ErrorCode::UpstreamError,
257 ErrorCode::StageInvalidInput,
258 ErrorCode::StageNoFiles,
259 ErrorCode::StageOverCap,
260 ErrorCode::StageCompileFailed,
261 ErrorCode::OnionCircuitUnavailable,
262 ErrorCode::PrivacyRequiresLocalNode,
263 ErrorCode::OnionHopsOutOfRange,
264 ErrorCode::Unauthorized,
265 ErrorCode::NotSupported,
266 ErrorCode::ControlError,
267 ];
268}
269
270/// The subsystem a failure arose in — carried in `data.origin` so a client can
271/// route the error (retry upstream, rebuild a circuit, re-auth the control
272/// plane) without parsing the message.
273#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
274#[serde(rename_all = "lowercase")]
275pub enum ErrorOrigin {
276 /// The node's own read/serve path.
277 Node,
278 /// The peer-network layer (discovery / availability / range serving).
279 Peer,
280 /// An upstream fetch (`rpc.dig.net` proxy / whole-store sync).
281 Upstream,
282 /// The onion (private-retrieval) layer.
283 Onion,
284 /// The loopback control plane.
285 Control,
286}
287
288/// Structured error context carried in `error.data`.
289///
290/// The canonical DIG envelope always carries `data.code` (the
291/// [`UPPER_SNAKE_CASE`](ErrorCode::machine_code) machine identifier) and
292/// `data.origin`. `redirect` is present only on
293/// [`ContentRedirect`](ErrorCode::ContentRedirect); `extra` carries any
294/// method-specific fields verbatim (flattened onto `data`).
295#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
296pub struct ErrorData {
297 /// The stable `UPPER_SNAKE_CASE` machine code (mirrors the numeric `code`).
298 pub code: String,
299 /// The subsystem the failure arose in.
300 pub origin: ErrorOrigin,
301 /// The redirect payload — present only on `CONTENT_REDIRECT`.
302 #[serde(skip_serializing_if = "Option::is_none", default)]
303 pub redirect: Option<crate::types::RedirectInfo>,
304 /// Any additional method-specific fields, flattened onto `data`.
305 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
306 pub extra: serde_json::Map<String, serde_json::Value>,
307}
308
309/// The canonical DIG-node RPC error object: `{code, message, data:{code, origin}}`.
310///
311/// Build one with [`RpcError::new`] (or the code-specific helpers) so the numeric
312/// code, the `data.code` machine string, and the origin can never drift apart.
313#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
314pub struct RpcError {
315 /// The numeric wire code.
316 pub code: ErrorCode,
317 /// A human-readable message. May be refined over time; `data.code` is the
318 /// stable branch key.
319 pub message: String,
320 /// Structured, machine-branchable context.
321 pub data: ErrorData,
322}
323
324impl RpcError {
325 /// The single constructor: mint the canonical envelope from a code, a
326 /// message, and an origin. `data.code` is derived from `code` so the two
327 /// can never disagree.
328 pub fn new(code: ErrorCode, message: impl Into<String>, origin: ErrorOrigin) -> Self {
329 Self {
330 code,
331 message: message.into(),
332 data: ErrorData {
333 code: code.machine_code().to_string(),
334 origin,
335 redirect: None,
336 extra: serde_json::Map::new(),
337 },
338 }
339 }
340
341 /// Mint an error using the code's [default origin](ErrorCode::default_origin).
342 pub fn of(code: ErrorCode, message: impl Into<String>) -> Self {
343 Self::new(code, message, code.default_origin())
344 }
345
346 /// Mint an error using both the code's default origin and its
347 /// [default message](ErrorCode::default_message).
348 pub fn code_only(code: ErrorCode) -> Self {
349 Self::new(code, code.default_message(), code.default_origin())
350 }
351
352 /// Attach a [`RedirectInfo`](crate::types::RedirectInfo) payload (for
353 /// [`ContentRedirect`](ErrorCode::ContentRedirect)).
354 pub fn with_redirect(mut self, redirect: crate::types::RedirectInfo) -> Self {
355 self.data.redirect = Some(redirect);
356 self
357 }
358
359 /// Attach one extra `data` field (flattened onto `data`).
360 pub fn with_extra(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
361 self.data.extra.insert(key.into(), value);
362 self
363 }
364}
365
366impl std::fmt::Display for RpcError {
367 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
368 write!(f, "[{}] {}", self.code.machine_code(), self.message)
369 }
370}
371
372impl std::error::Error for RpcError {}
373
374#[cfg(test)]
375mod tests {
376 use super::*;
377
378 /// **Proves:** every numeric code is pinned to its published wire value.
379 /// **Catches:** a reorder/renumber, or a lost `#[repr(i32)]`.
380 #[test]
381 fn numeric_values_pinned() {
382 assert_eq!(ErrorCode::ParseError.code(), -32700);
383 assert_eq!(ErrorCode::InvalidRequest.code(), -32600);
384 assert_eq!(ErrorCode::MethodNotFound.code(), -32601);
385 assert_eq!(ErrorCode::InvalidParams.code(), -32602);
386 assert_eq!(ErrorCode::InternalError.code(), -32603);
387 assert_eq!(ErrorCode::ServerError.code(), -32000);
388 assert_eq!(ErrorCode::ContentMissRateLimited.code(), -32003);
389 assert_eq!(ErrorCode::ResourceUnavailable.code(), -32004);
390 assert_eq!(ErrorCode::RootNotAnchored.code(), -32005);
391 assert_eq!(ErrorCode::PeerUnreachable.code(), -32006);
392 assert_eq!(ErrorCode::RangeNotSatisfiable.code(), -32007);
393 assert_eq!(ErrorCode::ContentRedirect.code(), -32008);
394 assert_eq!(ErrorCode::UpstreamError.code(), -32010);
395 assert_eq!(ErrorCode::StageInvalidInput.code(), -32011);
396 assert_eq!(ErrorCode::StageNoFiles.code(), -32012);
397 assert_eq!(ErrorCode::StageOverCap.code(), -32013);
398 assert_eq!(ErrorCode::StageCompileFailed.code(), -32014);
399 assert_eq!(ErrorCode::OnionCircuitUnavailable.code(), -32020);
400 assert_eq!(ErrorCode::PrivacyRequiresLocalNode.code(), -32021);
401 assert_eq!(ErrorCode::OnionHopsOutOfRange.code(), -32022);
402 assert_eq!(ErrorCode::Unauthorized.code(), -32030);
403 assert_eq!(ErrorCode::NotSupported.code(), -32031);
404 assert_eq!(ErrorCode::ControlError.code(), -32032);
405 }
406
407 /// **Proves:** the onion codes keep `-32020..-32022` and the control codes
408 /// are renumbered clear of them.
409 /// **Catches:** a regression that reintroduces the historical collision.
410 #[test]
411 fn onion_control_collision_resolved() {
412 assert_eq!(ErrorCode::OnionCircuitUnavailable.code(), -32020);
413 assert_eq!(ErrorCode::Unauthorized.code(), -32030);
414 assert_ne!(
415 ErrorCode::OnionCircuitUnavailable.code(),
416 ErrorCode::Unauthorized.code()
417 );
418 }
419
420 /// **Proves:** a code serializes as a bare integer, never a tagged object.
421 /// **Catches:** a swap of `Serialize_repr` for plain `Serialize`.
422 #[test]
423 fn code_serialises_as_integer() {
424 assert_eq!(
425 serde_json::to_string(&ErrorCode::MethodNotFound).unwrap(),
426 "-32601"
427 );
428 assert_eq!(
429 serde_json::to_string(&ErrorCode::ContentRedirect).unwrap(),
430 "-32008"
431 );
432 }
433
434 /// **Proves:** `ALL` lists exactly the distinct codes, with unique numbers
435 /// and unique machine strings.
436 /// **Catches:** a new variant left out of `ALL`, or a duplicated
437 /// code/machine string.
438 #[test]
439 fn all_codes_unique_and_complete() {
440 use std::collections::HashSet;
441 let nums: HashSet<i32> = ErrorCode::ALL.iter().map(|c| c.code()).collect();
442 let strs: HashSet<&str> = ErrorCode::ALL.iter().map(|c| c.machine_code()).collect();
443 assert_eq!(nums.len(), ErrorCode::ALL.len(), "duplicate numeric code");
444 assert_eq!(strs.len(), ErrorCode::ALL.len(), "duplicate machine code");
445 assert_eq!(ErrorCode::ALL.len(), 24);
446 }
447
448 /// **Proves:** the constructor mints the full `{code, message, data:{code,
449 /// origin}}` envelope and `data.code` mirrors the numeric code.
450 /// **Catches:** a drift between the numeric code and `data.code`.
451 #[test]
452 fn envelope_shape_and_data_code() {
453 let e = RpcError::new(
454 ErrorCode::ResourceUnavailable,
455 "not here",
456 ErrorOrigin::Node,
457 );
458 let v = serde_json::to_value(&e).unwrap();
459 assert_eq!(v["code"], -32004);
460 assert_eq!(v["message"], "not here");
461 assert_eq!(v["data"]["code"], "RESOURCE_UNAVAILABLE");
462 assert_eq!(v["data"]["origin"], "node");
463 // Round-trips.
464 let back: RpcError = serde_json::from_value(v).unwrap();
465 assert_eq!(back, e);
466 }
467
468 /// **Proves:** `UpstreamError` defaults to the `upstream` origin.
469 #[test]
470 fn upstream_default_origin() {
471 let e = RpcError::of(ErrorCode::UpstreamError, "upstream: boom");
472 assert_eq!(e.data.origin, ErrorOrigin::Upstream);
473 assert_eq!(
474 serde_json::to_value(&e).unwrap()["data"]["origin"],
475 "upstream"
476 );
477 }
478
479 /// **Proves:** `code_only` uses the default message + origin.
480 #[test]
481 fn code_only_defaults() {
482 let e = RpcError::code_only(ErrorCode::PeerUnreachable);
483 assert_eq!(e.message, "Peer unreachable");
484 assert_eq!(e.data.origin, ErrorOrigin::Peer);
485 }
486}