diagprint-error-stack 0.8.0

Structured error-stack interoperability for diagprint.
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
//! Structured [`error_stack`] interoperability for diagprint.
//!
//! This crate is the first ecosystem adapter built on
//! [`diagprint_bridge`]. It keeps `error-stack`-specific traversal and privacy
//! policy here while delegating normalized diagnostic/report/relationship
//! assembly to the reusable bridge SDK.
//!
//! Stable single-context [`error_stack::Report<C>`] and grouped
//! `Report<[C]>` values are both supported.
//!
//! # Structural conversion
//!
//! The adapter uses [`error_stack::Frame::sources`] and
//! [`error_stack::Frame::kind`] directly. It never parses the rendered
//! `Display` or `Debug` representation of a report.
//!
//! Context frames become diagnostic instances. Attachment frames are
//! traversal-transparent so source topology survives across attachments.
//!
//! # Attachment privacy
//!
//! Attachment content is omitted by default. Call
//! [`ErrorStackBridge::with_attachment_policy`] with
//! [`ErrorStackAttachmentPolicy::PrintableText`] to intentionally retain the
//! `Display` text of printable attachments as diagnostic notes.
//!
//! Opaque attachment values are never exported by this adapter.

use diagprint::{
    DiagnosticRelationshipEvidence, DiagnosticRelationshipGraph, DiagnosticRelationshipKind,
    DiagnosticReport, Reporter,
};
use diagprint_bridge::{
    BridgeBuildStats, BridgeDiagnosticMetadata, BridgeError, BridgeNodeId, BridgeOutput,
    BridgeOutputBuilder,
};
use error_stack::{AttachmentKind, Frame, FrameKind, Report};
use std::{
    collections::{BTreeMap, BTreeSet},
    error::Error,
    fmt,
};

const PRODUCER: &str = "error-stack";
const ATTACHMENT_NOTE_PREFIX: &str = "error-stack attachment: ";

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ErrorStackAttachmentPolicy {
    #[default]
    Omit,
    PrintableText,
}

impl ErrorStackAttachmentPolicy {
    pub const fn includes_printable_text(self) -> bool {
        matches!(self, Self::PrintableText)
    }
}

pub struct ErrorStackContextView<'a> {
    frame: &'a Frame,
    context: &'a (dyn Error + Send + Sync + 'static),
    depth: usize,
}

impl<'a> ErrorStackContextView<'a> {
    pub const fn frame(&self) -> &'a Frame {
        self.frame
    }

    pub const fn context(&self) -> &'a (dyn Error + Send + Sync + 'static) {
        self.context
    }

    pub const fn depth(&self) -> usize {
        self.depth
    }
}

pub trait ErrorStackContextMapper {
    fn map(&self, view: ErrorStackContextView<'_>)
    -> Result<BridgeDiagnosticMetadata, BridgeError>;
}

impl<T> ErrorStackContextMapper for &T
where
    T: ErrorStackContextMapper + ?Sized,
{
    fn map(
        &self,
        view: ErrorStackContextView<'_>,
    ) -> Result<BridgeDiagnosticMetadata, BridgeError> {
        (**self).map(view)
    }
}

#[derive(Debug, Clone, Copy, Default)]
pub struct DefaultErrorStackContextMapper;

impl ErrorStackContextMapper for DefaultErrorStackContextMapper {
    fn map(
        &self,
        view: ErrorStackContextView<'_>,
    ) -> Result<BridgeDiagnosticMetadata, BridgeError> {
        Ok(BridgeDiagnosticMetadata::new(view.context().to_string()))
    }
}

#[derive(Debug)]
pub struct ErrorStackBridgeOutput {
    bridge: BridgeOutput,
    context_frames: usize,
    attachment_frames: usize,
    printable_attachment_frames: usize,
    opaque_attachment_frames: usize,
    included_printable_attachments: usize,
}

impl ErrorStackBridgeOutput {
    pub fn bridge(&self) -> &BridgeOutput {
        &self.bridge
    }

    pub fn report(&self) -> &DiagnosticReport {
        self.bridge.report()
    }

    pub fn graph(&self) -> &DiagnosticRelationshipGraph {
        self.bridge.graph()
    }

    pub const fn stats(&self) -> BridgeBuildStats {
        self.bridge.stats()
    }

    pub const fn context_frames(&self) -> usize {
        self.context_frames
    }

    pub const fn attachment_frames(&self) -> usize {
        self.attachment_frames
    }

    pub const fn printable_attachment_frames(&self) -> usize {
        self.printable_attachment_frames
    }

    pub const fn opaque_attachment_frames(&self) -> usize {
        self.opaque_attachment_frames
    }

    pub const fn included_printable_attachments(&self) -> usize {
        self.included_printable_attachments
    }

