pi_result 0.2.0

Thin, typed, and observable Result aliases and error interoperability utilities
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
//! 标准库 / 第三方错误互操作辅助。
//!
//! 本模块的目标是让 `pi_result` 尽量方便、可靠地兼容现有生态中各种不同风格的
//! `Result` / `Error`:
//!
//! - `std::result::Result<T, E>`
//! - `std::io::Result<T>`
//! - 第三方 `thiserror` 错误
//! - 第三方 `error_stack::Report<C>`
//! - 依赖库已经公开返回的 `pi_result::Result<T>`
//!
//! 核心策略不是强行把所有外部错误揉成一个大枚举,而是:
//!
//! 1. 在公共边界收敛为稳定的 `ErrorKind`
//! 2. 在当前层保留 typed context
//! 3. 通过 attachment 保留来源、资源、阶段等运行时信息
//! 4. 在需要时按原始错误值动态决定收敛方式

use std::{error::Error as StdError, fmt, io};

use error_stack::IntoReport;

use crate::{ErrorKind, ErrorReport, Result, TypedResult, attachment::SourceTypeName};

/// 对不满足 `Error + Send + Sync + 'static` 约束的外部错误做结构化快照。
///
/// 该类型的目标不是“保留原始错误对象”,而是把那些无法直接并入 `Report`
/// 的错误标准化成可跨线程、可打印、可观察、可继续冒泡的结构化表示。
///
/// 它会保留两类关键信息:
///
/// - `display_text`:面向用户或日志的一行文本
/// - `debug_text`:面向调试的更完整快照
///
/// 原始错误类型名则继续通过 [`SourceTypeName`] attachment 附加在错误链上。
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{display_text}")]
pub struct ExternalError {
    display_text: String,
    debug_text: String,
}

impl ExternalError {
    /// 由已提取的显示文本和调试文本构造一个外部错误快照。
    pub fn new(display_text: impl Into<String>, debug_text: impl Into<String>) -> Self {
        Self {
            display_text: display_text.into(),
            debug_text: debug_text.into(),
        }
    }

    /// 基于 `Display + Debug` 自动捕获外部错误快照。
    pub fn capture<E>(error: &E) -> Self
    where
        E: fmt::Display + fmt::Debug,
    {
        Self::new(error.to_string(), format!("{error:?}"))
    }

    /// 返回快照中的显示文本。
    pub fn display_text(&self) -> &str {
        &self.display_text
    }

    /// 返回快照中的调试文本。
    pub fn debug_text(&self) -> &str {
        &self.debug_text
    }
}

impl ClassifyErrorKind for ExternalError {
    fn classify_error_kind(&self) -> ErrorKind {
        ErrorKind::Other
    }
}

/// 把外部或标准库错误标准化为公共 `ErrorKind` 的分类 trait。
///
/// 该 trait 适合:
///
/// - `std::io::Error`
/// - 第三方 `thiserror` 错误
/// - 第三方 `error_stack::Report<C>`
/// - 你自己的局部错误类型
///
/// 用户也可以在自己的 crate 中为第三方错误类型实现此 trait,
/// 然后直接使用 [`InteropResultExt::into_classified_error`]。
pub trait ClassifyErrorKind {
    /// 根据当前错误值给出稳定公共错误分类。
    fn classify_error_kind(&self) -> ErrorKind;
}

impl ClassifyErrorKind for ErrorKind {
    fn classify_error_kind(&self) -> ErrorKind {
        *self
    }
}

impl<C> ClassifyErrorKind for ErrorReport<C>
where
    C: ClassifyErrorKind + Send + Sync + 'static,
{
    fn classify_error_kind(&self) -> ErrorKind {
        self.current_context().classify_error_kind()
    }
}

impl ClassifyErrorKind for io::Error {
    fn classify_error_kind(&self) -> ErrorKind {
        classify_io_error(self)
    }
}

