errlanes 0.20.3

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
//! Smoke tests for `#[derive(errlanes::Classify)]`, covering the shapes from
//! the design handoff's Appendix A: a fault-only wrapper, a mixed wrapper
//! with a `delegate` to a pure rejection and a static lane, `narrow(Denied)`
//! over a delegate, and composition across layers via `.lift()`.

use std::convert::Infallible;

use errlanes::{Classify, Fail, Fault, Rejection, ResultExt, lanes};

type Tf = lanes!(Transient, Fatal);

#[derive(Debug, errlanes::Rejection)]
enum Validation {
    #[rejection(code = "INVALID_AMOUNT")]
    InvalidAmount,
}

#[derive(Debug, errlanes::Classify)]
#[classify(fatal(CorruptState), from)]
struct Stored(#[source] std::io::Error);

// `#[derive(Rejection)]` needs a `code = ".."` on a struct.
#[derive(Debug, errlanes::Rejection)]
#[rejection(code = "CONSTRAINT")]
struct ConstraintViolation(&'static str);

#[derive(Debug, errlanes::Classify)]
enum DbWrite {
    #[classify(delegate)]
    Constraint(ConstraintViolation),
    #[classify(transient(OptimisticConflict))]
    Conflict(std::io::Error),
    #[classify(delegate)]
    Other(Stored),
}

impl From<std::io::Error> for DbWrite {
    fn from(e: std::io::Error) -> Self {
        match e.kind() {
            std::io::ErrorKind::AlreadyExists => {
                DbWrite::Constraint(ConstraintViolation("users_email_key"))
            }
            std::io::ErrorKind::Interrupted => DbWrite::Conflict(e),
            _ => DbWrite::Other(Stored(e)),
        }
    }
}

#[derive(Debug, errlanes::Rejection)]
enum JobRejection {
    Dup(ConstraintViolation),
}

impl From<ConstraintViolation> for JobRejection {
    fn from(c: ConstraintViolation) -> Self {
        JobRejection::Dup(c)
    }
}

fn decode() -> Result<u8, std::io::Error> {
    Err(std::io::Error::other("x"))
}

fn insert() -> Result<u8, std::io::Error> {
    Err(std::io::Error::from(std::io::ErrorKind::AlreadyExists))
}

#[test]
fn fault_wrapper_enters_fault_by_question_mark() {
    fn fault_fn() -> Result<u8, Fault<Tf>> {
        let _ = decode().classify::<Stored>()?;
        Ok(0)
    }
    match fault_fn() {
        Err(Fault::Fatal(f)) => assert_eq!(f.kind, errlanes::FatalKind::CorruptState),
        other => panic!("expected Fatal(CorruptState), got {other:?}"),
    }
}

#[test]
fn mixed_wrapper_enters_fail_by_question_mark_total_absorption() {
    fn fail_fn() -> Result<u8, Fail<JobRejection, Tf>> {
        let _ = insert().classify::<DbWrite>()?;
        Ok(0)
    }
    match fail_fn() {
        Err(Fail::Rejected(JobRejection::Dup(c))) => assert_eq!(c.0, "users_email_key"),
        other => panic!("expected Rejected(Dup), got {other:?}"),
    }
}

#[test]
fn static_lane_variant_is_transient() {
    let e = std::io::Error::from(std::io::ErrorKind::Interrupted);
    let wrapped: DbWrite = e.into();
    match wrapped.classify() {
        Fail::Transient(t) => assert_eq!(t.kind, errlanes::TransientKind::OptimisticConflict),
        other => panic!("expected Transient(OptimisticConflict), got {other:?}"),
    }
}

#[test]
fn delegate_through_a_fault_only_payload_expands_its_lanes() {
    let e = std::io::Error::other("disk full");
    let wrapped: DbWrite = e.into();
    match wrapped.classify() {
        Fail::Fatal(f) => assert_eq!(f.kind, errlanes::FatalKind::CorruptState),
        other => panic!("expected Fatal(CorruptState), got {other:?}"),
    }
}

#[test]
fn a_bare_rejection_is_classify_via_the_blanket() {
    let r = Validation::InvalidAmount;
    let fail: Fail<Validation> = r.into();
    assert!(matches!(fail, Fail::Rejected(Validation::InvalidAmount)));
}

#[test]
fn narrow_rejected_turns_a_fail_into_a_fault() {
    let wrapped: DbWrite = insert().unwrap_err().into();
    let fail: Fail<ConstraintViolation, Tf> = Classify::classify(wrapped);
    let fault = fail.map_err_narrow();
    assert!(fault.is_fatal());
}

trait MapErrNarrow<L: errlanes::LaneProfile> {
    fn map_err_narrow(self) -> Fault<L>;
}
impl<D: Rejection, L: errlanes::LaneProfile<Fatal = errlanes::Fatal>> MapErrNarrow<L>
    for Fail<D, L>
{
    fn map_err_narrow(self) -> Fault<L> {
        self.narrow_rejected()
    }
}

#[test]
fn infallible_rejected_slot_is_a_rejected_slot() {
    fn assert_rejected_slot<T: errlanes::RejectedSlot>() {}
    assert_rejected_slot::<Infallible>();
    assert_rejected_slot::<Validation>();
}

// Pure mode: no lane/delegate anywhere, so `derive(Classify)` must emit
// exactly what `derive(Rejection)` emits (byte-identical grammar, same
// engine) and `Classify` comes from the blanket, not a direct impl.
#[derive(Debug, errlanes::Classify)]
enum PureViaClassify {
    #[classify(code = "TOO_SMALL")]
    TooSmall,
}

#[test]
fn pure_mode_delegates_to_the_rejection_engine() {
    let r = PureViaClassify::TooSmall;
    assert_eq!(r.code().to_string(), "TOO_SMALL");
    // Classify comes from the blanket `impl<R: Rejection> Classify for R`,
    // not a direct impl — a direct impl would conflict with it (E0119).
    let fail: Fail<PureViaClassify> = PureViaClassify::TooSmall.into();
    assert!(matches!(fail, Fail::Rejected(PureViaClassify::TooSmall)));
}

// A mixed wrapper with both a `Denied` and a `Fatal` lane (so `narrow_denied`
// has somewhere to land), narrowed away over a `delegate`.
#[derive(Debug, errlanes::Classify)]
enum Unauthorized {
    #[classify(denied)]
    NotOurs,
    #[classify(fatal(Config))]
    Misconfigured,
}

#[derive(Debug, errlanes::Classify)]
enum Proxy {
    #[classify(delegate, narrow(Denied))]
    Upstream(Unauthorized),
}

#[test]
fn narrow_denied_turns_a_delegated_denial_into_fatal() {
    let wrapped = Proxy::Upstream(Unauthorized::NotOurs);
    match wrapped.classify() {
        Fail::Fatal(f) => assert_eq!(f.kind, errlanes::FatalKind::Denied),
        other => panic!("expected Fatal(Denied), got {other:?}"),
    }
}

#[test]
fn a_fatal_variant_alongside_a_denied_one_stays_fatal() {
    let wrapped = Proxy::Upstream(Unauthorized::Misconfigured);
    match wrapped.classify() {
        Fail::Fatal(f) => assert_eq!(f.kind, errlanes::FatalKind::Config),
        other => panic!("expected Fatal(Config), got {other:?}"),
    }
}

// Composition across layers: each layer declares one lift against the type
// it actually receives.
#[derive(Debug, errlanes::Rejection)]
enum Api {
    #[rejection(from)]
    Job(JobRejection),
}

#[test]
fn composition_across_layers_expands_through_each_hop() {
    fn repo_insert() -> Result<u8, Fail<ConstraintViolation, Tf>> {
        let _ = insert().classify::<DbWrite>()?;
        Ok(0)
    }
    fn service() -> Result<u8, Fail<JobRejection, Tf>> {
        let _ = repo_insert().lift()?;
        Ok(0)
    }
    fn api() -> Result<u8, Fail<Api, Tf>> {
        let _ = service().lift()?;
        Ok(0)
    }
    match api() {
        Err(Fail::Rejected(Api::Job(JobRejection::Dup(c)))) => assert_eq!(c.0, "users_email_key"),
        other => panic!("expected Rejected(Job(Dup)), got {other:?}"),
    }
}

// Regression: `Rejected` is folded via `RejectedUnion` across every
// `delegate`, not read off whichever variant happens to be declared first.
// `Other` (never rejects) is declared *before* `Constraint` (the one
// genuine rejection) here — the reverse of `DbWrite` above.
#[derive(Debug, errlanes::Classify)]
enum DbWriteReordered {
    #[classify(delegate)]
    Other(Stored),
    #[classify(delegate)]
    Constraint(ConstraintViolation),
}

#[test]
fn rejected_is_folded_order_independently_across_delegates() {
    fn assert_rejected_is<R: errlanes::RejectedSlot>() {}
    assert_rejected_is::<<DbWriteReordered as Classify>::Rejected>();
    let _: <DbWriteReordered as Classify>::Rejected = ConstraintViolation("users_email_key");

    let wrapped = DbWriteReordered::Constraint(ConstraintViolation("users_email_key"));
    match wrapped.classify() {
        Fail::Rejected(ConstraintViolation(v)) => assert_eq!(v, "users_email_key"),
        other => panic!("expected Rejected, got {other:?}"),
    }

    let wrapped = DbWriteReordered::Other(Stored(std::io::Error::other("x")));
    match wrapped.classify() {
        Fail::Fatal(f) => assert_eq!(f.kind, errlanes::FatalKind::CorruptState),
        other => panic!("expected Fatal(CorruptState), got {other:?}"),
    }
}

// Named fields: a `#[source]` field among siblings (the shape errlanes also
// treats as the cause) and a lone named field both `delegate`; `from` on the
// lone one builds `Self::Wrapped { inner: value }`.
#[derive(Debug, errlanes::Classify)]
enum NamedPayloads {
    #[classify(delegate)]
    Decode {
        sequence: i32,
        #[source]
        source: Stored,
    },
    #[classify(delegate, from)]
    Wrapped { inner: ConstraintViolation },
}

#[derive(Debug, errlanes::Classify)]
#[classify(fatal(Config), from)]
struct NamedStruct {
    #[source]
    source: std::io::Error,
}

#[test]
fn a_source_field_among_siblings_delegates() {
    let wrapped = NamedPayloads::Decode {
        sequence: 7,
        source: Stored(std::io::Error::other("x")),
    };
    match wrapped.classify() {
        Fail::Fatal(f) => assert_eq!(f.kind, errlanes::FatalKind::CorruptState),
        other => panic!("expected Fatal(CorruptState), got {other:?}"),
    }
}

#[test]
fn a_lone_named_field_delegates_and_converts_with_from() {
    let wrapped: NamedPayloads = ConstraintViolation("users_email_key").into();
    match wrapped.classify() {
        Fail::Rejected(ConstraintViolation(v)) => assert_eq!(v, "users_email_key"),
        other => panic!("expected Rejected, got {other:?}"),
    }
}

#[test]
fn a_named_struct_field_converts_with_from() {
    let wrapped: NamedStruct = std::io::Error::other("x").into();
    match wrapped.classify() {
        Fail::Fatal(f) => assert_eq!(f.kind, errlanes::FatalKind::Config),
        other => panic!("expected Fatal(Config), got {other:?}"),
    }
}

/// A `Classify` wrapper's whole purpose can be to *override* the
/// classification its payload would get on its own — `Stored` lanes an
/// `io::Error` as `Fatal(CorruptState)`, where the bare error would fall
/// through to `Fatal(Dependency)`. The override lives in the `impl Classify`,
/// not in the value, so it only survives a `Box<dyn Error>` boundary if the
/// wrapper reaches a carrier *before* it reaches the box: `Fault::classify`
/// walks for lane payloads and blessed foreign types, and a half-entered
/// wrapper is neither.
///
/// `?` alone boxes the wrapper unlaned (std boxes any `Error`), which
/// compiles, keeps the message, and silently reverts the one field the
/// wrapper existed to set. `.into_fault()?` is the short spelling that
/// does not.
#[test]
fn a_wrapper_keeps_its_override_across_a_box_only_once_laned() {
    fn decode() -> Result<u8, Stored> {
        Err(Stored(std::io::Error::other("bad bytes")))
    }

    // Boxed raw: the wrapper is not a lane payload, so the boundary falls
    // through to rule 3 and the `CorruptState` override is gone.
    fn boxed_raw() -> Result<u8, Box<dyn std::error::Error + Send + Sync>> {
        Ok(decode()?)
    }
    match Fault::classify(&*boxed_raw().unwrap_err()) {
        Fault::Fatal(f) => assert_eq!(
            f.kind,
            errlanes::FatalKind::Dependency,
            "boxing a wrapper raw must not be mistaken for a laned one",
        ),
        other => panic!("expected Fatal, got {other:?}"),
    }

    // Converted to a Fault first: the override survives one hop into the box.
    fn boxed_laned() -> Result<u8, Box<dyn std::error::Error + Send + Sync>> {
        Ok(decode().into_fault()?)
    }
    match Fault::classify(&*boxed_laned().unwrap_err()) {
        Fault::Fatal(f) => assert_eq!(f.kind, errlanes::FatalKind::CorruptState),
        other => panic!("expected Fatal(CorruptState), got {other:?}"),
    }
}

/// The same pin on the shape that found this: a wrapper overriding a *blessed
/// foreign* classification. `serde_json::Error` lanes itself as
/// `Fatal(Invariant)`; bytes that came out of a database earn
/// `Fatal(CorruptState)` instead, and that is exactly what boxing the wrapper
/// raw throws away — the boundary finds the `serde_json::Error` in the chain
/// and lanes *that*.
#[cfg(feature = "classify-serde-json")]
#[test]
fn an_override_of_a_blessed_foreign_classification_needs_the_same_care() {
    #[derive(Debug, errlanes::Classify)]
    #[classify(fatal(CorruptState), from)]
    #[error("could not decode a stored row")]
    struct StoredRow(#[source] serde_json::Error);

    fn decode() -> Result<u8, StoredRow> {
        Err(StoredRow(
            serde_json::from_str::<u8>("\"not a number\"").unwrap_err(),
        ))
    }

    let raw: Box<dyn std::error::Error + Send + Sync> = Box::new(decode().unwrap_err());
    match Fault::classify(&*raw) {
        Fault::Fatal(f) => assert_eq!(f.kind, errlanes::FatalKind::Invariant),
        other => panic!("expected Fatal(Invariant), got {other:?}"),
    }

    let laned: Box<dyn std::error::Error + Send + Sync> =
        Box::new(decode().into_fault().unwrap_err());
    match Fault::classify(&*laned) {
        Fault::Fatal(f) => assert_eq!(f.kind, errlanes::FatalKind::CorruptState),
        other => panic!("expected Fatal(CorruptState), got {other:?}"),
    }
}

// A `delegate` payload only has to be `IntoLanes`: a `Fail` or a `Fault`
// delegates lane-for-lane like a `Classify` type does.
#[derive(Debug, errlanes::Classify)]
enum Carrying {
    #[classify(delegate, from)]
    Query(Fail<ConstraintViolation, lanes!(Transient, Fatal)>),
    #[classify(delegate, from)]
    Store(Fault<lanes!(Fatal)>),
}

fn lane_error(kind: errlanes::FatalKind) -> Fault<lanes!(Fatal)> {
    Fault::Fatal(errlanes::Fatal::new(kind))
}

#[test]
fn a_fail_payload_delegates_lane_for_lane() {
    let rejected: Carrying =
        Fail::<_, lanes!(Transient, Fatal)>::Rejected(ConstraintViolation("pkey")).into();
    let Fail::Rejected(violation) = rejected.classify() else {
        panic!("expected the payload's rejection");
    };
    assert_eq!(violation.0, "pkey");

    let fatal: Carrying = Fail::<ConstraintViolation, lanes!(Transient, Fatal)>::Fatal(
        errlanes::Fatal::new(errlanes::FatalKind::Config),
    )
    .into();
    match fatal.classify() {
        Fail::Fatal(f) => assert_eq!(f.kind, errlanes::FatalKind::Config),
        other => panic!("expected Fatal(Config), got {other:?}"),
    }
}

#[test]
fn a_fault_payload_delegates_lane_for_lane() {
    let wrapped: Carrying = lane_error(errlanes::FatalKind::CorruptState).into();
    match wrapped.classify() {
        Fail::Fatal(f) => assert_eq!(f.kind, errlanes::FatalKind::CorruptState),
        other => panic!("expected Fatal(CorruptState), got {other:?}"),
    }
}

#[derive(Debug, errlanes::Classify)]
enum NarrowedFail {
    #[classify(delegate, narrow(Denied))]
    Upstream(Fail<ConstraintViolation, lanes!(Denied, Fatal)>),
}

#[test]
fn narrow_denied_applies_to_a_fail_payload() {
    let denied = NarrowedFail::Upstream(Fail::Denied(errlanes::Denied::new()));
    match denied.classify() {
        Fail::Fatal(f) => assert_eq!(f.kind, errlanes::FatalKind::Denied),
        other => panic!("expected Fatal(Denied), got {other:?}"),
    }
}