1use serde_json::{Map, Value};
18
19use crate::remote_error::{DenyReason, OtherError, ParamProblem, RemoteError};
20
21pub 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 "-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 _ => DenyReason::MissingGrant { grant: s("grant"), scope: s("scope"), roles: strings("roles"), held_on: strings("held_on") },
44 },
45 },
46 "too_many_calls" => RemoteError::TooManyCalls {
47 max: o.get("max").and_then(Value::as_u64).unwrap_or_default(),
48 child: o.get("child").and_then(Value::as_str).map(str::to_string),
49 },
50 "child_unavailable" => RemoteError::ChildUnavailable { child: s("child"), reason: s("reason") },
51 "child_timeout" => RemoteError::ChildTimeout {
52 child: s("child"),
53 timeout_ms: o.get("timeout_ms").and_then(Value::as_u64).unwrap_or_default(),
54 },
55 other if o.contains_key("error_kind") => {
58 let mut fields = o.clone();
59 fields.remove("error_kind");
60 for k in ["type", "metadata", "code", "recoverable"] {
61 fields.remove(k);
62 }
63 RemoteError::Other(OtherError { kind: other.to_string(), fields })
64 }
65 _ => RemoteError::Execution { message },
66 }
67}
68
69fn not_found(message: &str) -> RemoteError {
72 if let Some(activation) = message.strip_prefix("Activation not found: ") {
73 return RemoteError::ActivationNotFound { activation: activation.trim().to_string() };
74 }
75 let path = message.strip_prefix("Method not found: ").unwrap_or_default().trim();
76 let (activation, method) = path.rsplit_once('.').unwrap_or(("", path));
77 RemoteError::MethodNotFound { activation: activation.to_string(), method: method.to_string() }
78}
79
80pub fn item(v: &Value) -> Option<Value> {
84 let mut v = v.clone();
85 let o = v.as_object_mut()?;
86 match o.get("type").and_then(Value::as_str)? {
87 "progress" if !o.contains_key("content") => {
88 let mut note = Map::new();
89 note.insert("message".into(), o.remove("message").unwrap_or(Value::from("")));
90 if let Some(p) = o.remove("percentage").filter(|p| !p.is_null()) {
91 note.insert("percentage".into(), p);
92 }
93 o.insert("content".into(), Value::Object(note));
94 }
95 "error" if !o.contains_key("error") => {
96 let error = remote_error(o);
97 o.insert("error".into(), serde_json::to_value(error).ok()?);
98 }
99 _ => return None,
100 }
101 Some(v)
102}
103
104#[cfg(test)]
105mod tests {
106 use super::*;
107 use crate::envelope::StreamItem;
108 use serde_json::json;
109
110 #[test]
111 fn a_main_wire_error_and_progress_read_as_0_8() {
112 let e = item(&json!({"type": "error", "message": "needs a.b", "code": "-32003", "error_kind": "forbidden",
113 "grant": "a.b", "scope": "*", "roles": ["admin"], "held_on": [], "recoverable": false}))
114 .unwrap();
115 let StreamItem::Error { error, .. } = serde_json::from_value(e).unwrap() else { panic!() };
116 assert_eq!(error.kind(), "forbidden");
117 let p = item(&json!({"type": "progress", "message": "half", "percentage": 50.0})).unwrap();
118 assert_eq!(p["content"], json!({"message": "half", "percentage": 50.0}));
119 assert!(serde_json::from_value::<StreamItem>(p).is_ok());
120 }
121
122 #[test]
123 fn a_0_8_frame_is_never_rewritten() {
124 assert!(item(&json!({"type": "error", "error": {"kind": "unauthenticated"}})).is_none());
125 assert!(item(&json!({"type": "progress", "content": 1})).is_none());
126 assert!(item(&json!({"type": "data", "content": 1})).is_none());
127 }
128}