1use std::fmt;
11
12use serde::{Deserialize, Serialize};
13use serde_json::{Map, Value};
14
15#[derive(Debug, thiserror::Error)]
18#[non_exhaustive]
19pub enum Error {
20 #[error(transparent)]
22 Api(Box<ApiError>),
23 #[error(transparent)]
26 Transport(#[from] TransportError),
27 #[error(transparent)]
29 Decode(#[from] DecodeError),
30 #[error("invalid client configuration: {0}")]
33 Config(&'static str),
34}
35
36impl From<ApiError> for Error {
37 fn from(error: ApiError) -> Self {
38 Error::Api(Box::new(error))
39 }
40}
41
42impl Error {
43 #[must_use]
45 pub fn status(&self) -> Option<u16> {
46 match self {
47 Error::Api(api) => Some(api.status),
48 _ => None,
49 }
50 }
51
52 #[must_use]
54 pub fn problem(&self) -> Option<&Problem> {
55 match self {
56 Error::Api(api) => Some(&api.problem),
57 _ => None,
58 }
59 }
60
61 #[must_use]
64 pub fn is_timeout(&self) -> bool {
65 matches!(self, Error::Transport(t) if t.timed_out)
66 }
67}
68
69#[derive(Debug, Clone, PartialEq)]
75pub struct ApiError {
76 pub status: u16,
78 pub problem: Problem,
80}
81
82impl ApiError {
83 #[must_use]
85 pub fn problem(&self) -> &Problem {
86 &self.problem
87 }
88
89 #[must_use]
91 pub fn code(&self) -> Option<&str> {
92 self.problem.code.as_deref()
93 }
94}
95
96impl fmt::Display for ApiError {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98 write!(
99 f,
100 "crypto-service API error: HTTP {} {} ({})",
101 self.status, self.problem.title, self.problem.kind
102 )
103 }
104}
105
106impl std::error::Error for ApiError {}
107
108#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
110#[serde(rename_all = "camelCase")]
111pub struct Problem {
112 #[serde(rename = "type", default = "about_blank")]
114 pub kind: String,
115 #[serde(default)]
117 pub title: String,
118 #[serde(default)]
120 pub status: u16,
121 pub detail: String,
124 #[serde(default, skip_serializing_if = "Option::is_none")]
126 pub instance: Option<String>,
127 #[serde(default, skip_serializing_if = "Option::is_none")]
130 pub code: Option<String>,
131 #[serde(default, skip_serializing_if = "Vec::is_empty")]
133 pub errors: Vec<ValidationError>,
134 #[serde(default, skip_serializing_if = "Option::is_none")]
136 pub limit: Option<u64>,
137 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub reset_seconds: Option<u64>,
140 #[serde(flatten)]
142 pub extensions: Map<String, Value>,
143}
144
145#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
147pub struct ValidationError {
148 pub field: String,
150 pub message: String,
152}
153
154fn about_blank() -> String {
155 String::from("about:blank")
156}
157
158impl Problem {
159 #[must_use]
164 pub fn from_body(status: u16, body: &[u8]) -> Self {
165 match serde_json::from_slice::<Problem>(body) {
166 Ok(mut problem) => {
167 if problem.title.is_empty() {
168 problem.title = reason(status);
169 }
170 if problem.status == 0 {
171 problem.status = status;
172 }
173 problem
174 }
175 Err(_) => Self::blank(status),
176 }
177 }
178
179 #[must_use]
181 pub fn blank(status: u16) -> Self {
182 Problem {
183 kind: about_blank(),
184 title: reason(status),
185 status,
186 detail: format!("The server answered {status} without a problem body"),
187 instance: None,
188 code: None,
189 errors: Vec::new(),
190 limit: None,
191 reset_seconds: None,
192 extensions: Map::new(),
193 }
194 }
195}
196
197fn reason(status: u16) -> String {
199 http::StatusCode::from_u16(status)
200 .ok()
201 .and_then(|code| code.canonical_reason())
202 .unwrap_or("HTTP error")
203 .to_owned()
204}
205
206#[derive(Debug, thiserror::Error)]
208#[error("{message}")]
209pub struct TransportError {
210 pub timed_out: bool,
212 message: &'static str,
213 #[source]
214 source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
215}
216
217impl TransportError {
218 pub fn new<E>(source: E, timed_out: bool) -> Self
221 where
222 E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
223 {
224 TransportError {
225 timed_out,
226 message: if timed_out {
227 "request timed out"
228 } else {
229 "network error"
230 },
231 source: Some(source.into()),
232 }
233 }
234
235 pub(crate) fn attempt_timeout() -> Self {
237 TransportError {
238 timed_out: true,
239 message: "request timed out",
240 source: None,
241 }
242 }
243
244 pub(crate) fn deadline() -> Self {
246 TransportError {
247 timed_out: true,
248 message: "deadline exceeded",
249 source: None,
250 }
251 }
252}
253
254#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
257#[error("response body could not be decoded ({category} error at line {line}, column {column})")]
258pub struct DecodeError {
259 category: &'static str,
260 line: usize,
261 column: usize,
262}
263
264impl DecodeError {
265 #[must_use]
267 pub fn line(&self) -> usize {
268 self.line
269 }
270
271 #[must_use]
273 pub fn column(&self) -> usize {
274 self.column
275 }
276}
277
278impl From<serde_json::Error> for DecodeError {
279 fn from(error: serde_json::Error) -> Self {
280 use serde_json::error::Category;
281 DecodeError {
282 category: match error.classify() {
283 Category::Io => "io",
284 Category::Syntax => "syntax",
285 Category::Data => "data",
286 Category::Eof => "eof",
287 },
288 line: error.line(),
289 column: error.column(),
290 }
291 }
292}
293
294#[cfg(test)]
295mod tests;