Skip to main content

qubit_fs/error/
open_failure.rs

1// =============================================================================
2//    Copyright (c) 2026 Haixing Hu.
3//
4//    SPDX-License-Identifier: Apache-2.0
5//
6//    Licensed under the Apache License, Version 2.0.
7// =============================================================================
8//! Opening failures that preserve isolated recovery ownership.
9
10use std::error::Error;
11use std::fmt::Debug;
12use std::fmt::Display;
13use std::fmt::Formatter;
14use std::fmt::Result as FmtResult;
15
16use super::FsError;
17use super::OpenFailureStage;
18
19/// A failed open with its causal error and optional isolated recovery session.
20///
21/// `R` owns only explicit cleanup authority. Keep this error or take its
22/// recovery session before reporting failure. Dropping the error does not
23/// confirm cleanup. There is deliberately no conversion into `FsError` that
24/// discards recovery.
25///
26/// # Type Parameters
27///
28/// - `R`: Recovery session type retained after the provider open fails.
29///
30/// # Examples
31///
32/// ```rust
33/// # mod support { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/common/rustdoc_support.rs")); }
34///
35/// # let filesystem = support::rustdoc_provider::filesystem();
36/// use qubit_fs::Path;
37/// use qubit_fs::write::WriteOptions;
38/// use qubit_fs::metadata::AtomicityRequirement;
39///
40/// let path = Path::parse("/report")?;
41/// let result = filesystem.open_writer(
42///     &path,
43///     WriteOptions::default().with_atomicity(AtomicityRequirement::Required),
44/// );
45/// let failure = result.expect_err("the fixture does not guarantee atomic writes");
46/// assert_eq!(failure.stage(), qubit_fs::error::OpenFailureStage::Preflight);
47/// assert_eq!(failure.error().operation(), qubit_fs::error::FsOperation::OpenWriter);
48///
49/// # Ok::<(), Box<dyn std::error::Error>>(())
50/// ```
51///
52/// # Type Parameters
53///
54/// - `R`: Recovery session type retained after the provider open fails.
55#[must_use = "inspect and retain recovery ownership before abandoning an open failure"]
56pub struct OpenFailure<R> {
57    /// Original contextual failure, unchanged by later recovery.
58    error: Box<FsError>,
59    /// Stage where opening stopped.
60    stage: OpenFailureStage,
61    /// Isolated session, present when a successfully opened envelope was
62    /// rejected.
63    recovery: Option<R>,
64}
65
66impl<R> OpenFailure<R> {
67    /// Creates a failure after classifying the stage and transferring
68    /// ownership.
69    ///
70    /// # Parameters
71    ///
72    /// - `error`: Filesystem error whose kind, source, and established facts
73    ///   are retained.
74    /// - `stage`: Stage at which the open operation failed.
75    /// - `recovery`: Optional isolated session retained for safe recovery.
76    pub(crate) fn new(error: FsError, stage: OpenFailureStage, recovery: Option<R>) -> Self {
77        Self {
78            error: Box::new(error),
79            stage,
80            recovery,
81        }
82    }
83
84    /// Returns the original failure; cleanup does not rewrite it.
85    #[must_use = "inspect the original filesystem error before discarding it"]
86    #[inline]
87    pub const fn error(&self) -> &FsError {
88        &self.error
89    }
90
91    /// Returns the stage where opening stopped.
92    #[must_use = "use the opening stage to classify the failure"]
93    #[inline]
94    pub const fn stage(&self) -> OpenFailureStage {
95        self.stage
96    }
97
98    /// Returns the retained recovery session, or None before an envelope
99    /// arrived.
100    #[inline]
101    pub const fn recovery(&self) -> Option<&R> {
102        self.recovery.as_ref()
103    }
104
105    /// Borrows the retained session for explicit cleanup, when available.
106    #[inline]
107    pub fn recovery_mut(&mut self) -> Option<&mut R> {
108        self.recovery.as_mut()
109    }
110
111    /// Transfers recovery ownership without changing the historical failure.
112    pub fn take_recovery(&mut self) -> Option<R> {
113        self.recovery.take()
114    }
115
116    /// Returns all failure facts and transfers any recovery ownership.
117    ///
118    /// # Returns
119    /// The original error, opening stage, and optional retained recovery
120    /// session.
121    #[must_use = "retain or inspect the failure facts returned by this method"]
122    pub fn into_parts(self) -> (FsError, OpenFailureStage, Option<R>) {
123        (*self.error, self.stage, self.recovery)
124    }
125}
126
127impl<R> Debug for OpenFailure<R> {
128    /// Formats failure facts without formatting the session or its claimed
129    /// identity.
130    ///
131    /// # Parameters
132    ///
133    /// - `f`: Formatter that receives the debug or display representation.
134    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
135        f.debug_struct("OpenFailure")
136            .field("error", &self.error)
137            .field("stage", &self.stage)
138            .field("has_recovery", &self.recovery.is_some())
139            .finish()
140    }
141}
142
143impl<R> Display for OpenFailure<R> {
144    /// Formats only the original contextual failure.
145    ///
146    /// # Parameters
147    ///
148    /// - `f`: Formatter that receives the debug or display representation.
149    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
150        Display::fmt(&self.error, f)
151    }
152}
153
154impl<R: 'static> Error for OpenFailure<R> {
155    /// Exposes the original error chain without surrendering recovery
156    /// ownership.
157    fn source(&self) -> Option<&(dyn Error + 'static)> {
158        Some(self.error.as_ref())
159    }
160}