errlanes 0.16.2

Four error lanes (Rejected/Denied/Transient/Fatal) carried in the type, not re-derived at every layer
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
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
use std::{error::Error, fmt};

use crate::profile::{AllLanes, LaneProfile, NarrowDenied, NarrowTransient};

use crate::lane::{Denied, Exhausted, Fatal, Lane, Transient};

/// Operator level, independent of any tracing dependency in the core API.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Level {
    Trace,
    Debug,
    Info,
    Warn,
    Error,
}

#[cfg(feature = "tracing")]
impl From<Level> for tracing::Level {
    fn from(level: Level) -> Self {
        match level {
            Level::Trace => tracing::Level::TRACE,
            Level::Debug => tracing::Level::DEBUG,
            Level::Info => tracing::Level::INFO,
            Level::Warn => tracing::Level::WARN,
            Level::Error => tracing::Level::ERROR,
        }
    }
}

/// A pure, caller-correctable domain outcome. Implemented by hand or via
/// `#[derive(errlanes::Rejection)]`, which emits `Display`/`Error` itself
/// (defaulting `Display` to the code) unless `#[rejection(error = manual)]`
/// hands that to `thiserror` or a hand-written impl.
pub trait Rejection: Error + Send + Sync + 'static {
    /// A stable, typed, wire-safe identity for this outcome.
    type Code: Copy
        + Eq
        + std::hash::Hash
        + fmt::Debug
        + fmt::Display
        + Into<&'static str>
        + Send
        + Sync
        + 'static;

    fn code(&self) -> Self::Code;

    /// Operator level for this outcome. Rejections default to `Info`.
    fn level(&self) -> Level {
        Level::Info
    }
}

/// Consuming mapping. `#[derive(Lift)]` with `#[lift(Source)]` generates an exhaustive
/// mapping with `Unmapped = Infallible` and a total `From<Source>` conversion.
/// `#[lift(Source, unhandled = fatal)]` returns the original unmapped source;
/// [`Fail::widen`] wraps it as a fatal invariant with its source intact.
/// The derive does not require or implement [`Rejection`]. Derive `Rejection`
/// separately to provide codes and levels; simple lift mappings forward that
/// metadata by default unless the destination declares its own.
pub trait Lift<X>: Sized {
    type Unmapped;
    fn lift(x: X) -> Result<Self, Self::Unmapped>;
}

/// A total `From` counts as a strict lift, so one call-site method can require
/// only `Lift` and still cover both mapping modes. Bounded to `X: Rejection`
/// (rather than any `X`) so it does not overlap the `Lift<Infallible>`
/// blanket below — both are needed, since a [`crate::Classify`] wrapper's
/// rejected slot is either a `Rejection` or `Infallible` (never anything
/// else, by `RejectedSlot`'s own two impls).
impl<X: Rejection, P: From<X>> Lift<X> for P {
    type Unmapped = core::convert::Infallible;
    fn lift(x: X) -> Result<Self, Self::Unmapped> {
        Ok(P::from(x))
    }
}

/// Every destination lifts an `Infallible` rejected slot trivially — this is
/// what lets a fault-only [`crate::Classify`] wrapper satisfy the `Fail`
/// blanket for *any* `D`, with no `Lift`/`From` declared at all.
impl<P> Lift<core::convert::Infallible> for P {
    type Unmapped = core::convert::Infallible;
    fn lift(x: core::convert::Infallible) -> Result<Self, Self::Unmapped> {
        match x {}
    }
}

/// Conversion of an unmapped value into an enabled fatal slot. Strict lifts
/// have no unmapped values and therefore work with any destination profile.
#[doc(hidden)]
pub trait UnmappedInto<F> {
    fn unmapped_into(self) -> F;
}
impl<F> UnmappedInto<F> for core::convert::Infallible {
    fn unmapped_into(self) -> F {
        match self {}
    }
}
impl<R: Rejection> UnmappedInto<Fatal> for R {
    fn unmapped_into(self) -> Fatal {
        // `with_opaque_source`: `self` is a `Rejection`, whose `Display` may
        // embed caller-supplied input (see the trait's display discipline);
        // `source()` still returns it for a handler or test to
        // `downcast_ref`, but `message_chain` must not walk into it.
        Fatal::from_error(crate::FatalKind::Invariant, self)
            .with_context("unhandled rejection at partial lift")
            .with_opaque_source()
    }
}

