basecamp-sdk 0.38.0

Official client for Basecamp - https://basecamp.com
Documentation
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
//! SPEC §6: the one error every call can answer with.

use std::collections::BTreeMap;
use std::fmt;

use jiff::{SignedDuration, Timestamp};
use serde_json::Value;

use crate::generated::types::TemplateLibraryConfirmationPerson;
use crate::http::{HeaderMap, StatusCode};

/// How far [`Error::find_source`] walks a cause chain before giving up.
const MAX_SOURCE_CHAIN_DEPTH: usize = 32;

/// The most of a server's message an error carries; longer ones end in `...`.
pub const MAX_ERROR_MESSAGE_LENGTH: usize = 500;
/// The most of a failure's body an error keeps.
pub const MAX_ERROR_BODY_BYTES: usize = 1_048_576;
/// The ceiling both `Retry-After` forms saturate at, in seconds (SPEC §7's Rust row).
pub const MAX_RETRY_AFTER_SECONDS: u32 = 2_147_483_647;

/// Machine-readable error categories, shared with every Basecamp SDK.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorCode {
    /// Client misconfiguration: bad arguments, a bad URL.
    Usage,
    /// 404.
    NotFound,
    /// 401, or no credentials to send.
    AuthRequired,
    /// 403.
    Forbidden,
    /// 429.
    RateLimit,
    /// Connection failure, timeout, DNS.
    Network,
    /// A server-side error, or a malformed 2xx body.
    ApiError,
    /// A name matched more than one record.
    Ambiguous,
    /// 400 or 422.
    Validation,
    /// 507: an account limit blocks the request.
    LimitExceeded,
}

impl ErrorCode {
    /// The code as every SDK spells it: `auth_required`, `rate_limit`.
    pub fn as_str(&self) -> &'static str {
        match self {
            ErrorCode::Usage => "usage",
            ErrorCode::NotFound => "not_found",
            ErrorCode::AuthRequired => "auth_required",
            ErrorCode::Forbidden => "forbidden",
            ErrorCode::RateLimit => "rate_limit",
            ErrorCode::Network => "network",
            ErrorCode::ApiError => "api_error",
            ErrorCode::Ambiguous => "ambiguous",
            ErrorCode::Validation => "validation",
            ErrorCode::LimitExceeded => "limit_exceeded",
        }
    }

    /// The process exit status a command should end with.
    pub fn exit_code(&self) -> i32 {
        match self {
            ErrorCode::Usage => 1,
            ErrorCode::NotFound => 2,
            ErrorCode::AuthRequired => 3,
            ErrorCode::Forbidden => 4,
            ErrorCode::RateLimit => 5,
            ErrorCode::Network => 6,
            ErrorCode::ApiError => 7,
            ErrorCode::Ambiguous => 8,
            ErrorCode::Validation => 9,
            ErrorCode::LimitExceeded => 10,
        }
    }
}

impl fmt::Display for ErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The error every SDK call can answer with: SPEC §6's record, read through accessors.
///
/// It is three pointers wide — the record lives behind a box, beside an optional boxed
/// cause — so a `Result<T, Error>` stays small on the success path.
#[derive(thiserror::Error)]
#[error("{}", self.render())]
pub struct Error {
    inner: Box<Inner>,
    #[source]
    source: Option<Box<dyn std::error::Error + Send + Sync>>,
}

struct Inner {
    code: ErrorCode,
    message: String,
    hint: Option<String>,
    http_status: Option<u16>,
    retryable: bool,
    retry_after: Option<u32>,
    request_id: Option<String>,
    field_errors: Option<BTreeMap<String, Vec<String>>>,
    confirmation_people: Option<Vec<TemplateLibraryConfirmationPerson>>,
    response_too_large: bool,
    deadline_exceeded: bool,
    timeout: bool,
    body: Option<Box<[u8]>>,
}

impl Error {
    /// An error with a code and a message. The message is bounded to
    /// [`MAX_ERROR_MESSAGE_LENGTH`] here, so every construction site is bounded.
    pub fn new(code: ErrorCode, message: impl Into<String>) -> Error {
        Error {
            inner: Box::new(Inner {
                code,
                message: truncate(&message.into()),
                hint: None,
                http_status: None,
                retryable: false,
                retry_after: None,
                request_id: None,
                field_errors: None,
                confirmation_people: None,
                response_too_large: false,
                deadline_exceeded: false,
                timeout: false,
                body: None,
            }),
            source: None,
        }
    }

