youtube-legend-cli 0.4.0

Non-interactive Rust CLI that downloads YouTube subtitles through third-party providers, using a native Unix stdin/stdout interface.
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
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
//! Error types and exit codes for the CLI.
//!
//! All public items return [`AppResult<T>`], which is a `Result<T, AppError>`.
//! The [`AppError`] enum carries the exit code, a display message, and
//! (when applicable) a structured [`NoSubtitleReason`] that callers can
//! branch on without parsing the error string.
//!
//! # Localisation
//!
//! `Display` renders the label of each variant through
//! [`crate::i18n`], so `stderr` speaks the operator's interface locale.
//! The stable parts of the contract are unchanged: the exit code, the
//! variant identity, and the payload embedded after the label (a path,
//! a URL, an upstream message) are never translated. Programmatic
//! consumers should branch on [`AppError::exit_code`] or on the variant
//! itself, never on the rendered prose — which was already the
//! documented rule before the catalogue existed.

use std::fmt;
use std::process::{ExitCode, Termination};

use crate::i18n::{t, Language, Message};

/// BSD sysexits.h constants. See `man 3 sysexits` and
/// <https://man.openbsd.org/sysexits>. Mapped from the legacy 2-7
/// scheme to provide interoperability with downstream POSIX tooling
/// that distinguishes exit codes by category.
pub mod sysexits {
    /// Command line usage error (BSD sysexits.h: `EX_USAGE`).
    pub const EX_USAGE: u8 = 64;
    /// Data format error (BSD sysexits.h: `EX_DATAERR`).
    pub const EX_DATAERR: u8 = 65;
    /// Cannot open input (BSD sysexits.h: `EX_NOINPUT`).
    pub const EX_NOINPUT: u8 = 66;
    /// Service unavailable (BSD sysexits.h: `EX_UNAVAILABLE`).
    pub const EX_UNAVAILABLE: u8 = 69;
    /// Internal software error (BSD sysexits.h: `EX_SOFTWARE`).
    pub const EX_SOFTWARE: u8 = 70;
    /// Input/output error (BSD sysexits.h: `EX_IOERR`).
    pub const EX_IOERR: u8 = 74;
    /// Temporary failure the caller may retry (BSD sysexits.h:
    /// `EX_TEMPFAIL`).
    pub const EX_TEMPFAIL: u8 = 75;
    /// The remote system answered something this crate could not
    /// interpret during a protocol exchange (BSD sysexits.h:
    /// `EX_PROTOCOL`).
    pub const EX_PROTOCOL: u8 = 76;
    /// The caller lacked permission to perform the operation (BSD
    /// sysexits.h: `EX_NOPERM`). Distinguishes "you may not" from the
    /// misconfiguration that `EX_CONFIG` reports.
    ///
    /// RESERVED: no variant of [`super::AppError`] maps here, and that is a
    /// decision rather than an omission. The one candidate is a refused
    /// `sudo -n` while installing Xvfb, and that path deliberately
    /// degrades to headless instead of failing, so emitting 77 there
    /// would trade graceful degradation for a hard stop. The constant
    /// stays because the sysexits table is a contract with the caller;
    /// inventing a consumer just to retire an unused name would make the
    /// exit code lie about what happened.
    pub const EX_NOPERM: u8 = 77;
    /// Configuration error (BSD sysexits.h: `EX_CONFIG`).
    pub const EX_CONFIG: u8 = 78;
}

/// Top-level error type returned by every public API in this crate.
///
/// The `Display` impl is the user-facing message written to stderr by
/// [`Termination::report`]. Its label comes from the compiled
/// [`crate::i18n`] catalogue and therefore follows the interface
/// locale; the payload after the label is the raw diagnostic and is
/// never translated. Downstream consumers must branch on
/// [`AppError::exit_code`] or on the variant, never on the prose.
#[doc(alias = "error")]
#[doc(alias = "Error")]
#[doc(alias = "cli_error")]
#[doc(alias = "exit code")]
#[doc(alias = "sysexits")]
#[doc(alias = "BSD")]
#[doc(alias = "error type")]
#[doc(alias = "thiserror")]
#[derive(Debug)]
#[non_exhaustive]
pub enum AppError {
    /// The CLI was invoked with an unsupported combination of flags.
    InvalidUsage(String),

    /// A user-supplied input string was rejected by validation.
    InvalidInput(String),

    /// stdin was empty or contained only whitespace.
    StdinEmpty,

    /// A URL was syntactically valid but not a recognized `YouTube` URL.
    InvalidUrl(String),

    /// Subtitle lookup succeeded but the video has no subtitle that matches
    /// the request. The inner reason captures *why*.
    NoSubtitle(NoSubtitleReason),

    /// A provider in the chain returned a transient error.
    ///
    /// Carries the name of the provider that failed so the JSON
    /// envelope can say *which* one did. The chain fills this in when it
    /// classifies the failure, because the call site that constructs the
    /// error does not always know which provider it is speaking for.
    ProviderUnavailable {
        /// Name of the provider that failed, as reported by
        /// [`crate::provider::Provider::name`].
        provider: &'static str,
    },

    /// Upstream answered HTTP 429. Carries the parsed `Retry-After`
    /// delta-seconds when the provider sent one (EC-021).
    RateLimited {
        /// Name of the provider that answered 429, as reported by
        /// [`crate::provider::Provider::name`].
        provider: &'static str,
        /// Parsed `Retry-After` value in seconds, when present.
        retry_after_secs: Option<u64>,
    },

    /// An HTTP request exceeded the configured timeout.
    Timeout(String),

    /// Wrapped [`std::io::Error`].
    Io(std::io::Error),

    /// Wrapped [`reqwest::Error`].
    Http(reqwest::Error),

    /// Wrapped [`url::ParseError`].
    UrlParse(url::ParseError),