/// `Fail` minus the `Rejected` lane: what an operation that cannot reject
/// (nothing about it is the caller's to correct) returns. Reads return
/// `Fault<L>`; writes return `Fail<{Entity}ConstraintViolation, L>` — the type
/// itself says whether a call can ever hand back a domain outcome.
#[derive(Debug, Clone)]
pub enum Fault<L: LaneProfile = AllLanes> {
    Denied(L::Denied),
    Transient(L::Transient),
    Fatal(L::Fatal),
}

impl<L: LaneProfile> Fault<L> {
    pub fn lane(&self) -> Lane {
        match self {
            Fault::Denied(_) => Lane::Denied,
            Fault::Transient(_) => Lane::Transient,
            Fault::Fatal(_) => Lane::Fatal,
        }
    }

    pub fn is_transient(&self) -> bool {
        matches!(self, Fault::Transient(_))
    }

    pub fn is_fatal(&self) -> bool {
        matches!(self, Fault::Fatal(_))
    }

    pub fn is_denied(&self) -> bool {
        matches!(self, Fault::Denied(_))
    }

    /// The operator-safe one-line text for this failure — exactly what
    /// `record` writes to `exception.message`, for a boundary that must
    /// persist it rather than (or as well as) record it. `Transient`/
    /// `Fatal`: the whole `source()` chain joined with `": "`. `Denied`: its
    /// `Display`.
    pub fn message(&self) -> String {
        match self {
            Fault::Denied(d) => d.to_string(),
            Fault::Transient(t) => crate::dynamic::message_chain(t),
            Fault::Fatal(x) => crate::dynamic::message_chain(x),
        }
    }

    /// Consumes the `Transient` lane, yielding the same profile with its
    /// transient slot disabled. `attempts` is what the retry loop counted; an
    /// exhausted transient becomes `Fatal(Exhausted)` with the last transient
    /// as its source.
    pub fn narrow_transient(self, attempts: u32) -> Fault<crate::profile::WithoutTransient<L>>
    where
        L::Transient: NarrowTransient<L::Fatal>,
    {
        match self {
            Fault::Denied(d) => Fault::Denied(d),
            Fault::Transient(last) => Fault::Fatal(last.narrow(attempts)),
            Fault::Fatal(f) => Fault::Fatal(f),
        }
    }

    /// Narrows away the `Denied` lane: a denial at a boundary with no
    /// subject (code running as the system) becomes `Fatal(Denied)` with
    /// the `Denied` as its source.
    pub fn narrow_denied(self) -> Fault<crate::profile::WithoutDenied<L>>
    where
        L::Denied: NarrowDenied<L::Fatal>,
    {
        match self {
            Fault::Denied(d) => Fault::Fatal(d.narrow()),
            Fault::Transient(t) => Fault::Transient(t),
            Fault::Fatal(f) => Fault::Fatal(f),
        }
    }
}

/// Borrowed lane accessors. `min_exhaustive_patterns` lets a *by-value* match
/// name only the lanes a profile enables, but a borrowed match still demands an
/// arm for every variant. These accessors are the borrowed form, so no caller
/// ever has to write a `match *never {}` arm. Each is available only when the
/// profile enables that lane, so `e.as_denied()` on a no-denial profile is a
/// compile error rather than a permanent `None`.
impl<L: LaneProfile<Denied = Denied>> Fault<L> {
    pub fn as_denied(&self) -> Option<&Denied> {
        match self {
            Fault::Denied(d) => Some(d),
            _ => None,
        }
    }
}

impl<L: LaneProfile<Transient = Transient>> Fault<L> {
    pub fn as_transient(&self) -> Option<&Transient> {
        match self {
            Fault::Transient(t) => Some(t),
            _ => None,
        }
    }

    pub fn is_congestion(&self) -> bool {
        self.as_transient().is_some_and(Transient::is_congestion)
    }

    /// See [`TransientKind::is_contention`].
    pub fn is_contention(&self) -> bool {
        self.as_transient().is_some_and(Transient::is_contention)
    }
}

impl<L: LaneProfile<Fatal = Fatal>> Fault<L> {
    pub fn as_fatal(&self) -> Option<&Fatal> {
        match self {
            Fault::Fatal(f) => Some(f),
            _ => None,
        }
    }
}

impl<D, L: LaneProfile<Denied = Denied>> Fail<D, L> {
    pub fn as_denied(&self) -> Option<&Denied> {
        match self {
            Fail::Denied(d) => Some(d),
            _ => None,
        }
    }
}

impl<D, L: LaneProfile<Transient = Transient>> Fail<D, L> {
    pub fn as_transient(&self) -> Option<&Transient> {
        match self {
            Fail::Transient(t) => Some(t),
            _ => None,
        }
    }

    pub fn is_congestion(&self) -> bool {
        self.as_transient().is_some_and(Transient::is_congestion)
    }

