Skip to main content

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}
350
351impl RemoteError {
352    /// The variant's `kind` tag, as on the wire (`"method_not_found"`, …) —
353    /// for a log line or an exit code; match on the variant to handle it.
354    pub fn kind(&self) -> &str {
355        match self {
356            RemoteError::Other(other) => &other.kind,
357            RemoteError::ActivationNotFound { .. } => "activation_not_found",
358            RemoteError::MethodNotFound { .. } => "method_not_found",
359            RemoteError::InvalidParams { .. } => "invalid_params",
360            RemoteError::Unauthenticated => "unauthenticated",
361            RemoteError::Forbidden { .. } => "forbidden",
362            RemoteError::HandleNotSupported { .. } => "handle_not_supported",
363            RemoteError::Execution { .. } => "execution",
364            RemoteError::TooManyCalls { .. } => "too_many_calls",
365            RemoteError::ChildUnavailable { .. } => "child_unavailable",
366            RemoteError::ChildTimeout { .. } => "child_timeout",
367        }
368    }
369}
370
371/// Writes `s` with every line break folded to a space, so the line a CLI
372/// prints stays one line whatever the server put in a free-text field.
373fn one_line(f: &mut fmt::Formatter<'_>, s: &str) -> fmt::Result {
374    for c in s.chars() {
375        f.write_char(if matches!(c, '\n' | '\r') { ' ' } else { c })?;
376    }
377    Ok(())
378}
379
380impl fmt::Display for RemoteError {
381    /// One line, for a human — what a CLI prints.
382    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383        match self {
384            RemoteError::ActivationNotFound { activation } => {
385                f.write_str("activation not found: ")?;
386                one_line(f, activation)
387            }
388            RemoteError::MethodNotFound { activation, method } => {
389                f.write_str("method not found: ")?;
390                one_line(f, activation)?;
391                f.write_char('.')?;
392                one_line(f, method)
393            }
394            RemoteError::InvalidParams { param, problem } => {
395                f.write_str("invalid params: ")?;
396                match (problem, param) {
397                    (ParamProblem::Missing, Some(p)) => {
398                        f.write_str("missing `")?;
399                        one_line(f, p)?;
400                        f.write_char('`')
401                    }
402                    (ParamProblem::Missing, None) => f.write_str("a required parameter is missing"),
403                    (ParamProblem::Malformed { detail }, Some(p)) => {
404                        f.write_str("malformed `")?;
405                        one_line(f, p)?;
406                        f.write_str("`: ")?;
407                        one_line(f, detail)
408                    }
409                    (ParamProblem::Malformed { detail }, None) => {
410                        f.write_str("malformed: ")?;
411                        one_line(f, detail)
412                    }
413                }
414            }
415            RemoteError::Unauthenticated => f.write_str("unauthenticated: credentials required"),
416            RemoteError::Forbidden { reason } => {
417                f.write_str("forbidden: ")?;
418                match reason {
419                    DenyReason::MissingScope { scope } => {
420                        f.write_str("missing required scope `")?;
421                        one_line(f, scope)?;
422                        f.write_char('`')
423                    }
424                    DenyReason::TenantBoundary => f.write_str("tenant boundary"),
425                    DenyReason::NotAccepted => f.write_str("call not accepted"),
426                    DenyReason::MissingGrant { grant, scope, .. } => {
427                        f.write_str("needs `")?;
428                        one_line(f, grant)?;
429                        f.write_char('`')?;
430                        if scope != "*" {
431                            f.write_str(" on `")?;
432                            one_line(f, scope)?;
433                            f.write_char('`')?;
434                        }
435                        Ok(())
436                    }
437                }
438            }
439            RemoteError::HandleNotSupported { activation } => {
440                f.write_str("handle resolution not supported by activation: ")?;
441                one_line(f, activation)
442            }
443            RemoteError::Execution { message } => {
444                f.write_str("execution failed: ")?;
445                one_line(f, message)
446            }
447            RemoteError::TooManyCalls { max, child } => {
448                f.write_str("too many calls open")?;
449                if let Some(child) = child {
450                    f.write_str(" on child ")?;
451                    one_line(f, child)?;
452                }
453                write!(f, " (at most {max}): close one, or call again later")
454            }
455            RemoteError::ChildUnavailable { child, reason } => {
456                f.write_str("child ")?;
457                one_line(f, child)?;
458                f.write_str(" is unavailable: ")?;
459                one_line(f, reason)
460            }
461            RemoteError::ChildTimeout { child, timeout_ms } => {
462                f.write_str("child ")?;
463                one_line(f, child)?;
464                write!(f, " did not open the call in {timeout_ms} ms")
465            }
466            RemoteError::Other(other) => {
467                one_line(f, &other.kind)?;
468                if let Some(message) = other.fields.get("message").and_then(|m| m.as_str()) {
469                    f.write_str(": ")?;
470                    one_line(f, message)?;
471                }
472                Ok(())
473            }
474        }
475    }
476}
477
478impl std::error::Error for RemoteError {}