/// 将 `std::io::Error` 映射到 `pi_result::ErrorKind`。
///
/// 该映射刻意保持保守:
///
/// - 只有最稳定、最明确的语义做专门分类
/// - 其余情况统一回落到 `ErrorKind::Io`
pub fn classify_io_error(error: &io::Error) -> ErrorKind {
    match error.kind() {
        io::ErrorKind::NotFound => ErrorKind::NotFound,
        io::ErrorKind::PermissionDenied => ErrorKind::PermissionDenied,
        io::ErrorKind::AlreadyExists => ErrorKind::AlreadyExists,
        io::ErrorKind::TimedOut => ErrorKind::Timeout,
        io::ErrorKind::InvalidInput => ErrorKind::InvalidInput,
        io::ErrorKind::InvalidData => ErrorKind::Corrupted,
        io::ErrorKind::WouldBlock => ErrorKind::Busy,
        io::ErrorKind::Interrupted => ErrorKind::Cancelled,
        _ => ErrorKind::Io,
    }
}

/// 返回指定错误类型的来源类型名 attachment。
pub fn source_type_name_of<E>() -> SourceTypeName {
    SourceTypeName::of::<E>()
}

/// 结果互操作扩展。
///
/// 该 trait 主要服务于“把标准库/第三方错误并入 `pi_result`”这一需求。
pub trait InteropResultExt<T, E>: Sized {
    /// 直接把不兼容的外部错误快照为 [`ExternalError`]。
    ///
    /// 适用场景:
    ///
    /// - 原始错误不实现 `std::error::Error`
    /// - 原始错误不是 `Send + Sync`
    /// - 原始错误生命周期不满足 `'static`
    fn into_external_report(self) -> core::result::Result<T, ErrorReport<ExternalError>>
    where
        E: fmt::Display + fmt::Debug;

    /// 使用自定义快照逻辑把外部错误转换为 [`ExternalError`]。
    ///
    /// 这是兼容最宽的一条路径,对 `E` 本身没有任何 trait 约束。
    fn into_external_report_with<F>(
        self,
        f: F,
    ) -> core::result::Result<T, ErrorReport<ExternalError>>
    where
        F: FnOnce(&E) -> ExternalError;

    /// 把不兼容外部错误快照后,直接收敛到公共 `ErrorKind`。
    fn into_external_error_by<F>(self, f: F) -> Result<T>
    where
        E: fmt::Display + fmt::Debug,
        F: FnOnce(&E) -> ErrorKind;

    /// 用自定义快照逻辑把外部错误直接收敛到公共 `ErrorKind`。
    fn into_external_error_with<F>(self, f: F) -> Result<T>
    where
        F: FnOnce(&E) -> (ErrorKind, ExternalError);

    /// 把不兼容外部错误快照后,收敛到新的 typed context。
    fn into_external_typed_by<C, F>(self, f: F) -> TypedResult<T, C>
    where
        C: StdError + Send + Sync + 'static,
        E: fmt::Display + fmt::Debug,
        F: FnOnce(&E) -> C;

    /// 用自定义快照逻辑把外部错误收敛到新的 typed context。
    fn into_external_typed_with<C, F>(self, f: F) -> TypedResult<T, C>
    where
        C: StdError + Send + Sync + 'static,
        F: FnOnce(&E) -> (C, ExternalError);

    /// 对不兼容外部错误执行“快照 + trait 分类”的公共收敛。
    fn into_external_classified_error(self) -> Result<T>
    where
        E: fmt::Display + fmt::Debug + ClassifyErrorKind;

    /// 根据原始错误值动态决定公共 `ErrorKind`。
    fn into_error_by<F>(self, f: F) -> Result<T>
    where
        E: IntoReport,
        F: FnOnce(&E) -> ErrorKind;

    /// 根据原始错误值动态决定新的 typed context。
    fn into_typed_by<C, F>(self, f: F) -> TypedResult<T, C>
    where
        C: StdError + Send + Sync + 'static,
        E: IntoReport,
        F: FnOnce(&E) -> C;

    /// 使用 [`ClassifyErrorKind`] 自动标准化到公共 `ErrorKind`。
    fn into_classified_error(self) -> Result<T>
    where
        E: IntoReport + ClassifyErrorKind;

    /// 把原始错误转换成同 context 的 `Report`,并附加来源类型名。
    ///
    /// 这适合在进入 typed/public 收敛前,先补充一层“错误来自什么原始类型”的
    /// 可观测信息。
    fn into_report_with_source(
        self,
    ) -> core::result::Result<T, ErrorReport<<E as IntoReport>::Context>>
    where
        E: IntoReport + Send + Sync + 'static;
}