    /// See [`TransientKind::is_contention`].
    pub fn is_contention(&self) -> bool {
        self.as_transient().is_some_and(Transient::is_contention)
    }
}

impl<D, L: LaneProfile<Fatal = Fatal>> Fail<D, L> {
    pub fn as_fatal(&self) -> Option<&Fatal> {
        match self {
            Fail::Fatal(f) => Some(f),
            _ => None,
        }
    }
}

impl<L: LaneProfile> fmt::Display for Fault<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Fault::Denied(d) => write!(f, "{d}"),
            Fault::Transient(t) => write!(f, "{t}"),
            Fault::Fatal(x) => write!(f, "{x}"),
        }
    }
}

impl<L: LaneProfile> Error for Fault<L> {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        // Same contract as `Fail::source` (pitfall 2): the lane payload
        // itself, so `lane_of` can downcast it.
        match self {
            Fault::Denied(d) => Some(d),
            Fault::Transient(t) => Some(t),
            Fault::Fatal(x) => Some(x),
        }
    }
}

impl<L: LaneProfile> From<Transient> for Fault<L>
where
    L: LaneProfile<Transient = Transient>,
{
    fn from(t: Transient) -> Self {
        Fault::Transient(t)
    }
}

impl<L: LaneProfile> From<Fatal> for Fault<L>
where
    L: LaneProfile<Fatal = Fatal>,
{
    fn from(f: Fatal) -> Self {
        Fault::Fatal(f)
    }
}

impl<L: LaneProfile> From<Denied> for Fault<L>
where
    L: LaneProfile<Denied = Denied>,
{
    fn from(d: Denied) -> Self {
        Fault::Denied(d)
    }
}

impl<L: LaneProfile> From<Exhausted> for Fault<L>
where
    L: LaneProfile<Fatal = Fatal>,
{
    fn from(e: Exhausted) -> Self {
        Fault::Fatal(Fatal::from_error(crate::lane::FatalKind::Exhausted, e))
    }
}

/// `Infallible` is what a disabled lane slot is, so a value proven never to
/// exist converts trivially — `match e {}`.
impl<L: LaneProfile> From<core::convert::Infallible> for Fault<L> {
    fn from(e: core::convert::Infallible) -> Self {
        match e {}
    }
}

/// The generic view over a domain rejection `D`, before retries have run.
///
/// **Display discipline**: [`Display`](fmt::Display)'s `Rejected` arm keeps
/// its `rejected: {d}` prefix for logs, but no boundary may build a
/// user-facing message from `to_string()` — a rejection's message may embed
/// caller-supplied input. Use [`as_rejected`](Fail::as_rejected) and
/// [`Rejection::code`] instead: `record_fail` keys `error.code` off the code,
/// never the message, and a GraphQL boundary should do the same for its error
/// extension.
#[derive(Debug, Clone)]
pub enum Fail<D, L: LaneProfile = AllLanes> {
    Rejected(D),
    Denied(L::Denied),
    Transient(L::Transient),
    Fatal(L::Fatal),
}

impl<D, L: LaneProfile> Fail<D, L> {
    pub fn lane(&self) -> Lane {
        match self {
            Fail::Rejected(_) => Lane::Rejected,
            Fail::Denied(_) => Lane::Denied,
            Fail::Transient(_) => Lane::Transient,
            Fail::Fatal(_) => Lane::Fatal,
        }
    }

    /// Widen the rejection and the lane profile without changing any
    /// classification. The value-level form of [`WidenResult::widen`], with
    /// the same single rule: `P: Lift<D>` is satisfied by a total `From<D>`
    /// (through errlanes' blanket, `Unmapped = Infallible`) and by a partial
    /// `#[lift(Source, unhandled = fatal)]` mapping (`Unmapped = Source`),
    /// whose unmapped cases demote to `Fatal(Invariant)` with the rejection
    /// as their source — which is why a partial mapping requires the
    /// destination to admit `Fatal`. The strict/partial choice is declared
    /// once on the destination enum; the call site does not repeat it.
    pub fn widen<P: Lift<D>, M: LaneProfile>(self) -> Fail<P, M>
    where
        L::Denied: Into<M::Denied>,
        L::Transient: Into<M::Transient>,
        L::Fatal: Into<M::Fatal>,
        P::Unmapped: UnmappedInto<M::Fatal>,
    {
        match self {
            Self::Rejected(d) => match P::lift(d) {
                Ok(mapped) => Fail::Rejected(mapped),
                Err(unmapped) => Fail::Fatal(unmapped.unmapped_into()),
            },
            Self::Denied(d) => Fail::Denied(d.into()),
            Self::Transient(t) => Fail::Transient(t.into()),
            Self::Fatal(f) => Fail::Fatal(f.into()),
        }
    }

