plexus_client/remote_error.rs
1//! The typed, exhaustive vocabulary of call failures.
2//!
3//! A call fails — as opposed to an activation saying no, which is an `err`
4//! item and therefore data — when the service could not or would not run it:
5//! no such activation or method, bad params, no credentials, not allowed,
6//! or the method itself blew up. The error frame carries exactly one
7//! [`RemoteError`], and so does the `data` of a JSON-RPC-level rejection.
8//!
9//! # Wire shape
10//!
11//! `kind`-tagged, `snake_case`. [`ParamProblem`] and [`DenyReason`] are
12//! flattened into their variant, each under the key its field is named for:
13//!
14//! ```json
15//! {"kind": "activation_not_found", "activation": "tickets"}
16//! {"kind": "method_not_found", "activation": "tickets", "method": "frob"}
17//! {"kind": "invalid_params", "param": "id", "problem": "missing"}
18//! {"kind": "invalid_params", "param": "id", "problem": "malformed", "detail": "expected a string"}
19//! {"kind": "unauthenticated"}
20//! {"kind": "forbidden", "reason": "missing_scope", "scope": "tickets:write"}
21//! {"kind": "forbidden", "reason": "tenant_boundary"}
22//! {"kind": "handle_not_supported", "activation": "tickets"}
23//! {"kind": "execution", "message": "database is locked"}
24//! {"kind": "forbidden", "reason": "missing_grant", "grant": "tickets.create", "scope": "*", "roles": ["editor", "admin"], "held_on": []}
25//! {"kind": "too_many_calls", "max": 8}
26//! {"kind": "child_unavailable", "child": "echo", "reason": "the connection has closed"}
27//! {"kind": "child_timeout", "child": "echo", "timeout_ms": 5000}
28//! ```
29//!
30//! The last four are main's refusals (AUTH-2's typed refusal, spec/05's
31//! `too_many_calls`, spec/12's `child_unavailable` and `child_timeout`),
32//! brought into this vocabulary by RETURNS-36: every error frame a server
33//! sends carries one `RemoteError`, beside spec/05's flattened
34//! `code` / `message` / `error_kind` fields.
35//!
36//! `param` is omitted when the failure is not about one parameter (and
37//! decodes as `None` when absent or `null`).
38//!
39//! # Open, typed
40//!
41//! A kind this build does not know — menger's `too_many_connections`, or
42//! `too_many_writes` with `retry_after_ms` — is [`RemoteError::Other`]: its
43//! `kind` and every other field kept, and written back exactly as it came
44//! (RETURNS-36, review #4). A known kind that does not fit its variant is
45//! still a decode error. The known variants stay exhaustive for a match;
46//! adding one means adding its `PlexusError` conversion in plexus-core and
47//! its mirrors in the Haskell protocol and the TS/Rust generators.
48
49use std::fmt::{self, Write as _};
50
51use serde::{Deserialize, Serialize};
52
53/// Why a call failed — what an error frame carries, and the `data` of a
54/// JSON-RPC-level rejection.
55///
56/// Its JSON Schema is written by hand (see the `JsonSchema` impl): the known
57/// kinds as one `kind`-tagged union, `KnownRemoteError`, and any other kind
58/// as [`OtherError`] — the two as an untagged union of references, a form
59/// synapse's IR reader takes (RETURNS-40), the wire unchanged.
60#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
61#[serde(tag = "kind", rename_all = "snake_case")]
62pub enum RemoteError {
63 /// The service has no activation by this name.
64 ActivationNotFound { activation: String },
65
66 /// The activation exists but has no method by this name.
67 MethodNotFound { activation: String, method: String },
68
69 /// The call's params did not fit the method.
70 InvalidParams {
71 /// The parameter at fault, when the failure is about one.
72 #[serde(default, skip_serializing_if = "Option::is_none")]
73 param: Option<String>,
74 /// What is wrong with it. Flattened: its `problem` tag sits beside
75 /// `param` on the wire.
76 #[serde(flatten)]
77 problem: ParamProblem,
78 },
79
80 /// The method requires credentials and the call carried none that
81 /// verified.
82 Unauthenticated,
83
84 /// The caller is authenticated but not allowed this call.
85 Forbidden {
86 /// Which check the caller failed. Flattened: its `reason` tag sits
87 /// beside `kind` on the wire.
88 #[serde(flatten)]
89 reason: DenyReason,
90 },
91
92 /// The activation does not resolve handles.
93 HandleNotSupported { activation: String },
94
95 /// The method ran and failed for a reason that is not the activation
96 /// saying no (that is an `err` item): a panic, a lost dependency.
97 Execution { message: String },
98
99 /// spec/05, 09: the connection — or the child the call was routed to —
100 /// holds its maximum of open calls; close one and call again.
101 TooManyCalls {
102 /// The most calls it holds open at once.
103 max: u64,
104 /// The child whose limit it is, when the limit is a child's.
105 #[serde(default, skip_serializing_if = "Option::is_none")]
106 child: Option<String>,
107 },
108
109 /// spec/12 rule 5: the child the call was routed to is not there.
110 ChildUnavailable { child: String, reason: String },
111
112 /// The child the call was routed to did not open it in the service's
113 /// time.
114 ChildTimeout { child: String, timeout_ms: u64 },
115
116 /// A kind this build does not know, kept whole: its `kind` and every
117 /// other field (RETURNS-36), written back as it came. Read only for a
118 /// kind no known variant has (see the `Deserialize` impl).
119 #[serde(untagged)]
120 Other(OtherError),
121}
122
123/// [`RemoteError::Other`]'s content: a kind this build does not know and
124/// its other fields, exactly as they came.
125#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
126pub struct OtherError {
127 /// The kind, as the server spelled it (`"too_many_writes"`).
128 pub kind: String,
129 /// Every other field (`retry_after_ms`, `message`, …).
130 #[serde(flatten)]
131 pub fields: serde_json::Map<String, serde_json::Value>,
132}
133
134/// The kinds the known variants take: one of them that does not fit its
135/// variant is a decode error, never [`RemoteError::Other`].
136const KNOWN_KINDS: &[&str] = &[
137 "activation_not_found",
138 "method_not_found",
139 "invalid_params",
140 "unauthenticated",
141 "forbidden",
142 "handle_not_supported",
143 "execution",
144 "too_many_calls",
145 "child_unavailable",
146 "child_timeout",
147];
148
149impl<'de> Deserialize<'de> for OtherError {
150 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
151 let mut fields = serde_json::Map::<String, serde_json::Value>::deserialize(d)?;
152 let kind = match fields.remove("kind") {
153 Some(serde_json::Value::String(k)) => k,
154 _ => return Err(serde::de::Error::missing_field("kind")),
155 };
156 if KNOWN_KINDS.contains(&kind.as_str()) {
157 return Err(serde::de::Error::custom(format!("a `{kind}` error that does not fit its fields")));
158 }
159 Ok(OtherError { kind, fields })
160 }
161}
162
163/// The known variants, as the wire reads them — the derive the public enum
164/// cannot have, since an unknown kind must read as [`RemoteError::Other`]
165/// while a known kind that does not fit stays a decode error naming why.
166///
167/// Its schema is [`RemoteError`]'s known half, `KnownRemoteError`: a
168/// `kind`-tagged union every member of which gives `kind` a const.
169#[derive(Deserialize)]
170#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
171#[cfg_attr(
172 feature = "schema",
173 schemars(rename = "KnownRemoteError", description = "A call failure of a kind this vocabulary knows.")
174)]
175#[serde(tag = "kind", rename_all = "snake_case")]
176enum Known {
177 /// The service has no activation by this name.
178 ActivationNotFound { activation: String },
179 /// The activation exists but has no method by this name.
180 MethodNotFound { activation: String, method: String },
181 /// The call's params did not fit the method.
182 InvalidParams {
183 /// The parameter at fault, when the failure is about one.
184 #[serde(default)]
185 param: Option<String>,
186 /// What is wrong with it. Flattened: its `problem` tag sits beside
187 /// `param` on the wire.
188 #[serde(flatten)]
189 problem: ParamProblem,
190 },
191 /// The method requires credentials and the call carried none that
192 /// verified.
193 Unauthenticated,
194 /// The caller is authenticated but not allowed this call.
195 Forbidden {
196 /// Which check the caller failed. Flattened: its `reason` tag sits
197 /// beside `kind` on the wire.
198 #[serde(flatten)]
199 reason: DenyReason,
200 },
201 /// The activation does not resolve handles.
202 HandleNotSupported { activation: String },
203 /// The method ran and failed for a reason that is not the activation
204 /// saying no (that is an `err` item): a panic, a lost dependency.
205 Execution { message: String },
206 /// spec/05, 09: the connection — or the child the call was routed to —
207 /// holds its maximum of open calls; close one and call again.
208 TooManyCalls {
209 /// The most calls it holds open at once.
210 max: u64,
211 /// The child whose limit it is, when the limit is a child's.
212 #[serde(default)]
213 child: Option<String>,
214 },
215 /// spec/12 rule 5: the child the call was routed to is not there.
216 ChildUnavailable { child: String, reason: String },
217 /// The child the call was routed to did not open it in the service's
218 /// time.
219 ChildTimeout { child: String, timeout_ms: u64 },
220}
221
222impl From<Known> for RemoteError {
223 fn from(k: Known) -> Self {
224 match k {
225 Known::ActivationNotFound { activation } => RemoteError::ActivationNotFound { activation },
226 Known::MethodNotFound { activation, method } => RemoteError::MethodNotFound { activation, method },
227 Known::InvalidParams { param, problem } => RemoteError::InvalidParams { param, problem },
228 Known::Unauthenticated => RemoteError::Unauthenticated,
229 Known::Forbidden { reason } => RemoteError::Forbidden { reason },
230 Known::HandleNotSupported { activation } => RemoteError::HandleNotSupported { activation },
231 Known::Execution { message } => RemoteError::Execution { message },
232 Known::TooManyCalls { max, child } => RemoteError::TooManyCalls { max, child },
233 Known::ChildUnavailable { child, reason } => RemoteError::ChildUnavailable { child, reason },
234 Known::ChildTimeout { child, timeout_ms } => RemoteError::ChildTimeout { child, timeout_ms },
235 }
236 }
237}
238
239impl<'de> Deserialize<'de> for RemoteError {
240 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
241 use serde::de::Error as _;
242 let v = serde_json::Value::deserialize(d)?;
243 let known = match v.get("kind") {
244 Some(serde_json::Value::String(k)) => KNOWN_KINDS.contains(&k.as_str()),
245 _ => return Err(D::Error::missing_field("kind")),
246 };
247 if known {
248 Known::deserialize(v).map(RemoteError::from).map_err(D::Error::custom)
249 } else {
250 OtherError::deserialize(v).map(RemoteError::Other).map_err(D::Error::custom)
251 }
252 }
253}
254
255impl std::hash::Hash for OtherError {
256 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
257 self.kind.hash(state);
258 serde_json::to_string(&self.fields).unwrap_or_default().hash(state);
259 }
260}
261
262#[cfg(feature = "schema")]
263impl schemars::JsonSchema for OtherError {
264 fn schema_name() -> std::borrow::Cow<'static, str> {
265 "OtherError".into()
266 }
267
268 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
269 // No `additionalProperties`: JSON Schema's default lets the other
270 // fields through, and synapse's IR reader has no form for a map
271 // beside properties (RETURNS-40) — so it reads as a struct of `kind`.
272 schemars::json_schema!({
273 "description": "A kind this build does not know: its `kind`, and any other fields beside it, kept as they came.",
274 "type": "object",
275 "properties": { "kind": { "type": "string" } },
276 "required": ["kind"]
277 })
278 }
279}
280
281/// The known kinds (`KnownRemoteError`) or any other ([`OtherError`]), as an
282/// untagged union of the two references — what synapse's IR reader takes
283/// for an open union (RETURNS-40); a tagged union cannot hold a member whose
284/// `kind` is no const. The wire is [`RemoteError`]'s serde, unchanged.
285#[cfg(feature = "schema")]
286impl schemars::JsonSchema for RemoteError {
287 fn schema_name() -> std::borrow::Cow<'static, str> {
288 "RemoteError".into()
289 }
290
291 fn schema_id() -> std::borrow::Cow<'static, str> {
292 concat!(module_path!(), "::RemoteError").into()
293 }
294
295 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
296 let known = generator.subschema_for::<Known>();
297 let other = generator.subschema_for::<OtherError>();
298 schemars::json_schema!({
299 "description": "Why a call failed — what an error frame carries, and the `data` of a JSON-RPC-level rejection: a kind this vocabulary knows, or another kept whole.",
300 "anyOf": [known, other]
301 })
302 }
303}
304
305/// What is wrong with a call's params. Flattened into
306/// [`RemoteError::InvalidParams`] under the `problem` key.
307#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
308#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
309#[serde(tag = "problem", rename_all = "snake_case")]
310pub enum ParamProblem {
311 /// A required parameter was not supplied.
312 Missing,
313 /// A parameter was supplied but did not decode; `detail` says how.
314 Malformed { detail: String },
315}
316
317/// Why an authenticated caller was refused. Flattened into
318/// [`RemoteError::Forbidden`] under the `reason` key.
319///
320/// Each variant carries at most the single fact the caller already failed
321/// (AUTHZ-CORE-1/5, rendered per AUTHZ-PRIVACY-4): the first unmet scope,
322/// never the method's full requirement set or the registry's taxonomy.
323#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
324#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
325#[serde(tag = "reason", rename_all = "snake_case")]
326pub enum DenyReason {
327 /// The caller's scopes do not include `scope` — the first unmet one.
328 MissingScope { scope: String },
329 /// The call reaches across the caller's tenant boundary.
330 TenantBoundary,
331 /// The call was not accepted in the caller's action context.
332 NotAccepted,
333 /// AUTH-2: the grant gate's refusal — the caller does not hold `grant`
334 /// on `scope`. Names what was needed and where the caller does hold it
335 /// (owner, 2026-10-10: "return the grants required to hit an
336 /// endpoint").
337 MissingGrant {
338 /// The method's grant, `<activation>.<method>`.
339 grant: String,
340 /// Where it was needed: the target's innermost scope, or `*`.
341 scope: String,
342 /// The roles that list the grant, `admin` last.
343 #[serde(default)]
344 roles: Vec<String>,
345 /// Where the caller holds it.
346 #[serde(default)]
347 held_on: Vec<String>,
348 },
349 /// NEST-16: a child called its service for `method`, which is neither
350 /// the standard upward interface (`host.schema`, `host.whoami`,
351 /// `host.log`, `host.notify`) nor one of the methods its schema says it
352 /// `needs`. Not in the JSON Schema (`schemars(skip)`): it would move
353 /// the hash of every service's `call`, whose items carry this type.
354 #[cfg_attr(feature = "schema", schemars(skip))]
355 NotNeeded {
356 /// The method the child called.
357 method: String,
358 },
359}
360
361impl RemoteError {
362 /// The variant's `kind` tag, as on the wire (`"method_not_found"`, …) —
363 /// for a log line or an exit code; match on the variant to handle it.
364 pub fn kind(&self) -> &str {
365 match self {
366 RemoteError::Other(other) => &other.kind,
367 RemoteError::ActivationNotFound { .. } => "activation_not_found",
368 RemoteError::MethodNotFound { .. } => "method_not_found",
369 RemoteError::InvalidParams { .. } => "invalid_params",
370 RemoteError::Unauthenticated => "unauthenticated",
371 RemoteError::Forbidden { .. } => "forbidden",
372 RemoteError::HandleNotSupported { .. } => "handle_not_supported",
373 RemoteError::Execution { .. } => "execution",
374 RemoteError::TooManyCalls { .. } => "too_many_calls",
375 RemoteError::ChildUnavailable { .. } => "child_unavailable",
376 RemoteError::ChildTimeout { .. } => "child_timeout",
377 }
378 }
379}
380
381/// Writes `s` with every line break folded to a space, so the line a CLI
382/// prints stays one line whatever the server put in a free-text field.
383fn one_line(f: &mut fmt::Formatter<'_>, s: &str) -> fmt::Result {
384 for c in s.chars() {
385 f.write_char(if matches!(c, '\n' | '\r') { ' ' } else { c })?;
386 }
387 Ok(())
388}
389
390impl fmt::Display for RemoteError {
391 /// One line, for a human — what a CLI prints.
392 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393 match self {
394 RemoteError::ActivationNotFound { activation } => {
395 f.write_str("activation not found: ")?;
396 one_line(f, activation)
397 }
398 RemoteError::MethodNotFound { activation, method } => {
399 f.write_str("method not found: ")?;
400 one_line(f, activation)?;
401 f.write_char('.')?;
402 one_line(f, method)
403 }
404 RemoteError::InvalidParams { param, problem } => {
405 f.write_str("invalid params: ")?;
406 match (problem, param) {
407 (ParamProblem::Missing, Some(p)) => {
408 f.write_str("missing `")?;
409 one_line(f, p)?;
410 f.write_char('`')
411 }
412 (ParamProblem::Missing, None) => f.write_str("a required parameter is missing"),
413 (ParamProblem::Malformed { detail }, Some(p)) => {
414 f.write_str("malformed `")?;
415 one_line(f, p)?;
416 f.write_str("`: ")?;
417 one_line(f, detail)
418 }
419 (ParamProblem::Malformed { detail }, None) => {
420 f.write_str("malformed: ")?;
421 one_line(f, detail)
422 }
423 }
424 }
425 RemoteError::Unauthenticated => f.write_str("unauthenticated: credentials required"),
426 RemoteError::Forbidden { reason } => {
427 f.write_str("forbidden: ")?;
428 match reason {
429 DenyReason::MissingScope { scope } => {
430 f.write_str("missing required scope `")?;
431 one_line(f, scope)?;
432 f.write_char('`')
433 }
434 DenyReason::TenantBoundary => f.write_str("tenant boundary"),
435 DenyReason::NotAccepted => f.write_str("call not accepted"),
436 DenyReason::NotNeeded { method } => {
437 f.write_char('`')?;
438 one_line(f, method)?;
439 f.write_str("` is not among the methods this child needs")
440 }
441 DenyReason::MissingGrant { grant, scope, .. } => {
442 f.write_str("needs `")?;
443 one_line(f, grant)?;
444 f.write_char('`')?;
445 if scope != "*" {
446 f.write_str(" on `")?;
447 one_line(f, scope)?;
448 f.write_char('`')?;
449 }
450 Ok(())
451 }
452 }
453 }
454 RemoteError::HandleNotSupported { activation } => {
455 f.write_str("handle resolution not supported by activation: ")?;
456 one_line(f, activation)
457 }
458 RemoteError::Execution { message } => {
459 f.write_str("execution failed: ")?;
460 one_line(f, message)
461 }
462 RemoteError::TooManyCalls { max, child } => {
463 f.write_str("too many calls open")?;
464 if let Some(child) = child {
465 f.write_str(" on child ")?;
466 one_line(f, child)?;
467 }
468 write!(f, " (at most {max}): close one, or call again later")
469 }
470 RemoteError::ChildUnavailable { child, reason } => {
471 f.write_str("child ")?;
472 one_line(f, child)?;
473 f.write_str(" is unavailable: ")?;
474 one_line(f, reason)
475 }
476 RemoteError::ChildTimeout { child, timeout_ms } => {
477 f.write_str("child ")?;
478 one_line(f, child)?;
479 write!(f, " did not open the call in {timeout_ms} ms")
480 }
481 RemoteError::Other(other) => {
482 one_line(f, &other.kind)?;
483 if let Some(message) = other.fields.get("message").and_then(|m| m.as_str()) {
484 f.write_str(": ")?;
485 one_line(f, message)?;
486 }
487 Ok(())
488 }
489 }
490 }
491}
492
493impl std::error::Error for RemoteError {}