1use std::fmt;
2
3use serde_json::{Value, json};
4use thiserror::Error;
5
6pub const SUBSCRIPTION_ERROR_CODES: [(&str, i64); 4] = [
8 ("NOT_ENTITLED", 4078),
9 ("QUEUE_CAP", 4079),
10 ("GRACE_RETRY", 4080),
11 ("SUBSCRIPTION_FEATURE_REQUIRES_UPGRADE", 4081),
12];
13
14pub const RETRYABLE_CHAT_ERROR_TYPES: &[&str] = &["server_restarting", "transport_lost"];
16
17#[derive(Clone, Debug)]
18pub struct ApiError {
19 pub status: u16,
20 pub error_code: Value,
21 pub message: String,
22 pub payload: Value,
23 pub retry_after_seconds: Option<u64>,
25}
26
27impl ApiError {
28 #[must_use]
29 pub fn new(status: u16, payload: Value) -> Self {
30 let message = payload
31 .get("message")
32 .and_then(Value::as_str)
33 .map_or_else(|| format!("HTTP {status}"), ToOwned::to_owned);
34 let error_code = payload
35 .get("errorCode")
36 .or_else(|| payload.get("error_code"))
37 .cloned()
38 .unwrap_or_else(|| json!(status));
39 Self {
40 status,
41 error_code,
42 message,
43 payload,
44 retry_after_seconds: None,
45 }
46 }
47
48 #[must_use]
49 pub fn with_retry_after(mut self, value: Option<&str>) -> Self {
50 self.retry_after_seconds =
51 value.and_then(|value| crate::retry_after::seconds(value, chrono::Utc::now()));
52 self
53 }
54}
55
56impl fmt::Display for ApiError {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 f.write_str(&self.message)
59 }
60}
61
62impl std::error::Error for ApiError {}
63
64#[derive(Clone, Debug)]
65pub struct ProjectError {
66 pub code: Option<Value>,
67 pub message: String,
68 pub payload: Value,
69}
70
71impl ProjectError {
72 #[must_use]
73 pub fn from_payload(payload: Value) -> Self {
74 let code = payload.get("code").cloned();
75 let message = payload
76 .get("message")
77 .and_then(Value::as_str)
78 .unwrap_or("Project failed")
79 .to_owned();
80 Self {
81 code,
82 message,
83 payload,
84 }
85 }
86}
87
88impl fmt::Display for ProjectError {
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 f.write_str(&self.message)
91 }
92}
93
94impl std::error::Error for ProjectError {}
95
96#[derive(Clone, Debug)]
97pub struct ChatError {
98 pub code: Option<String>,
99 pub error_type: Option<String>,
100 pub job_id: Option<String>,
101 pub status: Option<u16>,
102 pub message: String,
103 pub payload: Value,
104 pub subscription_limit: bool,
105 pub required_plans: Vec<String>,
106 pub feature: Option<String>,
107 pub limitation: Option<String>,
108}
109
110impl ChatError {
111 #[must_use]
112 pub fn from_payload(payload: Value, status: Option<u16>, job_id: Option<String>) -> Self {
113 let envelope = payload
114 .get("error")
115 .filter(|v| v.is_object())
116 .unwrap_or(&payload);
117 let subscription = envelope
118 .get("subscription")
119 .filter(|v| v.is_object())
120 .unwrap_or(envelope);
121 let code = envelope
122 .get("code")
123 .or_else(|| payload.get("error_code"))
124 .map(value_string);
125 let error_type = envelope
126 .get("type")
127 .or_else(|| payload.get("error"))
128 .and_then(Value::as_str)
129 .map(ToOwned::to_owned);
130 let message = envelope
131 .get("message")
132 .or_else(|| payload.get("error_message"))
133 .and_then(Value::as_str)
134 .unwrap_or("Chat request failed")
135 .to_owned();
136 let required_plans = subscription
137 .get("requiredPlans")
138 .and_then(Value::as_array)
139 .into_iter()
140 .flatten()
141 .filter_map(Value::as_str)
142 .map(ToOwned::to_owned)
143 .collect();
144 Self {
145 code,
146 error_type,
147 job_id,
148 status,
149 message,
150 subscription_limit: subscription
151 .get("subscriptionLimit")
152 .and_then(Value::as_bool)
153 .unwrap_or(false),
154 required_plans,
155 feature: subscription
156 .get("feature")
157 .and_then(Value::as_str)
158 .map(ToOwned::to_owned),
159 limitation: subscription
160 .get("limitation")
161 .and_then(Value::as_str)
162 .map(ToOwned::to_owned),
163 payload,
164 }
165 }
166
167 #[must_use]
168 pub fn subscription_error_code(&self) -> Option<i64> {
169 let code = self.code.as_deref()?.parse::<i64>().ok()?;
170 SUBSCRIPTION_ERROR_CODES
171 .iter()
172 .any(|(_, known)| *known == code)
173 .then_some(code)
174 }
175
176 #[must_use]
178 pub fn retryable(&self) -> bool {
179 self.error_type
180 .as_deref()
181 .is_some_and(|kind| RETRYABLE_CHAT_ERROR_TYPES.contains(&kind))
182 }
183}
184
185#[must_use]
186pub fn is_retryable_chat_error(error: &Error) -> bool {
187 matches!(error, Error::Chat(error) if error.retryable())
188}
189
190impl fmt::Display for ChatError {
191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192 f.write_str(&self.message)
193 }
194}
195
196impl std::error::Error for ChatError {}
197
198#[derive(Debug, Error)]
199pub enum Error {
200 #[error(transparent)]
201 Api(#[from] ApiError),
202 #[error(transparent)]
203 Project(#[from] ProjectError),
204 #[error(transparent)]
205 Chat(Box<ChatError>),
206 #[error("invalid input: {0}")]
207 InvalidInput(String),
208 #[error("protocol error: {0}")]
209 Protocol(String),
210 #[error("transport error: {0}")]
211 Transport(String),
212 #[error("operation timed out: {0}")]
213 Timeout(String),
214 #[error("client is closed")]
215 Closed,
216 #[error(transparent)]
217 Json(#[from] serde_json::Error),
218 #[error(transparent)]
219 Url(#[from] url::ParseError),
220 #[error(transparent)]
221 Http(#[from] reqwest::Error),
222 #[error(transparent)]
223 Io(#[from] std::io::Error),
224}
225
226impl From<ChatError> for Error {
227 fn from(error: ChatError) -> Self {
228 Self::Chat(Box::new(error))
229 }
230}
231
232pub type Result<T> = std::result::Result<T, Error>;
233
234#[must_use]
235pub fn is_subscription_limit_error(error: &Error) -> bool {
236 match error {
237 Error::Chat(error) => {
238 error.subscription_limit || error.subscription_error_code() == Some(4081)
239 }
240 Error::Api(error) => {
241 error
242 .payload
243 .get("subscriptionLimit")
244 .and_then(Value::as_bool)
245 .unwrap_or(false)
246 || value_i64(&error.error_code) == Some(4081)
247 }
248 _ => false,
249 }
250}
251
252pub(crate) fn value_string(value: &Value) -> String {
253 value
254 .as_str()
255 .map_or_else(|| value.to_string(), ToOwned::to_owned)
256}
257
258pub(crate) fn value_i64(value: &Value) -> Option<i64> {
259 value
260 .as_i64()
261 .or_else(|| value.as_u64().and_then(|v| i64::try_from(v).ok()))
262 .or_else(|| value.as_str().and_then(|v| v.parse().ok()))
263}