    pub fn widen_with<P, M: LaneProfile<Fatal = Fatal>>(
        self,
        f: impl FnOnce(D) -> Result<P, Fatal>,
    ) -> Fail<P, M>
    where
        L::Denied: Into<M::Denied>,
        L::Transient: Into<M::Transient>,
        L::Fatal: Into<M::Fatal>,
    {
        match self {
            Self::Rejected(d) => match f(d) {
                Ok(p) => Fail::Rejected(p),
                Err(e) => Fail::Fatal(e),
            },
            Self::Denied(d) => Fail::Denied(d.into()),
            Self::Transient(t) => Fail::Transient(t.into()),
            Self::Fatal(f) => Fail::Fatal(f.into()),
        }
    }

    pub fn map_rejected<D2>(self, f: impl FnOnce(D) -> D2) -> Fail<D2, L> {
        match self {
            Fail::Rejected(d) => Fail::Rejected(f(d)),
            Fail::Denied(d) => Fail::Denied(d),
            Fail::Transient(t) => Fail::Transient(t),
            Fail::Fatal(fatal) => Fail::Fatal(fatal),
        }
    }

    /// Narrows to the domain outcome, or the non-domain fault. `let d =
    /// e.rejected()?;` propagates the fault into any enclosing `Fail<_, L>` (or
    /// a `Failure` carrier) via the blanket `From<Fault<L>>`.
    pub fn rejected(self) -> Result<D, Fault<L>> {
        match self {
            Fail::Rejected(d) => Ok(d),
            Fail::Denied(d) => Err(Fault::Denied(d)),
            Fail::Transient(t) => Err(Fault::Transient(t)),
            Fail::Fatal(f) => Err(Fault::Fatal(f)),
        }
    }

    pub fn as_rejected(&self) -> Option<&D> {
        match self {
            Fail::Rejected(d) => Some(d),
            _ => None,
        }
    }

    pub fn is_transient(&self) -> bool {
        matches!(self, Fail::Transient(_))
    }

    pub fn is_fatal(&self) -> bool {
        matches!(self, Fail::Fatal(_))
    }

    pub fn is_denied(&self) -> bool {
        matches!(self, Fail::Denied(_))
    }

    /// The operator-safe one-line text for this failure — exactly what
    /// `record` writes to `exception.message`, for a boundary that must
    /// persist it rather than (or as well as) record it. `Transient`/
    /// `Fatal`: the whole `source()` chain joined with `": "`. `Denied`: its
    /// `Display`. `Rejected`: the rejection's `code`, never its message
    /// (display discipline — a rejection's message may embed caller-supplied
    /// input).
    pub fn message(&self) -> String
    where
        D: Rejection,
    {
        match self {
            Fail::Rejected(d) => d.code().to_string(),
            Fail::Denied(d) => d.to_string(),
            Fail::Transient(t) => crate::dynamic::message_chain(t),
            Fail::Fatal(x) => crate::dynamic::message_chain(x),
        }
    }

    /// Consumes the `Transient` lane, yielding the same rejection over `L`
    /// with its transient slot disabled. An exhausted transient becomes
    /// `Fatal(Exhausted)`, carrying `attempts` and the last transient as its
    /// source.
    pub fn narrow_transient(self, attempts: u32) -> Fail<D, crate::profile::WithoutTransient<L>>
    where
        L::Transient: NarrowTransient<L::Fatal>,
    {
        match self {
            Fail::Rejected(d) => Fail::Rejected(d),
            Fail::Denied(d) => Fail::Denied(d),
            Fail::Transient(last) => Fail::Fatal(last.narrow(attempts)),
            Fail::Fatal(f) => Fail::Fatal(f),
        }
    }

    /// Narrows away the `Denied` lane: a denial at a boundary with no
    /// subject (code running as the system) becomes `Fatal(Denied)` with
    /// the `Denied` as its source.
    pub fn narrow_denied(self) -> Fail<D, crate::profile::WithoutDenied<L>>
    where
        L::Denied: NarrowDenied<L::Fatal>,
    {
        match self {
            Fail::Rejected(d) => Fail::Rejected(d),
            Fail::Denied(d) => Fail::Fatal(d.narrow()),
            Fail::Transient(t) => Fail::Transient(t),
            Fail::Fatal(f) => Fail::Fatal(f),
        }
    }

