Skip to main content

diagprint_error_stack/
lib.rs

1//! Structured [`error_stack`] interoperability for diagprint.
2//!
3//! This crate is the first ecosystem adapter built on
4//! [`diagprint_bridge`]. It keeps `error-stack`-specific traversal and privacy
5//! policy here while delegating normalized diagnostic/report/relationship
6//! assembly to the reusable bridge SDK.
7//!
8//! Stable single-context [`error_stack::Report<C>`] and grouped
9//! `Report<[C]>` values are both supported.
10//!
11//! # Structural conversion
12//!
13//! The adapter uses [`error_stack::Frame::sources`] and
14//! [`error_stack::Frame::kind`] directly. It never parses the rendered
15//! `Display` or `Debug` representation of a report.
16//!
17//! Context frames become diagnostic instances. Attachment frames are
18//! traversal-transparent so source topology survives across attachments.
19//!
20//! # Attachment privacy
21//!
22//! Attachment content is omitted by default. Call
23//! [`ErrorStackBridge::with_attachment_policy`] with
24//! [`ErrorStackAttachmentPolicy::PrintableText`] to intentionally retain the
25//! `Display` text of printable attachments as diagnostic notes.
26//!
27//! Opaque attachment values are never exported by this adapter.
28
29use diagprint::{
30    DiagnosticRelationshipEvidence, DiagnosticRelationshipGraph, DiagnosticRelationshipKind,
31    DiagnosticReport, Reporter,
32};
33use diagprint_bridge::{
34    BridgeBuildStats, BridgeDiagnosticMetadata, BridgeError, BridgeNodeId, BridgeOutput,
35    BridgeOutputBuilder,
36};
37use error_stack::{AttachmentKind, Frame, FrameKind, Report};
38use std::{
39    collections::{BTreeMap, BTreeSet},
40    error::Error,
41    fmt,
42};
43
44const PRODUCER: &str = "error-stack";
45const ATTACHMENT_NOTE_PREFIX: &str = "error-stack attachment: ";
46
47#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
48pub enum ErrorStackAttachmentPolicy {
49    #[default]
50    Omit,
51    PrintableText,
52}
53
54impl ErrorStackAttachmentPolicy {
55    pub const fn includes_printable_text(self) -> bool {
56        matches!(self, Self::PrintableText)
57    }
58}
59
60pub struct ErrorStackContextView<'a> {
61    frame: &'a Frame,
62    context: &'a (dyn Error + Send + Sync + 'static),
63    depth: usize,
64}
65
66impl<'a> ErrorStackContextView<'a> {
67    pub const fn frame(&self) -> &'a Frame {
68        self.frame
69    }
70
71    pub const fn context(&self) -> &'a (dyn Error + Send + Sync + 'static) {
72        self.context
73    }
74
75    pub const fn depth(&self) -> usize {
76        self.depth
77    }
78}
79
80pub trait ErrorStackContextMapper {
81    fn map(&self, view: ErrorStackContextView<'_>)
82    -> Result<BridgeDiagnosticMetadata, BridgeError>;
83}
84
85impl<T> ErrorStackContextMapper for &T
86where
87    T: ErrorStackContextMapper + ?Sized,
88{
89    fn map(
90        &self,
91        view: ErrorStackContextView<'_>,
92    ) -> Result<BridgeDiagnosticMetadata, BridgeError> {
93        (**self).map(view)
94    }
95}
96
97#[derive(Debug, Clone, Copy, Default)]
98pub struct DefaultErrorStackContextMapper;
99
100impl ErrorStackContextMapper for DefaultErrorStackContextMapper {
101    fn map(
102        &self,
103        view: ErrorStackContextView<'_>,
104    ) -> Result<BridgeDiagnosticMetadata, BridgeError> {
105        Ok(BridgeDiagnosticMetadata::new(view.context().to_string()))
106    }
107}
108
109#[derive(Debug)]
110pub struct ErrorStackBridgeOutput {
111    bridge: BridgeOutput,
112    context_frames: usize,
113    attachment_frames: usize,
114    printable_attachment_frames: usize,
115    opaque_attachment_frames: usize,
116    included_printable_attachments: usize,
117}
118
119impl ErrorStackBridgeOutput {
120    pub fn bridge(&self) -> &BridgeOutput {
121        &self.bridge
122    }
123
124    pub fn report(&self) -> &DiagnosticReport {
125        self.bridge.report()
126    }
127
128    pub fn graph(&self) -> &DiagnosticRelationshipGraph {
129        self.bridge.graph()
130    }
131
132    pub const fn stats(&self) -> BridgeBuildStats {
133        self.bridge.stats()
134    }
135
136    pub const fn context_frames(&self) -> usize {
137        self.context_frames
138    }
139
140    pub const fn attachment_frames(&self) -> usize {
141        self.attachment_frames
142    }
143
144    pub const fn printable_attachment_frames(&self) -> usize {
145        self.printable_attachment_frames
146    }
147
148    pub const fn opaque_attachment_frames(&self) -> usize {
149        self.opaque_attachment_frames
150    }
151
152    pub const fn included_printable_attachments(&self) -> usize {
153        self.included_printable_attachments
154    }
155
156    pub fn into_bridge(self) -> BridgeOutput {
157        self.bridge
158    }
159}
160
161#[derive(Debug, Clone)]
162pub struct ErrorStackBridge<M = DefaultErrorStackContextMapper> {
163    mapper: M,
164    attachment_policy: ErrorStackAttachmentPolicy,
165}
166
167impl ErrorStackBridge<DefaultErrorStackContextMapper> {
168    pub const fn new() -> Self {
169        Self {
170            mapper: DefaultErrorStackContextMapper,
171            attachment_policy: ErrorStackAttachmentPolicy::Omit,
172        }
173    }
174}
175
176impl Default for ErrorStackBridge<DefaultErrorStackContextMapper> {
177    fn default() -> Self {
178        Self::new()
179    }
180}
181
182impl<M> ErrorStackBridge<M>
183where
184    M: ErrorStackContextMapper,
185{
186    pub const fn with_mapper(mapper: M) -> Self {
187        Self {
188            mapper,
189            attachment_policy: ErrorStackAttachmentPolicy::Omit,
190        }
191    }
192
193    pub const fn with_attachment_policy(
194        mut self,
195        attachment_policy: ErrorStackAttachmentPolicy,
196    ) -> Self {
197        self.attachment_policy = attachment_policy;
198        self
199    }
200
201    pub const fn attachment_policy(&self) -> ErrorStackAttachmentPolicy {
202        self.attachment_policy
203    }
204
205    pub fn convert<C>(
206        &self,
207        report: &Report<C>,
208        reporter: &Reporter,
209    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError>
210    where
211        C: Error + Send + Sync + 'static,
212    {
213        let mut traversal = Traversal::new(&self.mapper, reporter, self.attachment_policy)?;
214
215        traversal.walk(report.current_frame(), 0, Vec::new())?;
216        traversal.finish()
217    }
218
219    pub fn convert_grouped<C>(
220        &self,
221        report: &Report<[C]>,
222        reporter: &Reporter,
223    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError>
224    where
225        C: Error + Send + Sync + 'static,
226    {
227        let mut traversal = Traversal::new(&self.mapper, reporter, self.attachment_policy)?;
228
229        for current in report.current_frames() {
230            traversal.walk(current, 0, Vec::new())?;
231        }
232
233        traversal.finish()
234    }
235}
236
237pub trait ErrorStackReportExt {
238    fn to_diagprint(
239        &self,
240        reporter: &Reporter,
241    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError>;
242
243    fn to_diagprint_with<M>(
244        &self,
245        reporter: &Reporter,
246        mapper: &M,
247    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError>
248    where
249        M: ErrorStackContextMapper + ?Sized;
250
251    fn to_diagprint_with_policy(
252        &self,
253        reporter: &Reporter,
254        policy: ErrorStackAttachmentPolicy,
255    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError>;
256
257    fn to_diagprint_with_mapper_and_policy<M>(
258        &self,
259        reporter: &Reporter,
260        mapper: &M,
261        policy: ErrorStackAttachmentPolicy,
262    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError>
263    where
264        M: ErrorStackContextMapper + ?Sized;
265}
266
267impl<C> ErrorStackReportExt for Report<C>
268where
269    C: Error + Send + Sync + 'static,
270{
271    fn to_diagprint(
272        &self,
273        reporter: &Reporter,
274    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError> {
275        ErrorStackBridge::new().convert(self, reporter)
276    }
277
278    fn to_diagprint_with<M>(
279        &self,
280        reporter: &Reporter,
281        mapper: &M,
282    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError>
283    where
284        M: ErrorStackContextMapper + ?Sized,
285    {
286        ErrorStackBridge::with_mapper(mapper).convert(self, reporter)
287    }
288
289    fn to_diagprint_with_policy(
290        &self,
291        reporter: &Reporter,
292        policy: ErrorStackAttachmentPolicy,
293    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError> {
294        ErrorStackBridge::new()
295            .with_attachment_policy(policy)
296            .convert(self, reporter)
297    }
298
299    fn to_diagprint_with_mapper_and_policy<M>(
300        &self,
301        reporter: &Reporter,
302        mapper: &M,
303        policy: ErrorStackAttachmentPolicy,
304    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError>
305    where
306        M: ErrorStackContextMapper + ?Sized,
307    {
308        ErrorStackBridge::with_mapper(mapper)
309            .with_attachment_policy(policy)
310            .convert(self, reporter)
311    }
312}
313
314impl<C> ErrorStackReportExt for Report<[C]>
315where
316    C: Error + Send + Sync + 'static,
317{
318    fn to_diagprint(
319        &self,
320        reporter: &Reporter,
321    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError> {
322        ErrorStackBridge::new().convert_grouped(self, reporter)
323    }
324
325    fn to_diagprint_with<M>(
326        &self,
327        reporter: &Reporter,
328        mapper: &M,
329    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError>
330    where
331        M: ErrorStackContextMapper + ?Sized,
332    {
333        ErrorStackBridge::with_mapper(mapper).convert_grouped(self, reporter)
334    }
335
336    fn to_diagprint_with_policy(
337        &self,
338        reporter: &Reporter,
339        policy: ErrorStackAttachmentPolicy,
340    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError> {
341        ErrorStackBridge::new()
342            .with_attachment_policy(policy)
343            .convert_grouped(self, reporter)
344    }
345
346    fn to_diagprint_with_mapper_and_policy<M>(
347        &self,
348        reporter: &Reporter,
349        mapper: &M,
350        policy: ErrorStackAttachmentPolicy,
351    ) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError>
352    where
353        M: ErrorStackContextMapper + ?Sized,
354    {
355        ErrorStackBridge::with_mapper(mapper)
356            .with_attachment_policy(policy)
357            .convert_grouped(self, reporter)
358    }
359}
360
361#[derive(Clone)]
362enum VisitState {
363    Visiting,
364    Done(Vec<BridgeNodeId>),
365}
366
367struct Traversal<'mapper, 'reporter, M>
368where
369    M: ErrorStackContextMapper + ?Sized,
370{
371    mapper: &'mapper M,
372    attachment_policy: ErrorStackAttachmentPolicy,
373    builder: BridgeOutputBuilder<'reporter>,
374    visited: BTreeMap<usize, VisitState>,
375    context_frames: usize,
376    attachment_frames: usize,
377    printable_attachment_frames: usize,
378    opaque_attachment_frames: usize,
379    included_printable_attachments: usize,
380}
381
382impl<'mapper, 'reporter, M> Traversal<'mapper, 'reporter, M>
383where
384    M: ErrorStackContextMapper + ?Sized,
385{
386    fn new(
387        mapper: &'mapper M,
388        reporter: &'reporter Reporter,
389        attachment_policy: ErrorStackAttachmentPolicy,
390    ) -> Result<Self, ErrorStackBridgeError> {
391        Ok(Self {
392            mapper,
393            attachment_policy,
394            builder: BridgeOutputBuilder::new(reporter, PRODUCER)?,
395            visited: BTreeMap::new(),
396            context_frames: 0,
397            attachment_frames: 0,
398            printable_attachment_frames: 0,
399            opaque_attachment_frames: 0,
400            included_printable_attachments: 0,
401        })
402    }
403
404    fn walk(
405        &mut self,
406        frame: &Frame,
407        depth: usize,
408        pending_printable: Vec<String>,
409    ) -> Result<Vec<BridgeNodeId>, ErrorStackBridgeError> {
410        let frame_key = frame as *const Frame as usize;
411
412        if let Some(state) = self.visited.get(&frame_key) {
413            return Ok(match state {
414                VisitState::Visiting => Vec::new(),
415                VisitState::Done(nodes) => nodes.clone(),
416            });
417        }
418
419        self.visited.insert(frame_key, VisitState::Visiting);
420
421        let nearest = match frame.kind() {
422            FrameKind::Context(context) => {
423                self.context_frames = self.context_frames.saturating_add(1);
424
425                let mut metadata = self.mapper.map(ErrorStackContextView {
426                    frame,
427                    context,
428                    depth,
429                })?;
430
431                for attachment in pending_printable {
432                    metadata = metadata.note(format!("{ATTACHMENT_NOTE_PREFIX}{attachment}"));
433                    self.included_printable_attachments =
434                        self.included_printable_attachments.saturating_add(1);
435                }
436
437                let current = self.builder.push(metadata)?;
438                let mut source_nodes = BTreeSet::new();
439
440                for source in frame.sources() {
441                    source_nodes.extend(self.walk(source, depth.saturating_add(1), Vec::new())?);
442                }
443
444                for source in source_nodes {
445                    self.builder.relate(
446                        source,
447                        current,
448                        DiagnosticRelationshipKind::ContributesTo,
449                        DiagnosticRelationshipEvidence::SourceChain,
450                    )?;
451                }
452
453                vec![current]
454            }
455
456            FrameKind::Attachment(kind) => {
457                self.attachment_frames = self.attachment_frames.saturating_add(1);
458
459                let mut pending_printable = pending_printable;
460
461                match kind {
462                    AttachmentKind::Printable(value) => {
463                        self.printable_attachment_frames =
464                            self.printable_attachment_frames.saturating_add(1);
465
466                        if self.attachment_policy.includes_printable_text() {
467                            pending_printable.push(value.to_string());
468                        }
469                    }
470
471                    AttachmentKind::Opaque(_) => {
472                        self.opaque_attachment_frames =
473                            self.opaque_attachment_frames.saturating_add(1);
474                    }
475
476                    _ => {}
477                }
478
479                let mut nearest = BTreeSet::new();
480
481                for source in frame.sources() {
482                    nearest.extend(self.walk(
483                        source,
484                        depth.saturating_add(1),
485                        pending_printable.clone(),
486                    )?);
487                }
488
489                nearest.into_iter().collect()
490            }
491        };
492
493        self.visited
494            .insert(frame_key, VisitState::Done(nearest.clone()));
495
496        Ok(nearest)
497    }
498
499    fn finish(self) -> Result<ErrorStackBridgeOutput, ErrorStackBridgeError> {
500        Ok(ErrorStackBridgeOutput {
501            bridge: self.builder.finish()?,
502            context_frames: self.context_frames,
503            attachment_frames: self.attachment_frames,
504            printable_attachment_frames: self.printable_attachment_frames,
505            opaque_attachment_frames: self.opaque_attachment_frames,
506            included_printable_attachments: self.included_printable_attachments,
507        })
508    }
509}
510
511#[derive(Debug)]
512pub enum ErrorStackBridgeError {
513    Bridge(BridgeError),
514}
515
516impl fmt::Display for ErrorStackBridgeError {
517    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
518        match self {
519            Self::Bridge(source) => {
520                write!(formatter, "error-stack bridge conversion failed: {source}")
521            }
522        }
523    }
524}
525
526impl Error for ErrorStackBridgeError {
527    fn source(&self) -> Option<&(dyn Error + 'static)> {
528        match self {
529            Self::Bridge(source) => Some(source),
530        }
531    }
532}
533
534impl From<BridgeError> for ErrorStackBridgeError {
535    fn from(source: BridgeError) -> Self {
536        Self::Bridge(source)
537    }
538}