impl<T, E> InteropResultExt<T, E> for core::result::Result<T, E> {
    fn into_external_report(self) -> core::result::Result<T, ErrorReport<ExternalError>>
    where
        E: fmt::Display + fmt::Debug,
    {
        self.into_external_report_with(ExternalError::capture)
    }

    fn into_external_report_with<F>(
        self,
        f: F,
    ) -> core::result::Result<T, ErrorReport<ExternalError>>
    where
        F: FnOnce(&E) -> ExternalError,
    {
        match self {
            Ok(value) => Ok(value),
            Err(error) => {
                Err(error_stack::Report::new(f(&error)).attach(SourceTypeName::of::<E>()))
            }
        }
    }

    fn into_external_error_by<F>(self, f: F) -> Result<T>
    where
        E: fmt::Display + fmt::Debug,
        F: FnOnce(&E) -> ErrorKind,
    {
        self.into_external_error_with(|error| (f(error), ExternalError::capture(error)))
    }

    fn into_external_error_with<F>(self, f: F) -> Result<T>
    where
        F: FnOnce(&E) -> (ErrorKind, ExternalError),
    {
        match self {
            Ok(value) => Ok(value),
            Err(error) => {
                let (kind, external) = f(&error);
                Err(error_stack::Report::new(external)
                    .attach(SourceTypeName::of::<E>())
                    .change_context(kind))
            }
        }
    }

    fn into_external_typed_by<C, F>(self, f: F) -> TypedResult<T, C>
    where
        C: StdError + Send + Sync + 'static,
        E: fmt::Display + fmt::Debug,
        F: FnOnce(&E) -> C,
    {
        self.into_external_typed_with(|error| (f(error), ExternalError::capture(error)))
    }

    fn into_external_typed_with<C, F>(self, f: F) -> TypedResult<T, C>
    where
        C: StdError + Send + Sync + 'static,
        F: FnOnce(&E) -> (C, ExternalError),
    {
        match self {
            Ok(value) => Ok(value),
            Err(error) => {
                let (context, external) = f(&error);
                Err(error_stack::Report::new(external)
                    .attach(SourceTypeName::of::<E>())
                    .change_context(context))
            }
        }
    }

    fn into_external_classified_error(self) -> Result<T>
    where
        E: fmt::Display + fmt::Debug + ClassifyErrorKind,
    {
        self.into_external_error_by(ClassifyErrorKind::classify_error_kind)
    }

    fn into_error_by<F>(self, f: F) -> Result<T>
    where
        E: IntoReport,
        F: FnOnce(&E) -> ErrorKind,
    {
        match self {
            Ok(value) => Ok(value),
            Err(error) => {
                let kind = f(&error);
                Err(error.into_report().change_context(kind))
            }
        }
    }

    fn into_typed_by<C, F>(self, f: F) -> TypedResult<T, C>
    where
        C: StdError + Send + Sync + 'static,
        E: IntoReport,
        F: FnOnce(&E) -> C,
    {
        match self {
            Ok(value) => Ok(value),
            Err(error) => {
                let context = f(&error);
                Err(error.into_report().change_context(context))
            }
        }
    }

    fn into_classified_error(self) -> Result<T>
    where
        E: IntoReport + ClassifyErrorKind,
    {
        self.into_error_by(ClassifyErrorKind::classify_error_kind)
    }

    fn into_report_with_source(
        self,
    ) -> core::result::Result<T, ErrorReport<<E as IntoReport>::Context>>
    where
        E: IntoReport + Send + Sync + 'static,
    {
        match self {
            Ok(value) => Ok(value),
            Err(error) => Err(error.into_report().attach(SourceTypeName::of::<E>())),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        ClassifyErrorKind, ExternalError, InteropResultExt, classify_io_error, source_type_name_of,
    };
    use crate::{ErrorKind, attachment::SourceTypeName};
    use error_stack::Report;
    use std::{fmt, rc::Rc};
    use thiserror::Error;

    #[derive(Debug, Error)]
    #[error("third-party decode failed")]
    struct ThirdPartyDecodeError;

    #[derive(Debug, Error, PartialEq, Eq)]
    enum ExternalContext {
        #[error("failed to decode third-party payload")]
        Decode,

        #[error("legacy parser rejected input")]
        LegacyParse,
    }

    impl ClassifyErrorKind for ThirdPartyDecodeError {
        fn classify_error_kind(&self) -> ErrorKind {
            ErrorKind::Dependency
        }
    }

    #[derive(Debug)]
    struct BorrowedLegacyError<'a> {
        input: &'a str,
        shared: Rc<String>,
    }