    /// Narrows away the `Rejected` lane: a rejection at a boundary with no
    /// caller to correct it is an invariant violation, and becomes
    /// `Fatal(Invariant)` with the rejection as its source — the same rule
    /// a partial `#[lift(.., unhandled = fatal)]` applies. Nothing is left
    /// to reject, so the result is a `Fault`. `with_opaque_source`: `d`'s
    /// `Display` may embed caller-supplied input (the same display
    /// discipline `Rejection` documents everywhere else), so `source()`
    /// still returns it for a handler or test to `downcast_ref`, but
    /// `message_chain` must not walk into it.
    pub fn narrow_rejected(self) -> Fault<L>
    where
        D: Rejection,
        L: LaneProfile<Fatal = Fatal>,
    {
        match self {
            Fail::Rejected(d) => Fault::Fatal(
                Fatal::from_error(crate::FatalKind::Invariant, d)
                    .with_context("rejected with no caller to correct")
                    .with_opaque_source(),
            ),
            Fail::Denied(d) => Fault::Denied(d),
            Fail::Transient(t) => Fault::Transient(t),
            Fail::Fatal(f) => Fault::Fatal(f),
        }
    }
}

/// The real blanket the `Infallible` encoding could not have: `Fault<L>` is not
/// `Fail`, so this does not overlap `From<T> for T`.
impl<D, S: LaneProfile, L: LaneProfile> From<Fault<S>> for Fail<D, L>
where
    S::Denied: Into<L::Denied>,
    S::Transient: Into<L::Transient>,
    S::Fatal: Into<L::Fatal>,
{
    fn from(f: Fault<S>) -> Self {
        match f {
            Fault::Denied(d) => Fail::Denied(d.into()),
            Fault::Transient(t) => Fail::Transient(t.into()),
            Fault::Fatal(x) => Fail::Fatal(x.into()),
        }
    }
}

impl<D, L: LaneProfile> From<Transient> for Fail<D, L>
where
    L: LaneProfile<Transient = Transient>,
{
    fn from(t: Transient) -> Self {
        Fail::Transient(t)
    }
}

impl<D, L: LaneProfile> From<Fatal> for Fail<D, L>
where
    L: LaneProfile<Fatal = Fatal>,
{
    fn from(f: Fatal) -> Self {
        Fail::Fatal(f)
    }
}

impl<D, L: LaneProfile> From<Denied> for Fail<D, L>
where
    L: LaneProfile<Denied = Denied>,
{
    fn from(d: Denied) -> Self {
        Fail::Denied(d)
    }
}

impl<D, L: LaneProfile> From<Exhausted> for Fail<D, L>
where
    L: LaneProfile<Fatal = Fatal>,
{
    fn from(e: Exhausted) -> Self {
        Fail::Fatal(Fatal::from_error(crate::lane::FatalKind::Exhausted, e))
    }
}

impl<D: fmt::Display, L: LaneProfile> fmt::Display for Fail<D, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Fail::Rejected(d) => write!(f, "rejected: {d}"),
            Fail::Denied(d) => write!(f, "{d}"),
            Fail::Transient(t) => write!(f, "{t}"),
            Fail::Fatal(x) => write!(f, "{x}"),
        }
    }
}

impl<D: Error + 'static, L: LaneProfile> Error for Fail<D, L> {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            // The lane payload itself must be the *next* link in the chain
            // so that `lane_of` can find it by downcasting.
            Fail::Rejected(d) => Some(d),
            Fail::Denied(d) => Some(d),
            Fail::Transient(t) => Some(t),
            Fail::Fatal(x) => Some(x),
        }
    }
}

/// Implemented by per-crate carrier newtypes, typically via
/// `#[derive(errlanes::Failure)]`. Generic machinery (retry, boundary
/// recorders) is written against this, not against `Fail<D, L>` directly.
pub trait Failure: Error + Send + Sync + Sized + 'static {
    type Rejection: Rejection;
    type Lanes: LaneProfile;

    fn into_fail(self) -> Fail<Self::Rejection, Self::Lanes>;
    fn from_fail(f: Fail<Self::Rejection, Self::Lanes>) -> Self;
    fn as_fail(&self) -> &Fail<Self::Rejection, Self::Lanes>;

    fn lane(&self) -> Lane {
        self.as_fail().lane()
    }

    fn is_transient(&self) -> bool {
        matches!(self.lane(), Lane::Transient)
    }
}

impl<D: Rejection, L: LaneProfile> Failure for Fail<D, L> {
    type Rejection = D;
    type Lanes = L;

    fn into_fail(self) -> Fail<Self::Rejection, Self::Lanes> {
        self
    }