    /// A transport failure that was a timeout: the request was sent and no answer arrived
    /// in the transport's own time. Retryable, and told apart from other transport failures
    /// by [`Error::is_timeout`] where a loop treats the two differently (SPEC §16).
    pub fn network_timeout(source: impl std::error::Error + Send + Sync + 'static) -> Error {
        let mut error = Error::network(source);
        error.inner.timeout = true;
        error
    }

    /// A client-side misuse.
    pub fn usage(message: impl Into<String>) -> Error {
        Error::new(ErrorCode::Usage, message)
    }

    /// A transport failure: no connection, a timeout, a broken stream. Retryable.
    pub fn network(source: impl std::error::Error + Send + Sync + 'static) -> Error {
        Error::new(ErrorCode::Network, "Network error")
            .with_hint(source.to_string())
            .retryable(true)
            .with_source(source)
    }

    /// A transport failure whose cause is not chained, for a request whose URL carries a
    /// credential (SPEC §9): only the origin is named.
    pub fn network_at(origin: &str) -> Error {
        Error::new(
            ErrorCode::Network,
            format!("Network error contacting {origin}"),
        )
        .retryable(true)
    }

    /// A successful status whose body could not be read as the type the operation
    /// declares: statusless, non-retryable `api_error` (SPEC §6).
    pub fn malformed_response(detail: impl Into<String>) -> Error {
        Error::new(
            ErrorCode::ApiError,
            truncate(&format!("malformed response: {}", detail.into())),
        )
    }

    /// A body the client refused to read past its cap.
    pub fn response_too_large(limit: usize) -> Error {
        let mut error = Error::new(
            ErrorCode::ApiError,
            format!("response body exceeds {limit} bytes"),
        );
        error.inner.response_too_large = true;
        error
    }

    /// The operation deadline passed before the call finished.
    pub fn deadline_exceeded(after: std::time::Duration) -> Error {
        let mut error = Error::new(
            ErrorCode::Network,
            format!("operation deadline of {after:?} exceeded"),
        );
        error.inner.deadline_exceeded = true;
        error
    }

    /// Maps a non-2xx response onto SPEC §6's status table, parses the body per its Error
    /// Body Parsing and field-keyed algorithms, and reads `Retry-After` and `X-Request-Id`.
    pub fn from_response(status: StatusCode, headers: &HeaderMap, body: &[u8]) -> Error {
        let status_code = status.as_u16();
        let (code, retryable) = match status_code {
            401 => (ErrorCode::AuthRequired, false),
            403 => (ErrorCode::Forbidden, false),
            404 => (ErrorCode::NotFound, false),
            429 => (ErrorCode::RateLimit, true),
            400 | 422 => (ErrorCode::Validation, false),
            500 | 502 | 503 | 504 => (ErrorCode::ApiError, true),
            507 => (ErrorCode::LimitExceeded, false),
            code if code >= 500 => (ErrorCode::ApiError, true),
            _ => (ErrorCode::ApiError, false),
        };
        let parsed = serde_json::from_slice::<Value>(body).ok();
        let scalar = parsed
            .as_ref()
            .and_then(|value| value.get("error").and_then(Value::as_str))
            .or_else(|| {
                parsed
                    .as_ref()
                    .and_then(|value| value.get("message").and_then(Value::as_str))
            })
            .map(str::to_string);
        let mut message = scalar
            .clone()
            .unwrap_or_else(|| format!("Request failed (HTTP {status_code})"));
        let hint = parsed
            .as_ref()
            .and_then(|value| value.get("error_description").and_then(Value::as_str))
            .map(truncate);

        let field_errors = match (status_code, &parsed) {
            (400 | 422, Some(value)) => field_errors_of(value),
            _ => None,
        };
        if let Some(fields) = &field_errors {
            let flattened = flatten(fields);
            message = match scalar {
                Some(_) => format!("{message} ({flattened})"),
                None => flattened,
            };
        }
        let confirmation_people = match (status_code, &parsed) {
            (422, Some(value)) => confirmation_people_of(value),
            _ => None,
        };

        let mut error = Error::new(code, truncate(&message))
            .retryable(retryable)
            .with_status(status_code);
        error.inner.hint = hint;
        error.inner.retry_after = parse_retry_after_header(headers, Timestamp::now());
        error.inner.request_id = headers
            .get("x-request-id")
            .and_then(|value| value.to_str().ok())
            .map(truncate);
        error.inner.field_errors = field_errors;
        error.inner.confirmation_people = confirmation_people;
        if !body.is_empty() {
            let kept = body.len().min(MAX_ERROR_BODY_BYTES);
            error.inner.body = Some(Box::from(&body[..kept]));
        }
        error
    }