    /// Wrapped [`serde_json::Error`].
    Serde(serde_json::Error),

    /// A cryptographic primitive failed (PBKDF2, AES, etc.).
    Crypto(String),

    /// Decoded subtitle exceeded the 50 MiB in-memory safety cap.
    SubtitleTooLarge(usize),

    /// Catch-all for internal invariant violations. Indicates a bug.
    Internal(String),

    /// The watch-page HTML did not contain the `ytInitialPlayerResponse`
    /// JavaScript variable. Surfaces a structurally broken `YouTube` page
    /// (anti-bot interstitial, age gate, or layout change) without
    /// silently treating it as a missing subtitle.
    PlayerResponseMissing(String),

    /// The watch-page response body exceeded the configured `DoS` guard
    /// before `serde_json` was allowed to allocate. The size is
    /// recorded so operators can tune the limit via configuration.
    PlayerResponseTooLarge {
        /// Observed body size in bytes (from `Content-Length` or actual read).
        bytes: usize,
        /// Configured cap, in bytes.
        limit: usize,
    },

    /// The `playerCaptionsTracklistRenderer` block was present but
    /// contained zero usable tracks. Differs from a language miss:
    /// this means the video has no captions at all.
    CaptionTrackNotFound,

    /// The video publishes captions, but none in the requested
    /// language. Carries the BCP 47 tags the watch-page probe in
    /// [`crate::parse::player_response`] actually found.
    ///
    /// [`NoSubtitleReason::LanguageUnavailable`] states the same fact
    /// and is `Copy`, so it cannot carry a list; this variant exists
    /// solely to be that list's carrier, which is what finally fills
    /// the `available_languages` property the error envelope schema
    /// has declared and never populated. Exit code and `kind` are
    /// deliberately identical to the reason-only form, so no new
    /// observable failure mode reaches a caller.
    LanguageUnavailable {
        /// BCP 47 tags the video publishes, sorted and deduplicated.
        available: Vec<String>,
    },

    /// The video publishes the requested language, every track it
    /// publishes was produced by speech recognition, and no provider in
    /// the chain delivered one.
    ///
    /// The condition is composed on purpose: it is only asserted after
    /// the whole chain has failed, because no provider refuses an ASR
    /// track by decision of its own code. Emitting this from a simpler
    /// signal — "the track is ASR" — would make the `kind` lie about
    /// why the download failed. The producer is the watch-page probe at
    /// the exhaustion point of [`crate::provider::ProviderChain`].
    ///
    /// Exit code is the one the whole absence-of-subtitle family uses,
    /// so a script branching on the code alone keeps working; the
    /// variant and the `kind` are what tell the cause apart.
    CaptionsAsrOnly {
        /// BCP 47 tags of the speech-recognition tracks the watch page
        /// publishes, sorted and deduplicated.
        asr_languages: Vec<String>,
    },

    /// The `playabilityStatus.status` field was anything other than
    /// `OK` (e.g. `LOGIN_REQUIRED`, `ERROR`, `CONTENT_CHECK_REQUIRED`).
    /// Carries the raw status string for diagnosis.
    PlayabilityStatusDenied(String),

    /// A BCP-47 language tag from a `CaptionTrack` failed to parse.
    /// Surfaces a malformed upstream payload without panicking.
    LanguageParseError(String),

    /// The `player.js` decipher routine could not produce a valid
    /// plaintext signature. This happens when the regex fails to
    /// locate the operation table, when the operations vector is
    /// empty after extraction, or when a `&sig=` query parameter is
    /// shorter than the expected number of operations.
    SignatureDecipherFailed(String),

    /// The `YouTube` `timedtext` endpoint returned an error that the
    /// provider could not classify (non-JSON body, HTTP status
    /// outside the known mapping, or body that fails to parse as
    /// Srv3/JSON3). This variant is distinct from `Http` (transport
    /// failure before reaching the upstream) and from
    /// `ProviderUnavailable` (chain exhausted without a structured
    /// reason): the request reached the upstream but the response
    /// could not be turned into a `SubtitleInfo`.
    TimedtextUpstreamError(String),

    /// A provider answered, but the body did not match the shape this
    /// crate models for it.
    ///
    /// Distinct from [`AppError::TimedtextUpstreamError`], which belongs
    /// to the `YouTube` `timedtext` parser in [`crate::parse`]. The four
    /// third-party providers borrowed that variant and inherited a
    /// diagnostic naming a service they never contact, which sent
    /// operators looking in the wrong place.
    ///
    /// Carries the provider name and the deserialisation detail. The
    /// exit code stays `EX_SOFTWARE` because a shape we failed to
    /// model is our defect to fix, not an upstream outage.
    ProviderProtocolError {
        /// Stable identifier of the provider, matching
        /// [`crate::provider::Provider::name`].
        ///
        /// Structured rather than interpolated into `detail`, and this
        /// is the correction of a real divergence: the doc above had
        /// promised "carries the provider name" while the type carried
        /// only a `String`, so the JSON envelope emitted `provider:
        /// null` even though the human message named the service.
        /// MEASURED on 2026-09-01 against the real upstream.
        provider: &'static str,
        /// The deserialisation failure, as the parser reported it.
        detail: String,
    },

    /// No provider could locate a Chromium or Chrome executable.
    ///
    /// DORMANT since 2026-09-04. The two browser-driven providers were
    /// removed on that date and nothing in the delivery path launches a
    /// browser any more, so no production code path constructs this
    /// variant. It survives because the provider chain's attempt ledger
    /// still maps it to an `attempts` outcome and the `browser_missing`
    /// value is published in `docs/schemas/error-envelope.schema.json`:
    /// removing the variant is a breaking change to that contract, not
    /// a cleanup. Only the unit tests construct it today.
    ///
    /// This paragraph told the reader to install a browser via `apt`,
    /// `brew`, or a `browser.path` configuration key until 2026-09-04.
    /// That key does not exist: `config list-keys` prints no `browser`
    /// namespace at all, so the advice pointed at a setting the binary
    /// would reject. Cite a configuration key only after reading that
    /// command.
    BrowserNotFound(String),

