1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
//! Typed SDK errors and transport-independent error introspection.
use reqwest::{Method, StatusCode};
use std::{fmt, string::FromUtf8Error, time::Duration};
use thiserror::Error;
use url::Url;
use crate::{ProxyError, ProxyScheme};
/// Stable category for an [`enum@Error`] without exposing its variant fields.
///
/// This is useful for metrics and policy decisions that should not depend on
/// the concrete error payload. Use [`Error::status`], [`Error::method`], and
/// [`Error::url`] when the associated HTTP context is needed.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ErrorKind {
/// Invalid client or request configuration.
Configuration,
/// Missing or expired authentication.
Unauthorized,
/// Authorization or CSRF rejection.
Forbidden,
/// Non-success HTTP status other than 401 or 403.
HttpStatus,
/// HTTP transport or response-body IO failure.
Transport,
/// HTTP response body exceeded its configured memory limit.
ResponseTooLarge,
/// Request serialization failure.
Encode,
/// Application-level rejection in a successful HTTP response.
Api,
/// HTTP response JSON decoding failure.
Decode,
/// Invalid UTF-8 response body.
Utf8,
/// WebSocket connection timeout.
WebSocketConnectTimeout,
/// WebSocket handshake, transport, or protocol failure.
WebSocket,
/// Explicit outbound proxy connection or negotiation failure.
Proxy,
/// WebSocket event JSON decoding failure.
EventDecode,
/// Unsupported WebSocket application frame.
UnexpectedWebSocketFrame,
/// Successful response missing its required object.
MissingObject,
}
impl ErrorKind {
/// Returns a stable snake-case label suitable for logs and metrics.
pub const fn as_str(self) -> &'static str {
match self {
Self::Configuration => "configuration",
Self::Unauthorized => "unauthorized",
Self::Forbidden => "forbidden",
Self::HttpStatus => "http_status",
Self::Transport => "transport",
Self::ResponseTooLarge => "response_too_large",
Self::Encode => "encode",
Self::Api => "api",
Self::Decode => "decode",
Self::Utf8 => "utf8",
Self::WebSocketConnectTimeout => "websocket_connect_timeout",
Self::WebSocket => "websocket",
Self::Proxy => "proxy",
Self::EventDecode => "event_decode",
Self::UnexpectedWebSocketFrame => "unexpected_websocket_frame",
Self::MissingObject => "missing_object",
}
}
}
impl fmt::Display for ErrorKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
/// Errors returned by the SDK.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
/// The client configuration is invalid.
#[error("invalid client configuration: {0}")]
Configuration(String),
/// The panel rejected the caller's credentials or session.
#[error("{method} {url} requires authentication")]
Unauthorized {
/// HTTP method used for the request.
method: Method,
/// Request URL.
url: Box<Url>,
},
/// The panel rejected a request, commonly due to an invalid CSRF token.
#[error("{method} {url} was forbidden")]
Forbidden {
/// HTTP method used for the request.
method: Method,
/// Request URL.
url: Box<Url>,
},
/// The panel returned an unsuccessful HTTP status.
#[error("{method} {url} returned HTTP {status}")]
HttpStatus {
/// HTTP method used for the request.
method: Method,
/// Request URL.
url: Box<Url>,
/// Response status.
status: StatusCode,
},
/// The request could not be sent or its body could not be read.
#[error("request {method} {url} failed: {source}")]
Transport {
/// HTTP method used for the request.
method: Method,
/// Request URL.
url: Box<Url>,
/// Underlying HTTP client error.
#[source]
source: reqwest::Error,
},
/// The response body exceeded the configured in-memory size limit.
#[error("response from {method} {url} exceeded the {limit}-byte body limit")]
ResponseTooLarge {
/// HTTP method used for the request.
method: Method,
/// Request URL, redacted for public subscription routes.
url: Box<Url>,
/// Configured maximum response body size in bytes.
limit: usize,
/// Server-advertised body size, when a `Content-Length` was present.
content_length: Option<u64>,
},
/// A request value could not be encoded in the endpoint's wire format.
#[error("could not encode request for {operation}: {source}")]
Encode {
/// Human-readable operation name.
operation: &'static str,
/// Underlying JSON encoding error.
#[source]
source: serde_json::Error,
},
/// The panel returned HTTP success with `success: false`.
#[error("panel rejected {method} {url}: {message}")]
Api {
/// HTTP method used for the request.
method: Method,
/// Request URL.
url: Box<Url>,
/// Human-readable message returned by 3x-ui.
message: String,
},
/// The panel response did not match the documented schema.
#[error("could not decode response from {method} {url}: {source}")]
Decode {
/// HTTP method used for the request.
method: Method,
/// Request URL.
url: Box<Url>,
/// JSON decoding error.
#[source]
source: serde_json::Error,
},
/// A text endpoint returned bytes that are not valid UTF-8.
#[error("response from {method} {url} was not valid UTF-8: {source}")]
Utf8 {
/// HTTP method used for the request.
method: Method,
/// Redacted request URL.
url: Box<Url>,
/// Underlying UTF-8 decoding error.
#[source]
source: FromUtf8Error,
},
/// Establishing the authenticated WebSocket exceeded the configured
/// connection timeout.
#[error("WebSocket connection to {url} timed out after {timeout:?}")]
WebSocketConnectTimeout {
/// WebSocket endpoint.
url: Box<Url>,
/// Configured connection timeout.
timeout: Duration,
},
/// A WebSocket handshake or frame operation failed.
#[error("WebSocket operation on {url} failed: {source}")]
WebSocket {
/// WebSocket endpoint.
url: Box<Url>,
/// Underlying protocol/transport error.
#[source]
source: Box<tokio_tungstenite::tungstenite::Error>,
},
/// An explicit proxy could not establish a WebSocket tunnel.
#[error("{scheme} proxy could not connect WebSocket to {url}: {source}")]
Proxy {
/// Proxy protocol in use. The proxy endpoint is deliberately omitted.
scheme: ProxyScheme,
/// Target WebSocket endpoint, never the proxy endpoint.
url: Box<Url>,
/// Underlying proxy transport or negotiation failure.
#[source]
source: Box<ProxyError>,
},
/// A WebSocket text message did not match its source-defined JSON shape.
#[error("could not decode WebSocket {message_type:?} event: {source}")]
EventDecode {
/// Message name when the envelope was valid enough to identify it.
message_type: Option<String>,
/// Underlying JSON decoding error.
#[source]
source: serde_json::Error,
},
/// The panel sent a data-frame format not used by the v3.7.0 protocol.
#[error("unexpected WebSocket {kind} frame from {url}")]
UnexpectedWebSocketFrame {
/// WebSocket endpoint.
url: Box<Url>,
/// Human-readable frame kind.
kind: &'static str,
},
/// A successful response omitted its documented `obj` value.
#[error("response from {method} {url} did not contain obj")]
MissingObject {
/// HTTP method used for the request.
method: Method,
/// Request URL.
url: Box<Url>,
},
}
impl Error {
/// Returns the stable category of this error.
pub const fn kind(&self) -> ErrorKind {
match self {
Self::Configuration(_) => ErrorKind::Configuration,
Self::Unauthorized { .. } => ErrorKind::Unauthorized,
Self::Forbidden { .. } => ErrorKind::Forbidden,
Self::HttpStatus { .. } => ErrorKind::HttpStatus,
Self::Transport { .. } => ErrorKind::Transport,
Self::ResponseTooLarge { .. } => ErrorKind::ResponseTooLarge,
Self::Encode { .. } => ErrorKind::Encode,
Self::Api { .. } => ErrorKind::Api,
Self::Decode { .. } => ErrorKind::Decode,
Self::Utf8 { .. } => ErrorKind::Utf8,
Self::WebSocketConnectTimeout { .. } => ErrorKind::WebSocketConnectTimeout,
Self::WebSocket { .. } => ErrorKind::WebSocket,
Self::Proxy { .. } => ErrorKind::Proxy,
Self::EventDecode { .. } => ErrorKind::EventDecode,
Self::UnexpectedWebSocketFrame { .. } => ErrorKind::UnexpectedWebSocketFrame,
Self::MissingObject { .. } => ErrorKind::MissingObject,
}
}
/// Returns the HTTP status that caused this error, when available.
///
/// Authentication errors report 401 or 403 even though they have dedicated
/// variants. Application-level [`Error::Api`] responses used HTTP success
/// and therefore return `None`.
pub const fn status(&self) -> Option<StatusCode> {
match self {
Self::Unauthorized { .. } => Some(StatusCode::UNAUTHORIZED),
Self::Forbidden { .. } => Some(StatusCode::FORBIDDEN),
Self::HttpStatus { status, .. } => Some(*status),
_ => None,
}
}
/// Returns the HTTP method associated with the failed operation.
pub const fn method(&self) -> Option<&Method> {
match self {
Self::Unauthorized { method, .. }
| Self::Forbidden { method, .. }
| Self::HttpStatus { method, .. }
| Self::Transport { method, .. }
| Self::ResponseTooLarge { method, .. }
| Self::Api { method, .. }
| Self::Decode { method, .. }
| Self::Utf8 { method, .. }
| Self::MissingObject { method, .. } => Some(method),
_ => None,
}
}
/// Returns the request or WebSocket URL associated with the failure.
pub fn url(&self) -> Option<&Url> {
match self {
Self::Unauthorized { url, .. }
| Self::Forbidden { url, .. }
| Self::HttpStatus { url, .. }
| Self::Transport { url, .. }
| Self::ResponseTooLarge { url, .. }
| Self::Api { url, .. }
| Self::Decode { url, .. }
| Self::Utf8 { url, .. }
| Self::WebSocketConnectTimeout { url, .. }
| Self::WebSocket { url, .. }
| Self::Proxy { url, .. }
| Self::UnexpectedWebSocketFrame { url, .. }
| Self::MissingObject { url, .. } => Some(url),
Self::Configuration(_) | Self::Encode { .. } | Self::EventDecode { .. } => None,
}
}
/// Returns `true` when authentication must be supplied or refreshed.
pub const fn is_unauthorized(&self) -> bool {
matches!(self, Self::Unauthorized { .. })
}
/// Returns `true` when the operation was rejected with HTTP 403.
pub const fn is_forbidden(&self) -> bool {
matches!(self, Self::Forbidden { .. })
}
/// Returns `true` when the panel asked the caller to slow down.
pub const fn is_rate_limited(&self) -> bool {
matches!(self.status(), Some(StatusCode::TOO_MANY_REQUESTS))
}
/// Returns `true` when the response body exceeded its configured limit.
pub const fn is_response_too_large(&self) -> bool {
matches!(self, Self::ResponseTooLarge { .. })
}
/// Returns the configured response body limit that was exceeded.
pub const fn response_body_limit(&self) -> Option<usize> {
match self {
Self::ResponseTooLarge { limit, .. } => Some(*limit),
_ => None,
}
}
/// Returns the server-advertised `Content-Length` for an oversized body.
pub const fn advertised_content_length(&self) -> Option<u64> {
match self {
Self::ResponseTooLarge { content_length, .. } => *content_length,
_ => None,
}
}
/// Returns `true` for an HTTP 5xx response.
pub fn is_server_error(&self) -> bool {
self.status().is_some_and(|status| status.is_server_error())
}
/// Returns `true` when an HTTP or WebSocket transport timed out.
pub fn is_timeout(&self) -> bool {
match self {
Self::Transport { source, .. } => source.is_timeout(),
Self::WebSocketConnectTimeout { .. } => true,
Self::WebSocket { source, .. } => matches!(
source.as_ref(),
tokio_tungstenite::tungstenite::Error::Io(error)
if error.kind() == std::io::ErrorKind::TimedOut
),
Self::Proxy { source, .. } => source.is_timeout(),
_ => false,
}
}
}
/// Result type used throughout the SDK.
pub type Result<T> = std::result::Result<T, Error>;