    /// The first cause of a given type anywhere in the error's chain.
    ///
    /// A cause is how this crate carries an identity the closed taxonomy of [`ErrorCode`]
    /// has no member for — the recording-summary composite's own verdicts, the discovery
    /// cache's listing-overflow marker. A single-level `downcast_ref` would lose that
    /// identity the moment anything re-wrapped the error, and [`Error::with_source`] is
    /// public, so the whole chain is walked. The depth bound is insurance against an
    /// `Error` implementation whose `source` cycles; a real chain is two or three deep.
    pub(crate) fn find_source<T: std::error::Error + 'static>(&self) -> Option<&T> {
        let mut current = std::error::Error::source(self);
        for _ in 0..MAX_SOURCE_CHAIN_DEPTH {
            let error = current?;
            if let Some(found) = error.downcast_ref::<T>() {
                return Some(found);
            }
            current = error.source();
        }
        None
    }

    /// A full-fidelity copy of the record, without the cause.
    ///
    /// [`Error`] is not `Clone` — its cause is a boxed trait object — so a failure that must
    /// reach more than one caller is copied here and the shared original chained back on as
    /// the cause. Every member of the record travels, the classification flags included: an
    /// error that loses `is_timeout` on the way to a second caller is an error that caller
    /// would handle differently (SPEC §16).
    pub(crate) fn duplicate(&self) -> Error {
        Error {
            inner: Box::new(Inner {
                code: self.inner.code,
                message: self.inner.message.clone(),
                hint: self.inner.hint.clone(),
                http_status: self.inner.http_status,
                retryable: self.inner.retryable,
                retry_after: self.inner.retry_after,
                request_id: self.inner.request_id.clone(),
                field_errors: self.inner.field_errors.clone(),
                confirmation_people: self.inner.confirmation_people.clone(),
                response_too_large: self.inner.response_too_large,
                deadline_exceeded: self.inner.deadline_exceeded,
                timeout: self.inner.timeout,
                body: self.inner.body.clone(),
            }),
            source: None,
        }
    }

    /// The same error, its message prefixed with what the caller was doing. Everything else
    /// — code, status, hint, the classification flags, the cause — is left exactly as it
    /// was, so adding context never costs a caller the accessors it classifies on. This is
    /// the Rust spelling of Go's `fmt.Errorf("doing x: %w", err)`.
    pub(crate) fn with_context(mut self, context: impl fmt::Display) -> Error {
        self.inner.message = truncate(&format!("{context}: {}", self.inner.message));
        self
    }

    /// The same error with a hint, cut to the message cap like the message itself: a
    /// transport's rendering of its own failure is not bounded by anyone else.
    pub fn with_hint(mut self, hint: impl Into<String>) -> Error {
        self.inner.hint = Some(truncate(&hint.into()));
        self
    }

    /// The same error carrying an HTTP status.
    pub fn with_status(mut self, status: u16) -> Error {
        self.inner.http_status = Some(status);
        self
    }

    /// The same error carrying a request id, bounded like the message: the header is the
    /// server's to fill.
    pub fn with_request_id(mut self, request_id: impl Into<String>) -> Error {
        self.inner.request_id = Some(truncate(&request_id.into()));
        self
    }

    /// The same error carrying the seconds a `Retry-After` header named.
    pub fn with_retry_after(mut self, seconds: u32) -> Error {
        self.inner.retry_after = Some(seconds);
        self
    }

    /// The same error marked as a transport timeout, for a projection of one that kept
    /// only the origin (SPEC §9).
    pub(crate) fn timed_out(mut self) -> Error {
        self.inner.timeout = true;
        self
    }

    /// The same error with a cause.
    pub fn with_source(mut self, source: impl std::error::Error + Send + Sync + 'static) -> Error {
        self.source = Some(Box::new(source));
        self
    }

    /// The same error, retryable or not.
    pub fn retryable(mut self, retryable: bool) -> Error {
        self.inner.retryable = retryable;
        self
    }

    /// The categorical code.
    pub fn code(&self) -> ErrorCode {
        self.inner.code
    }

    /// The human-readable description, at most [`MAX_ERROR_MESSAGE_LENGTH`] characters.
    pub fn message(&self) -> &str {
        &self.inner.message
    }

    /// Resolution guidance, when there is any.
    pub fn hint(&self) -> Option<&str> {
        self.inner.hint.as_deref()
    }

    /// The HTTP status that caused the error, when one did.
    pub fn http_status(&self) -> Option<u16> {
        self.inner.http_status
    }

    /// Whether the operation can be retried.
    pub fn is_retryable(&self) -> bool {
        self.inner.retryable
    }

    /// The seconds `Retry-After` named, parsed per SPEC §6, at whatever status carried it.
    pub fn retry_after(&self) -> Option<u32> {
        self.inner.retry_after
    }

    /// `X-Request-Id`, when the response carried one.
    pub fn request_id(&self) -> Option<&str> {
        self.inner.request_id.as_deref()
    }

    /// The structured 400/422 field messages, raw and untruncated. Row-keyed bodies land
    /// here keyed by email address, then `index`, then position.
    pub fn field_errors(&self) -> Option<&BTreeMap<String, Vec<String>>> {
        self.inner.field_errors.as_ref()
    }

    /// The people a template-library copy needs confirmed, when a 422 named them.
    pub fn confirmation_people(&self) -> Option<&[TemplateLibraryConfirmationPerson]> {
        self.inner.confirmation_people.as_deref()
    }

    /// The process exit status a command should end with.
    pub fn exit_code(&self) -> i32 {
        self.inner.code.exit_code()
    }

    /// The failure body, up to [`MAX_ERROR_BODY_BYTES`], when the server sent one.
    pub fn body(&self) -> Option<&[u8]> {
        self.inner.body.as_deref()
    }

    /// The answer was longer than the client will hold.
    pub fn is_response_too_large(&self) -> bool {
        self.inner.response_too_large
    }

    /// The operation deadline passed.
    pub fn is_deadline_exceeded(&self) -> bool {
        self.inner.deadline_exceeded
    }

    /// The transport reported a timeout.
    pub fn is_timeout(&self) -> bool {
        self.inner.timeout
    }

    fn render(&self) -> String {
        match &self.inner.hint {
            Some(hint) => format!("{}: {hint}", self.inner.message),
            None => self.inner.message.clone(),
        }
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Error")
            .field("code", &self.inner.code)
            .field("message", &self.inner.message)
            .field("hint", &self.inner.hint)
            .field("http_status", &self.inner.http_status)
            .field("retryable", &self.inner.retryable)
            .field("retry_after", &self.inner.retry_after)
            .field("request_id", &self.inner.request_id)
            .field("field_errors", &self.inner.field_errors)
            .finish_non_exhaustive()
    }
}