    fn from_fail(f: Fail<Self::Rejection, Self::Lanes>) -> Self {
        f
    }

    fn as_fail(&self) -> &Fail<Self::Rejection, Self::Lanes> {
        self
    }
}

pub(crate) mod sealed {
    pub trait Sealed {}
    impl<F: super::Failure> Sealed for F {}
    impl<L: super::LaneProfile> Sealed for super::Fault<L> {}
}

/// Sealed. The thing `retry`/`record` need from any error they are handed:
/// its lane, and how to narrow it. Implemented by every [`Failure`] (which
/// covers `Fail<D, L>` itself and every carrier) and by [`Fault<L>`] — the two
/// shapes a generated repo op can return.
pub trait Laned: sealed::Sealed + Error + Send + Sync + 'static + Sized {
    type WithoutTransient: Error + Send + Sync + 'static;

    fn lane(&self) -> Lane;

    fn is_transient(&self) -> bool {
        self.lane() == Lane::Transient
    }

    fn is_fatal(&self) -> bool {
        self.lane() == Lane::Fatal
    }

    fn is_denied(&self) -> bool {
        self.lane() == Lane::Denied
    }

    fn narrow_transient(self, attempts: u32) -> Self::WithoutTransient;

    /// The operator-safe one-line text for this failure — exactly what
    /// `record` writes to `exception.message`, for a boundary that must
    /// persist it rather than (or as well as) record it. `Transient`/
    /// `Fatal`: the whole `source()` chain joined with `": "`. `Denied`: its
    /// `Display`. `Rejected`: the rejection's `code`, never its message
    /// (display discipline — a rejection's message may embed caller-supplied
    /// input).
    fn message(&self) -> String;

    #[cfg(feature = "tracing")]
    fn record(&self, span: &tracing::Span);
}

/// Note the `NarrowTransient` bound: a profile that admits `Transient` but
/// not `Fatal` is not `Laned`, so `retry` cannot be handed one. Retrying an
/// operation that claims it can never fail permanently is exactly the
/// contradiction the bound rules out.
impl<F: Failure> Laned for F
where
    <F::Lanes as LaneProfile>::Transient: NarrowTransient<<F::Lanes as LaneProfile>::Fatal>,
{
    type WithoutTransient = Fail<F::Rejection, crate::profile::WithoutTransient<F::Lanes>>;

    fn lane(&self) -> Lane {
        Failure::lane(self)
    }

    fn narrow_transient(self, attempts: u32) -> Self::WithoutTransient {
        self.into_fail().narrow_transient(attempts)
    }

    fn message(&self) -> String {
        self.as_fail().message()
    }

    #[cfg(feature = "tracing")]
    fn record(&self, span: &tracing::Span) {
        crate::record::record_fail(span, self.as_fail());
    }
}

impl<L: LaneProfile> Laned for Fault<L>
where
    L::Transient: NarrowTransient<L::Fatal>,
{
    type WithoutTransient = Fault<crate::profile::WithoutTransient<L>>;

    fn lane(&self) -> Lane {
        Fault::lane(self)
    }

    fn narrow_transient(self, attempts: u32) -> Self::WithoutTransient {
        Fault::narrow_transient(self, attempts)
    }

    fn message(&self) -> String {
        Fault::message(self)
    }

    #[cfg(feature = "tracing")]
    fn record(&self, span: &tracing::Span) {
        crate::record::record_fault(span, self);
    }
}

/// Dispatch engine for [`crate::ResultExt::widen`], keyed on the source
/// shape so each carrier (`Fault`, `Fail`, a bare [`crate::Classify`] source)
/// gets its own body. Hidden: a consumer calls `.widen()` on a `Result`,
/// never this trait directly. See `ResultExt::widen` for the full doc,
/// including the `compile_fail` example of a lane widening cannot discard.
#[doc(hidden)]
pub trait WidenResult<T, E>: Sized {
    fn widen(self) -> Result<T, E>;
}

impl<T, L: LaneProfile, M: LaneProfile> WidenResult<T, Fault<M>> for Result<T, Fault<L>>
where
    L::Denied: Into<M::Denied>,
    L::Transient: Into<M::Transient>,
    L::Fatal: Into<M::Fatal>,
{
    fn widen(self) -> Result<T, Fault<M>> {
        self.map_err(Fault::widen)
    }
}