    /// A user-supplied configuration file (loaded via `--config`) could
    /// not be read, contained invalid TOML, or carried an unknown key.
    /// This variant is distinct from [`AppError::InvalidUsage`]: a
    /// config parse failure is a server-side / file-side error
    /// (sysexits `EX_CONFIG = 78`), not a CLI argument mistake
    /// (sysexits `EX_USAGE = 64`). Operators that branch on the BSD
    /// category need the signal that `--config /tmp/bad.toml` failed
    /// because the file is bad, not because the CLI was misused.
    Config(String),

    /// The upstream provider answered with a captcha challenge
    /// (Cloudflare `cf-turnstile` or `h-captcha`). This is structurally
    /// different from a transient [`AppError::ProviderUnavailable`]:
    /// captcha requires human interaction and cannot resolve by
    /// retrying. The exit code is `EX_UNAVAILABLE = 69` for
    /// backward compatibility with scripts that branch on exit code
    /// alone; the structured variant lets programmatic callers
    /// distinguish via [`AppError::is_captcha`].
    CaptchaChallenge {
        /// Short identifier of the provider that raised the challenge.
        provider: &'static str,
        /// Captcha implementation detected (`"cf-turnstile"` or `"h-captcha"`).
        kind: &'static str,
    },
}

/// Structured reason why a video has no matching subtitle.
///
/// Returned via [`NoSubtitleReason::from_status`] when the upstream provider
/// answers with one of the recognized HTTP status codes, or constructed
/// directly by providers that discover the absence in the response body.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum NoSubtitleReason {
    /// Video is private, members-only, or age-restricted (HTTP 403).
    PrivateOrAgeRestricted,

    /// Video does not exist (HTTP 404).
    NotFound,

    /// Video was removed by the author (HTTP 410).
    Gone,

    /// Video is unavailable for legal reasons (HTTP 451).
    UnavailableForLegalReasons,

    /// The video exists but no captions have been published.
    NotPublished,

    /// Captions exist but not in the requested language.
    LanguageUnavailable,
}

impl NoSubtitleReason {
    /// Catalogue key for this reason.
    fn message(self) -> Message {
        match self {
            NoSubtitleReason::PrivateOrAgeRestricted => Message::ReasonPrivateOrAgeRestricted,
            NoSubtitleReason::NotFound => Message::ReasonNotFound,
            NoSubtitleReason::Gone => Message::ReasonGone,
            NoSubtitleReason::UnavailableForLegalReasons => {
                Message::ReasonUnavailableForLegalReasons
            }
            NoSubtitleReason::NotPublished => Message::ReasonNotPublished,
            NoSubtitleReason::LanguageUnavailable => Message::ReasonLanguageUnavailable,
        }
    }

    /// Render this reason in `language`, independent of the
    /// process-wide interface locale.
    #[must_use]
    pub fn display_in(self, language: Language) -> &'static str {
        self.message().text(language)
    }
}

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

impl std::error::Error for NoSubtitleReason {}