/// Cuts a message to [`MAX_ERROR_MESSAGE_LENGTH`] bytes, ending it in `...` when it was
/// longer. The unit is the byte, as in Go and Ruby (SPEC §9); the cut lands on a UTF-8
/// character boundary so the result is always a valid `str`.
pub fn truncate(message: &str) -> String {
    if message.len() <= MAX_ERROR_MESSAGE_LENGTH {
        return message.to_string();
    }
    let mut end = MAX_ERROR_MESSAGE_LENGTH - 3;
    while !message.is_char_boundary(end) {
        end -= 1;
    }
    format!("{}...", &message[..end])
}

/// SPEC §6's field-keyed algorithm, steps 1, 1b and 2.
fn field_errors_of(body: &Value) -> Option<BTreeMap<String, Vec<String>>> {
    let object = body.as_object()?;
    match object.get("errors") {
        Some(Value::Object(fields)) => {
            let mut map = BTreeMap::new();
            for (field, messages) in fields {
                if let Some(messages) = messages.as_array() {
                    let kept: Vec<String> = messages
                        .iter()
                        .filter_map(Value::as_str)
                        .map(str::to_string)
                        .collect();
                    if !kept.is_empty() {
                        map.insert(field.clone(), kept);
                    }
                }
            }
            (!map.is_empty()).then_some(map)
        }
        Some(Value::Array(rows)) => row_keyed(rows),
        Some(_) => None,
        None => {
            if object.is_empty() {
                return None;
            }
            let mut map = BTreeMap::new();
            for (field, messages) in object {
                let messages = messages.as_array()?;
                if messages.is_empty() {
                    return None;
                }
                let mut kept = Vec::new();
                for message in messages {
                    match message.as_str() {
                        Some(text) if !text.is_empty() => kept.push(text.to_string()),
                        _ => return None,
                    }
                }
                map.insert(field.clone(), kept);
            }
            Some(map)
        }
    }
}

