Skip to main content

basecamp_sdk/
error.rs

1//! SPEC §6: the one error every call can answer with.
2
3use std::collections::BTreeMap;
4use std::fmt;
5
6use chrono::{DateTime, Utc};
7use serde_json::Value;
8
9use crate::generated::types::TemplateLibraryConfirmationPerson;
10use crate::http::{HeaderMap, StatusCode};
11
12/// How far [`Error::find_source`] walks a cause chain before giving up.
13const MAX_SOURCE_CHAIN_DEPTH: usize = 32;
14
15/// The most of a server's message an error carries; longer ones end in `...`.
16pub const MAX_ERROR_MESSAGE_LENGTH: usize = 500;
17/// The most of a failure's body an error keeps.
18pub const MAX_ERROR_BODY_BYTES: usize = 1_048_576;
19/// The ceiling both `Retry-After` forms saturate at, in seconds (SPEC §7's Rust row).
20pub const MAX_RETRY_AFTER_SECONDS: u32 = 2_147_483_647;
21
22/// Machine-readable error categories, shared with every Basecamp SDK.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24#[non_exhaustive]
25pub enum ErrorCode {
26    /// Client misconfiguration: bad arguments, a bad URL.
27    Usage,
28    /// 404.
29    NotFound,
30    /// 401, or no credentials to send.
31    AuthRequired,
32    /// 403.
33    Forbidden,
34    /// 429.
35    RateLimit,
36    /// Connection failure, timeout, DNS.
37    Network,
38    /// A server-side error, or a malformed 2xx body.
39    ApiError,
40    /// A name matched more than one record.
41    Ambiguous,
42    /// 400 or 422.
43    Validation,
44    /// 507: an account limit blocks the request.
45    LimitExceeded,
46}
47
48impl ErrorCode {
49    /// The code as every SDK spells it: `auth_required`, `rate_limit`.
50    pub fn as_str(&self) -> &'static str {
51        match self {
52            ErrorCode::Usage => "usage",
53            ErrorCode::NotFound => "not_found",
54            ErrorCode::AuthRequired => "auth_required",
55            ErrorCode::Forbidden => "forbidden",
56            ErrorCode::RateLimit => "rate_limit",
57            ErrorCode::Network => "network",
58            ErrorCode::ApiError => "api_error",
59            ErrorCode::Ambiguous => "ambiguous",
60            ErrorCode::Validation => "validation",
61            ErrorCode::LimitExceeded => "limit_exceeded",
62        }
63    }
64
65    /// The process exit status a command should end with.
66    pub fn exit_code(&self) -> i32 {
67        match self {
68            ErrorCode::Usage => 1,
69            ErrorCode::NotFound => 2,
70            ErrorCode::AuthRequired => 3,
71            ErrorCode::Forbidden => 4,
72            ErrorCode::RateLimit => 5,
73            ErrorCode::Network => 6,
74            ErrorCode::ApiError => 7,
75            ErrorCode::Ambiguous => 8,
76            ErrorCode::Validation => 9,
77            ErrorCode::LimitExceeded => 10,
78        }
79    }
80}
81
82impl fmt::Display for ErrorCode {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        f.write_str(self.as_str())
85    }
86}
87
88/// The error every SDK call can answer with: SPEC §6's record, read through accessors.
89///
90/// It is three pointers wide — the record lives behind a box, beside an optional boxed
91/// cause — so a `Result<T, Error>` stays small on the success path.
92#[derive(thiserror::Error)]
93#[error("{}", self.render())]
94pub struct Error {
95    inner: Box<Inner>,
96    #[source]
97    source: Option<Box<dyn std::error::Error + Send + Sync>>,
98}
99
100struct Inner {
101    code: ErrorCode,
102    message: String,
103    hint: Option<String>,
104    http_status: Option<u16>,
105    retryable: bool,
106    retry_after: Option<u32>,
107    request_id: Option<String>,
108    field_errors: Option<BTreeMap<String, Vec<String>>>,
109    confirmation_people: Option<Vec<TemplateLibraryConfirmationPerson>>,
110    response_too_large: bool,
111    deadline_exceeded: bool,
112    timeout: bool,
113    body: Option<Box<[u8]>>,
114}
115
116impl Error {
117    /// An error with a code and a message. The message is bounded to
118    /// [`MAX_ERROR_MESSAGE_LENGTH`] here, so every construction site is bounded.
119    pub fn new(code: ErrorCode, message: impl Into<String>) -> Error {
120        Error {
121            inner: Box::new(Inner {
122                code,
123                message: truncate(&message.into()),
124                hint: None,
125                http_status: None,
126                retryable: false,
127                retry_after: None,
128                request_id: None,
129                field_errors: None,
130                confirmation_people: None,
131                response_too_large: false,
132                deadline_exceeded: false,
133                timeout: false,
134                body: None,
135            }),
136            source: None,
137        }
138    }
139
140    /// A transport failure that was a timeout: the request was sent and no answer arrived
141    /// in the transport's own time. Retryable, and told apart from other transport failures
142    /// by [`Error::is_timeout`] where a loop treats the two differently (SPEC §16).
143    pub fn network_timeout(source: impl std::error::Error + Send + Sync + 'static) -> Error {
144        let mut error = Error::network(source);
145        error.inner.timeout = true;
146        error
147    }
148
149    /// A client-side misuse.
150    pub fn usage(message: impl Into<String>) -> Error {
151        Error::new(ErrorCode::Usage, message)
152    }
153
154    /// A transport failure: no connection, a timeout, a broken stream. Retryable.
155    pub fn network(source: impl std::error::Error + Send + Sync + 'static) -> Error {
156        Error::new(ErrorCode::Network, "Network error")
157            .with_hint(source.to_string())
158            .retryable(true)
159            .with_source(source)
160    }
161
162    /// A transport failure whose cause is not chained, for a request whose URL carries a
163    /// credential (SPEC §9): only the origin is named.
164    pub fn network_at(origin: &str) -> Error {
165        Error::new(
166            ErrorCode::Network,
167            format!("Network error contacting {origin}"),
168        )
169        .retryable(true)
170    }
171
172    /// A successful status whose body could not be read as the type the operation
173    /// declares: statusless, non-retryable `api_error` (SPEC §6).
174    pub fn malformed_response(detail: impl Into<String>) -> Error {
175        Error::new(
176            ErrorCode::ApiError,
177            truncate(&format!("malformed response: {}", detail.into())),
178        )
179    }
180
181    /// A body the client refused to read past its cap.
182    pub fn response_too_large(limit: usize) -> Error {
183        let mut error = Error::new(
184            ErrorCode::ApiError,
185            format!("response body exceeds {limit} bytes"),
186        );
187        error.inner.response_too_large = true;
188        error
189    }
190
191    /// The operation deadline passed before the call finished.
192    pub fn deadline_exceeded(after: std::time::Duration) -> Error {
193        let mut error = Error::new(
194            ErrorCode::Network,
195            format!("operation deadline of {after:?} exceeded"),
196        );
197        error.inner.deadline_exceeded = true;
198        error
199    }
200
201    /// Maps a non-2xx response onto SPEC §6's status table, parses the body per its Error
202    /// Body Parsing and field-keyed algorithms, and reads `Retry-After` and `X-Request-Id`.
203    pub fn from_response(status: StatusCode, headers: &HeaderMap, body: &[u8]) -> Error {
204        let status_code = status.as_u16();
205        let (code, retryable) = match status_code {
206            401 => (ErrorCode::AuthRequired, false),
207            403 => (ErrorCode::Forbidden, false),
208            404 => (ErrorCode::NotFound, false),
209            429 => (ErrorCode::RateLimit, true),
210            400 | 422 => (ErrorCode::Validation, false),
211            500 | 502 | 503 | 504 => (ErrorCode::ApiError, true),
212            507 => (ErrorCode::LimitExceeded, false),
213            code if code >= 500 => (ErrorCode::ApiError, true),
214            _ => (ErrorCode::ApiError, false),
215        };
216        let parsed = serde_json::from_slice::<Value>(body).ok();
217        let scalar = parsed
218            .as_ref()
219            .and_then(|value| value.get("error").and_then(Value::as_str))
220            .or_else(|| {
221                parsed
222                    .as_ref()
223                    .and_then(|value| value.get("message").and_then(Value::as_str))
224            })
225            .map(str::to_string);
226        let mut message = scalar
227            .clone()
228            .unwrap_or_else(|| format!("Request failed (HTTP {status_code})"));
229        let hint = parsed
230            .as_ref()
231            .and_then(|value| value.get("error_description").and_then(Value::as_str))
232            .map(truncate);
233
234        let field_errors = match (status_code, &parsed) {
235            (400 | 422, Some(value)) => field_errors_of(value),
236            _ => None,
237        };
238        if let Some(fields) = &field_errors {
239            let flattened = flatten(fields);
240            message = match scalar {
241                Some(_) => format!("{message} ({flattened})"),
242                None => flattened,
243            };
244        }
245        let confirmation_people = match (status_code, &parsed) {
246            (422, Some(value)) => confirmation_people_of(value),
247            _ => None,
248        };
249
250        let mut error = Error::new(code, truncate(&message))
251            .retryable(retryable)
252            .with_status(status_code);
253        error.inner.hint = hint;
254        error.inner.retry_after = parse_retry_after_header(headers, Utc::now());
255        error.inner.request_id = headers
256            .get("x-request-id")
257            .and_then(|value| value.to_str().ok())
258            .map(truncate);
259        error.inner.field_errors = field_errors;
260        error.inner.confirmation_people = confirmation_people;
261        if !body.is_empty() {
262            let kept = body.len().min(MAX_ERROR_BODY_BYTES);
263            error.inner.body = Some(Box::from(&body[..kept]));
264        }
265        error
266    }
267
268    /// The first cause of a given type anywhere in the error's chain.
269    ///
270    /// A cause is how this crate carries an identity the closed taxonomy of [`ErrorCode`]
271    /// has no member for — the recording-summary composite's own verdicts, the discovery
272    /// cache's listing-overflow marker. A single-level `downcast_ref` would lose that
273    /// identity the moment anything re-wrapped the error, and [`Error::with_source`] is
274    /// public, so the whole chain is walked. The depth bound is insurance against an
275    /// `Error` implementation whose `source` cycles; a real chain is two or three deep.
276    pub(crate) fn find_source<T: std::error::Error + 'static>(&self) -> Option<&T> {
277        let mut current = std::error::Error::source(self);
278        for _ in 0..MAX_SOURCE_CHAIN_DEPTH {
279            let error = current?;
280            if let Some(found) = error.downcast_ref::<T>() {
281                return Some(found);
282            }
283            current = error.source();
284        }
285        None
286    }
287
288    /// A full-fidelity copy of the record, without the cause.
289    ///
290    /// [`Error`] is not `Clone` — its cause is a boxed trait object — so a failure that must
291    /// reach more than one caller is copied here and the shared original chained back on as
292    /// the cause. Every member of the record travels, the classification flags included: an
293    /// error that loses `is_timeout` on the way to a second caller is an error that caller
294    /// would handle differently (SPEC §16).
295    pub(crate) fn duplicate(&self) -> Error {
296        Error {
297            inner: Box::new(Inner {
298                code: self.inner.code,
299                message: self.inner.message.clone(),
300                hint: self.inner.hint.clone(),
301                http_status: self.inner.http_status,
302                retryable: self.inner.retryable,
303                retry_after: self.inner.retry_after,
304                request_id: self.inner.request_id.clone(),
305                field_errors: self.inner.field_errors.clone(),
306                confirmation_people: self.inner.confirmation_people.clone(),
307                response_too_large: self.inner.response_too_large,
308                deadline_exceeded: self.inner.deadline_exceeded,
309                timeout: self.inner.timeout,
310                body: self.inner.body.clone(),
311            }),
312            source: None,
313        }
314    }
315
316    /// The same error, its message prefixed with what the caller was doing. Everything else
317    /// — code, status, hint, the classification flags, the cause — is left exactly as it
318    /// was, so adding context never costs a caller the accessors it classifies on. This is
319    /// the Rust spelling of Go's `fmt.Errorf("doing x: %w", err)`.
320    pub(crate) fn with_context(mut self, context: impl fmt::Display) -> Error {
321        self.inner.message = truncate(&format!("{context}: {}", self.inner.message));
322        self
323    }
324
325    /// The same error with a hint, cut to the message cap like the message itself: a
326    /// transport's rendering of its own failure is not bounded by anyone else.
327    pub fn with_hint(mut self, hint: impl Into<String>) -> Error {
328        self.inner.hint = Some(truncate(&hint.into()));
329        self
330    }
331
332    /// The same error carrying an HTTP status.
333    pub fn with_status(mut self, status: u16) -> Error {
334        self.inner.http_status = Some(status);
335        self
336    }
337
338    /// The same error carrying a request id, bounded like the message: the header is the
339    /// server's to fill.
340    pub fn with_request_id(mut self, request_id: impl Into<String>) -> Error {
341        self.inner.request_id = Some(truncate(&request_id.into()));
342        self
343    }
344
345    /// The same error carrying the seconds a `Retry-After` header named.
346    pub fn with_retry_after(mut self, seconds: u32) -> Error {
347        self.inner.retry_after = Some(seconds);
348        self
349    }
350
351    /// The same error marked as a transport timeout, for a projection of one that kept
352    /// only the origin (SPEC §9).
353    pub(crate) fn timed_out(mut self) -> Error {
354        self.inner.timeout = true;
355        self
356    }
357
358    /// The same error with a cause.
359    pub fn with_source(mut self, source: impl std::error::Error + Send + Sync + 'static) -> Error {
360        self.source = Some(Box::new(source));
361        self
362    }
363
364    /// The same error, retryable or not.
365    pub fn retryable(mut self, retryable: bool) -> Error {
366        self.inner.retryable = retryable;
367        self
368    }
369
370    /// The categorical code.
371    pub fn code(&self) -> ErrorCode {
372        self.inner.code
373    }
374
375    /// The human-readable description, at most [`MAX_ERROR_MESSAGE_LENGTH`] characters.
376    pub fn message(&self) -> &str {
377        &self.inner.message
378    }
379
380    /// Resolution guidance, when there is any.
381    pub fn hint(&self) -> Option<&str> {
382        self.inner.hint.as_deref()
383    }
384
385    /// The HTTP status that caused the error, when one did.
386    pub fn http_status(&self) -> Option<u16> {
387        self.inner.http_status
388    }
389
390    /// Whether the operation can be retried.
391    pub fn is_retryable(&self) -> bool {
392        self.inner.retryable
393    }
394
395    /// The seconds `Retry-After` named, parsed per SPEC §6, at whatever status carried it.
396    pub fn retry_after(&self) -> Option<u32> {
397        self.inner.retry_after
398    }
399
400    /// `X-Request-Id`, when the response carried one.
401    pub fn request_id(&self) -> Option<&str> {
402        self.inner.request_id.as_deref()
403    }
404
405    /// The structured 400/422 field messages, raw and untruncated. Row-keyed bodies land
406    /// here keyed by email address, then `index`, then position.
407    pub fn field_errors(&self) -> Option<&BTreeMap<String, Vec<String>>> {
408        self.inner.field_errors.as_ref()
409    }
410
411    /// The people a template-library copy needs confirmed, when a 422 named them.
412    pub fn confirmation_people(&self) -> Option<&[TemplateLibraryConfirmationPerson]> {
413        self.inner.confirmation_people.as_deref()
414    }
415
416    /// The process exit status a command should end with.
417    pub fn exit_code(&self) -> i32 {
418        self.inner.code.exit_code()
419    }
420
421    /// The failure body, up to [`MAX_ERROR_BODY_BYTES`], when the server sent one.
422    pub fn body(&self) -> Option<&[u8]> {
423        self.inner.body.as_deref()
424    }
425
426    /// The answer was longer than the client will hold.
427    pub fn is_response_too_large(&self) -> bool {
428        self.inner.response_too_large
429    }
430
431    /// The operation deadline passed.
432    pub fn is_deadline_exceeded(&self) -> bool {
433        self.inner.deadline_exceeded
434    }
435
436    /// The transport reported a timeout.
437    pub fn is_timeout(&self) -> bool {
438        self.inner.timeout
439    }
440
441    fn render(&self) -> String {
442        match &self.inner.hint {
443            Some(hint) => format!("{}: {hint}", self.inner.message),
444            None => self.inner.message.clone(),
445        }
446    }
447}
448
449impl fmt::Debug for Error {
450    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
451        f.debug_struct("Error")
452            .field("code", &self.inner.code)
453            .field("message", &self.inner.message)
454            .field("hint", &self.inner.hint)
455            .field("http_status", &self.inner.http_status)
456            .field("retryable", &self.inner.retryable)
457            .field("retry_after", &self.inner.retry_after)
458            .field("request_id", &self.inner.request_id)
459            .field("field_errors", &self.inner.field_errors)
460            .finish_non_exhaustive()
461    }
462}
463
464/// Cuts a message to [`MAX_ERROR_MESSAGE_LENGTH`] bytes, ending it in `...` when it was
465/// longer. The unit is the byte, as in Go and Ruby (SPEC §9); the cut lands on a UTF-8
466/// character boundary so the result is always a valid `str`.
467pub fn truncate(message: &str) -> String {
468    if message.len() <= MAX_ERROR_MESSAGE_LENGTH {
469        return message.to_string();
470    }
471    let mut end = MAX_ERROR_MESSAGE_LENGTH - 3;
472    while !message.is_char_boundary(end) {
473        end -= 1;
474    }
475    format!("{}...", &message[..end])
476}
477
478/// SPEC §6's field-keyed algorithm, steps 1, 1b and 2.
479fn field_errors_of(body: &Value) -> Option<BTreeMap<String, Vec<String>>> {
480    let object = body.as_object()?;
481    match object.get("errors") {
482        Some(Value::Object(fields)) => {
483            let mut map = BTreeMap::new();
484            for (field, messages) in fields {
485                if let Some(messages) = messages.as_array() {
486                    let kept: Vec<String> = messages
487                        .iter()
488                        .filter_map(Value::as_str)
489                        .map(str::to_string)
490                        .collect();
491                    if !kept.is_empty() {
492                        map.insert(field.clone(), kept);
493                    }
494                }
495            }
496            (!map.is_empty()).then_some(map)
497        }
498        Some(Value::Array(rows)) => row_keyed(rows),
499        Some(_) => None,
500        None => {
501            if object.is_empty() {
502                return None;
503            }
504            let mut map = BTreeMap::new();
505            for (field, messages) in object {
506                let messages = messages.as_array()?;
507                if messages.is_empty() {
508                    return None;
509                }
510                let mut kept = Vec::new();
511                for message in messages {
512                    match message.as_str() {
513                        Some(text) if !text.is_empty() => kept.push(text.to_string()),
514                        _ => return None,
515                    }
516                }
517                map.insert(field.clone(), kept);
518            }
519            Some(map)
520        }
521    }
522}
523
524/// Step 1b: every element an object whose `messages` holds at least one non-empty string,
525/// keyed by `email_address`, then `index`, then position.
526fn row_keyed(rows: &[Value]) -> Option<BTreeMap<String, Vec<String>>> {
527    if rows.is_empty() {
528        return None;
529    }
530    let mut map: BTreeMap<String, Vec<String>> = BTreeMap::new();
531    for (position, row) in rows.iter().enumerate() {
532        let object = row.as_object()?;
533        let messages: Vec<String> = object
534            .get("messages")?
535            .as_array()?
536            .iter()
537            .filter_map(Value::as_str)
538            .filter(|text| !text.is_empty())
539            .map(str::to_string)
540            .collect();
541        if messages.is_empty() {
542            return None;
543        }
544        let key = match object.get("email_address").and_then(Value::as_str) {
545            Some(address) if !address.is_empty() => address.to_string(),
546            _ => match object.get("index").and_then(Value::as_i64) {
547                Some(index) => index.to_string(),
548                None => position.to_string(),
549            },
550        };
551        map.entry(key).or_default().extend(messages);
552    }
553    Some(map)
554}
555
556/// `field: m1; m2, other: m3`, fields sorted.
557fn flatten(fields: &BTreeMap<String, Vec<String>>) -> String {
558    fields
559        .iter()
560        .map(|(field, messages)| format!("{field}: {}", messages.join("; ")))
561        .collect::<Vec<_>>()
562        .join(", ")
563}
564
565fn confirmation_people_of(body: &Value) -> Option<Vec<TemplateLibraryConfirmationPerson>> {
566    let people = body.get("people")?.as_array()?;
567    if people.is_empty() {
568        return None;
569    }
570    let mut result = Vec::new();
571    for person in people {
572        let object = person.as_object()?;
573        let id = object.get("id")?.as_i64()?;
574        let name = object.get("name")?.as_str()?;
575        let avatar_url = object.get("avatar_url")?.as_str()?;
576        if id <= 0 || name.is_empty() || avatar_url.is_empty() {
577            return None;
578        }
579        result.push(serde_json::from_value(person.clone()).ok()?);
580    }
581    Some(result)
582}
583
584/// SPEC §6's `Retry-After` table: `1*DIGIT` (no sign, no fraction) saturating at
585/// [`MAX_RETRY_AFTER_SECONDS`], with `0` falling through; or an HTTP-date, rounded up to
586/// whole seconds from `now` and saturating at the same ceiling, with a past date falling
587/// through. Anything else is no value.
588pub fn parse_retry_after(value: &str, now: DateTime<Utc>) -> Option<u32> {
589    let value = value.trim_matches([' ', '\t']);
590    if value.is_empty() {
591        return None;
592    }
593    if value.bytes().all(|b| b.is_ascii_digit()) {
594        let seconds = match value.parse::<u64>() {
595            Ok(seconds) => seconds.min(u64::from(MAX_RETRY_AFTER_SECONDS)),
596            Err(_) => u64::from(MAX_RETRY_AFTER_SECONDS),
597        };
598        return (seconds > 0).then(|| u32::try_from(seconds).unwrap_or(MAX_RETRY_AFTER_SECONDS));
599    }
600    let until = parse_http_date(value)?;
601    let left = until.signed_duration_since(now);
602    let whole = left.num_seconds();
603    let started = left > chrono::TimeDelta::seconds(whole);
604    if whole < 0 || (whole == 0 && !started) {
605        return None;
606    }
607    let seconds = whole.saturating_add(i64::from(started));
608    Some(
609        u32::try_from(seconds)
610            .unwrap_or(MAX_RETRY_AFTER_SECONDS)
611            .min(MAX_RETRY_AFTER_SECONDS),
612    )
613}
614
615/// An HTTP-date and nothing else: IMF-fixdate, then the obsolete RFC 850 and asctime forms
616/// (RFC 9110 §5.6.7). RFC 2822's wider grammar — numeric offsets, zone names, `Z`, a
617/// missing weekday — is not an HTTP-date and falls through.
618fn parse_http_date(value: &str) -> Option<DateTime<Utc>> {
619    let collapsed: String = value.split_whitespace().collect::<Vec<_>>().join(" ");
620    for format in [
621        "%a, %d %b %Y %H:%M:%S GMT",
622        "%A, %d-%b-%y %H:%M:%S GMT",
623        "%a %b %d %H:%M:%S %Y",
624    ] {
625        if let Ok(naive) = chrono::NaiveDateTime::parse_from_str(&collapsed, format) {
626            return Some(naive.and_utc());
627        }
628    }
629    None
630}
631
632/// The `Retry-After` header, parsed.
633pub(crate) fn parse_retry_after_header(headers: &HeaderMap, now: DateTime<Utc>) -> Option<u32> {
634    headers
635        .get("retry-after")
636        .and_then(|value| value.to_str().ok())
637        .and_then(|value| parse_retry_after(value, now))
638}
639
640#[cfg(test)]
641mod tests {
642    use super::*;
643    use crate::http::HeaderValue;
644
645    fn at(seconds: i64) -> DateTime<Utc> {
646        DateTime::from_timestamp(1_700_000_000 + seconds, 0).unwrap()
647    }
648
649    fn headers(pairs: &[(&str, &str)]) -> HeaderMap {
650        let mut headers = HeaderMap::new();
651        for (name, value) in pairs {
652            headers.insert(
653                crate::http::HeaderName::from_bytes(name.as_bytes()).unwrap(),
654                HeaderValue::from_str(value).unwrap(),
655            );
656        }
657        headers
658    }
659
660    #[test]
661    fn retry_after_digits_saturate_and_zero_falls_through() {
662        assert_eq!(parse_retry_after("5", at(0)), Some(5));
663        assert_eq!(parse_retry_after(" 5 ", at(0)), Some(5));
664        assert_eq!(parse_retry_after("0", at(0)), None);
665        assert_eq!(parse_retry_after("+5", at(0)), None);
666        assert_eq!(parse_retry_after("-5", at(0)), None);
667        assert_eq!(parse_retry_after("2.5", at(0)), None);
668        assert_eq!(parse_retry_after("5s", at(0)), None);
669        assert_eq!(parse_retry_after("2147483647", at(0)), Some(2_147_483_647));
670        assert_eq!(parse_retry_after("2147483648", at(0)), Some(2_147_483_647));
671        assert_eq!(
672            parse_retry_after("99999999999999999999999999", at(0)),
673            Some(2_147_483_647)
674        );
675        assert_eq!(parse_retry_after("", at(0)), None);
676    }
677
678    #[test]
679    fn retry_after_dates_round_up_and_past_dates_fall_through() {
680        let now = DateTime::parse_from_rfc3339("2021-06-09T10:18:14.250Z")
681            .unwrap()
682            .with_timezone(&Utc);
683        assert_eq!(
684            parse_retry_after("Wed, 09 Jun 2021 10:18:16 GMT", now),
685            Some(2)
686        );
687        assert_eq!(
688            parse_retry_after("Wed, 09 Jun 2021 10:18:15 GMT", now),
689            Some(1)
690        );
691        assert_eq!(
692            parse_retry_after("Wed, 09 Jun 2021 10:18:14 GMT", now),
693            None
694        );
695        let just_before = DateTime::parse_from_rfc3339("2021-06-09T10:18:14.999999999Z")
696            .unwrap()
697            .with_timezone(&Utc);
698        assert_eq!(
699            parse_retry_after("Wed, 09 Jun 2021 10:18:15 GMT", just_before),
700            Some(1)
701        );
702        let just_after = DateTime::parse_from_rfc3339("2021-06-09T10:18:13.999999999Z")
703            .unwrap()
704            .with_timezone(&Utc);
705        assert_eq!(
706            parse_retry_after("Wed, 09 Jun 2021 10:18:15 GMT", just_after),
707            Some(2)
708        );
709        assert_eq!(
710            parse_retry_after("Wed, 09 Jun 2021 09:00:00 GMT", now),
711            None
712        );
713        assert_eq!(
714            parse_retry_after("Wednesday, 09-Jun-21 10:18:16 GMT", now),
715            Some(2)
716        );
717        assert_eq!(parse_retry_after("Wed Jun  9 10:18:16 2021", now), Some(2));
718        assert_eq!(
719            parse_retry_after("Tue, 31 Dec 2999 00:00:00 GMT", now),
720            Some(2_147_483_647)
721        );
722        for not_http_date in [
723            "Wed, 09 Jun 2021 10:18:16 -0500",
724            "Wed, 09 Jun 2021 10:18:16 +0000",
725            "Wed, 09 Jun 2021 10:18:16 UT",
726            "Wed, 09 Jun 2021 10:18:16 EST",
727            "Wed, 09 Jun 2021 10:18:16 Z",
728            "09 Jun 2021 10:18:16 GMT",
729            "Wed, 09 Jun 21 10:18:16 GMT",
730        ] {
731            assert_eq!(
732                parse_retry_after(not_http_date, now),
733                None,
734                "{not_http_date} is RFC 2822, not an HTTP-date"
735            );
736        }
737        assert_eq!(parse_retry_after("not a date", now), None);
738    }
739
740    #[test]
741    fn statuses_map_to_codes_in_order() {
742        let cases = [
743            (401, ErrorCode::AuthRequired, false),
744            (403, ErrorCode::Forbidden, false),
745            (404, ErrorCode::NotFound, false),
746            (429, ErrorCode::RateLimit, true),
747            (400, ErrorCode::Validation, false),
748            (422, ErrorCode::Validation, false),
749            (500, ErrorCode::ApiError, true),
750            (502, ErrorCode::ApiError, true),
751            (503, ErrorCode::ApiError, true),
752            (504, ErrorCode::ApiError, true),
753            (507, ErrorCode::LimitExceeded, false),
754            (599, ErrorCode::ApiError, true),
755            (418, ErrorCode::ApiError, false),
756        ];
757        for (status, code, retryable) in cases {
758            let error = Error::from_response(
759                StatusCode::from_u16(status).unwrap(),
760                &headers(&[("x-request-id", "req-1")]),
761                b"",
762            );
763            assert_eq!(error.code(), code, "{status}");
764            assert_eq!(error.is_retryable(), retryable, "{status}");
765            assert_eq!(error.http_status(), Some(status));
766            assert_eq!(error.request_id(), Some("req-1"));
767            assert_eq!(error.message(), format!("Request failed (HTTP {status})"));
768        }
769    }
770
771    #[test]
772    fn a_composed_validation_message_is_truncated_once() {
773        // 496 ASCII bytes, a three-byte character straddling the cut, then more: cutting the
774        // scalar before composition would leave an ellipsis for the final cut to land in.
775        let scalar = format!("{}\u{20ac}bb", "a".repeat(MAX_ERROR_MESSAGE_LENGTH - 4));
776        let body = serde_json::json!({"error": scalar, "errors": {"name": ["x"]}}).to_string();
777        let error = Error::from_response(
778            StatusCode::UNPROCESSABLE_ENTITY,
779            &HeaderMap::new(),
780            body.as_bytes(),
781        );
782        assert_eq!(
783            error.message(),
784            format!("{}...", "a".repeat(MAX_ERROR_MESSAGE_LENGTH - 4))
785        );
786        assert_eq!(error.field_errors().unwrap()["name"], vec!["x".to_string()]);
787    }
788
789    #[test]
790    fn request_id_read_off_a_response_is_bounded_like_the_setter() {
791        let long = "r".repeat(MAX_ERROR_MESSAGE_LENGTH + 1);
792        let error = Error::from_response(
793            StatusCode::BAD_GATEWAY,
794            &headers(&[("x-request-id", &long)]),
795            b"",
796        );
797        let expected = Error::usage("x").with_request_id(&long);
798        assert_eq!(error.request_id(), expected.request_id());
799        assert_eq!(error.request_id().unwrap().len(), MAX_ERROR_MESSAGE_LENGTH);
800        assert!(error.request_id().unwrap().ends_with("..."));
801    }
802
803    #[test]
804    fn retry_after_is_read_at_every_status() {
805        let error = Error::from_response(
806            StatusCode::SERVICE_UNAVAILABLE,
807            &headers(&[("retry-after", "7")]),
808            b"{}",
809        );
810        assert_eq!(error.retry_after(), Some(7));
811        let error = Error::from_response(
812            StatusCode::NOT_FOUND,
813            &headers(&[("retry-after", "3")]),
814            b"",
815        );
816        assert_eq!(error.retry_after(), Some(3));
817    }
818
819    #[test]
820    fn bodies_supply_message_and_hint() {
821        let error = Error::from_response(
822            StatusCode::UNAUTHORIZED,
823            &headers(&[]),
824            br#"{"error": "Unauthorized", "error_description": "token expired"}"#,
825        );
826        assert_eq!(error.message(), "Unauthorized");
827        assert_eq!(error.hint(), Some("token expired"));
828        let error = Error::from_response(
829            StatusCode::NOT_FOUND,
830            &headers(&[]),
831            br#"{"message": "Not found"}"#,
832        );
833        assert_eq!(error.message(), "Not found");
834        let error = Error::from_response(StatusCode::NOT_FOUND, &headers(&[]), b"<html>");
835        assert_eq!(error.message(), "Request failed (HTTP 404)");
836        let long = format!(r#"{{"error": "{}"}}"#, "x".repeat(600));
837        let error = Error::from_response(StatusCode::BAD_REQUEST, &headers(&[]), long.as_bytes());
838        assert_eq!(error.message().chars().count(), 500);
839        assert!(error.message().ends_with("..."));
840    }
841
842    #[test]
843    fn field_keyed_bodies_are_flattened_and_exposed() {
844        let error = Error::from_response(
845            StatusCode::UNPROCESSABLE_ENTITY,
846            &headers(&[]),
847            br#"{"error": "Validation failed", "errors": {"color": ["is not a valid color"], "name": ["can't be blank", "is too short"]}}"#,
848        );
849        assert_eq!(error.code(), ErrorCode::Validation);
850        assert_eq!(
851            error.message(),
852            "Validation failed (color: is not a valid color, name: can't be blank; is too short)"
853        );
854        assert_eq!(
855            error.field_errors().unwrap()["name"],
856            vec!["can't be blank", "is too short"]
857        );
858
859        let error = Error::from_response(
860            StatusCode::BAD_REQUEST,
861            &headers(&[]),
862            br#"{"payload_url": ["is not a valid URL"]}"#,
863        );
864        assert_eq!(error.message(), "payload_url: is not a valid URL");
865        assert_eq!(error.field_errors().unwrap().len(), 1);
866
867        let error = Error::from_response(
868            StatusCode::BAD_REQUEST,
869            &headers(&[]),
870            br#"{"error": "Webhook is invalid", "payload_url": ["is invalid"]}"#,
871        );
872        assert_eq!(error.message(), "Webhook is invalid");
873        assert!(error.field_errors().is_none());
874
875        let error = Error::from_response(
876            StatusCode::UNPROCESSABLE_ENTITY,
877            &headers(&[]),
878            br#"{"error": {}, "errors": {"base": ["Can't be undocked"], "__proto__": ["x"]}}"#,
879        );
880        assert_eq!(error.message(), "__proto__: x, base: Can't be undocked");
881
882        let error = Error::from_response(
883            StatusCode::NOT_FOUND,
884            &headers(&[]),
885            br#"{"errors": {"x": ["y"]}}"#,
886        );
887        assert!(error.field_errors().is_none());
888    }
889
890    #[test]
891    fn a_server_message_that_looks_synthetic_is_still_composed() {
892        let error = Error::from_response(
893            StatusCode::UNPROCESSABLE_ENTITY,
894            &headers(&[]),
895            br#"{"error": "Request failed (HTTP 422) upstream", "errors": {"x": ["y"]}}"#,
896        );
897        assert_eq!(error.message(), "Request failed (HTTP 422) upstream (x: y)");
898    }
899
900    #[test]
901    fn row_keyed_bodies_land_on_addresses_indexes_then_positions() {
902        let error = Error::from_response(
903            StatusCode::UNPROCESSABLE_ENTITY,
904            &headers(&[]),
905            br#"{"errors": [{"email_address": "not-an-address", "messages": ["Email address must be valid"]}, {"email_address": null, "messages": ["Email address can't be blank"]}, {"index": 7, "messages": ["Name can't be blank"]}, {"email_address": "not-an-address", "messages": ["Already invited"]}]}"#,
906        );
907        let fields = error.field_errors().unwrap();
908        assert_eq!(
909            fields["not-an-address"],
910            vec!["Email address must be valid", "Already invited"]
911        );
912        assert_eq!(fields["1"], vec!["Email address can't be blank"]);
913        assert_eq!(fields["7"], vec!["Name can't be blank"]);
914        assert_eq!(
915            error.message(),
916            "1: Email address can't be blank, 7: Name can't be blank, not-an-address: Email address must be valid; Already invited"
917        );
918
919        let error = Error::from_response(
920            StatusCode::UNPROCESSABLE_ENTITY,
921            &headers(&[]),
922            br#"{"errors": [{"email_address": "a", "messages": ["x"]}, {"email_address": "b"}]}"#,
923        );
924        assert!(error.field_errors().is_none());
925        assert_eq!(error.message(), "Request failed (HTTP 422)");
926    }
927
928    #[test]
929    fn confirmation_people_are_projected_only_when_every_entry_conforms() {
930        let error = Error::from_response(
931            StatusCode::UNPROCESSABLE_ENTITY,
932            &headers(&[]),
933            br#"{"error": "Confirmation required", "people": [{"id": 1, "name": "Ann", "avatar_url": "https://x/a.png"}]}"#,
934        );
935        assert_eq!(error.code(), ErrorCode::Validation);
936        assert_eq!(error.confirmation_people().unwrap().len(), 1);
937        assert_eq!(error.confirmation_people().unwrap()[0].id, 1);
938
939        let error = Error::from_response(
940            StatusCode::UNPROCESSABLE_ENTITY,
941            &headers(&[]),
942            br#"{"error": "x", "people": [{"id": 0, "name": "Ann", "avatar_url": "u"}]}"#,
943        );
944        assert!(error.confirmation_people().is_none());
945    }
946
947    #[test]
948    fn errors_are_send_and_sync() {
949        fn assert_send_sync<T: Send + Sync>() {}
950        assert_send_sync::<Error>();
951    }
952}