Skip to main content

qubit_fs/write/
async_write_all_operation_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 for an owning asynchronous whole-file write.
9use std::error::Error;
10use std::fmt::Display;
11use std::fmt::Formatter;
12
13use crate::error::FsError;
14use crate::write::WriteFailureState;
15/// Error returned by an owning asynchronous whole-file write.
16///
17/// Recovery ownership remains in the operation even when this error is
18/// consumed.
19///
20/// # Examples
21/// ```rust
22/// # mod support { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/common/rustdoc_support.rs")); }
23/// # use support::*;
24/// # let (filesystem, _) = async_recording_spi::async_recording_file_system(async_recording_spi::AsyncRecordingConfig {
25/// #     writer_commit_failure: Some(qubit_fs::write::WriteFailureState::NotPublished),
26/// #     ..Default::default()
27/// # });
28/// # poll_support::ready(async {
29/// use qubit_fs::Path;
30/// use qubit_fs::write::WriteOptions;
31/// use qubit_fs::write::AsyncWriterRecovery;
32/// use qubit_fs::write::WriteFailureState;
33/// let mut operation = filesystem.begin_write_all(
34///     Path::parse("/report")?, b"bytes".to_vec(), WriteOptions::default(),
35/// )?;
36/// let failure = operation.execute().await.expect_err("fixture commit failure");
37/// assert_eq!(WriteFailureState::NotPublished, failure.state());
38/// assert_eq!(5, failure.written_bytes());
39/// assert!(operation.has_recovery());
40/// let cleanup = match operation.recovery().expect("retained session") {
41///     AsyncWriterRecovery::Opened(writer) => writer.abort_async().await,
42///     AsyncWriterRecovery::Rejected(writer) => writer.abort_async().await,
43/// };
44/// assert!(cleanup.is_ok());
45/// // Application error handling can retain `failure`, `cleanup`, and `operation`.
46/// # Ok::<(), Box<dyn std::error::Error>>(())
47/// # }).unwrap();
48/// ```
49#[must_use]
50pub struct AsyncWriteAllOperationFailure {
51    /// Original contextual error.
52    error: FsError,
53    /// Publication facts at failure.
54    state: WriteFailureState,
55    /// Bytes acknowledged by completed writes.
56    written_bytes: u64,
57}
58impl AsyncWriteAllOperationFailure {
59    /// Creates a failure with its recovery facts.
60    /// # Parameters
61    /// - `error`: Failure whose trusted filesystem context is being restored.
62    /// - `state`: Publication state used to classify or retain this outcome.
63    /// - `written_bytes`: Value used by `new` to preserve the writer operation
64    ///   contract.
65    pub(crate) fn new(error: FsError, state: WriteFailureState, written_bytes: u64) -> Self {
66        Self {
67            error,
68            state,
69            written_bytes,
70        }
71    }
72    /// Returns the contextual filesystem error.
73    #[inline]
74    pub const fn error(&self) -> &FsError {
75        &self.error
76    }
77    /// Returns the publication facts recorded when execution stopped.
78    #[inline]
79    pub const fn state(&self) -> WriteFailureState {
80        self.state
81    }
82    /// Returns bytes acknowledged by completed writes before execution stopped.
83    #[must_use]
84    #[inline]
85    pub const fn written_bytes(&self) -> u64 {
86        self.written_bytes
87    }
88    /// Consumes the failure and returns its filesystem error.
89    ///
90    /// This discards publication state and confirmed byte count. The operation
91    /// still owns any recovery writer; prefer `into_parts` when recovering.
92    pub fn into_error(self) -> FsError {
93        self.error
94    }
95    /// Consumes the failure and returns all recovery facts.
96    pub fn into_parts(self) -> (FsError, WriteFailureState, u64) {
97        (self.error, self.state, self.written_bytes)
98    }
99}
100impl Display for AsyncWriteAllOperationFailure {
101    /// Formats the underlying filesystem failure for user-facing output.
102    /// # Parameters
103    /// - `f`: Formatter receiving the diagnostic representation.
104    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
105        self.error.fmt(f)
106    }
107}
108impl std::fmt::Debug for AsyncWriteAllOperationFailure {
109    /// Includes recovery facts while formatting the failure.
110    ///
111    /// # Parameters
112    /// - `f`: Formatter receiving the diagnostic representation.
113    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
114        f.debug_struct("AsyncWriteAllOperationFailure")
115            .field("error", &self.error)
116            .field("state", &self.state)
117            .field("written_bytes", &self.written_bytes)
118            .finish()
119    }
120}
121impl Error for AsyncWriteAllOperationFailure {
122    /// Returns the contextual filesystem error that caused this failure.
123    fn source(&self) -> Option<&(dyn Error + 'static)> {
124        Some(&self.error)
125    }
126}