-
-
Notifications
You must be signed in to change notification settings - Fork 116
/
status.rs
369 lines (342 loc) · 12.3 KB
/
status.rs
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
use std::{collections::HashSet, fmt::Display};
use http::StatusCode;
use reqwest::Response;
use serde::ser::SerializeStruct;
use serde::{Serialize, Serializer};
use crate::ErrorKind;
use super::CacheStatus;
const ICON_OK: &str = "\u{2714}"; // ✔
const ICON_REDIRECTED: &str = "\u{21c4}"; // ⇄
const ICON_EXCLUDED: &str = "\u{003f}"; // ?
const ICON_UNSUPPORTED: &str = "\u{003f}"; // ? (using same icon, but under different name for explicitness)
const ICON_UNKNOWN: &str = "\u{003f}"; // ?
const ICON_ERROR: &str = "\u{2717}"; // ✗
const ICON_TIMEOUT: &str = "\u{29d6}"; // ⧖
const ICON_CACHED: &str = "\u{21bb}"; // ↻
/// Response status of the request.
#[allow(variant_size_differences)]
#[derive(Debug, Hash, PartialEq, Eq)]
pub enum Status {
/// Request was successful
Ok(StatusCode),
/// Failed request
Error(ErrorKind),
/// Request timed out
Timeout(Option<StatusCode>),
/// Got redirected to different resource
Redirected(StatusCode),
/// The given status code is not known by lychee
UnknownStatusCode(StatusCode),
/// Resource was excluded from checking
Excluded,
/// The request type is currently not supported,
/// for example when the URL scheme is `slack://`.
/// See https://github.com/lycheeverse/lychee/issues/199
Unsupported(ErrorKind),
/// Cached request status from previous run
Cached(CacheStatus),
}
impl Display for Status {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Status::Ok(code) => write!(f, "OK ({code})"),
Status::Redirected(code) => write!(f, "Redirect ({code})"),
Status::UnknownStatusCode(code) => write!(f, "Unknown status ({code})"),
Status::Excluded => f.write_str("Excluded"),
Status::Timeout(Some(code)) => write!(f, "Timeout ({code})"),
Status::Timeout(None) => f.write_str("Timeout"),
Status::Unsupported(e) => write!(f, "Unsupported: {e}"),
Status::Error(e) => write!(f, "Failed: {e}"),
Status::Cached(status) => write!(f, "Cached: {status}"),
}
}
}
impl Serialize for Status {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut s;
if let Some(code) = self.code() {
s = serializer.serialize_struct("Status", 2)?;
s.serialize_field("text", &self.to_string())?;
s.serialize_field("code", &code.as_u16())?;
} else {
s = serializer.serialize_struct("Status", 1)?;
s.serialize_field("text", &self.to_string())?;
}
s.end()
}
}
impl Status {
#[must_use]
/// Create a status object from a response and the set of accepted status codes
pub fn new(response: &Response, accepted: Option<HashSet<StatusCode>>) -> Self {
let code = response.status();
if let Some(true) = accepted.map(|a| a.contains(&code)) {
Self::Ok(code)
} else {
match response.error_for_status_ref() {
Ok(_) if code.is_success() => Self::Ok(code),
Ok(_) if code.is_redirection() => Self::Redirected(code),
Ok(_) => Self::UnknownStatusCode(code),
Err(e) => e.into(),
}
}
}
/// Create a status object from a cached status (from a previous run of
/// lychee) and the set of accepted status codes.
///
/// The set of accepted status codes can change between runs,
/// necessitating more complex logic than just using the cached status.
///
/// Note that the accepted status codes are not of type `StatusCode`,
/// because they are provided by the user and can be invalid according to
/// the HTTP spec and IANA, but the user might still want to accept them.
#[must_use]
pub fn from_cache_status(s: CacheStatus, accepted: &HashSet<u16>) -> Self {
match s {
CacheStatus::Ok(code) => {
if matches!(s, CacheStatus::Ok(_)) || accepted.contains(&code) {
return Self::Cached(CacheStatus::Ok(code));
};
Self::Cached(CacheStatus::Error(Some(code)))
}
CacheStatus::Error(code) => {
if let Some(code) = code {
if accepted.contains(&code) {
return Self::Cached(CacheStatus::Ok(code));
};
}
Self::Cached(CacheStatus::Error(code))
}
_ => Self::Cached(s),
}
}
/// Return more details about the status (if any)
///
/// Which additional information we can extract depends on the underlying
/// request type. The output is purely meant for humans and future changes
/// are expected.
///
/// It is modeled after reqwest's `details` method.
#[must_use]
#[allow(clippy::match_same_arms)]
pub fn details(&self) -> Option<String> {
match &self {
Status::Ok(code) => code.canonical_reason().map(String::from),
Status::Redirected(code) => code.canonical_reason().map(String::from),
Status::Error(e) => e.details(),
Status::Timeout(_) => None,
Status::UnknownStatusCode(_) => None,
Status::Unsupported(_) => None,
Status::Cached(_) => None,
Status::Excluded => None,
}
}
#[inline]
#[must_use]
/// Returns `true` if the check was successful
pub const fn is_success(&self) -> bool {
matches!(self, Status::Ok(_) | Status::Cached(CacheStatus::Ok(_)))
}
#[inline]
#[must_use]
/// Returns `true` if the check was not successful
pub const fn is_failure(&self) -> bool {
matches!(
self,
Status::Error(_) | Status::Cached(CacheStatus::Error(_)) | Status::Timeout(_)
)
}
#[inline]
#[must_use]
/// Returns `true` if the check was excluded
pub const fn is_excluded(&self) -> bool {
matches!(
self,
Status::Excluded | Status::Cached(CacheStatus::Excluded)
)
}
#[inline]
#[must_use]
/// Returns `true` if a check took too long to complete
pub const fn is_timeout(&self) -> bool {
matches!(self, Status::Timeout(_))
}
#[inline]
#[must_use]
/// Returns `true` if a URI is unsupported
pub const fn is_unsupported(&self) -> bool {
matches!(
self,
Status::Unsupported(_) | Status::Cached(CacheStatus::Unsupported)
)
}
#[must_use]
/// Return a unicode icon to visualize the status
pub const fn icon(&self) -> &str {
match self {
Status::Ok(_) => ICON_OK,
Status::Redirected(_) => ICON_REDIRECTED,
Status::UnknownStatusCode(_) => ICON_UNKNOWN,
Status::Excluded => ICON_EXCLUDED,
Status::Error(_) => ICON_ERROR,
Status::Timeout(_) => ICON_TIMEOUT,
Status::Unsupported(_) => ICON_UNSUPPORTED,
Status::Cached(_) => ICON_CACHED,
}
}
/// Return the HTTP status code (if any)
#[must_use]
pub fn code(&self) -> Option<StatusCode> {
match self {
Status::Ok(code)
| Status::Redirected(code)
| Status::UnknownStatusCode(code)
| Status::Timeout(Some(code)) => Some(*code),
Status::Error(kind) | Status::Unsupported(kind) => {
if let Some(error) = kind.reqwest_error() {
error.status()
} else {
None
}
}
Status::Cached(cache_status) => match cache_status {
CacheStatus::Ok(code) | CacheStatus::Error(Some(code)) => {
match StatusCode::from_u16(*code) {
Ok(code) => Some(code),
Err(_) => None,
}
}
_ => None,
},
_ => None,
}
}
/// Return the HTTP status code as string (if any)
#[must_use]
pub fn code_as_string(&self) -> String {
match self {
Status::Ok(code) | Status::Redirected(code) | Status::UnknownStatusCode(code) => {
code.as_str().to_string()
}
Status::Excluded => "EXCLUDED".to_string(),
Status::Error(e) => match e {
ErrorKind::NetworkRequest(e)
| ErrorKind::ReadResponseBody(e)
| ErrorKind::BuildRequestClient(e) => match e.status() {
Some(code) => code.as_str().to_string(),
None => "ERR".to_string(),
},
_ => "ERR".to_string(),
},
Status::Timeout(code) => match code {
Some(code) => code.as_str().to_string(),
None => "TIMEOUT".to_string(),
},
Status::Unsupported(_) => "IGNORED".to_string(),
Status::Cached(cache_status) => match cache_status {
CacheStatus::Ok(code) => code.to_string(),
CacheStatus::Error(code) => match code {
Some(code) => code.to_string(),
None => "ERR".to_string(),
},
CacheStatus::Excluded => "EXCLUDED".to_string(),
CacheStatus::Unsupported => "IGNORED".to_string(),
},
}
}
/// Returns true if the status code is unknown
/// (i.e. not a valid HTTP status code)
///
/// For example, `200` is a valid HTTP status code,
/// while `999` is not.
#[must_use]
pub const fn is_unknown(&self) -> bool {
matches!(self, Status::UnknownStatusCode(_))
}
}
impl From<ErrorKind> for Status {
fn from(e: ErrorKind) -> Self {
Self::Error(e)
}
}
impl From<reqwest::Error> for Status {
fn from(e: reqwest::Error) -> Self {
if e.is_timeout() {
Self::Timeout(e.status())
} else if e.is_redirect() {
Self::Error(ErrorKind::TooManyRedirects(e))
} else if e.is_builder() {
Self::Unsupported(ErrorKind::BuildRequestClient(e))
} else if e.is_body() || e.is_decode() {
Self::Unsupported(ErrorKind::ReadResponseBody(e))
} else {
Self::Error(ErrorKind::NetworkRequest(e))
}
}
}
#[cfg(test)]
mod tests {
use crate::{CacheStatus, ErrorKind, Status};
use http::StatusCode;
#[test]
fn test_status_serialization() {
let status_ok = Status::Ok(StatusCode::from_u16(200).unwrap());
let serialized_with_code = serde_json::to_string(&status_ok).unwrap();
assert_eq!(
"{\"text\":\"OK (200 OK)\",\"code\":200}",
serialized_with_code
);
let status_timeout = Status::Timeout(None);
let serialized_without_code = serde_json::to_string(&status_timeout).unwrap();
assert_eq!("{\"text\":\"Timeout\"}", serialized_without_code);
}
#[test]
fn test_get_status_code() {
assert_eq!(
Status::Ok(StatusCode::from_u16(200).unwrap())
.code()
.unwrap(),
200
);
assert_eq!(
Status::Timeout(Some(StatusCode::from_u16(408).unwrap()))
.code()
.unwrap(),
408
);
assert_eq!(
Status::UnknownStatusCode(StatusCode::from_u16(999).unwrap())
.code()
.unwrap(),
999
);
assert_eq!(
Status::Redirected(StatusCode::from_u16(300).unwrap())
.code()
.unwrap(),
300
);
assert_eq!(Status::Cached(CacheStatus::Ok(200)).code().unwrap(), 200);
assert_eq!(
Status::Cached(CacheStatus::Error(Some(404)))
.code()
.unwrap(),
404
);
assert_eq!(Status::Timeout(None).code(), None);
assert_eq!(Status::Cached(CacheStatus::Error(None)).code(), None);
assert_eq!(Status::Excluded.code(), None);
assert_eq!(
Status::Unsupported(ErrorKind::InvalidStatusCode(999)).code(),
None
);
}
#[test]
fn test_status_unknown() {
assert!(Status::UnknownStatusCode(StatusCode::from_u16(999).unwrap()).is_unknown());
assert!(!Status::Ok(StatusCode::from_u16(200).unwrap()).is_unknown());
}
}