use std::fmt::{self, Write as _};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum RemoteError {
ActivationNotFound { activation: String },
MethodNotFound { activation: String, method: String },
InvalidParams {
#[serde(default, skip_serializing_if = "Option::is_none")]
param: Option<String>,
#[serde(flatten)]
problem: ParamProblem,
},
Unauthenticated,
Forbidden {
#[serde(flatten)]
reason: DenyReason,
},
HandleNotSupported { activation: String },
Execution { message: String },
TooManyCalls {
max: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
child: Option<String>,
},
ChildUnavailable { child: String, reason: String },
ChildTimeout { child: String, timeout_ms: u64 },
#[serde(untagged)]
Other(OtherError),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct OtherError {
pub kind: String,
#[serde(flatten)]
pub fields: serde_json::Map<String, serde_json::Value>,
}
const KNOWN_KINDS: &[&str] = &[
"activation_not_found",
"method_not_found",
"invalid_params",
"unauthenticated",
"forbidden",
"handle_not_supported",
"execution",
"too_many_calls",
"child_unavailable",
"child_timeout",
];
impl<'de> Deserialize<'de> for OtherError {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let mut fields = serde_json::Map::<String, serde_json::Value>::deserialize(d)?;
let kind = match fields.remove("kind") {
Some(serde_json::Value::String(k)) => k,
_ => return Err(serde::de::Error::missing_field("kind")),
};
if KNOWN_KINDS.contains(&kind.as_str()) {
return Err(serde::de::Error::custom(format!("a `{kind}` error that does not fit its fields")));
}
Ok(OtherError { kind, fields })
}
}
#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(
feature = "schema",
schemars(rename = "KnownRemoteError", description = "A call failure of a kind this vocabulary knows.")
)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum Known {
ActivationNotFound { activation: String },
MethodNotFound { activation: String, method: String },
InvalidParams {
#[serde(default)]
param: Option<String>,
#[serde(flatten)]
problem: ParamProblem,
},
Unauthenticated,
Forbidden {
#[serde(flatten)]
reason: DenyReason,
},
HandleNotSupported { activation: String },
Execution { message: String },
TooManyCalls {
max: u64,
#[serde(default)]
child: Option<String>,
},
ChildUnavailable { child: String, reason: String },
ChildTimeout { child: String, timeout_ms: u64 },
}
impl From<Known> for RemoteError {
fn from(k: Known) -> Self {
match k {
Known::ActivationNotFound { activation } => RemoteError::ActivationNotFound { activation },
Known::MethodNotFound { activation, method } => RemoteError::MethodNotFound { activation, method },
Known::InvalidParams { param, problem } => RemoteError::InvalidParams { param, problem },
Known::Unauthenticated => RemoteError::Unauthenticated,
Known::Forbidden { reason } => RemoteError::Forbidden { reason },
Known::HandleNotSupported { activation } => RemoteError::HandleNotSupported { activation },
Known::Execution { message } => RemoteError::Execution { message },
Known::TooManyCalls { max, child } => RemoteError::TooManyCalls { max, child },
Known::ChildUnavailable { child, reason } => RemoteError::ChildUnavailable { child, reason },
Known::ChildTimeout { child, timeout_ms } => RemoteError::ChildTimeout { child, timeout_ms },
}
}
}
impl<'de> Deserialize<'de> for RemoteError {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
use serde::de::Error as _;
let v = serde_json::Value::deserialize(d)?;
let known = match v.get("kind") {
Some(serde_json::Value::String(k)) => KNOWN_KINDS.contains(&k.as_str()),
_ => return Err(D::Error::missing_field("kind")),
};
if known {
Known::deserialize(v).map(RemoteError::from).map_err(D::Error::custom)
} else {
OtherError::deserialize(v).map(RemoteError::Other).map_err(D::Error::custom)
}
}
}
impl std::hash::Hash for OtherError {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.kind.hash(state);
serde_json::to_string(&self.fields).unwrap_or_default().hash(state);
}
}
#[cfg(feature = "schema")]
impl schemars::JsonSchema for OtherError {
fn schema_name() -> std::borrow::Cow<'static, str> {
"OtherError".into()
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"description": "A kind this build does not know: its `kind`, and any other fields beside it, kept as they came.",
"type": "object",
"properties": { "kind": { "type": "string" } },
"required": ["kind"]
})
}
}
#[cfg(feature = "schema")]
impl schemars::JsonSchema for RemoteError {
fn schema_name() -> std::borrow::Cow<'static, str> {
"RemoteError".into()
}
fn schema_id() -> std::borrow::Cow<'static, str> {
concat!(module_path!(), "::RemoteError").into()
}
fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
let known = generator.subschema_for::<Known>();
let other = generator.subschema_for::<OtherError>();
schemars::json_schema!({
"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.",
"anyOf": [known, other]
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "problem", rename_all = "snake_case")]
pub enum ParamProblem {
Missing,
Malformed { detail: String },
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "reason", rename_all = "snake_case")]
pub enum DenyReason {
MissingScope { scope: String },
TenantBoundary,
NotAccepted,
MissingGrant {
grant: String,
scope: String,
#[serde(default)]
roles: Vec<String>,
#[serde(default)]
held_on: Vec<String>,
},
#[cfg_attr(feature = "schema", schemars(skip))]
NotNeeded {
method: String,
},
}
impl RemoteError {
pub fn kind(&self) -> &str {
match self {
RemoteError::Other(other) => &other.kind,
RemoteError::ActivationNotFound { .. } => "activation_not_found",
RemoteError::MethodNotFound { .. } => "method_not_found",
RemoteError::InvalidParams { .. } => "invalid_params",
RemoteError::Unauthenticated => "unauthenticated",
RemoteError::Forbidden { .. } => "forbidden",
RemoteError::HandleNotSupported { .. } => "handle_not_supported",
RemoteError::Execution { .. } => "execution",
RemoteError::TooManyCalls { .. } => "too_many_calls",
RemoteError::ChildUnavailable { .. } => "child_unavailable",
RemoteError::ChildTimeout { .. } => "child_timeout",
}
}
}
fn one_line(f: &mut fmt::Formatter<'_>, s: &str) -> fmt::Result {
for c in s.chars() {
f.write_char(if matches!(c, '\n' | '\r') { ' ' } else { c })?;
}
Ok(())
}
impl fmt::Display for RemoteError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RemoteError::ActivationNotFound { activation } => {
f.write_str("activation not found: ")?;
one_line(f, activation)
}
RemoteError::MethodNotFound { activation, method } => {
f.write_str("method not found: ")?;
one_line(f, activation)?;
f.write_char('.')?;
one_line(f, method)
}
RemoteError::InvalidParams { param, problem } => {
f.write_str("invalid params: ")?;
match (problem, param) {
(ParamProblem::Missing, Some(p)) => {
f.write_str("missing `")?;
one_line(f, p)?;
f.write_char('`')
}
(ParamProblem::Missing, None) => f.write_str("a required parameter is missing"),
(ParamProblem::Malformed { detail }, Some(p)) => {
f.write_str("malformed `")?;
one_line(f, p)?;
f.write_str("`: ")?;
one_line(f, detail)
}
(ParamProblem::Malformed { detail }, None) => {
f.write_str("malformed: ")?;
one_line(f, detail)
}
}
}
RemoteError::Unauthenticated => f.write_str("unauthenticated: credentials required"),
RemoteError::Forbidden { reason } => {
f.write_str("forbidden: ")?;
match reason {
DenyReason::MissingScope { scope } => {
f.write_str("missing required scope `")?;
one_line(f, scope)?;
f.write_char('`')
}
DenyReason::TenantBoundary => f.write_str("tenant boundary"),
DenyReason::NotAccepted => f.write_str("call not accepted"),
DenyReason::NotNeeded { method } => {
f.write_char('`')?;
one_line(f, method)?;
f.write_str("` is not among the methods this child needs")
}
DenyReason::MissingGrant { grant, scope, .. } => {
f.write_str("needs `")?;
one_line(f, grant)?;
f.write_char('`')?;
if scope != "*" {
f.write_str(" on `")?;
one_line(f, scope)?;
f.write_char('`')?;
}
Ok(())
}
}
}
RemoteError::HandleNotSupported { activation } => {
f.write_str("handle resolution not supported by activation: ")?;
one_line(f, activation)
}
RemoteError::Execution { message } => {
f.write_str("execution failed: ")?;
one_line(f, message)
}
RemoteError::TooManyCalls { max, child } => {
f.write_str("too many calls open")?;
if let Some(child) = child {
f.write_str(" on child ")?;
one_line(f, child)?;
}
write!(f, " (at most {max}): close one, or call again later")
}
RemoteError::ChildUnavailable { child, reason } => {
f.write_str("child ")?;
one_line(f, child)?;
f.write_str(" is unavailable: ")?;
one_line(f, reason)
}
RemoteError::ChildTimeout { child, timeout_ms } => {
f.write_str("child ")?;
one_line(f, child)?;
write!(f, " did not open the call in {timeout_ms} ms")
}
RemoteError::Other(other) => {
one_line(f, &other.kind)?;
if let Some(message) = other.fields.get("message").and_then(|m| m.as_str()) {
f.write_str(": ")?;
one_line(f, message)?;
}
Ok(())
}
}
}
}
impl std::error::Error for RemoteError {}