Skip to main content

plexus_client/
spec05.rs

1//! RETURNS-36 ยท a peer on plexus-wire's spec as main wrote it (spec/03, 05),
2//! read into 0.8's shapes โ€” one rule for the client and plexus-core's child
3//! seam (its `remote_child::peer`), never guessed from anything the peer did
4//! not say:
5//!
6//! - a progress frame without `content` is the default progress type, a
7//!   [`Note`](crate::Note): `{message, percentage}`;
8//! - an error frame without `error` is typed from its spec/05 fields
9//!   ([`remote_error`]): by `error_kind`, else by `code` โ€” `-32601` not
10//!   found, `-32602` invalid params, `-32001` unauthenticated, `-32003`
11//!   forbidden โ€” a kind this build does not know kept whole
12//!   ([`RemoteError::Other`]), and nothing named the method failing.
13//!
14//! A 0.8 frame is never rewritten: each rule fills only what the peer left
15//! out, and a reader asks only when a frame did not read as 0.8.
16
17use serde_json::{Map, Value};
18
19use crate::remote_error::{DenyReason, OtherError, ParamProblem, RemoteError};
20
21/// spec/05's error fields as the typed [`RemoteError`] they say.
22pub fn remote_error(o: &Map<String, Value>) -> RemoteError {
23    let s = |k: &str| o.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
24    let strings = |k: &str| -> Vec<String> {
25        o.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default()
26    };
27    let message = s("message");
28    let code = match o.get("code") {
29        Some(Value::String(c)) => c.clone(),
30        Some(other) => other.to_string(),
31        None => String::new(),
32    };
33    match o.get("error_kind").and_then(Value::as_str).unwrap_or(code.as_str()) {
34        // spec/05: activation or method not found (review #5).
35        "-32601" => not_found(&message),
36        "invalid_params" | "-32602" => RemoteError::InvalidParams { param: None, problem: ParamProblem::Malformed { detail: message } },
37        "unauthenticated" | "-32001" => RemoteError::Unauthenticated,
38        "forbidden" | "-32003" => RemoteError::Forbidden {
39            reason: match o.get("reason").and_then(Value::as_str) {
40                Some("missing_scope") => DenyReason::MissingScope { scope: s("scope") },
41                Some("tenant_boundary") => DenyReason::TenantBoundary,
42                Some("not_accepted") => DenyReason::NotAccepted,
43                Some("not_needed") => DenyReason::NotNeeded { method: s("method") },
44                _ => DenyReason::MissingGrant { grant: s("grant"), scope: s("scope"), roles: strings("roles"), held_on: strings("held_on") },
45            },
46        },
47        "too_many_calls" => RemoteError::TooManyCalls {
48            max: o.get("max").and_then(Value::as_u64).unwrap_or_default(),
49            child: o.get("child").and_then(Value::as_str).map(str::to_string),
50        },
51        "child_unavailable" => RemoteError::ChildUnavailable { child: s("child"), reason: s("reason") },
52        "child_timeout" => RemoteError::ChildTimeout {
53            child: s("child"),
54            timeout_ms: o.get("timeout_ms").and_then(Value::as_u64).unwrap_or_default(),
55        },
56        // A kind this build does not know, by its `error_kind`, keeps it and
57        // its fields (review #4); with no kind at all, the method failing.
58        other if o.contains_key("error_kind") => {
59            let mut fields = o.clone();
60            fields.remove("error_kind");
61            for k in ["type", "metadata", "code", "recoverable"] {
62                fields.remove(k);
63            }
64            RemoteError::Other(OtherError { kind: other.to_string(), fields })
65        }
66        _ => RemoteError::Execution { message },
67    }
68}
69
70/// `-32601`'s two meanings, from spec/05's message (`Activation not found:
71/// x`, `Method not found: a.b`); a bare one is a method not found.
72fn not_found(message: &str) -> RemoteError {
73    if let Some(activation) = message.strip_prefix("Activation not found: ") {
74        return RemoteError::ActivationNotFound { activation: activation.trim().to_string() };
75    }
76    let path = message.strip_prefix("Method not found: ").unwrap_or_default().trim();
77    let (activation, method) = path.rsplit_once('.').unwrap_or(("", path));
78    RemoteError::MethodNotFound { activation: activation.to_string(), method: method.to_string() }
79}
80
81/// A stream item that did not read as 0.8, in 0.8's shape: a progress frame
82/// without `content`, an error frame without `error`. `None` for anything
83/// else (it stays unreadable, as it was).
84pub fn item(v: &Value) -> Option<Value> {
85    let mut v = v.clone();
86    let o = v.as_object_mut()?;
87    match o.get("type").and_then(Value::as_str)? {
88        "progress" if !o.contains_key("content") => {
89            let mut note = Map::new();
90            note.insert("message".into(), o.remove("message").unwrap_or(Value::from("")));
91            if let Some(p) = o.remove("percentage").filter(|p| !p.is_null()) {
92                note.insert("percentage".into(), p);
93            }
94            o.insert("content".into(), Value::Object(note));
95        }
96        "error" if !o.contains_key("error") => {
97            let error = remote_error(o);
98            o.insert("error".into(), serde_json::to_value(error).ok()?);
99        }
100        _ => return None,
101    }
102    Some(v)
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108    use crate::envelope::StreamItem;
109    use serde_json::json;
110
111    #[test]
112    fn a_main_wire_error_and_progress_read_as_0_8() {
113        let e = item(&json!({"type": "error", "message": "needs a.b", "code": "-32003", "error_kind": "forbidden",
114                             "grant": "a.b", "scope": "*", "roles": ["admin"], "held_on": [], "recoverable": false}))
115        .unwrap();
116        let StreamItem::Error { error, .. } = serde_json::from_value(e).unwrap() else { panic!() };
117        assert_eq!(error.kind(), "forbidden");
118        let p = item(&json!({"type": "progress", "message": "half", "percentage": 50.0})).unwrap();
119        assert_eq!(p["content"], json!({"message": "half", "percentage": 50.0}));
120        assert!(serde_json::from_value::<StreamItem>(p).is_ok());
121    }
122
123    #[test]
124    fn a_0_8_frame_is_never_rewritten() {
125        assert!(item(&json!({"type": "error", "error": {"kind": "unauthenticated"}})).is_none());
126        assert!(item(&json!({"type": "progress", "content": 1})).is_none());
127        assert!(item(&json!({"type": "data", "content": 1})).is_none());
128    }
129}