/// One rule for every rejection remapping. `P: Lift<R>` is satisfied by a total
/// `From<R>` (through errlanes' blanket, `Unmapped = Infallible`) and by a
/// partial `#[lift(Source, unhandled = fatal)]` mapping (`Unmapped = Source`).
/// The `UnmappedInto` bound then enforces, per destination, exactly what each
/// mode needs: a total mapping works into any profile, while a partial one
/// requires the destination to admit `Fatal`. The strict/partial choice is
/// declared once on the destination enum, so the call site does not repeat it.
impl<T, R, P: Lift<R>, L: LaneProfile, M: LaneProfile> WidenResult<T, Fail<P, M>>
    for Result<T, Fail<R, L>>
where
    L::Denied: Into<M::Denied>,
    L::Transient: Into<M::Transient>,
    L::Fatal: Into<M::Fatal>,
    P::Unmapped: UnmappedInto<M::Fatal>,
{
    fn widen(self) -> Result<T, Fail<P, M>> {
        self.map_err(Fail::widen)
    }
}

// The bare-source impl for `Result<T, C>` (a rejection, a fault wrapper, or a
// mixed wrapper alike) lives in `classify.rs`, generalised from `C: Rejection`
// to `C: Classify` — a bare rejection is the `Rejected = C, Lanes = NoLanes`
// case of that.

impl<L: LaneProfile> Fault<L> {
    pub fn widen<M: LaneProfile>(self) -> Fault<M>
    where
        L::Denied: Into<M::Denied>,
        L::Transient: Into<M::Transient>,
        L::Fatal: Into<M::Fatal>,
    {
        match self {
            Self::Denied(d) => Fault::Denied(d.into()),
            Self::Transient(t) => Fault::Transient(t.into()),
            Self::Fatal(f) => Fault::Fatal(f.into()),
        }
    }
}

/// Compile-time field metadata used by the rejection composition protocol.
#[doc(hidden)]
pub trait RejectionField<const VARIANT: u64, const FIELD: usize> {
    type Type;
}

/// Borrowed metadata protocol; forwarding does not clone or reconstruct errors.
#[doc(hidden)]
pub trait RejectionMetadata<const VARIANT: u64>: Rejection {
    type Fields<'a>;
    fn field_code(fields: Self::Fields<'_>) -> Self::Code;
    fn field_level(fields: Self::Fields<'_>) -> Level;
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lane::{FatalKind, TransientKind};

    #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
    struct SmallCode;
    impl fmt::Display for SmallCode {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("SMALL")
        }
    }
    impl From<SmallCode> for &'static str {
        fn from(_: SmallCode) -> Self {
            "SMALL"
        }
    }