impl AppError {
    /// Render this error in `language`, independent of the process-wide
    /// interface locale.
    ///
    /// This is the deterministic counterpart of the `Display` impl:
    /// tests call it so their expectations never depend on the locale
    /// of the machine running the suite.
    #[must_use]
    pub fn display_in(&self, language: Language) -> String {
        let tr = |m: Message| m.text(language);
        match self {
            AppError::InvalidUsage(detail) => {
                format!("{}: {detail}", tr(Message::ErrInvalidUsage))
            }
            AppError::InvalidInput(detail) => {
                format!("{}: {detail}", tr(Message::ErrInvalidInput))
            }
            AppError::StdinEmpty => tr(Message::ErrStdinEmpty).to_string(),
            AppError::InvalidUrl(detail) => format!("{}: {detail}", tr(Message::ErrInvalidUrl)),
            AppError::NoSubtitle(reason) => format!(
                "{}: {}",
                tr(Message::ErrNoSubtitle),
                reason.display_in(language)
            ),
            AppError::ProviderUnavailable { .. } => tr(Message::ErrProviderUnavailable).to_string(),
            AppError::RateLimited { .. } => tr(Message::ErrRateLimited).to_string(),
            AppError::Timeout(detail) => format!("{}: {detail}", tr(Message::ErrTimeout)),
            AppError::Io(e) => format!("{}: {e}", tr(Message::ErrIo)),
            AppError::Http(e) => format!("{}: {e}", tr(Message::ErrHttp)),
            AppError::UrlParse(e) => format!("{}: {e}", tr(Message::ErrUrlParse)),
            AppError::Serde(e) => format!("{}: {e}", tr(Message::ErrSerde)),
            AppError::Crypto(detail) => format!("{}: {detail}", tr(Message::ErrCrypto)),
            AppError::SubtitleTooLarge(bytes) => format!(
                "{}: {bytes} {}",
                tr(Message::ErrSubtitleTooLarge),
                tr(Message::UnitBytes)
            ),
            AppError::Internal(detail) => format!("{}: {detail}", tr(Message::ErrInternal)),
            AppError::PlayerResponseMissing(detail) => {
                format!("{}: {detail}", tr(Message::ErrPlayerResponseMissing))
            }
            AppError::PlayerResponseTooLarge { bytes, limit } => format!(
                "{}: {bytes} {} {} {limit}",
                tr(Message::ErrPlayerResponseTooLarge),
                tr(Message::UnitBytes),
                tr(Message::WordExceeds)
            ),
            AppError::CaptionTrackNotFound => tr(Message::ErrCaptionTrackNotFound).to_string(),
            // Composed from the two catalogue keys that already state
            // this fact instead of adding a thirteenth translation of
            // it. The tag list is a payload, and payloads are never
            // translated.
            // The bracket carries the tags the video DOES publish, and
            // the sentence right before it ends on the word "requested".
            // Unlabelled, the reader binds the list to the nearest noun
            // and reads the available tag as the requested one — measured
            // on 2026-09-04, `--lang en` against a pt-only video printed
            // "requested language is unavailable [pt]". The label is what
            // makes the list name itself.
            AppError::LanguageUnavailable { available } => format!(
                "{}: {} [{}: {}]",
                tr(Message::ErrNoSubtitle),
                tr(Message::ReasonLanguageUnavailable),
                tr(Message::WordAvailable),
                available.join(", ")
            ),
            // Composed the same way, and the second half is a NEW key:
            // no combination of the existing ones states "the only
            // tracks published were machine-generated", and a sentence
            // assembled from `ErrNoSubtitle` plus `ErrProviderUnavailable`
            // would blame the provider for a fact about the video.
            AppError::CaptionsAsrOnly { asr_languages } => format!(
                "{}: {} [{}: {}]",
                tr(Message::ErrNoSubtitle),
                tr(Message::ErrCaptionsAsrOnly),
                tr(Message::WordAvailable),
                asr_languages.join(", ")
            ),
            AppError::PlayabilityStatusDenied(detail) => {
                format!("{}: {detail}", tr(Message::ErrPlayabilityStatusDenied))
            }
            AppError::LanguageParseError(detail) => {
                format!("{}: {detail}", tr(Message::ErrLanguageParse))
            }
            AppError::SignatureDecipherFailed(detail) => {
                format!("{}: {detail}", tr(Message::ErrSignatureDecipherFailed))
            }
            AppError::TimedtextUpstreamError(detail) => {
                format!("{}: {detail}", tr(Message::ErrTimedtextUpstream))
            }
            AppError::ProviderProtocolError { provider, detail } => {
                format!("{}: {provider}: {detail}", tr(Message::ErrProviderProtocol))
            }
            AppError::BrowserNotFound(detail) => {
                format!("{}: {detail}", tr(Message::ErrBrowserNotFound))
            }
            AppError::Config(detail) => format!("{}: {detail}", tr(Message::ErrConfig)),
            AppError::CaptchaChallenge { provider, kind } => format!(
                "{} {provider} ({kind}): {}",
                tr(Message::ErrCaptchaChallengeFrom),
                tr(Message::ErrCaptchaHumanRequired)
            ),
        }
    }
}

impl fmt::Display for AppError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.display_in(crate::i18n::current()))
    }
}

impl std::error::Error for AppError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            AppError::Io(e) => Some(e),
            AppError::Http(e) => Some(e),
            AppError::UrlParse(e) => Some(e),
            AppError::Serde(e) => Some(e),
            AppError::NoSubtitle(reason) => Some(reason),
            _ => None,
        }
    }
}

impl From<std::io::Error> for AppError {
    fn from(e: std::io::Error) -> Self {
        AppError::Io(e)
    }
}

impl From<reqwest::Error> for AppError {
    fn from(e: reqwest::Error) -> Self {
        AppError::Http(e)
    }
}

impl From<url::ParseError> for AppError {
    fn from(e: url::ParseError) -> Self {
        AppError::UrlParse(e)
    }
}

impl From<serde_json::Error> for AppError {
    fn from(e: serde_json::Error) -> Self {
        AppError::Serde(e)
    }
}

impl NoSubtitleReason {
    /// Map an HTTP status code to a known reason, or `None` if the status
    /// does not correspond to any of the structured cases.
    pub fn from_status(status: u16) -> Option<Self> {
        match status {
            400 => Some(Self::NotPublished),
            403 => Some(Self::PrivateOrAgeRestricted),
            404 => Some(Self::NotFound),
            410 => Some(Self::Gone),
            451 => Some(Self::UnavailableForLegalReasons),
            _ => None,
        }
    }
}

impl AppError {
    /// Process exit code for this error. See the README exit-code table.
    ///
    /// The mapping follows the same semantics [`AppError::kind`]
    /// publishes: a transitory failure, a local I/O failure and an
    /// unintelligible upstream answer are three different facts, and
    /// folding all three into `EX_SOFTWARE` made a `Timeout` that a
    /// retry would clear indistinguishable from a bug in this crate.
    /// `EX_SOFTWARE` is now reserved for defects that are ours.
    pub fn exit_code(&self) -> u8 {
        use sysexits::*;
        match self {
            AppError::InvalidUsage(_) | AppError::InvalidInput(_) => EX_USAGE,
            // Same category as a bad flag, but a distinct arm: "nothing
            // arrived on stdin" is an operator-visible fact of its own.
            AppError::StdinEmpty => EX_USAGE,
            AppError::InvalidUrl(_) | AppError::UrlParse(_) => EX_DATAERR,
            // Same category, and deliberately the same code: a language
            // miss that names the alternatives is still a language miss.
            // Same category again: an ASR-only video the chain could not
            // serve is still an absence of usable subtitle, so it shares
            // the code rather than inventing one.
            AppError::NoSubtitle(_)
            | AppError::LanguageUnavailable { .. }
            | AppError::CaptionsAsrOnly { .. } => EX_NOINPUT,
            AppError::ProviderUnavailable { .. }
            | AppError::RateLimited { .. }
            | AppError::BrowserNotFound(_) => EX_UNAVAILABLE,
            // Shares the code for backward compatibility, but a captcha
            // needs a human and a rate limit needs a clock; the arms
            // stay apart so the difference is visible in the source.
            AppError::CaptchaChallenge { .. } => EX_UNAVAILABLE,
            AppError::Config(_) => EX_CONFIG,
            // Transitory: the same invocation later may well succeed.
            AppError::Timeout(_) => EX_TEMPFAIL,
            // Local I/O, not a defect of this crate.
            AppError::Io(_) => EX_IOERR,
            // The exchange with the upstream produced something this
            // crate could not interpret.
            AppError::Http(_)
            | AppError::Serde(_)
            | AppError::ProviderProtocolError { .. }
            | AppError::TimedtextUpstreamError(_) => EX_PROTOCOL,
            // What is left is a bug on our side.
            AppError::Crypto(_)
            | AppError::SubtitleTooLarge(_)
            | AppError::Internal(_)
            | AppError::PlayerResponseMissing(_)
            | AppError::PlayerResponseTooLarge { .. }
            | AppError::CaptionTrackNotFound
            | AppError::PlayabilityStatusDenied(_)
            | AppError::LanguageParseError(_)
            | AppError::SignatureDecipherFailed(_) => EX_SOFTWARE,
        }
    }

