use std::collections::BTreeSet;
use std::fmt::{Display, Formatter};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DispatchError {
Unauthorized(String),
Forbidden {
required: BTreeSet<String>,
granted: BTreeSet<String>,
},
ForbiddenPrincipalKind {
allowed: BTreeSet<String>,
},
RateLimited {
scope: String,
retry_after_ms: u64,
},
BudgetExceeded {
category: String,
message: String,
},
Validation(String),
MissingExport(String),
Cancelled(String),
Execution(String),
Io(String),
Cache(String),
}
impl DispatchError {
pub fn message(&self) -> String {
match self {
Self::Unauthorized(message)
| Self::Validation(message)
| Self::MissingExport(message)
| Self::Cancelled(message)
| Self::Execution(message)
| Self::Io(message)
| Self::Cache(message) => message.clone(),
Self::Forbidden { required, granted } => forbidden_message(required, granted),
Self::ForbiddenPrincipalKind { allowed } => forbidden_principal_kind_message(allowed),
Self::RateLimited {
scope,
retry_after_ms,
} => format!("rate limit exceeded ({scope}); retry after {retry_after_ms} ms"),
Self::BudgetExceeded { category, message } => {
format!("budget exceeded ({category}): {message}")
}
}
}
}
pub fn forbidden_message(required: &BTreeSet<String>, granted: &BTreeSet<String>) -> String {
let missing: Vec<&str> = required.difference(granted).map(String::as_str).collect();
if missing.is_empty() {
"missing required scope".to_string()
} else {
format!("missing required scope(s): {}", missing.join(", "))
}
}
pub fn forbidden_principal_kind_message(allowed: &BTreeSet<String>) -> String {
if allowed.is_empty() {
"principal kind not permitted for this route".to_string()
} else {
let allowed: Vec<&str> = allowed.iter().map(String::as_str).collect();
format!(
"principal kind not permitted for this route; allowed: {}",
allowed.join(", ")
)
}
}
pub fn forbidden_data_payload(
required: &BTreeSet<String>,
granted: &BTreeSet<String>,
) -> serde_json::Value {
let missing: Vec<&str> = required.difference(granted).map(String::as_str).collect();
serde_json::json!({
"kind": "forbidden",
"required_scopes": required.iter().collect::<Vec<_>>(),
"granted_scopes": granted.iter().collect::<Vec<_>>(),
"missing_scopes": missing,
})
}
impl Display for DispatchError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message())
}
}
impl std::error::Error for DispatchError {}