1use std::fmt;
2use std::time::Duration;
3
4use reqwest::header::HeaderMap;
5use reqwest::StatusCode;
6use serde_json::Value;
7
8#[derive(Debug, thiserror::Error)]
10pub enum Error {
11 #[error("{0}")]
13 Api(ApiError),
14 #[error("{0}")]
16 Authentication(ApiError),
17 #[error("{0}")]
19 NotFound(ApiError),
20 #[error("{0}")]
22 RateLimit(Box<RateLimitError>),
23 #[error("http error: {0}")]
25 Http(#[source] reqwest::Error),
26 #[error("request timed out")]
28 Timeout,
29 #[error("decode error: {0}")]
31 Decode(#[from] serde_json::Error),
32}
33
34impl Error {
35 pub fn api_error(&self) -> Option<&ApiError> {
37 match self {
38 Error::Api(e) | Error::Authentication(e) | Error::NotFound(e) => Some(e),
39 Error::RateLimit(e) => Some(&e.api),
40 _ => None,
41 }
42 }
43
44 pub fn status(&self) -> Option<u16> {
46 self.api_error().map(|e| e.status)
47 }
48
49 pub fn code(&self) -> Option<&str> {
51 self.api_error().map(|e| e.code.as_str())
52 }
53}
54
55impl From<reqwest::Error> for Error {
56 fn from(e: reqwest::Error) -> Self {
57 if e.is_timeout() {
58 Error::Timeout
59 } else {
60 Error::Http(e)
61 }
62 }
63}
64
65#[derive(Debug, Clone)]
67pub struct ApiError {
68 pub status: u16,
69 pub code: String,
70 pub message: String,
71 pub details: Option<Value>,
72 pub body: String,
73}
74
75impl fmt::Display for ApiError {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 write!(f, "{} ({}): {}", self.code, self.status, self.message)
78 }
79}
80
81impl std::error::Error for ApiError {}
82
83#[derive(Debug, Clone)]
85pub struct RateLimitError {
86 pub api: ApiError,
87 pub reason: Option<String>,
88 pub retry_after: Option<Duration>,
89 pub reset_at: Option<String>,
90 pub reset_date: Option<String>,
91 pub limit: Option<i64>,
92 pub usage: Option<i64>,
93 pub remaining: Option<i64>,
94 pub needed: Option<i64>,
95 pub plan: Option<String>,
96 pub upgrade_url: Option<String>,
97 pub rate_limit: RateLimitHeaders,
98}
99
100impl fmt::Display for RateLimitError {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 self.api.fmt(f)
103 }
104}
105
106impl std::error::Error for RateLimitError {}
107
108#[derive(Debug, Clone, Default)]
110pub struct RateLimitHeaders {
111 pub meter: Option<String>,
112 pub limit: Option<i64>,
113 pub remaining: Option<i64>,
114 pub reset: Option<i64>,
115 pub daily_limit: Option<i64>,
116 pub daily_remaining: Option<i64>,
117 pub daily_reset: Option<i64>,
118 pub hourly_limit: Option<i64>,
119 pub hourly_remaining: Option<i64>,
120 pub hourly_reset: Option<i64>,
121 pub usage_percent: Option<f64>,
122 pub upgrade_hint: Option<String>,
123 pub upgrade_url: Option<String>,
124 pub upgrade_plan: Option<String>,
125 pub retry_after: Option<u64>,
126}
127
128impl RateLimitHeaders {
129 pub(crate) fn from_headers(h: &HeaderMap) -> Self {
130 let s = |name: &str| {
131 h.get(name)
132 .and_then(|v| v.to_str().ok())
133 .map(|v| v.trim().to_string())
134 .filter(|v| !v.is_empty())
135 };
136 let n = |name: &str| s(name).and_then(|v| v.parse().ok());
137 RateLimitHeaders {
138 meter: s("x-ratelimit-meter"),
139 limit: n("x-ratelimit-limit"),
140 remaining: n("x-ratelimit-remaining"),
141 reset: n("x-ratelimit-reset"),
142 daily_limit: n("x-ratelimit-daily-limit"),
143 daily_remaining: n("x-ratelimit-daily-remaining"),
144 daily_reset: n("x-ratelimit-daily-reset"),
145 hourly_limit: n("x-ratelimit-hourly-limit"),
146 hourly_remaining: n("x-ratelimit-hourly-remaining"),
147 hourly_reset: n("x-ratelimit-hourly-reset"),
148 usage_percent: s("x-ratelimit-usage-percent").and_then(|v| v.parse().ok()),
149 upgrade_hint: s("x-quota-upgrade-hint"),
150 upgrade_url: s("x-quota-upgrade-url"),
151 upgrade_plan: s("x-quota-upgrade-plan"),
152 retry_after: s("retry-after").and_then(|v| v.parse().ok()),
153 }
154 }
155}
156
157pub(crate) fn from_response(status: StatusCode, headers: &HeaderMap, body: String) -> Error {
158 let parsed: Option<serde_json::Map<String, Value>> = serde_json::from_str(&body).ok();
159 let with_code = parsed
160 .as_ref()
161 .and_then(|m| m.get("error").and_then(Value::as_str).map(|c| (m, c)));
162
163 let api = match with_code {
164 Some((m, code)) => ApiError {
165 status: status.as_u16(),
166 code: code.to_string(),
167 message: m
168 .get("message")
169 .and_then(Value::as_str)
170 .unwrap_or_default()
171 .to_string(),
172 details: m.get("details").filter(|v| !v.is_null()).cloned(),
173 body: body.clone(),
174 },
175 None => ApiError {
176 status: status.as_u16(),
177 code: format!("http_{}", status.as_u16()),
178 message: status.canonical_reason().unwrap_or_default().to_string(),
179 details: None,
180 body: body.clone(),
181 },
182 };
183
184 match status.as_u16() {
185 401 | 403 => Error::Authentication(api),
186 404 => Error::NotFound(api),
187 429 => {
188 let get = |k: &str| parsed.as_ref().and_then(|m| m.get(k));
189 let str_field = |k: &str| get(k).and_then(Value::as_str).map(str::to_string);
190 let int_field = |k: &str| get(k).and_then(Value::as_i64);
191 let rate_limit = RateLimitHeaders::from_headers(headers);
192 let retry_after = get("retryAfter")
193 .and_then(Value::as_u64)
194 .or(rate_limit.retry_after)
195 .map(Duration::from_secs);
196 let upgrade_url = get("upgrade")
197 .and_then(|u| u.get("url"))
198 .and_then(Value::as_str)
199 .map(str::to_string)
200 .or_else(|| rate_limit.upgrade_url.clone());
201 Error::RateLimit(Box::new(RateLimitError {
202 reason: str_field("reason"),
203 retry_after,
204 reset_at: str_field("resetAt"),
205 reset_date: str_field("resetDate"),
206 limit: int_field("limit"),
207 usage: int_field("usage"),
208 remaining: int_field("remaining"),
209 needed: int_field("needed"),
210 plan: str_field("plan"),
211 upgrade_url,
212 rate_limit,
213 api,
214 }))
215 }
216 _ => Error::Api(api),
217 }
218}