    /// If this is [`AppError::NoSubtitle`], return the inner reason.
    /// Otherwise, return [`NoSubtitleReason::NotPublished`] as a neutral
    /// default so callers can always branch on the reason.
    pub fn reason(&self) -> NoSubtitleReason {
        match self {
            AppError::NoSubtitle(r) => *r,
            AppError::LanguageUnavailable { .. } => NoSubtitleReason::LanguageUnavailable,
            _ => NoSubtitleReason::NotPublished,
        }
    }

    /// `true` if this is a captcha challenge (Cloudflare `cf-turnstile`
    /// or `h-captcha`). Captcha requires human interaction and cannot
    /// resolve by retrying. Distinct from [`AppError::ProviderUnavailable`]
    /// which signals a transient upstream failure.
    pub fn is_captcha(&self) -> bool {
        matches!(self, AppError::CaptchaChallenge { .. })
    }

    /// Stable, machine-readable identifier for this failure.
    ///
    /// This is the field an automated caller branches on. Unlike
    /// [`AppError::display_in`], it is always English and never
    /// localised, so a consumer that parses `--json` keeps working when
    /// the interface language changes. The returned values are the
    /// `kind` enum of `docs/schemas/error-envelope.schema.json`; adding
    /// a variant here without adding it there breaks the published
    /// contract. The bidirectional guard is
    /// `commands::tests::error_envelope_matches_the_published_schema`,
    /// which serialises a real envelope and compares the emitted keys
    /// with the schema's `properties` in both directions. Before that
    /// test existed this comment promised a round-trip check that did
    /// not exist, and the envelope drifted to five keys against
    /// fourteen declared properties.
    pub fn kind(&self) -> &'static str {
        match self {
            AppError::InvalidUsage(_) | AppError::StdinEmpty => "invalid_usage",
            AppError::InvalidInput(_) | AppError::InvalidUrl(_) | AppError::UrlParse(_) => {
                "invalid_input"
            }
            AppError::NoSubtitle(NoSubtitleReason::LanguageUnavailable)
            | AppError::LanguageUnavailable { .. } => "language_unavailable",
            AppError::CaptionsAsrOnly { .. } => "captions_asr_unsupported_by_provider",
            AppError::NoSubtitle(_) => "no_captions",
            AppError::ProviderUnavailable { .. } => "provider_unavailable",
            AppError::RateLimited { .. } => "provider_rate_limited",
            AppError::CaptchaChallenge { .. } => "provider_captcha",
            AppError::BrowserNotFound(_) => "browser_missing",
            AppError::Timeout(_) => "timeout",
            AppError::Config(_) => "config_error",
            AppError::Io(_) => "io_error",
            // MEASURED on 2026-09-01 against the real upstream: this
            // variant was falling into the catch-all and reporting
            // `internal_error`, which accuses this crate of a bug when
            // the cause is a third party sending a shape we do not
            // model. The exit code had already been redistributed to
            // 76; the `kind` had not, so the two disagreed about who
            // was at fault.
            AppError::ProviderProtocolError { .. } => "provider_protocol_error",
            AppError::TimedtextUpstreamError { .. } => "provider_protocol_error",
            _ => "internal_error",
        }
    }

    /// Whether retrying the same invocation later may succeed.
    ///
    /// `false` means the failure is definitive: a caller that retries is
    /// guaranteed to burn the same time for the same answer. This is the
    /// single source of truth for retry decisions — `crate::retry`
    /// delegates to it rather than keeping a second list, so the two can
    /// never drift apart.
    ///
    /// A content answer that is well formed but negative, such as a
    /// provider reporting that a video has no transcript, is *not*
    /// retryable even though it arrived over a network that could fail.
    pub fn retryable(&self) -> bool {
        match self {
            AppError::Timeout(_) | AppError::ProviderUnavailable { .. } => true,
            // A rate limit is only worth repeating when the upstream
            // said WHEN. MEASURED on 2026-09-01 against the real noiz
            // endpoint: a daily quota comes back as 429 with no
            // `Retry-After`, and the envelope was announcing
            // `retryable: true` with `retry_after_ms: null`. That tells
            // an automated caller to try again and refuses to say when,
            // for a condition that clears the next day — so the caller
            // loops. With a `Retry-After` the upstream has named a
            // horizon and retrying is exactly right; without one the
            // limit is stable within any useful horizon.
            AppError::RateLimited {
                retry_after_secs, ..
            } => retry_after_secs.is_some(),
            // A transport failure never reached a status line, so the
            // next attempt may still connect. A status-bearing answer is
            // only worth repeating when the upstream said the condition
            // was temporary: a 404 is the upstream's final word, and
            // retrying it burned the whole budget to be told the same
            // thing again.
            AppError::Http(e) => match e.status() {
                None => true,
                Some(status) => {
                    status.is_server_error()
                        || status == reqwest::StatusCode::REQUEST_TIMEOUT
                        || status == reqwest::StatusCode::TOO_MANY_REQUESTS
                }
            },
            // Everything else is definitive. `CaptchaChallenge` is named
            // here rather than left to the wildcard because it is the one
            // failure that arrives over the same transport as a transient
            // one and still needs a human: no wait clears it.
            AppError::CaptchaChallenge { .. } => false,
            // Also named rather than left to the wildcard: the cause is
            // a property of the video, so a track no provider served
            // today is the same track tomorrow.
            AppError::CaptionsAsrOnly { .. } => false,
            _ => false,
        }
    }

    /// Upstream-declared delay before a retry is worth attempting.
    ///
    /// Present only for [`AppError::RateLimited`] carrying a
    /// `Retry-After`; every other variant returns `None` so the envelope
    /// omits the field instead of inventing a number.
    pub fn retry_after_ms(&self) -> Option<u64> {
        match self {
            AppError::RateLimited {
                retry_after_secs, ..
            } => retry_after_secs.map(|s| s.saturating_mul(1_000)),
            _ => None,
        }
    }
}

