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
use super::{
    super::super::{EndpointParseError, RetriedStatsInfo, RetryDecision},
    X_LOG_HEADER_NAME, X_REQ_ID_HEADER_NAME,
};
use anyhow::Error as AnyError;
use assert_impl::assert_impl;
use qiniu_http::{
    Extensions, HeaderValue, Metrics, ResponseError as HttpResponseError, ResponseErrorKind as HttpResponseErrorKind,
    ResponseParts as HttpResponseParts, StatusCode as HttpStatusCode,
};
use qiniu_upload_token::ToStringError;
use serde_json::Error as JsonError;
use std::{
    error::Error as StdError,
    fmt::{self, Debug, Display},
    io::{Error as IoError, Read, Result as IOResult},
    mem::take,
    net::IpAddr,
    num::NonZeroU16,
};

#[cfg(feature = "async")]
use futures::{AsyncRead, AsyncReadExt};

/// HTTP 响应错误类型
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorKind {
    /// HTTP 客户端错误
    HttpError(HttpResponseErrorKind),

    /// 响应状态码错误
    StatusCodeError(HttpStatusCode),

    /// 未预期的状态码(例如 0 - 199 或 300 - 399,理论上应该由 HttpCaller 自动处理)
    UnexpectedStatusCode(HttpStatusCode),

    /// 解析响应体错误
    ParseResponseError,

    /// 响应体提前结束
    UnexpectedEof,

    /// 疑似响应被劫持
    MaliciousResponse,

    /// 系统调用失败
    SystemCallError,

    /// 没有尝试
    NoTry,
}

/// HTTP 响应错误
#[derive(Debug)]
pub struct Error {
    kind: ErrorKind,
    error: AnyError,
    server_ip: Option<IpAddr>,
    server_port: Option<NonZeroU16>,
    metrics: Option<Metrics>,
    x_headers: XHeaders,
    response_body_sample: Vec<u8>,
    retried: Option<RetriedStatsInfo>,
    retry_decision: Option<RetryDecision>,
    extensions: Extensions,
}

const RESPONSE_BODY_SAMPLE_LEN_LIMIT: u64 = 1024;

impl Error {
    /// 创建 HTTP 响应错误
    #[inline]
    pub fn new(kind: ErrorKind, err: impl Into<AnyError>) -> Self {
        Error {
            kind,
            error: err.into(),
            server_ip: Default::default(),
            server_port: Default::default(),
            metrics: Default::default(),
            x_headers: Default::default(),
            response_body_sample: Default::default(),
            retried: Default::default(),
            retry_decision: Default::default(),
            extensions: Default::default(),
        }
    }

    /// 创建 HTTP 响应错误
    #[inline]
    pub fn new_with_msg(kind: ErrorKind, msg: impl Display + Debug + Send + Sync + 'static) -> Self {
        Error {
            kind,
            error: AnyError::msg(msg),
            server_ip: Default::default(),
            server_port: Default::default(),
            metrics: Default::default(),
            x_headers: Default::default(),
            response_body_sample: Default::default(),
            retried: Default::default(),
            retry_decision: Default::default(),
            extensions: Default::default(),
        }
    }

    /// 设置重试信息
    #[inline]
    #[must_use]
    pub fn retried(mut self, retried: &RetriedStatsInfo) -> Self {
        self.retried = Some(retried.to_owned());
        self
    }

    /// 设置重试决定
    #[inline]
    #[must_use]
    pub fn set_retry_decision(mut self, retry_decision: RetryDecision) -> Self {
        self.retry_decision = Some(retry_decision);
        self
    }

    /// 设置 HTTP 响应信息
    #[inline]
    #[must_use]
    pub fn response_parts(mut self, response_parts: &HttpResponseParts) -> Self {
        self.server_ip = response_parts.server_ip();
        self.server_port = response_parts.server_port();
        self.metrics = extract_metrics_from_response_parts(response_parts);
        self.x_headers = response_parts.into();
        self
    }

    /// 直接设置响应体样本
    #[inline]
    pub fn set_response_body_sample(mut self, body: Vec<u8>) -> Self {
        self.response_body_sample = body;
        self
    }

    /// 设置响应体样本
    ///
    /// 该方法的异步版本为 [`Error::async_read_response_body_sample`]。
    #[inline]
    pub fn read_response_body_sample<R: Read>(mut self, body: R) -> IOResult<Self> {
        body.take(RESPONSE_BODY_SAMPLE_LEN_LIMIT)
            .read_to_end(&mut self.response_body_sample)?;
        Ok(self)
    }

    /// 异步设置响应体样本
    #[inline]
    #[cfg(feature = "async")]
    pub async fn async_read_response_body_sample<R: AsyncRead + Unpin>(mut self, body: R) -> IOResult<Self> {
        body.take(RESPONSE_BODY_SAMPLE_LEN_LIMIT)
            .read_to_end(&mut self.response_body_sample)
            .await?;
        Ok(self)
    }

    /// 获取 HTTP 响应错误类型
    #[inline]
    pub fn kind(&self) -> ErrorKind {
        self.kind
    }

    /// 获取重试决定
    #[inline]
    pub fn retry_decision(&self) -> Option<RetryDecision> {
        self.retry_decision
    }