    #[derive(Debug, Clone, PartialEq, Eq)]
    struct Small;
    impl fmt::Display for Small {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("small")
        }
    }
    impl Error for Small {}
    impl Rejection for Small {
        type Code = SmallCode;
        fn code(&self) -> SmallCode {
            SmallCode
        }
    }

    #[derive(Debug, Clone, PartialEq, Eq)]
    struct Big(Small);
    impl fmt::Display for Big {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "big({})", self.0)
        }
    }
    impl Error for Big {}
    impl From<Small> for Big {
        fn from(s: Small) -> Self {
            Big(s)
        }
    }
    impl Rejection for Big {
        type Code = SmallCode;
        fn code(&self) -> SmallCode {
            self.0.code()
        }
    }

    #[test]
    fn widen_preserves_the_lane() {
        let f: Fail<Small> = Fail::Rejected(Small);
        let widened: Fail<Big> = f.widen();
        assert_eq!(widened.lane(), Lane::Rejected);
        assert_eq!(widened.as_rejected(), Some(&Big(Small)));

        let t: Fail<Small> = Transient::new(TransientKind::Deadlock).into();
        let widened: Fail<Big> = t.widen();
        assert_eq!(widened.lane(), Lane::Transient);
    }

    #[test]
    fn widen_with_demotes_an_unmapped_rejection_to_fatal() {
        let f: Fail<Small> = Fail::Rejected(Small);
        let widened: Fail<Big> = f.widen_with(|_| Err(Fatal::invariant("unmapped")));
        assert_eq!(widened.lane(), Lane::Fatal);

        let f: Fail<Small> = Fail::Rejected(Small);
        let widened: Fail<Big> = f.widen_with(|s| Ok(Big(s)));
        assert_eq!(widened.lane(), Lane::Rejected);
    }

    /// Regression: `UnmappedInto<Fatal> for R: Rejection` (the partial-lift
    /// path) must keep the unmapped rejection reachable by `downcast_ref`
    /// for a handler or test, but never let its `Display` -- which may embed
    /// caller-supplied input -- reach an operator-facing message.
    #[test]
    fn unmapped_rejection_demoted_to_fatal_does_not_leak_its_display() {
        let fatal: Fatal = Small.unmapped_into();
        assert_eq!(fatal.kind, FatalKind::Invariant);
        assert!(
            fatal.source().unwrap().downcast_ref::<Small>().is_some(),
            "the rejection must still be reachable for a handler or test to downcast"
        );
        let message = crate::dynamic::message_chain(&fatal);
        assert!(
            !message.contains("small"),
            "a partial lift's unmapped rejection's Display must never reach an \
             operator-facing message; got {message:?}"
        );
    }

    /// Same regression as `unmapped_rejection_demoted_to_fatal_does_not_leak_its_display`,
    /// for `narrow_rejected`'s own construction site.
    #[test]
    fn narrow_rejected_does_not_leak_the_rejections_display() {
        let f: Fail<Small> = Fail::Rejected(Small);
        let narrowed = f.narrow_rejected();
        match &narrowed {
            Fault::Fatal(fatal) => {
                assert_eq!(fatal.kind, FatalKind::Invariant);
                assert!(fatal.source().unwrap().downcast_ref::<Small>().is_some());
            }
            other => panic!("expected Fatal(Invariant), got {other:?}"),
        }
        let message = narrowed.message();
        assert!(
            !message.contains("small"),
            "narrow_rejected's rejection Display must never reach an operator-facing \
             message; got {message:?}"
        );
    }

    #[test]
    fn narrow_transient_turns_transient_into_exhausted_and_leaves_everything_else_alone() {
        let t: Fail<Small> = Transient::new(TransientKind::Deadlock).into();
        match t.narrow_transient(3) {
            Fail::Fatal(f) => {
                assert_eq!(f.kind, FatalKind::Exhausted);
                let e = Error::source(&f)
                    .and_then(|s| s.downcast_ref::<Exhausted>())
                    .expect("exhaustion is the fatal's source");
                assert_eq!(e.attempts, 3);
                assert_eq!(e.last.kind, TransientKind::Deadlock);
            }
            other => panic!("expected Fatal(Exhausted), got {other:?}"),
        }

        let r: Fail<Small> = Fail::Rejected(Small);
        assert!(matches!(r.narrow_transient(1), Fail::Rejected(Small)));

        let fatal: Fail<Small> = Fatal::new(FatalKind::Config).into();
        assert!(matches!(fatal.narrow_transient(1), Fail::Fatal(_)));
    }

    #[test]
    fn fault_converts_into_any_fail_via_the_real_blanket() {
        let fault: Fault = Fatal::new(FatalKind::CorruptState).into();
        let widened: Fail<Small> = fault.into();
        assert_eq!(widened.lane(), Lane::Fatal);
    }

    #[test]
    fn rejected_narrows_or_returns_the_fault() {
        let f: Fail<Small> = Fail::Rejected(Small);
        assert_eq!(f.rejected().unwrap(), Small);

        let t: Fail<Small> = Transient::new(TransientKind::Deadlock).into();
        assert!(t.rejected().is_err());
    }

    #[test]
    fn fail_source_is_the_lane_payload_itself_so_lane_of_can_downcast_it() {
        let t: Fail<Small> = Transient::new(TransientKind::Deadlock).into();
        let source = std::error::Error::source(&t).expect("source present");
        assert!(source.is::<Transient>());
    }

    #[test]
    fn fault_source_is_the_lane_payload_itself_so_lane_of_can_downcast_it() {
        let t: Fault = Transient::new(TransientKind::Deadlock).into();
        let source = std::error::Error::source(&t).expect("source present");
        assert!(source.is::<Transient>());
    }

    #[test]
    fn laned_narrow_transient_agrees_between_fail_and_fault() {
        fn exhausted_attempts(e: &(dyn Error + 'static)) -> u32 {
            e.source()
                .and_then(|s| s.downcast_ref::<Exhausted>())
                .expect("exhaustion is the fatal's source")
                .attempts
        }

        let t: Fail<Small> = Transient::new(TransientKind::Deadlock).into();
        let narrowed: Fail<Small, crate::profile::WithoutTransient<AllLanes>> =
            Laned::narrow_transient(t, 2);
        assert_eq!(narrowed.lane(), Lane::Fatal);
        assert_eq!(exhausted_attempts(narrowed.as_fatal().unwrap()), 2);

        let t: Fault = Transient::new(TransientKind::Deadlock).into();
        let narrowed: Fault<crate::profile::WithoutTransient<AllLanes>> =
            Laned::narrow_transient(t, 2);
        assert_eq!(narrowed.lane(), Lane::Fatal);
        assert_eq!(exhausted_attempts(narrowed.as_fatal().unwrap()), 2);
    }
}