impl Termination for AppError {
    fn report(self) -> ExitCode {
        tracing::error!(target: "user_error", code = self.exit_code(), "{}", self);
        ExitCode::from(self.exit_code())
    }
}

impl From<AppError> for ExitCode {
    fn from(err: AppError) -> Self {
        ExitCode::from(err.exit_code())
    }
}

/// Convenience alias for `Result<T, AppError>`.
pub type AppResult<T> = Result<T, AppError>;

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

    /// The bracket has to name what it holds.
    ///
    /// MEASURED on 2026-09-04: a run asking for `en` printed "sem
    /// legenda: o idioma solicitado está indisponível [pt]" while
    /// `requested_language` in the same envelope was `en`. The sentence
    /// ends on "requested" and the bracket follows it immediately, so a
    /// reader binds the tag to the wrong noun and concludes the request
    /// was `pt`. Labelling the list is what breaks that binding.
    #[test]
    fn the_available_list_names_itself_in_every_language() {
        for language in [Language::En, Language::PtBr] {
            let message = AppError::LanguageUnavailable {
                available: vec!["pt".to_string()],
            }
            .display_in(language);
            let label = Message::WordAvailable.text(language);
            assert!(
                message.contains(&format!("[{label}: pt]")),
                "{language:?}: the tag list must carry its own label, got {message}"
            );
        }
    }

    #[test]
    fn no_subtitle_reason_from_status() {
        assert_eq!(
            NoSubtitleReason::from_status(403),
            Some(NoSubtitleReason::PrivateOrAgeRestricted)
        );
        assert_eq!(
            NoSubtitleReason::from_status(404),
            Some(NoSubtitleReason::NotFound)
        );
        assert_eq!(
            NoSubtitleReason::from_status(410),
            Some(NoSubtitleReason::Gone)
        );
        assert_eq!(
            NoSubtitleReason::from_status(451),
            Some(NoSubtitleReason::UnavailableForLegalReasons)
        );
        assert_eq!(NoSubtitleReason::from_status(500), None);
    }

    #[test]
    fn no_subtitle_exit_code_is_66() {
        let err = AppError::NoSubtitle(NoSubtitleReason::NotPublished);
        assert_eq!(err.exit_code(), 66);
    }

    #[test]
    fn stdin_empty_exit_code_is_64() {
        assert_eq!(AppError::StdinEmpty.exit_code(), 64);
    }

    #[test]
    fn subtitle_too_large_exit_code_is_70() {
        assert_eq!(AppError::SubtitleTooLarge(60_000_000).exit_code(), 70);
    }

    /// A timeout is transitory, so it must not share the code reserved
    /// for defects of this crate.
    #[test]
    fn timeout_exit_code_is_tempfail() {
        assert_eq!(
            AppError::Timeout("after 30s".to_string()).exit_code(),
            sysexits::EX_TEMPFAIL
        );
        assert_eq!(AppError::Timeout("after 30s".to_string()).exit_code(), 75);
    }

    /// A local read/write failure is an I/O error, not a bug.
    #[test]
    fn io_exit_code_is_ioerr() {
        let err = AppError::Io(std::io::Error::other("disk gone"));
        assert_eq!(err.exit_code(), sysexits::EX_IOERR);
        assert_eq!(err.exit_code(), 74);
    }

    /// An answer this crate could not interpret belongs to the protocol
    /// category, which is what separates "the upstream spoke nonsense"
    /// from "we have a bug".
    #[test]
    fn unintelligible_upstream_answers_are_protocol_errors() {
        for err in [
            AppError::TimedtextUpstreamError("unexpected EOF".to_string()),
            AppError::ProviderProtocolError {
                provider: "provider-noiz",
                detail: "missing field".to_string(),
            },
        ] {
            assert_eq!(err.exit_code(), sysexits::EX_PROTOCOL, "{err:?}");
            assert_eq!(err.exit_code(), 76, "{err:?}");
        }
    }

    /// Exit 70 is now reserved: every variant that still maps to it is
    /// a defect of this crate, never an upstream or environment fact.
    #[test]
    fn ex_software_is_reserved_for_our_own_defects() {
        for err in [
            AppError::Internal("x".to_string()),
            AppError::CaptionTrackNotFound,
            AppError::SubtitleTooLarge(1),
            AppError::Crypto("x".to_string()),
        ] {
            assert_eq!(err.exit_code(), sysexits::EX_SOFTWARE, "{err:?}");
        }
        for err in [
            AppError::Timeout("x".to_string()),
            AppError::Io(std::io::Error::other("x")),
            AppError::TimedtextUpstreamError("x".to_string()),
        ] {
            assert_ne!(err.exit_code(), sysexits::EX_SOFTWARE, "{err:?}");
        }
    }

    #[test]
    fn provider_unavailable_exit_code_is_69() {
        let err = AppError::ProviderUnavailable {
            provider: "provider-noiz",
        };
        assert_eq!(err.exit_code(), 69);
    }

    #[test]
    fn rate_limited_exit_code_is_69() {
        let err = AppError::RateLimited {
            provider: "provider-noiz",
            retry_after_secs: Some(60),
        };
        assert_eq!(err.exit_code(), 69);
    }

    #[test]
    fn invalid_url_exit_code_is_65() {
        assert_eq!(AppError::InvalidUrl("bad".to_string()).exit_code(), 65);
    }

    #[test]
    fn internal_error_exit_code_is_70() {
        assert_eq!(AppError::Internal("oops".to_string()).exit_code(), 70);
    }

    #[test]
    fn player_response_missing_exit_code_is_70() {
        let err = AppError::PlayerResponseMissing("watch?v=abc".to_string());
        assert_eq!(err.exit_code(), 70);
    }

    #[test]
    fn player_response_too_large_exit_code_is_70() {
        let err = AppError::PlayerResponseTooLarge {
            bytes: 11_000_000,
            limit: 10_000_000,
        };
        assert_eq!(err.exit_code(), 70);
    }

    #[test]
    fn caption_track_not_found_exit_code_is_70() {
        assert_eq!(AppError::CaptionTrackNotFound.exit_code(), 70);
    }

    #[test]
    fn playability_status_denied_exit_code_is_70() {
        let err = AppError::PlayabilityStatusDenied("LOGIN_REQUIRED".to_string());
        assert_eq!(err.exit_code(), 70);
    }

    #[test]
    fn language_parse_error_exit_code_is_70() {
        let err = AppError::LanguageParseError("not-bcp47".to_string());
        assert_eq!(err.exit_code(), 70);
    }

    #[test]
    fn signature_decipher_failed_exit_code_is_70() {
        let err = AppError::SignatureDecipherFailed("op table empty".to_string());
        assert_eq!(err.exit_code(), 70);
    }

    #[test]
    fn timedtext_upstream_error_exit_code_is_76() {
        let err = AppError::TimedtextUpstreamError("unexpected EOF".to_string());
        assert_eq!(err.exit_code(), 76);
    }

    #[test]
    fn browser_not_found_exit_code_is_69() {
        let err = AppError::BrowserNotFound("chrome missing".to_string());
        assert_eq!(err.exit_code(), sysexits::EX_UNAVAILABLE);
        assert_eq!(err.exit_code(), 69);
    }

    #[test]
    fn browser_not_found_display_includes_context() {
        let err = AppError::BrowserNotFound("install via dnf install chromium".to_string());
        let msg = err.display_in(Language::En);
        assert!(
            msg.contains("chromium/chrome not found"),
            "missing prefix: {msg}"
        );
        assert!(
            msg.contains("install via dnf install chromium"),
            "missing context: {msg}"
        );
    }

    #[test]
    fn timedtext_upstream_error_display_includes_payload() {
        let err = AppError::TimedtextUpstreamError("http 503 from timedtext".to_string());
        let msg = err.display_in(Language::En);
        assert!(msg.contains("timedtext"), "missing variant name in {msg}");
        assert!(
            msg.contains("http 503 from timedtext"),
            "missing payload in {msg}"
        );
    }

    #[test]
    fn timedtext_upstream_error_is_distinct_from_http_and_provider_unavailable() {
        // Compile-time check: TimedtextUpstreamError is a separate
        // variant from Http, Timeout, and ProviderUnavailable. The
        // pattern match below must NOT match those alternatives.
        let err = AppError::TimedtextUpstreamError("bad json".to_string());
        assert!(!matches!(err, AppError::Http(_)));
        assert!(!matches!(err, AppError::Timeout(_)));
        assert!(!matches!(err, AppError::ProviderUnavailable { .. }));
        assert!(!matches!(err, AppError::Serde(_)));
    }

    #[test]
    fn all_exit_codes_are_in_sysexits_range() {
        let errs = vec![
            AppError::InvalidUsage("x".into()),
            AppError::InvalidInput("x".into()),
            AppError::StdinEmpty,
            AppError::InvalidUrl("x".into()),
            AppError::UrlParse(url::ParseError::EmptyHost),
            AppError::NoSubtitle(NoSubtitleReason::NotPublished),
            AppError::ProviderUnavailable {
                provider: "provider-noiz",
            },
            AppError::RateLimited {
                provider: "provider-noiz",
                retry_after_secs: None,
            },
            AppError::Timeout("x".into()),
            AppError::Internal("x".into()),
            AppError::PlayerResponseMissing("x".into()),
            AppError::PlayerResponseTooLarge { bytes: 1, limit: 1 },
            AppError::CaptionTrackNotFound,
            AppError::PlayabilityStatusDenied("x".into()),
            AppError::LanguageParseError("x".into()),
            AppError::TimedtextUpstreamError("x".into()),
            AppError::BrowserNotFound("x".into()),
            AppError::Config("x".into()),
            AppError::CaptchaChallenge {
                provider: "x",
                kind: "x",
            },
        ];
        for e in errs {
            let code = e.exit_code();
            assert!(
                (64..=78).contains(&code),
                "exit code {code} out of sysexits range 64-78 for {e:?}"
            );
        }
    }

    #[test]
    fn config_error_exit_code_is_78() {
        assert_eq!(
            AppError::Config("bad".to_string()).exit_code(),
            sysexits::EX_CONFIG
        );
        assert_eq!(AppError::Config("bad".to_string()).exit_code(), 78);
    }

    #[test]
    fn config_error_display_includes_message() {
        let err = AppError::Config("could not read config file /tmp/bad.toml".to_string());
        let msg = err.display_in(Language::En);
        assert!(msg.contains("config error"), "missing prefix: {msg}");
        assert!(msg.contains("/tmp/bad.toml"), "missing path context: {msg}");
    }

    #[test]
    fn reason_helper_returns_inner_reason() {
        let err = AppError::NoSubtitle(NoSubtitleReason::NotFound);
        assert_eq!(err.reason(), NoSubtitleReason::NotFound);
    }

    #[test]
    fn reason_helper_defaults_to_not_published() {
        let err = AppError::Timeout("x".to_string());
        assert_eq!(err.reason(), NoSubtitleReason::NotPublished);
    }

    #[test]
    fn no_subtitle_reason_messages_are_human_readable() {
        assert!(NoSubtitleReason::PrivateOrAgeRestricted
            .display_in(Language::En)
            .contains("403"));
        assert!(NoSubtitleReason::UnavailableForLegalReasons
            .display_in(Language::En)
            .contains("451"));
    }

    // GAP-E2E-026: HTTP 400 from the YouTube timedtext endpoint
    // means "no captions exist for this video". The previous
    // implementation only mapped 403/404/410/451, causing 400 to fall
    // through to ProviderUnavailable (exit 69). Adding 400 to
    // from_status unifies the behaviour across all providers so the
    // operator sees NoSubtitle (exit 66) consistently.
    #[test]
    fn no_subtitle_reason_from_status_maps_400_to_not_published() {
        assert_eq!(
            NoSubtitleReason::from_status(400),
            Some(NoSubtitleReason::NotPublished)
        );
    }

    // GAP-E2E-030: CaptchaChallenge is a new variant for upstream
    // captcha responses (Cloudflare cf-turnstile, h-captcha). Exit
    // code 69 is shared with ProviderUnavailable for backward
    // compatibility; the structured variant allows programmatic
    // distinction via is_captcha().
    #[test]
    fn captcha_challenge_exit_code_is_69() {
        let err = AppError::CaptchaChallenge {
            provider: "provider-b",
            kind: "cf-turnstile",
        };
        assert_eq!(err.exit_code(), sysexits::EX_UNAVAILABLE);
        assert_eq!(err.exit_code(), 69);
    }

    #[test]
    fn captcha_challenge_display_includes_provider_and_kind() {
        let err = AppError::CaptchaChallenge {
            provider: "provider-b",
            kind: "h-captcha",
        };
        let msg = err.display_in(Language::En);
        assert!(msg.contains("captcha"), "missing variant name in {msg}");
        assert!(msg.contains("provider-b"), "missing provider in {msg}");
        assert!(msg.contains("h-captcha"), "missing kind in {msg}");
    }

    #[test]
    fn captcha_challenge_is_captcha_helper_returns_true() {
        let err = AppError::CaptchaChallenge {
            provider: "provider-b",
            kind: "cf-turnstile",
        };
        assert!(err.is_captcha());
    }

    #[test]
    fn provider_unavailable_is_captcha_helper_returns_false() {
        assert!(!AppError::ProviderUnavailable {
            provider: "provider-noiz"
        }
        .is_captcha());
    }

    /// A captcha is a stable cause: it needs a human, so no wait clears
    /// it and the retry layer must never spend a budget on it. The
    /// assertion is here rather than left implicit because
    /// `CaptchaChallenge` shares its exit code with the transient
    /// `ProviderUnavailable`, which is exactly how the two get confused.
    #[test]
    fn captcha_challenge_is_never_retryable() {
        let err = AppError::CaptchaChallenge {
            provider: "provider-decopy",
            kind: "cf-turnstile",
        };
        assert!(!err.retryable());
        assert!(AppError::ProviderUnavailable {
            provider: "provider-decopy"
        }
        .retryable());
    }

    /// Build a real [`reqwest::Error`] carrying `status`, by asking a
    /// local server for it. `reqwest::Error` has no public constructor,
    /// so the status has to come from an actual exchange.
    async fn http_error_with_status(status: u16) -> AppError {
        use wiremock::matchers::any;
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        Mock::given(any())
            .respond_with(ResponseTemplate::new(status))
            .mount(&server)
            .await;
        let response = reqwest::get(server.uri()).await.expect("request reaches");
        let err = response.error_for_status().expect_err("status is an error");
        assert_eq!(err.status().map(|s| s.as_u16()), Some(status));
        AppError::Http(err)
    }

    /// A 404 is the upstream's final word. Treating every `Http` as
    /// transient made the retry layer burn the whole budget to be told
    /// the same thing again.
    #[tokio::test]
    async fn a_definitive_4xx_is_not_retryable() {
        assert!(!http_error_with_status(404).await.retryable());
        assert!(!http_error_with_status(403).await.retryable());
    }

    /// 5xx, 408 and 429 are the statuses that announce a temporary
    /// condition, so they stay retryable.
    #[tokio::test]
    async fn transient_statuses_stay_retryable() {
        for status in [500, 502, 503, 408, 429] {
            assert!(
                http_error_with_status(status).await.retryable(),
                "status {status} must stay retryable"
            );
        }
    }

    /// A failure that never reached a status line is a transport
    /// failure, and the next attempt may still connect.
    #[tokio::test]
    async fn a_transport_failure_without_a_status_is_retryable() {
        let err = reqwest::Client::new()
            .get("http://127.0.0.1:1/")
            .timeout(std::time::Duration::from_secs(2))
            .send()
            .await
            .expect_err("port 1 refuses the connection");
        assert!(err.status().is_none(), "the probe must carry no status");
        assert!(AppError::Http(err).retryable());
    }
}