Skip to main content

nb_api/
error.rs

1//! Structured error types for `nb-api`.
2//!
3//! This module hosts [`NbError`] and its associated types
4//! ([`ParseErrorKind`], [`IoError`], [`IoErrorKind`]) as defined by
5//! the `add-note-document-model` (P1) specification. All variants
6//! derive `Serialize`/`Deserialize` so errors round-trip cleanly
7//! through JSON-encoded wire protocols (MCP tool responses, etc.).
8//!
9//! [`NbError`] also derives `Display` and implements
10//! [`std::error::Error`], so existing textual error reporting paths
11//! continue to work unchanged.
12//!
13//! # Migration (from `nb-api` 0.2.x to 0.3.0)
14//!
15//! | Old variant | New variant | Migration |
16//! |---|---|---|
17//! | `CommandFailed(String)` | `CommandFailed { command, stderr, exit_code }` | capture fields at call sites; map validation/policy failures to `ValidationError` |
18//! | `NotFound` (unit) | `ExecutableNotFound { path }` | the unit means `nb` binary missing; track path |
19//! | `Io(std::io::Error)` | `Io { path, source: IoError }` | track path in callers; convert via `From`; reverse is lossy |
20//! | `UnsupportedShowTarget { selector, actual_type }` | Same | Unchanged |
21//! | `DuplicateTitleHeading { title, heading }` | Same | Unchanged |
22//!
23//! New variants introduced in 0.3.0: `ParseError`, `InvalidFingerprint`,
24//! `JsonParseError`, `ValidationError`, `ExecutableNotFound`,
25//! `UnsupportedDocumentFormat`.
26//!
27//! ## New `UnsupportedDocumentFormat` variant (R3 revision)
28//!
29//! This is a NEW variant. There is no `nb-api 0.2.x` predecessor.
30//! Consumers upgrading to `nb-api 0.3.0` SHALL add the variant to
31//! their match arms. **Adding a variant to an exhaustive enum
32//! match produces a compile error, not a warning; wildcard
33//! matches continue compiling.** The constant
34//! [`SUPPORTED_DOCUMENT_EXTENSIONS`] (crate-root re-export of the
35//! source-of-truth declared in `parser`) is the basis for the
36//! `supported` payload at construction time.
37
38use std::error::Error as _; // `.source()` on `std::io::Error`
39use std::path::PathBuf;
40
41use serde::{Deserialize, Serialize};
42
43/// Errors raised by `nb-api` operations.
44///
45/// All variants are serializable so they can traverse MCP tool
46/// response envelopes without lossy string flattening. The
47/// [`std::error::Error`] implementation remains for ergonomic
48/// interop with code that uses `?` and standard error reporting.
49///
50/// `std::error::Error` is implemented MANUALLY below rather than
51/// via `thiserror::Error` derive. The derive's autodetect
52/// treats any field named `source` as a `#[source]` chain link
53/// and tries to convert it to `dyn Error`, which fails for
54/// fields of type `String` (e.g., `JsonParseError { source:
55/// String }` per the P1 specification). The manual impl
56/// preserves the field name and only sets a source-chain link
57/// for variants whose source field is itself an `Error`.
58#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
59#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
60#[serde(tag = "type", rename_all = "snake_case")]
61pub enum NbError {
62    /// An `nb` subprocess invocation failed (non-zero exit, or
63    /// spawning failed for a non-NotFound reason).
64    CommandFailed {
65        /// The argument vector (joined) that was executed.
66        command: String,
67        /// Captured stderr (or stdout when stderr was empty).
68        stderr: String,
69        /// Process exit code, if the process started.
70        exit_code: Option<i32>,
71    },
72
73    /// The `nb` executable could not be located on `PATH` (or in
74    /// the resolved location) when a subprocess was spawned.
75    ExecutableNotFound {
76        /// The resolved path the spawn attempt targeted.
77        path: String,
78    },
79
80    /// `nb` reported that the requested selector was not found.
81    NotFound {
82        /// The selector that was not resolved.
83        selector: String,
84    },
85
86    /// An I/O error occurred while accessing a notebook file or
87    /// the on-disk notebook directory. The `source` field captures
88    /// the original `std::io::Error` chain as a serializable
89    /// snapshot (recursive [`IoError`]).
90    Io {
91        /// Path that triggered the I/O error.
92        path: PathBuf,
93        /// Snapshot of the `std::io::Error` chain.
94        source: IoError,
95    },
96
97    /// `nb show` was invoked on a selector whose type is not
98    /// classified as text by `nb` itself (per the
99    /// `add-0-2-0-foundation` public-API spec). Folders, archives,
100    /// audio, video, image, and any other non-textual type reach
101    /// this path. The classification delegates to
102    /// `nb show <selector> --type text` so forward compatibility
103    /// is automatic when `nb` adds new textual types. Probe
104    /// failure (e.g., selector not found) does NOT route here;
105    /// it falls through to the original `CommandFailed` error
106    /// from the content-read path.
107    UnsupportedShowTarget {
108        selector: String,
109        actual_type: String,
110    },
111
112    /// `nb add` was called with a `title` and `content` where the
113    /// first nonblank line of `content` is an exact Markdown ATX H1
114    /// duplicating the title. The validation runs in the caller
115    /// process before any subprocess invocation or notebook side
116    /// effect (including `resolve_notebook`); the rejection
117    /// happens entirely in-process. `heading` carries the exact
118    /// detected source line (including the leading `#` and any
119    /// surrounding whitespace) for actionable diagnostics. See
120    /// `add-0-2-0-foundation` public-API specification.
121    DuplicateTitleHeading { title: String, heading: String },
122
123    /// A structural parse failure.
124    ParseError {
125        kind: ParseErrorKind,
126        location: std::ops::Range<usize>,
127    },
128
129    /// A fingerprint string failed structural validation (wrong
130    /// prefix, wrong length, mixed case, etc.). `reason` carries a
131    /// machine-readable category (e.g., `"empty"`,
132    /// `"unknown_algorithm_prefix"`, `"uppercase_hex"`).
133    InvalidFingerprint { reason: String },
134
135    /// JSON deserialization failed when constructing a typed
136    /// wrapper (e.g., [`crate::fingerprint::Fingerprint::from_json`]).
137    JsonParseError {
138        // Field is named `source` per the P1 specification.
139        source: String,
140    },
141
142    /// A semantic validation error raised by an operation boundary
143    /// (e.g., rejecting input that is structurally valid but
144    /// semantically illegal). `location` is `None` when the
145    /// failure is not byte-anchored.
146    ValidationError {
147        reason: String,
148        location: Option<std::ops::Range<usize>>,
149    },
150
151    /// Format-dispatch refusal (R3 revision).
152    ///
153    /// `parse(bytes, FromPath(path))` returned this error because
154    /// the final filename matched one of the recognized-but-
155    /// unsupported dotted suffixes (e.g., `.org`, `.latex`,
156    /// `.tex`, `.adoc`, `.asciidoc`). Format dispatch precedes
157    /// byte parsing, so no bytes were consumed and no
158    /// parse-error location is meaningful — this is a
159    /// contextual configuration error, not a parse failure.
160    ///
161    /// `extension` carries the lowercase dotted suffix WITHOUT
162    /// the leading dot (e.g., `"org"`, `"latex"`).
163    /// `supported` is the owned canonical list of supported
164    /// extensions, populated at construction time from
165    /// `crate::SUPPORTED_DOCUMENT_EXTENSIONS`. The owned
166    /// `Vec<String>` shape is required for the derived
167    /// `Serialize` / `Deserialize` round-trip contract on
168    /// `NbError`.
169    UnsupportedDocumentFormat {
170        extension: String,
171        supported: Vec<String>,
172    },
173
174    /// Process-shared gate queue wait exceeded. Notebook was not mutated.
175    GateTimeout { gate: String, timeout_ms: u64 },
176
177    /// `Transaction::commit` refused because the notebook worktree/index is dirty.
178    DirtyBaseline { guidance: String },
179
180    /// Plan-op path collision against snapshot or earlier plan ops.
181    PathCollision {
182        path: String,
183        plan_index: Option<u32>,
184    },
185
186    /// Plan targets or would leave durable state on a Git-ignored path in a
187    /// way that cannot be represented in the single checkpoint (existing
188    /// ignored entry mutation), or requires force-staging (reported only when
189    /// force-stage is unavailable). Prefer rejecting existing-ignored mutators.
190    PathIgnored {
191        path: String,
192        guidance: String,
193        plan_index: Option<u32>,
194    },
195
196    /// Validation/apply failure tied to a plan entry.
197    PlanValidation {
198        kind: String,
199        message: String,
200        plan_index: Option<u32>,
201    },
202
203    /// Commit completion is unknown (e.g. transport timeout after checkpoint may have started).
204    IndeterminateCommit {
205        pre_revision: String,
206        post_revision_observed: Option<String>,
207        guidance: String,
208    },
209
210    /// Cleanup after a known failed apply could not verify clean `pre_revision`.
211    RecoveryRequired {
212        pre_revision: String,
213        post_revision_observed: Option<String>,
214        status_observed: Option<String>,
215        preserved_paths: Option<Vec<String>>,
216        guidance: String,
217    },
218
219    /// Body fingerprint precondition failed.
220    FingerprintMismatch {
221        target: crate::types::NoteTarget,
222        guidance: String,
223    },
224
225    /// Line number/anchor precondition failed.
226    AnchorMismatch {
227        target: String,
228        number: u32,
229        guidance: String,
230    },
231
232    /// Substring `expected_count` did not match actual matches.
233    OccurrenceMismatch { expected: u32, actual: u32 },
234
235    /// Overlapping line edits in one batch.
236    OverlappingEdits { indices: Vec<u32> },
237
238    /// Invalid `show_note_lines` window.
239    InvalidLineWindow {
240        offset: u32,
241        limit: u32,
242        total_lines: u32,
243    },
244
245    /// Empty substring pattern refused at enqueue/apply.
246    EmptySubstringPattern,
247
248    /// Contiguous-body-only op invoked on a multi-fragment document.
249    FragmentedBody {
250        fragment_count: u32,
251        guidance: String,
252    },
253
254    /// Document structure is not supported for the requested op.
255    UnsupportedStructure { reason: String },
256}
257
258impl std::fmt::Display for NbError {
259    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
260        match self {
261            Self::CommandFailed {
262                command,
263                stderr,
264                exit_code,
265            } => write!(
266                f,
267                "command {command:?} failed (exit {exit_code:?}): {stderr}"
268            ),
269            Self::ExecutableNotFound { path } => {
270                write!(f, "`nb` executable not found at path {path:?}")
271            }
272            Self::NotFound { selector } => write!(f, "not found: {selector:?}"),
273            Self::Io { path, source } => write!(f, "I/O error at {path:?}: {source}"),
274            Self::UnsupportedShowTarget {
275                selector,
276                actual_type,
277            } => write!(
278                f,
279                "selector `{selector}` resolved to non-textual type `{actual_type}`; \
280                 `nb show` does not display non-textual content"
281            ),
282            Self::DuplicateTitleHeading { title, heading } => write!(
283                f,
284                "title `{title}` duplicates the first H1 in content (`{heading}`); \
285                 remove the duplicate heading to avoid double-rendering"
286            ),
287            Self::ParseError { kind, location } => {
288                write!(f, "parse error: {kind:?} at {location:?}")
289            }
290            Self::InvalidFingerprint { reason } => {
291                write!(f, "invalid fingerprint: {reason:?}")
292            }
293            Self::JsonParseError { source } => {
294                write!(f, "JSON parse error: {source:?}")
295            }
296            Self::ValidationError {
297                reason,
298                location: _,
299            } => {
300                write!(f, "validation error: {reason:?}")
301            }
302            Self::UnsupportedDocumentFormat {
303                extension,
304                supported,
305            } => {
306                write!(
307                    f,
308                    "unsupported document format: {extension:?} (supported: {supported:?})"
309                )
310            }
311            Self::GateTimeout { gate, timeout_ms } => {
312                write!(f, "gate timeout waiting on {gate} after {timeout_ms}ms")
313            }
314            Self::DirtyBaseline { guidance } => {
315                write!(f, "dirty baseline: {guidance}")
316            }
317            Self::PathCollision { path, plan_index } => {
318                write!(f, "path collision at {path:?} (plan_index={plan_index:?})")
319            }
320            Self::PathIgnored {
321                path,
322                guidance,
323                plan_index,
324            } => write!(
325                f,
326                "ignored path {path:?} (plan_index={plan_index:?}): {guidance}"
327            ),
328            Self::PlanValidation {
329                kind,
330                message,
331                plan_index,
332            } => write!(
333                f,
334                "plan validation ({kind}) at index {plan_index:?}: {message}"
335            ),
336            Self::IndeterminateCommit {
337                pre_revision,
338                post_revision_observed,
339                guidance,
340            } => write!(
341                f,
342                "indeterminate commit (pre={pre_revision}, post={post_revision_observed:?}): {guidance}"
343            ),
344            Self::RecoveryRequired {
345                pre_revision,
346                guidance,
347                ..
348            } => write!(
349                f,
350                "recovery required (pre_revision={pre_revision}): {guidance}"
351            ),
352            Self::FingerprintMismatch { target, guidance } => {
353                write!(f, "fingerprint mismatch for {target:?}: {guidance}")
354            }
355            Self::AnchorMismatch {
356                target,
357                number,
358                guidance,
359            } => write!(f, "anchor mismatch for {target} line {number}: {guidance}"),
360            Self::OccurrenceMismatch { expected, actual } => {
361                write!(
362                    f,
363                    "occurrence mismatch: expected={expected} actual={actual}"
364                )
365            }
366            Self::OverlappingEdits { indices } => {
367                write!(f, "overlapping edits at indices {indices:?}")
368            }
369            Self::InvalidLineWindow {
370                offset,
371                limit,
372                total_lines,
373            } => write!(
374                f,
375                "invalid line window offset={offset} limit={limit} total_lines={total_lines}"
376            ),
377            Self::EmptySubstringPattern => write!(f, "empty substring pattern"),
378            Self::FragmentedBody {
379                fragment_count,
380                guidance,
381            } => write!(
382                f,
383                "fragmented body ({fragment_count} fragments): {guidance}"
384            ),
385            Self::UnsupportedStructure { reason } => {
386                write!(f, "unsupported structure: {reason}")
387            }
388        }
389    }
390}
391
392impl std::error::Error for NbError {
393    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
394        // Only `Io { source: IoError }` carries a true source-chain
395        // link. Every other variant's `source` field (where
396        // present) is a diagnostic String or a non-Error type, so
397        // we explicitly return `None` for them.
398        match self {
399            Self::Io { source, .. } => Some(source),
400            _ => None,
401        }
402    }
403}
404
405/// Narrow refusal contract for the structural parser.
406///
407/// `parse` accepts every input that can be losslessly partitioned
408/// into a [`crate::parser::NoteDocument`], including the frozen
409/// W1 and E1-E11 noncanonical forms. The ONLY refusal cases at
410/// the parse layer are:
411///
412/// - Todo with no non-blank line at all: [`ParseErrorKind::MissingTitle`].
413/// - Bookmark with no non-blank line at all: [`ParseErrorKind::MissingTitle`].
414///
415/// Notes are permissive on empty source. Title-shape errors belong
416/// to a later strict validator (P5+), not to the parser.
417#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
418#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
419pub enum ParseErrorKind {
420    /// The first non-blank line was missing entirely (Todo/Bookmark
421    /// only; Notes are permissive).
422    MissingTitle,
423}
424
425/// Serializable snapshot of a [`std::io::Error`] chain.
426///
427/// `IoError` captures the **chain structure** (as a tree of
428/// snapshots) but does NOT preserve the original `std::io::Error`
429/// identity. The forward conversion [`From<std::io::Error>`] walks
430/// [`std::error::Error::source`] and recurses for each
431/// `std::io::Error` link; nested non-`io::Error` sources are
432/// stringified into [`IoErrorKind::Other`].
433///
434/// The reverse conversion [`From<IoError>`] for `std::io::Error`
435/// is **explicitly lossy** — see [`IoError`]'s `From` impl.
436#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, thiserror::Error)]
437#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
438#[error("{kind:?}: {message}")]
439pub struct IoError {
440    pub kind: IoErrorKind,
441    pub message: String,
442    pub os_error: Option<i32>,
443    pub source: Option<Box<IoError>>,
444}
445
446/// Discriminator for the `std::io::ErrorKind` taxonomy, lifted into
447/// a serializable form. Marked `#[non_exhaustive]` so future
448/// versions can add new kinds without breaking downstream
449/// `match` arms that include a default branch.
450#[non_exhaustive]
451#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
452#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
453pub enum IoErrorKind {
454    NotFound,
455    PermissionDenied,
456    ConnectionRefused,
457    ConnectionReset,
458    ConnectionAborted,
459    NotConnected,
460    AddrInUse,
461    AddrNotAvailable,
462    BrokenPipe,
463    AlreadyExists,
464    WouldBlock,
465    InvalidInput,
466    InvalidData,
467    TimedOut,
468    WriteZero,
469    Interrupted,
470    UnexpectedEof,
471    OutOfMemory,
472    /// Catch-all for nested sources that are not themselves
473    /// `std::io::Error` (e.g., a third-party crate's error type
474    /// captured as `source`).
475    Other,
476}
477
478impl IoErrorKind {
479    /// Map a `std::io::ErrorKind` into the serializable variant.
480    pub fn from_std(kind: std::io::ErrorKind) -> Self {
481        match kind {
482            std::io::ErrorKind::NotFound => Self::NotFound,
483            std::io::ErrorKind::PermissionDenied => Self::PermissionDenied,
484            std::io::ErrorKind::ConnectionRefused => Self::ConnectionRefused,
485            std::io::ErrorKind::ConnectionReset => Self::ConnectionReset,
486            std::io::ErrorKind::ConnectionAborted => Self::ConnectionAborted,
487            std::io::ErrorKind::NotConnected => Self::NotConnected,
488            std::io::ErrorKind::AddrInUse => Self::AddrInUse,
489            std::io::ErrorKind::AddrNotAvailable => Self::AddrNotAvailable,
490            std::io::ErrorKind::BrokenPipe => Self::BrokenPipe,
491            std::io::ErrorKind::AlreadyExists => Self::AlreadyExists,
492            std::io::ErrorKind::WouldBlock => Self::WouldBlock,
493            std::io::ErrorKind::InvalidInput => Self::InvalidInput,
494            std::io::ErrorKind::InvalidData => Self::InvalidData,
495            std::io::ErrorKind::TimedOut => Self::TimedOut,
496            std::io::ErrorKind::WriteZero => Self::WriteZero,
497            std::io::ErrorKind::Interrupted => Self::Interrupted,
498            std::io::ErrorKind::UnexpectedEof => Self::UnexpectedEof,
499            std::io::ErrorKind::OutOfMemory => Self::OutOfMemory,
500            _ => Self::Other,
501        }
502    }
503}
504
505impl From<std::io::ErrorKind> for IoErrorKind {
506    fn from(kind: std::io::ErrorKind) -> Self {
507        Self::from_std(kind)
508    }
509}
510
511impl From<std::io::Error> for IoError {
512    /// Capture an `io::Error` chain as a tree of serializable
513    /// snapshots.
514    ///
515    /// The implementation recursively walks the
516    /// [`std::error::Error::source`] chain on BORROWED
517    /// `&dyn Error` references. This is critical: `std::io::Error`
518    /// is not `Clone`, so we cannot reconstruct an inner error
519    /// from a borrow without losing its `raw_os_error()` and its
520    /// own source chain. Walking the borrow preserves the chain
521    /// STRUCTURE exactly.
522    ///
523    /// At each level: if the source is itself an `io::Error`,
524    /// recurse on its borrow; otherwise, capture the source as
525    /// an [`IoErrorKind::Other`] snapshot (preserving the
526    /// `Display` text and walking its own source chain for
527    /// nested non-io links).
528    fn from(err: std::io::Error) -> Self {
529        snapshot_io_error(err)
530    }
531}
532
533/// Build an `IoError` snapshot from an `io::Error` value, then
534/// walk its source chain via the borrowed `dyn Error` to
535/// preserve chain structure exactly.
536fn snapshot_io_error(err: std::io::Error) -> IoError {
537    let kind = IoErrorKind::from_std(err.kind());
538    let os_error = err.raw_os_error();
539    let message = err.to_string();
540    let source = walk_source_chain(err.source());
541    IoError {
542        kind,
543        message,
544        os_error,
545        source,
546    }
547}
548
549/// Walk a `&(dyn Error + 'static)` chain, building a list of
550/// `IoError` snapshots. Each link appears EXACTLY ONCE in the
551/// chain (no duplication). Each `std::io::Error` link has its
552/// `raw_os_error()` preserved verbatim via the recursive walk
553/// on the borrowed `dyn Error`.
554///
555/// The chain is built by snapshotting the CURRENT node with its
556/// `source` field set to the recursive walk of the NEXT node.
557/// This avoids the A→B→B duplication that would arise from both
558/// recursing into the source AND iterating/appending the same
559/// source.
560fn walk_source_chain(source: Option<&(dyn std::error::Error + 'static)>) -> Option<Box<IoError>> {
561    let head = source?;
562    Some(Box::new(snapshot_link(head)))
563}
564
565/// Snapshot a single link in the source chain. The link's `source`
566/// field is set to the recursive snapshot of the next link.
567fn snapshot_link(current: &(dyn std::error::Error + 'static)) -> IoError {
568    if let Some(io_err) = current.downcast_ref::<std::io::Error>() {
569        IoError {
570            kind: IoErrorKind::from_std(io_err.kind()),
571            message: io_err.to_string(),
572            os_error: io_err.raw_os_error(),
573            // The recursive walk captures the io_err's own
574            // chain. Each io_err-level appears exactly once.
575            source: walk_source_chain(io_err.source()),
576        }
577    } else {
578        IoError {
579            kind: IoErrorKind::Other,
580            message: current.to_string(),
581            os_error: None,
582            // Recurse on the next link. Because `walk_source_chain`
583            // snapshots its OWN first link and recurses, the
584            // outer iteration does NOT see the next link — no
585            // duplication.
586            source: walk_source_chain(current.source()),
587        }
588    }
589}
590
591impl From<IoError> for std::io::Error {
592    /// Reverse conversion is **explicitly lossy**.
593    ///
594    /// The implementation prefers [`std::io::Error::from_raw_os_error`]
595    /// when [`IoError::os_error`] is `Some`, which LOSES the
596    /// snapshot message and any source chain. Otherwise, it
597    /// constructs a new `io::Error::new(kind, message)`, which
598    /// loses `raw_os_error()`.
599    ///
600    /// The forward conversion ([`From<std::io::Error>`] for
601    /// `IoError`) preserves chain STRUCTURE; this reverse
602    /// conversion does not — the snapshot tree is collapsed to a
603    /// single `std::io::Error`.
604    fn from(snapshot: IoError) -> Self {
605        if let Some(code) = snapshot.os_error {
606            std::io::Error::from_raw_os_error(code)
607        } else {
608            let kind = match snapshot.kind {
609                IoErrorKind::NotFound => std::io::ErrorKind::NotFound,
610                IoErrorKind::PermissionDenied => std::io::ErrorKind::PermissionDenied,
611                IoErrorKind::ConnectionRefused => std::io::ErrorKind::ConnectionRefused,
612                IoErrorKind::ConnectionReset => std::io::ErrorKind::ConnectionReset,
613                IoErrorKind::ConnectionAborted => std::io::ErrorKind::ConnectionAborted,
614                IoErrorKind::NotConnected => std::io::ErrorKind::NotConnected,
615                IoErrorKind::AddrInUse => std::io::ErrorKind::AddrInUse,
616                IoErrorKind::AddrNotAvailable => std::io::ErrorKind::AddrNotAvailable,
617                IoErrorKind::BrokenPipe => std::io::ErrorKind::BrokenPipe,
618                IoErrorKind::AlreadyExists => std::io::ErrorKind::AlreadyExists,
619                IoErrorKind::WouldBlock => std::io::ErrorKind::WouldBlock,
620                IoErrorKind::InvalidInput => std::io::ErrorKind::InvalidInput,
621                IoErrorKind::InvalidData => std::io::ErrorKind::InvalidData,
622                IoErrorKind::TimedOut => std::io::ErrorKind::TimedOut,
623                IoErrorKind::WriteZero => std::io::ErrorKind::WriteZero,
624                IoErrorKind::Interrupted => std::io::ErrorKind::Interrupted,
625                IoErrorKind::UnexpectedEof => std::io::ErrorKind::UnexpectedEof,
626                IoErrorKind::OutOfMemory => std::io::ErrorKind::OutOfMemory,
627                IoErrorKind::Other => std::io::ErrorKind::Other,
628            };
629            std::io::Error::new(kind, snapshot.message)
630        }
631    }
632}