Skip to main content

qubit_fs/write/
write_all_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//! Failure returned by the convenience whole-file write operation.
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 crate::error::FsError;
17use crate::write::WriteFailureState;
18use crate::write::WriterRecovery;
19
20/// A whole-file write failure retaining the recoverable writer when available.
21///
22/// This value is returned by `FileSystem::write_all` and is not constructed
23/// directly by callers.
24///
25/// # Examples
26///
27/// ```rust
28/// use qubit_fs::write::WriteAllFailure;
29///
30/// fn inspect_failure(failure: WriteAllFailure) {
31///     let (error, state, confirmed_bytes, recovery) = failure.into_parts();
32///     eprintln!("write failed after {confirmed_bytes} confirmed bytes: {error}");
33///     if recovery.is_some() {
34///         eprintln!("a writer is available for explicit recovery");
35///     }
36///     eprintln!("publication state: {state:?}");
37/// }
38/// ```
39#[must_use]
40pub struct WriteAllFailure {
41    /// Contextual filesystem error that interrupted the whole-file write.
42    error: Box<FsError>,
43    /// Immutable publication certainty captured at failure.
44    state: WriteFailureState,
45    /// Bytes acknowledged before the failure, independent of later recovery.
46    written_bytes: u64,
47    /// Opened writer retained for explicit recovery when available.
48    writer: Option<WriterRecovery>,
49}
50
51impl WriteAllFailure {
52    /// Builds a failure within the facade after a write or commit error.
53    /// # Parameters
54    /// - `error`: Failure whose trusted filesystem context is being restored.
55    /// - `state`: Publication state used to classify or retain this outcome.
56    /// - `written_bytes`: Value used by `new` to preserve the writer operation
57    ///   contract.
58    /// - `writer`: Retained writer slot updated by cancellation tracking.
59    pub(crate) fn new(
60        error: FsError,
61        state: WriteFailureState,
62        written_bytes: u64,
63        writer: Option<WriterRecovery>,
64    ) -> Self {
65        Self {
66            error: Box::new(error),
67            state,
68            written_bytes,
69            writer,
70        }
71    }
72
73    /// Returns the causal filesystem error.
74    ///
75    /// # Returns
76    /// The filesystem error with its original operation and provider context.
77    #[must_use = "inspect the filesystem error instead of silently discarding it"]
78    #[inline]
79    pub const fn error(&self) -> &FsError {
80        &self.error
81    }
82    /// Returns publication certainty at the original failure, even after
83    /// recovery.
84    ///
85    /// # Returns
86    /// The immutable publication state captured when the write failed.
87    pub const fn state(&self) -> WriteFailureState {
88        self.state
89    }
90    /// Returns the original acknowledged byte count, excluding uncertain
91    /// writes.
92    ///
93    /// # Returns
94    /// The number of bytes acknowledged before the failure.
95    #[must_use]
96    pub const fn written_bytes(&self) -> u64 {
97        self.written_bytes
98    }
99    /// Transfers the retained session without changing the failure snapshot.
100    ///
101    /// # Returns
102    /// The retained writer, or `None` if no writer remains available.
103    pub fn take_recovery(&mut self) -> Option<WriterRecovery> {
104        self.writer.take()
105    }
106    /// Returns the retained writer, if opening had completed.
107    ///
108    /// # Returns
109    /// A shared reference to the retained writer, or `None` if unavailable.
110    #[inline]
111    #[must_use = "inspect the recovery state before abandoning the retained writer"]
112    pub fn recovery(&self) -> Option<&WriterRecovery> {
113        self.writer.as_ref()
114    }
115    /// Returns a mutable retained writer for explicit recovery.
116    ///
117    /// # Returns
118    /// A mutable reference to the retained writer, or `None` if unavailable.
119    #[inline]
120    #[must_use = "inspect the recovery state before abandoning the retained writer"]
121    pub fn recovery_mut(&mut self) -> Option<&mut WriterRecovery> {
122        self.writer.as_mut()
123    }
124    /// Returns the causal error and optional writer.
125    ///
126    /// # Returns
127    /// The original error, publication state, confirmed byte count, and
128    /// optional retained writer.
129    #[must_use = "retain the failure details or recover the retained writer"]
130    #[inline]
131    pub fn into_parts(self) -> (FsError, WriteFailureState, u64, Option<WriterRecovery>) {
132        (*self.error, self.state, self.written_bytes, self.writer)
133    }
134}
135
136impl Display for WriteAllFailure {
137    /// Formats the causal failure without exposing writer internals.
138    /// # Parameters
139    /// - `formatter`: Formatter receiving the diagnostic representation.
140    #[inline]
141    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
142        Display::fmt(&self.error, formatter)
143    }
144}
145
146impl Debug for WriteAllFailure {
147    /// Formats the causal error and whether recovery is available.
148    /// # Parameters
149    /// - `formatter`: Formatter receiving the diagnostic representation.
150    #[inline]
151    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
152        formatter
153            .debug_struct("WriteAllFailure")
154            .field("error", &self.error)
155            .field("state", &self.state)
156            .field("written_bytes", &self.written_bytes)
157            .field("has_recovery", &self.writer.is_some())
158            .finish()
159    }
160}
161
162impl Error for WriteAllFailure {
163    /// Returns the underlying filesystem error.
164    #[inline]
165    fn source(&self) -> Option<&(dyn Error + 'static)> {
166        Some(self.error.as_ref())
167    }
168}