/// Step 1b: every element an object whose `messages` holds at least one non-empty string,
/// keyed by `email_address`, then `index`, then position.
fn row_keyed(rows: &[Value]) -> Option<BTreeMap<String, Vec<String>>> {
    if rows.is_empty() {
        return None;
    }
    let mut map: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for (position, row) in rows.iter().enumerate() {
        let object = row.as_object()?;
        let messages: Vec<String> = object
            .get("messages")?
            .as_array()?
            .iter()
            .filter_map(Value::as_str)
            .filter(|text| !text.is_empty())
            .map(str::to_string)
            .collect();
        if messages.is_empty() {
            return None;
        }
        let key = match object.get("email_address").and_then(Value::as_str) {
            Some(address) if !address.is_empty() => address.to_string(),
            _ => match object.get("index").and_then(Value::as_i64) {
                Some(index) => index.to_string(),
                None => position.to_string(),
            },
        };
        map.entry(key).or_default().extend(messages);
    }
    Some(map)
}

/// `field: m1; m2, other: m3`, fields sorted.
fn flatten(fields: &BTreeMap<String, Vec<String>>) -> String {
    fields
        .iter()
        .map(|(field, messages)| format!("{field}: {}", messages.join("; ")))
        .collect::<Vec<_>>()
        .join(", ")
}

fn confirmation_people_of(body: &Value) -> Option<Vec<TemplateLibraryConfirmationPerson>> {
    let people = body.get("people")?.as_array()?;
    if people.is_empty() {
        return None;
    }
    let mut result = Vec::new();
    for person in people {
        let object = person.as_object()?;
        let id = object.get("id")?.as_i64()?;
        let name = object.get("name")?.as_str()?;
        let avatar_url = object.get("avatar_url")?.as_str()?;
        if id <= 0 || name.is_empty() || avatar_url.is_empty() {
            return None;
        }
        result.push(serde_json::from_value(person.clone()).ok()?);
    }
    Some(result)
}

/// SPEC §6's `Retry-After` table: `1*DIGIT` (no sign, no fraction) saturating at
/// [`MAX_RETRY_AFTER_SECONDS`], with `0` falling through; or an HTTP-date, rounded up to
/// whole seconds from `now` and saturating at the same ceiling, with a past date falling
/// through. Anything else is no value.
pub fn parse_retry_after(value: &str, now: Timestamp) -> Option<u32> {
    let value = value.trim_matches([' ', '\t']);
    if value.is_empty() {
        return None;
    }
    if value.bytes().all(|b| b.is_ascii_digit()) {
        let seconds = match value.parse::<u64>() {
            Ok(seconds) => seconds.min(u64::from(MAX_RETRY_AFTER_SECONDS)),
            Err(_) => u64::from(MAX_RETRY_AFTER_SECONDS),
        };
        return (seconds > 0).then(|| u32::try_from(seconds).unwrap_or(MAX_RETRY_AFTER_SECONDS));
    }
    let until = parse_http_date(value)?;
    let left = until.duration_since(now);
    let whole = left.as_secs();
    let started = left > SignedDuration::from_secs(whole);
    if whole < 0 || (whole == 0 && !started) {
        return None;
    }
    let seconds = whole.saturating_add(i64::from(started));
    Some(
        u32::try_from(seconds)
            .unwrap_or(MAX_RETRY_AFTER_SECONDS)
            .min(MAX_RETRY_AFTER_SECONDS),
    )
}

/// An HTTP-date and nothing else: IMF-fixdate, then the obsolete RFC 850 and asctime forms
/// (RFC 9110 §5.6.7). RFC 2822's wider grammar — numeric offsets, zone names, `Z`, a
/// missing weekday — is not an HTTP-date and falls through.
fn parse_http_date(value: &str) -> Option<Timestamp> {
    let collapsed: String = value.split_whitespace().collect::<Vec<_>>().join(" ");
    for format in [
        "%a, %d %b %Y %H:%M:%S GMT",
        "%A, %d-%b-%y %H:%M:%S GMT",
        "%a %b %d %H:%M:%S %Y",
    ] {
        if let Ok(civil) = jiff::civil::DateTime::strptime(format, &collapsed) {
            return jiff::tz::Offset::UTC.to_timestamp(civil).ok();
        }
    }
    None
}