    impl fmt::Display for BorrowedLegacyError<'_> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(
                f,
                "legacy parser rejected `{}` from {}",
                self.input, self.shared
            )
        }
    }

    impl ClassifyErrorKind for BorrowedLegacyError<'_> {
        fn classify_error_kind(&self) -> ErrorKind {
            ErrorKind::InvalidInput
        }
    }

    #[derive(Debug)]
    struct RawForeignCode {
        code: u16,
        subsystem: &'static str,
    }

    #[test]
    fn test_classify_io_error_maps_stable_common_cases() {
        assert_eq!(
            classify_io_error(&std::io::Error::from(std::io::ErrorKind::NotFound)),
            ErrorKind::NotFound
        );
        assert_eq!(
            classify_io_error(&std::io::Error::from(std::io::ErrorKind::TimedOut)),
            ErrorKind::Timeout
        );
        assert_eq!(
            classify_io_error(&std::io::Error::from(std::io::ErrorKind::InvalidData)),
            ErrorKind::Corrupted
        );
        assert_eq!(
            classify_io_error(&std::io::Error::from(std::io::ErrorKind::BrokenPipe)),
            ErrorKind::Io
        );
    }

    #[test]
    fn test_into_error_by_can_classify_raw_std_result() {
        let report = Err::<(), std::io::Error>(std::io::Error::from(std::io::ErrorKind::NotFound))
            .into_error_by(classify_io_error)
            .expect_err("expected report");

        assert_eq!(report.current_context(), &ErrorKind::NotFound);
        assert!(report.contains::<std::io::Error>());
    }

    #[test]
    fn test_into_typed_by_can_build_context_from_original_error() {
        let report = Err::<(), ThirdPartyDecodeError>(ThirdPartyDecodeError)
            .into_typed_by(|_| ExternalContext::Decode)
            .expect_err("expected typed report");

        assert_eq!(report.current_context(), &ExternalContext::Decode);
        assert!(report.contains::<ThirdPartyDecodeError>());
    }

    #[test]
    fn test_into_classified_error_uses_trait_based_mapping() {
        let report = Err::<(), ThirdPartyDecodeError>(ThirdPartyDecodeError)
            .into_classified_error()
            .expect_err("expected report");

        assert_eq!(report.current_context(), &ErrorKind::Dependency);
        assert!(report.contains::<ThirdPartyDecodeError>());
    }

    #[test]
    fn test_into_report_with_source_attaches_original_error_type() {
        let report =
            Err::<(), std::io::Error>(std::io::Error::from(std::io::ErrorKind::PermissionDenied))
                .into_report_with_source()
                .expect_err("expected typed report");

        assert!(report.contains::<std::io::Error>());
        assert_eq!(
            report.downcast_ref::<SourceTypeName>(),
            Some(&SourceTypeName::of::<std::io::Error>())
        );
    }

    #[test]
    fn test_source_type_name_helper_matches_attachment_constructor() {
        assert_eq!(
            source_type_name_of::<ThirdPartyDecodeError>(),
            SourceTypeName::of::<ThirdPartyDecodeError>()
        );
    }

    #[test]
    fn test_report_of_classifiable_context_can_be_reclassified_again() {
        let report = Err::<(), std::io::Error>(std::io::Error::from(std::io::ErrorKind::TimedOut))
            .into_classified_error()
            .expect_err("expected public report");

        let reclassified = Err::<(), Report<ErrorKind>>(report)
            .into_classified_error()
            .expect_err("expected reclassified report");

        assert_eq!(reclassified.current_context(), &ErrorKind::Timeout);
        assert!(reclassified.contains::<std::io::Error>());
        assert!(reclassified.contains::<ErrorKind>());
    }

    #[test]
    fn test_external_report_can_snapshot_non_error_non_send_sync_non_static_value() {
        let report = {
            let input = String::from("bad-token");
            let shared = Rc::new(String::from("legacy_parser"));

            Err::<(), BorrowedLegacyError<'_>>(BorrowedLegacyError {
                input: &input,
                shared,
            })
            .into_external_report()
            .expect_err("expected external report")
        };

        let captured = report
            .downcast_ref::<ExternalError>()
            .expect("external snapshot should exist");
        assert_eq!(
            captured.display_text(),
            "legacy parser rejected `bad-token` from legacy_parser"
        );
        assert!(captured.debug_text().contains("BorrowedLegacyError"));
        assert_eq!(
            report.downcast_ref::<SourceTypeName>(),
            Some(&SourceTypeName::of::<BorrowedLegacyError<'static>>())
        );
    }

    #[test]
    fn test_external_error_by_can_classify_borrowed_legacy_error() {
        let report = {
            let input = String::from("name with spaces");
            let shared = Rc::new(String::from("legacy_parser"));

            Err::<(), BorrowedLegacyError<'_>>(BorrowedLegacyError {
                input: &input,
                shared,
            })
            .into_external_error_by(|error| {
                if error.input.contains(' ') {
                    ErrorKind::InvalidInput
                } else {
                    ErrorKind::Other
                }
            })
            .expect_err("expected public report")
        };

        assert_eq!(report.current_context(), &ErrorKind::InvalidInput);
        assert!(report.contains::<ExternalError>());
        assert_eq!(
            report.downcast_ref::<SourceTypeName>(),
            Some(&SourceTypeName::of::<BorrowedLegacyError<'static>>())
        );
    }

    #[test]
    fn test_external_typed_by_keeps_snapshot_and_new_typed_context() {
        let report = {
            let input = String::from("bad-token");
            let shared = Rc::new(String::from("legacy_parser"));

            Err::<(), BorrowedLegacyError<'_>>(BorrowedLegacyError {
                input: &input,
                shared,
            })
            .into_external_typed_by(|_| ExternalContext::LegacyParse)
            .expect_err("expected typed report")
        };

        assert_eq!(report.current_context(), &ExternalContext::LegacyParse);
        assert!(report.contains::<ExternalError>());
        assert_eq!(
            report.downcast_ref::<SourceTypeName>(),
            Some(&SourceTypeName::of::<BorrowedLegacyError<'static>>())
        );
    }

    #[test]
    fn test_external_error_with_supports_errors_without_display_or_std_error() {
        let report = Err::<(), RawForeignCode>(RawForeignCode {
            code: 503,
            subsystem: "ffi_gateway",
        })
        .into_external_error_with(|error| {
            (
                ErrorKind::Dependency,
                ExternalError::new(
                    format!(
                        "{} rejected request with code {}",
                        error.subsystem, error.code
                    ),
                    format!("{error:?}"),
                ),
            )
        })
        .expect_err("expected public report");

        assert_eq!(report.current_context(), &ErrorKind::Dependency);
        let captured = report
            .downcast_ref::<ExternalError>()
            .expect("external snapshot should exist");
        assert_eq!(
            captured.display_text(),
            "ffi_gateway rejected request with code 503"
        );
        assert!(captured.debug_text().contains("ffi_gateway"));
        assert_eq!(
            report.downcast_ref::<SourceTypeName>(),
            Some(&SourceTypeName::of::<RawForeignCode>())
        );
    }

    #[test]
    fn test_external_classified_error_uses_trait_based_mapping_for_non_std_error() {
        let report = {
            let input = String::from("bad-token");
            let shared = Rc::new(String::from("legacy_parser"));

            Err::<(), BorrowedLegacyError<'_>>(BorrowedLegacyError {
                input: &input,
                shared,
            })
            .into_external_classified_error()
            .expect_err("expected public report")
        };

        assert_eq!(report.current_context(), &ErrorKind::InvalidInput);
        assert!(report.contains::<ExternalError>());
    }
}