    pub fn into_bridge(self) -> BridgeOutput {
        self.bridge
    }
}

#[derive(Debug, Clone)]
pub struct ErrorStackBridge<M = DefaultErrorStackContextMapper> {
    mapper: M,
    attachment_policy: ErrorStackAttachmentPolicy,
}

impl ErrorStackBridge<DefaultErrorStackContextMapper> {
    pub const fn new() -> Self {
        Self {
            mapper: DefaultErrorStackContextMapper,
            attachment_policy: ErrorStackAttachmentPolicy::Omit,
        }
    }
}

impl Default for ErrorStackBridge<DefaultErrorStackContextMapper> {
    fn default() -> Self {
        Self::new()
    }
}

impl<M> ErrorStackBridge<M>
where
    M: ErrorStackContextMapper,
{
    pub const fn with_mapper(mapper: M) -> Self {
        Self {
            mapper,
            attachment_policy: ErrorStackAttachmentPolicy::Omit,
        }
    }

    pub const fn with_attachment_policy(
        mut self,
        attachment_policy: ErrorStackAttachmentPolicy,
    ) -> Self {
        self.attachment_policy = attachment_policy;
        self
    }

    pub const fn attachment_policy(&self) -> ErrorStackAttachmentPolicy {
        self.attachment_policy
    }

    pub fn convert<C>(
        &self,
        report: &Report<C>,
        reporter: &Reporter,
    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError>
    where
        C: Error + Send + Sync + 'static,
    {
        let mut traversal = Traversal::new(&self.mapper, reporter, self.attachment_policy)?;

        traversal.walk(report.current_frame(), 0, Vec::new())?;
        traversal.finish()
    }

    pub fn convert_grouped<C>(
        &self,
        report: &Report<[C]>,
        reporter: &Reporter,
    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError>
    where
        C: Error + Send + Sync + 'static,
    {
        let mut traversal = Traversal::new(&self.mapper, reporter, self.attachment_policy)?;

        for current in report.current_frames() {
            traversal.walk(current, 0, Vec::new())?;
        }

        traversal.finish()
    }
}

pub trait ErrorStackReportExt {
    fn to_diagprint(
        &self,
        reporter: &Reporter,
    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError>;

    fn to_diagprint_with<M>(
        &self,
        reporter: &Reporter,
        mapper: &M,
    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError>
    where
        M: ErrorStackContextMapper + ?Sized;

    fn to_diagprint_with_policy(
        &self,
        reporter: &Reporter,
        policy: ErrorStackAttachmentPolicy,
    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError>;

    fn to_diagprint_with_mapper_and_policy<M>(
        &self,
        reporter: &Reporter,
        mapper: &M,
        policy: ErrorStackAttachmentPolicy,
    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError>
    where
        M: ErrorStackContextMapper + ?Sized;
}

impl<C> ErrorStackReportExt for Report<C>
where
    C: Error + Send + Sync + 'static,
{
    fn to_diagprint(
        &self,
        reporter: &Reporter,
    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError> {
        ErrorStackBridge::new().convert(self, reporter)
    }

    fn to_diagprint_with<M>(
        &self,
        reporter: &Reporter,
        mapper: &M,
    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError>
    where
        M: ErrorStackContextMapper + ?Sized,
    {
        ErrorStackBridge::with_mapper(mapper).convert(self, reporter)
    }

    fn to_diagprint_with_policy(
        &self,
        reporter: &Reporter,
        policy: ErrorStackAttachmentPolicy,
    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError> {
        ErrorStackBridge::new()
            .with_attachment_policy(policy)
            .convert(self, reporter)
    }

    fn to_diagprint_with_mapper_and_policy<M>(
        &self,
        reporter: &Reporter,
        mapper: &M,
        policy: ErrorStackAttachmentPolicy,
    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError>
    where
        M: ErrorStackContextMapper + ?Sized,
    {
        ErrorStackBridge::with_mapper(mapper)
            .with_attachment_policy(policy)
            .convert(self, reporter)
    }
}

impl<C> ErrorStackReportExt for Report<[C]>
where
    C: Error + Send + Sync + 'static,
{
    fn to_diagprint(
        &self,
        reporter: &Reporter,
    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError> {
        ErrorStackBridge::new().convert_grouped(self, reporter)
    }

    fn to_diagprint_with<M>(
        &self,
        reporter: &Reporter,
        mapper: &M,
    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError>
    where
        M: ErrorStackContextMapper + ?Sized,
    {
        ErrorStackBridge::with_mapper(mapper).convert_grouped(self, reporter)
    }

    fn to_diagprint_with_policy(
        &self,
        reporter: &Reporter,
        policy: ErrorStackAttachmentPolicy,
    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError> {
        ErrorStackBridge::new()
            .with_attachment_policy(policy)
            .convert_grouped(self, reporter)
    }

    fn to_diagprint_with_mapper_and_policy<M>(
        &self,
        reporter: &Reporter,
        mapper: &M,
        policy: ErrorStackAttachmentPolicy,
    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError>
    where
        M: ErrorStackContextMapper + ?Sized,
    {
        ErrorStackBridge::with_mapper(mapper)
            .with_attachment_policy(policy)
            .convert_grouped(self, reporter)
    }
}

#[derive(Clone)]
enum VisitState {
    Visiting,
    Done(Vec<BridgeNodeId>),
}

struct Traversal<'mapper, 'reporter, M>
where
    M: ErrorStackContextMapper + ?Sized,
{
    mapper: &'mapper M,
    attachment_policy: ErrorStackAttachmentPolicy,
    builder: BridgeOutputBuilder<'reporter>,
    visited: BTreeMap<usize, VisitState>,
    context_frames: usize,
    attachment_frames: usize,
    printable_attachment_frames: usize,
    opaque_attachment_frames: usize,
    included_printable_attachments: usize,
}

impl<'mapper, 'reporter, M> Traversal<'mapper, 'reporter, M>
where
    M: ErrorStackContextMapper + ?Sized,
{
    fn new(
        mapper: &'mapper M,
        reporter: &'reporter Reporter,
        attachment_policy: ErrorStackAttachmentPolicy,
    ) -> Result<Self, ErrorStackBridgeError> {
        Ok(Self {
            mapper,
            attachment_policy,
            builder: BridgeOutputBuilder::new(reporter, PRODUCER)?,
            visited: BTreeMap::new(),
            context_frames: 0,
            attachment_frames: 0,
            printable_attachment_frames: 0,
            opaque_attachment_frames: 0,
            included_printable_attachments: 0,
        })
    }

    fn walk(
        &mut self,
        frame: &Frame,
        depth: usize,
        pending_printable: Vec<String>,
    ) -> Result<Vec<BridgeNodeId>, ErrorStackBridgeError> {
        let frame_key = frame as *const Frame as usize;

        if let Some(state) = self.visited.get(&frame_key) {
            return Ok(match state {
                VisitState::Visiting => Vec::new(),
                VisitState::Done(nodes) => nodes.clone(),
            });
        }

        self.visited.insert(frame_key, VisitState::Visiting);

        let nearest = match frame.kind() {
            FrameKind::Context(context) => {
                self.context_frames = self.context_frames.saturating_add(1);

                let mut metadata = self.mapper.map(ErrorStackContextView {
                    frame,
                    context,
                    depth,
                })?;

                for attachment in pending_printable {
                    metadata = metadata.note(format!("{ATTACHMENT_NOTE_PREFIX}{attachment}"));
                    self.included_printable_attachments =
                        self.included_printable_attachments.saturating_add(1);
                }

                let current = self.builder.push(metadata)?;
                let mut source_nodes = BTreeSet::new();

                for source in frame.sources() {
                    source_nodes.extend(self.walk(source, depth.saturating_add(1), Vec::new())?);
                }

                for source in source_nodes {
                    self.builder.relate(
                        source,
                        current,
                        DiagnosticRelationshipKind::ContributesTo,
                        DiagnosticRelationshipEvidence::SourceChain,
                    )?;
                }

                vec![current]
            }

            FrameKind::Attachment(kind) => {
                self.attachment_frames = self.attachment_frames.saturating_add(1);

                let mut pending_printable = pending_printable;

                match kind {
                    AttachmentKind::Printable(value) => {
                        self.printable_attachment_frames =
                            self.printable_attachment_frames.saturating_add(1);

                        if self.attachment_policy.includes_printable_text() {
                            pending_printable.push(value.to_string());
                        }
                    }

                    AttachmentKind::Opaque(_) => {
                        self.opaque_attachment_frames =
                            self.opaque_attachment_frames.saturating_add(1);
                    }

                    _ => {}
                }

                let mut nearest = BTreeSet::new();

                for source in frame.sources() {
                    nearest.extend(self.walk(
                        source,
                        depth.saturating_add(1),
                        pending_printable.clone(),
                    )?);
                }

                nearest.into_iter().collect()
            }
        };

        self.visited
            .insert(frame_key, VisitState::Done(nearest.clone()));

        Ok(nearest)
    }

    fn finish(self) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError> {
        Ok(ErrorStackBridgeOutput {
            bridge: self.builder.finish()?,
            context_frames: self.context_frames,
            attachment_frames: self.attachment_frames,
            printable_attachment_frames: self.printable_attachment_frames,
            opaque_attachment_frames: self.opaque_attachment_frames,
            included_printable_attachments: self.included_printable_attachments,
        })
    }
}

#[derive(Debug)]
pub enum ErrorStackBridgeError {
    Bridge(BridgeError),
}

impl fmt::Display for ErrorStackBridgeError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Bridge(source) => {
                write!(formatter, "error-stack bridge conversion failed: {source}")
            }
        }
    }
}

impl Error for ErrorStackBridgeError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Bridge(source) => Some(source),
        }
    }
}

impl From<BridgeError> for ErrorStackBridgeError {
    fn from(source: BridgeError) -> Self {
        Self::Bridge(source)
    }
}