    /// 获取响应体样本
    #[inline]
    pub fn response_body_sample(&self) -> &[u8] {
        &self.response_body_sample
    }

    /// 获取服务器 IP 地址
    #[inline]
    pub fn server_ip(&self) -> Option<IpAddr> {
        self.server_ip
    }

    /// 获取服务器端口号
    #[inline]
    pub fn server_port(&self) -> Option<NonZeroU16> {
        self.server_port
    }

    /// 获取 HTTP 响应指标信息
    #[inline]
    pub fn metrics(&self) -> Option<&Metrics> {
        self.metrics.as_ref()
    }

    /// 获取 HTTP 响应的 X-Log 信息
    #[inline]
    pub fn x_log(&self) -> Option<&HeaderValue> {
        self.x_headers.x_log.as_ref()
    }

    /// 获取 HTTP 响应的 X-ReqId 信息
    #[inline]
    pub fn x_reqid(&self) -> Option<&HeaderValue> {
        self.x_headers.x_reqid.as_ref()
    }

    /// 获取扩展信息
    #[inline]
    pub fn extensions(&self) -> &Extensions {
        &self.extensions
    }

    /// 获取扩展信息的可变引用
    #[inline]
    pub fn extensions_mut(&mut self) -> &mut Extensions {
        &mut self.extensions
    }

    pub(in super::super) fn from_http_response_error(
        mut err: HttpResponseError,
        x_headers: XHeaders,
        kind: Option<ErrorKind>,
    ) -> Self {
        Self {
            x_headers,
            server_ip: err.server_ip(),
            server_port: err.server_port(),
            metrics: take(err.metrics_mut()),
            kind: kind.unwrap_or_else(|| err.kind().into()),
            error: err.into_inner(),
            response_body_sample: Default::default(),
            retried: Default::default(),
            retry_decision: Default::default(),
            extensions: Default::default(),
        }
    }

    pub(crate) fn from_endpoint_parse_error(error: EndpointParseError, parts: &HttpResponseParts) -> Self {
        Self::new(ErrorKind::ParseResponseError, error).response_parts(parts)
    }

    #[allow(dead_code)]
    fn assert() {
        assert_impl!(Send: Self);
        assert_impl!(Sync: Self);
    }
}

#[derive(Debug, Default)]
pub(in super::super) struct XHeaders {
    x_log: Option<HeaderValue>,
    x_reqid: Option<HeaderValue>,
}

impl From<&HttpResponseParts> for XHeaders {
    #[inline]
    fn from(parts: &HttpResponseParts) -> Self {
        Self {
            x_log: extract_x_log_from_response_parts(parts),
            x_reqid: extract_x_reqid_from_response_parts(parts),
        }
    }
}

fn extract_x_log_from_response_parts(parts: &HttpResponseParts) -> Option<HeaderValue> {
    parts.header(X_LOG_HEADER_NAME).cloned()
}

fn extract_x_reqid_from_response_parts(parts: &HttpResponseParts) -> Option<HeaderValue> {
    parts.header(X_REQ_ID_HEADER_NAME).cloned()
}

fn extract_metrics_from_response_parts(parts: &HttpResponseParts) -> Option<Metrics> {
    parts.metrics().cloned()
}

impl Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "[{:?}]", self.kind)?;
        if let Some(retried) = self.retried.as_ref() {
            write!(f, "[{retried}]")?;
        }
        if let Some(x_reqid) = self.x_headers.x_reqid.as_ref() {
            write!(f, "[{x_reqid:?}]")?;
        }
        if let Some(x_log) = self.x_headers.x_log.as_ref() {
            write!(f, "[{x_log:?}]")?;
        }
        write!(f, " {}", self.error)?;
        if !self.response_body_sample.is_empty() {
            write!(f, " [{}]", String::from_utf8_lossy(&self.response_body_sample))?;
        }
        Ok(())
    }
}

impl StdError for Error {
    #[inline]
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        Some(self.error.as_ref())
    }
}

impl From<HttpResponseError> for Error {
    #[inline]
    fn from(error: HttpResponseError) -> Self {
        Self::from_http_response_error(error, Default::default(), None)
    }
}

impl From<HttpResponseErrorKind> for ErrorKind {
    #[inline]
    fn from(kind: HttpResponseErrorKind) -> Self {
        ErrorKind::HttpError(kind)
    }
}

impl From<JsonError> for Error {
    #[inline]
    fn from(error: JsonError) -> Self {
        Self::new(ErrorKind::ParseResponseError, error)
    }
}

impl From<IoError> for Error {
    #[inline]
    fn from(error: IoError) -> Self {
        Self::new(ErrorKind::HttpError(HttpResponseErrorKind::LocalIoError), error)
    }
}

impl From<ToStringError> for Error {
    #[inline]
    fn from(error: ToStringError) -> Self {
        match error {
            ToStringError::CredentialGetError(err) => err.into(),
            ToStringError::CallbackError(err) => Self::new(HttpResponseErrorKind::CallbackError.into(), err),
            err => Self::new(HttpResponseErrorKind::UnknownError.into(), err),
        }
    }
}