/// The `Retry-After` header, parsed.
pub(crate) fn parse_retry_after_header(headers: &HeaderMap, now: Timestamp) -> Option<u32> {
    headers
        .get("retry-after")
        .and_then(|value| value.to_str().ok())
        .and_then(|value| parse_retry_after(value, now))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::http::HeaderValue;

    fn at(seconds: i64) -> Timestamp {
        Timestamp::from_second(1_700_000_000 + seconds).unwrap()
    }

    fn headers(pairs: &[(&str, &str)]) -> HeaderMap {
        let mut headers = HeaderMap::new();
        for (name, value) in pairs {
            headers.insert(
                crate::http::HeaderName::from_bytes(name.as_bytes()).unwrap(),
                HeaderValue::from_str(value).unwrap(),
            );
        }
        headers
    }

    #[test]
    fn retry_after_digits_saturate_and_zero_falls_through() {
        assert_eq!(parse_retry_after("5", at(0)), Some(5));
        assert_eq!(parse_retry_after(" 5 ", at(0)), Some(5));
        assert_eq!(parse_retry_after("0", at(0)), None);
        assert_eq!(parse_retry_after("+5", at(0)), None);
        assert_eq!(parse_retry_after("-5", at(0)), None);
        assert_eq!(parse_retry_after("2.5", at(0)), None);
        assert_eq!(parse_retry_after("5s", at(0)), None);
        assert_eq!(parse_retry_after("2147483647", at(0)), Some(2_147_483_647));
        assert_eq!(parse_retry_after("2147483648", at(0)), Some(2_147_483_647));
        assert_eq!(
            parse_retry_after("99999999999999999999999999", at(0)),
            Some(2_147_483_647)
        );
        assert_eq!(parse_retry_after("", at(0)), None);
    }

    #[test]
    fn retry_after_dates_round_up_and_past_dates_fall_through() {
        let now = "2021-06-09T10:18:14.250Z".parse::<Timestamp>().unwrap();
        assert_eq!(
            parse_retry_after("Wed, 09 Jun 2021 10:18:16 GMT", now),
            Some(2)
        );
        assert_eq!(
            parse_retry_after("Wed, 09 Jun 2021 10:18:15 GMT", now),
            Some(1)
        );
        assert_eq!(
            parse_retry_after("Wed, 09 Jun 2021 10:18:14 GMT", now),
            None
        );
        let just_before = "2021-06-09T10:18:14.999999999Z"
            .parse::<Timestamp>()
            .unwrap();
        assert_eq!(
            parse_retry_after("Wed, 09 Jun 2021 10:18:15 GMT", just_before),
            Some(1)
        );
        let just_after = "2021-06-09T10:18:13.999999999Z"
            .parse::<Timestamp>()
            .unwrap();
        assert_eq!(
            parse_retry_after("Wed, 09 Jun 2021 10:18:15 GMT", just_after),
            Some(2)
        );
        assert_eq!(
            parse_retry_after("Wed, 09 Jun 2021 09:00:00 GMT", now),
            None
        );
        assert_eq!(
            parse_retry_after("Wednesday, 09-Jun-21 10:18:16 GMT", now),
            Some(2)
        );
        assert_eq!(parse_retry_after("Wed Jun  9 10:18:16 2021", now), Some(2));
        assert_eq!(
            parse_retry_after("Tue, 31 Dec 2999 00:00:00 GMT", now),
            Some(2_147_483_647)
        );
        for not_http_date in [
            "Wed, 09 Jun 2021 10:18:16 -0500",
            "Wed, 09 Jun 2021 10:18:16 +0000",
            "Wed, 09 Jun 2021 10:18:16 UT",
            "Wed, 09 Jun 2021 10:18:16 EST",
            "Wed, 09 Jun 2021 10:18:16 Z",
            "09 Jun 2021 10:18:16 GMT",
            "Wed, 09 Jun 21 10:18:16 GMT",
        ] {
            assert_eq!(
                parse_retry_after(not_http_date, now),
                None,
                "{not_http_date} is RFC 2822, not an HTTP-date"
            );
        }
        assert_eq!(parse_retry_after("not a date", now), None);
    }

    #[test]
    fn statuses_map_to_codes_in_order() {
        let cases = [
            (401, ErrorCode::AuthRequired, false),
            (403, ErrorCode::Forbidden, false),
            (404, ErrorCode::NotFound, false),
            (429, ErrorCode::RateLimit, true),
            (400, ErrorCode::Validation, false),
            (422, ErrorCode::Validation, false),
            (500, ErrorCode::ApiError, true),
            (502, ErrorCode::ApiError, true),
            (503, ErrorCode::ApiError, true),
            (504, ErrorCode::ApiError, true),
            (507, ErrorCode::LimitExceeded, false),
            (599, ErrorCode::ApiError, true),
            (418, ErrorCode::ApiError, false),
        ];
        for (status, code, retryable) in cases {
            let error = Error::from_response(
                StatusCode::from_u16(status).unwrap(),
                &headers(&[("x-request-id", "req-1")]),
                b"",
            );
            assert_eq!(error.code(), code, "{status}");
            assert_eq!(error.is_retryable(), retryable, "{status}");
            assert_eq!(error.http_status(), Some(status));
            assert_eq!(error.request_id(), Some("req-1"));
            assert_eq!(error.message(), format!("Request failed (HTTP {status})"));
        }
    }

    #[test]
    fn a_composed_validation_message_is_truncated_once() {
        // 496 ASCII bytes, a three-byte character straddling the cut, then more: cutting the
        // scalar before composition would leave an ellipsis for the final cut to land in.
        let scalar = format!("{}\u{20ac}bb", "a".repeat(MAX_ERROR_MESSAGE_LENGTH - 4));
        let body = serde_json::json!({"error": scalar, "errors": {"name": ["x"]}}).to_string();
        let error = Error::from_response(
            StatusCode::UNPROCESSABLE_ENTITY,
            &HeaderMap::new(),
            body.as_bytes(),
        );
        assert_eq!(
            error.message(),
            format!("{}...", "a".repeat(MAX_ERROR_MESSAGE_LENGTH - 4))
        );
        assert_eq!(error.field_errors().unwrap()["name"], vec!["x".to_string()]);
    }

    #[test]
    fn request_id_read_off_a_response_is_bounded_like_the_setter() {
        let long = "r".repeat(MAX_ERROR_MESSAGE_LENGTH + 1);
        let error = Error::from_response(
            StatusCode::BAD_GATEWAY,
            &headers(&[("x-request-id", &long)]),
            b"",
        );
        let expected = Error::usage("x").with_request_id(&long);
        assert_eq!(error.request_id(), expected.request_id());
        assert_eq!(error.request_id().unwrap().len(), MAX_ERROR_MESSAGE_LENGTH);
        assert!(error.request_id().unwrap().ends_with("..."));
    }

    #[test]
    fn retry_after_is_read_at_every_status() {
        let error = Error::from_response(
            StatusCode::SERVICE_UNAVAILABLE,
            &headers(&[("retry-after", "7")]),
            b"{}",
        );
        assert_eq!(error.retry_after(), Some(7));
        let error = Error::from_response(
            StatusCode::NOT_FOUND,
            &headers(&[("retry-after", "3")]),
            b"",
        );
        assert_eq!(error.retry_after(), Some(3));
    }

    #[test]
    fn bodies_supply_message_and_hint() {
        let error = Error::from_response(
            StatusCode::UNAUTHORIZED,
            &headers(&[]),
            br#"{"error": "Unauthorized", "error_description": "token expired"}"#,
        );
        assert_eq!(error.message(), "Unauthorized");
        assert_eq!(error.hint(), Some("token expired"));
        let error = Error::from_response(
            StatusCode::NOT_FOUND,
            &headers(&[]),
            br#"{"message": "Not found"}"#,
        );
        assert_eq!(error.message(), "Not found");
        let error = Error::from_response(StatusCode::NOT_FOUND, &headers(&[]), b"<html>");
        assert_eq!(error.message(), "Request failed (HTTP 404)");
        let long = format!(r#"{{"error": "{}"}}"#, "x".repeat(600));
        let error = Error::from_response(StatusCode::BAD_REQUEST, &headers(&[]), long.as_bytes());
        assert_eq!(error.message().chars().count(), 500);
        assert!(error.message().ends_with("..."));
    }

    #[test]
    fn field_keyed_bodies_are_flattened_and_exposed() {
        let error = Error::from_response(
            StatusCode::UNPROCESSABLE_ENTITY,
            &headers(&[]),
            br#"{"error": "Validation failed", "errors": {"color": ["is not a valid color"], "name": ["can't be blank", "is too short"]}}"#,
        );
        assert_eq!(error.code(), ErrorCode::Validation);
        assert_eq!(
            error.message(),
            "Validation failed (color: is not a valid color, name: can't be blank; is too short)"
        );
        assert_eq!(
            error.field_errors().unwrap()["name"],
            vec!["can't be blank", "is too short"]
        );

        let error = Error::from_response(
            StatusCode::BAD_REQUEST,
            &headers(&[]),
            br#"{"payload_url": ["is not a valid URL"]}"#,
        );
        assert_eq!(error.message(), "payload_url: is not a valid URL");
        assert_eq!(error.field_errors().unwrap().len(), 1);

        let error = Error::from_response(
            StatusCode::BAD_REQUEST,
            &headers(&[]),
            br#"{"error": "Webhook is invalid", "payload_url": ["is invalid"]}"#,
        );
        assert_eq!(error.message(), "Webhook is invalid");
        assert!(error.field_errors().is_none());

        let error = Error::from_response(
            StatusCode::UNPROCESSABLE_ENTITY,
            &headers(&[]),
            br#"{"error": {}, "errors": {"base": ["Can't be undocked"], "__proto__": ["x"]}}"#,
        );
        assert_eq!(error.message(), "__proto__: x, base: Can't be undocked");

        let error = Error::from_response(
            StatusCode::NOT_FOUND,
            &headers(&[]),
            br#"{"errors": {"x": ["y"]}}"#,
        );
        assert!(error.field_errors().is_none());
    }

    #[test]
    fn a_server_message_that_looks_synthetic_is_still_composed() {
        let error = Error::from_response(
            StatusCode::UNPROCESSABLE_ENTITY,
            &headers(&[]),
            br#"{"error": "Request failed (HTTP 422) upstream", "errors": {"x": ["y"]}}"#,
        );
        assert_eq!(error.message(), "Request failed (HTTP 422) upstream (x: y)");
    }

    #[test]
    fn row_keyed_bodies_land_on_addresses_indexes_then_positions() {
        let error = Error::from_response(
            StatusCode::UNPROCESSABLE_ENTITY,
            &headers(&[]),
            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"]}]}"#,
        );
        let fields = error.field_errors().unwrap();
        assert_eq!(
            fields["not-an-address"],
            vec!["Email address must be valid", "Already invited"]
        );
        assert_eq!(fields["1"], vec!["Email address can't be blank"]);
        assert_eq!(fields["7"], vec!["Name can't be blank"]);
        assert_eq!(
            error.message(),
            "1: Email address can't be blank, 7: Name can't be blank, not-an-address: Email address must be valid; Already invited"
        );

        let error = Error::from_response(
            StatusCode::UNPROCESSABLE_ENTITY,
            &headers(&[]),
            br#"{"errors": [{"email_address": "a", "messages": ["x"]}, {"email_address": "b"}]}"#,
        );
        assert!(error.field_errors().is_none());
        assert_eq!(error.message(), "Request failed (HTTP 422)");
    }

    #[test]
    fn confirmation_people_are_projected_only_when_every_entry_conforms() {
        let error = Error::from_response(
            StatusCode::UNPROCESSABLE_ENTITY,
            &headers(&[]),
            br#"{"error": "Confirmation required", "people": [{"id": 1, "name": "Ann", "avatar_url": "https://x/a.png"}]}"#,
        );
        assert_eq!(error.code(), ErrorCode::Validation);
        assert_eq!(error.confirmation_people().unwrap().len(), 1);
        assert_eq!(error.confirmation_people().unwrap()[0].id, 1);

        let error = Error::from_response(
            StatusCode::UNPROCESSABLE_ENTITY,
            &headers(&[]),
            br#"{"error": "x", "people": [{"id": 0, "name": "Ann", "avatar_url": "u"}]}"#,
        );
        assert!(error.confirmation_people().is_none());
    }

    #[test]
    fn errors_are_send_and_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<Error>();
    }
}