1use serde_json::Value;
4use std::time::Duration;
5
6pub type Result<T> = std::result::Result<T, Error>;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum ErrorKind {
12 BadRequest,
14 Authentication,
16 PermissionDenied,
18 NotFound,
20 RateLimit,
22 EndpointNotSupported,
24 Internal,
26 Transport,
28 Timeout,
30 Serialization,
32 InvalidConfiguration,
34 Attestation,
36 OAuth,
38}
39
40#[derive(Debug, Clone)]
42pub struct ApiError {
43 pub status_code: u16,
45 pub message: String,
47 pub payload: Option<Value>,
49 pub retry_after: Option<Duration>,
51 pub layer: Option<String>,
53 pub source: Option<String>,
55 pub provider: Option<String>,
57 pub request_id: Option<String>,
59}
60
61impl std::fmt::Display for ApiError {
62 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 write!(formatter, "{}", self.message)
64 }
65}
66
67impl std::error::Error for ApiError {}
68
69#[derive(Debug, thiserror::Error)]
71pub enum Error {
72 #[error("{kind:?}: {error}")]
74 Api {
75 kind: ErrorKind,
77 error: Box<ApiError>,
79 },
80 #[error("TrustedRouter endpoint unavailable: {0}")]
82 Transport(String),
83 #[error("TrustedRouter request timed out: {0}")]
85 Timeout(String),
86 #[error("TrustedRouter JSON error: {0}")]
88 Serialization(String),
89 #[error("Invalid TrustedRouter configuration: {0}")]
91 InvalidConfiguration(String),
92 #[error("TrustedRouter attestation verification failed: {0}")]
94 Attestation(String),
95 #[error("TrustedRouter OAuth error: {0}")]
97 OAuth(String),
98}
99
100impl Error {
101 pub fn kind(&self) -> ErrorKind {
103 match self {
104 Self::Api { kind, .. } => *kind,
105 Self::Transport(_) => ErrorKind::Transport,
106 Self::Timeout(_) => ErrorKind::Timeout,
107 Self::Serialization(_) => ErrorKind::Serialization,
108 Self::InvalidConfiguration(_) => ErrorKind::InvalidConfiguration,
109 Self::Attestation(_) => ErrorKind::Attestation,
110 Self::OAuth(_) => ErrorKind::OAuth,
111 }
112 }
113
114 pub fn status_code(&self) -> Option<u16> {
116 match self {
117 Self::Api { error, .. } => Some(error.status_code),
118 _ => None,
119 }
120 }
121
122 pub fn api_error(&self) -> Option<&ApiError> {
124 match self {
125 Self::Api { error, .. } => Some(error.as_ref()),
126 _ => None,
127 }
128 }
129}
130
131pub(crate) fn classify_api_error(
132 status_code: u16,
133 payload: Option<Value>,
134 retry_after: Option<Duration>,
135) -> Error {
136 let message = payload
137 .as_ref()
138 .and_then(error_object)
139 .and_then(|error| error.get("message"))
140 .and_then(Value::as_str)
141 .or_else(|| {
142 payload
143 .as_ref()
144 .and_then(|value| value.get("message"))
145 .and_then(Value::as_str)
146 })
147 .unwrap_or("TrustedRouter error")
148 .to_owned();
149 let string_field = |name: &str| -> Option<String> {
150 payload
151 .as_ref()
152 .and_then(error_object)
153 .and_then(|value| value.get(name))
154 .or_else(|| payload.as_ref().and_then(|value| value.get(name)))
155 .and_then(Value::as_str)
156 .map(str::to_owned)
157 };
158 let layer = string_field("layer");
159 let source = string_field("source");
160 let provider = string_field("provider");
161 let request_id = string_field("request_id");
162 let kind = match status_code {
163 401 => ErrorKind::Authentication,
164 403 => ErrorKind::PermissionDenied,
165 404 => ErrorKind::NotFound,
166 429 => ErrorKind::RateLimit,
167 501 => ErrorKind::EndpointNotSupported,
168 400..=499 => ErrorKind::BadRequest,
169 _ => ErrorKind::Internal,
170 };
171 Error::Api {
172 kind,
173 error: Box::new(ApiError {
174 status_code,
175 message,
176 payload,
177 retry_after,
178 layer,
179 source,
180 provider,
181 request_id,
182 }),
183 }
184}
185
186fn error_object(payload: &Value) -> Option<&serde_json::Map<String, Value>> {
187 payload.get("error")?.as_object()
188}