Skip to main content

qubit_fs/write/
async_write_all_operation.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//! Owning asynchronous whole-file write operation.
9use std::fmt::Debug;
10use std::fmt::Formatter;
11use std::fmt::Result as FmtResult;
12use std::io::Error as IoError;
13
14use qubit_io::AsyncOutput;
15
16use crate::AsyncFileSystem;
17use crate::error::FsError;
18use crate::error::FsErrorKind;
19use crate::error::FsOperation;
20use crate::error::OpenFailureStage;
21use crate::metadata::WriteOutcome;
22use crate::path::Path;
23use crate::write::AsyncWriteAllOperationFailure;
24use crate::write::AsyncWriteAllOperationState;
25use crate::write::AsyncWriterRecovery;
26use crate::write::WriteFailureState;
27use crate::write::WriteOptions;
28use crate::write::WriterState;
29use crate::write::internal::WriteAllCancellationGuard;
30use crate::write::internal::WriteAllRecoverySnapshot;
31use crate::write::internal::open_failure_state;
32/// Owning asynchronous whole-file write that survives cancellation.
33///
34/// # Examples
35///
36/// The example runs against an isolated in-memory fixture. Applications obtain
37/// their configured facade from a provider or registry integration.
38///
39/// ```rust
40/// # mod support { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/common/rustdoc_support.rs")); }
41/// # use support::*;
42/// # let (filesystem, _) = async_recording_spi::async_recording_file_system(Default::default());
43/// # poll_support::ready(async {
44/// use qubit_fs::Path;
45/// use qubit_fs::write::WriteOptions;
46/// use qubit_fs::write::AsyncWriteAllOperationState;
47///
48/// let mut operation = filesystem.begin_write_all(
49///     Path::parse("/report")?, b"bytes".to_vec(), WriteOptions::default(),
50/// )?;
51/// operation.execute().await?;
52/// assert_eq!(AsyncWriteAllOperationState::Completed, operation.state());
53/// assert_eq!(5, operation.written_bytes());
54/// assert!(!operation.has_recovery());
55/// # Ok::<(), Box<dyn std::error::Error>>(())
56/// # }).unwrap();
57/// ```
58#[must_use]
59pub struct AsyncWriteAllOperation {
60    /// Filesystem retained independently of the caller.
61    filesystem: AsyncFileSystem,
62    /// Target retained for recovery inspection.
63    path: Path,
64    /// Request payload, held only until execution ends or is cancelled.
65    bytes: Vec<u8>,
66    /// Validated request options.
67    options: WriteOptions,
68    /// Historical execution state.
69    state: AsyncWriteAllOperationState,
70    /// Opened writer retained while recovery may be required.
71    writer: Option<AsyncWriterRecovery>,
72    /// Frozen publication and confirmed-progress snapshot.
73    recovery: WriteAllRecoverySnapshot,
74}
75impl AsyncWriteAllOperation {
76    /// Creates an operation after facade preflight has succeeded.
77    /// # Parameters
78    /// - `filesystem`: Filesystem whose provider stages execute this write.
79    /// - `path`: Target path used for error context and provider requests.
80    /// - `bytes`: Payload retained for the whole-file write.
81    /// - `options`: Write policy applied to the provider request.
82    pub(crate) fn new(filesystem: AsyncFileSystem, path: Path, bytes: Vec<u8>, options: WriteOptions) -> Self {
83        Self {
84            filesystem,
85            path,
86            bytes,
87            options,
88            state: AsyncWriteAllOperationState::Ready,
89            writer: None,
90            recovery: WriteAllRecoverySnapshot::new(),
91        }
92    }
93    /// Returns the filesystem retained for execution and recovery inspection.
94    #[inline]
95    #[must_use]
96    pub const fn filesystem(&self) -> &AsyncFileSystem {
97        &self.filesystem
98    }
99    /// Returns the requested target path.
100    #[inline]
101    #[must_use]
102    pub const fn path(&self) -> &Path {
103        &self.path
104    }
105    /// Returns the operation state.
106    #[inline]
107    pub const fn state(&self) -> AsyncWriteAllOperationState {
108        self.state
109    }
110    /// Reports whether an opened writer is retained for recovery.
111    #[inline]
112    #[must_use]
113    pub const fn has_recovery(&self) -> bool {
114        self.writer.is_some()
115    }
116    /// Returns mutable access to the retained recovery writer.
117    #[inline]
118    pub fn recovery(&mut self) -> Option<&mut AsyncWriterRecovery> {
119        self.writer.as_mut()
120    }
121    /// Transfers recovery responsibility to the caller.
122    ///
123    /// Subsequent writer recovery does not change this operation's historical
124    /// publication state or byte count.
125    #[inline]
126    pub fn take_recovery(&mut self) -> Option<AsyncWriterRecovery> {
127        self.writer.take()
128    }
129    /// Returns the frozen count of bytes confirmed before execution stopped.
130    #[inline]
131    #[must_use]
132    pub const fn written_bytes(&self) -> u64 {
133        self.recovery.written_bytes
134    }
135    /// Executes the operation once, retaining recovery state on failure.
136    ///
137    /// # Cancellation
138    ///
139    /// Keep this operation outside the cancellation scope and cancel only this
140    /// future. Dropping an unpolled future leaves the operation ready. After
141    /// execution starts, cancellation records indeterminate publication and
142    /// retains any opened writer. A missing writer does not prove no effects.
143    /// The payload is released when this future finishes or is dropped.
144    ///
145    /// # Returns
146    ///
147    /// The confirmed write outcome. Success freezes the acknowledged byte count
148    /// and releases the committed writer.
149    ///
150    /// # Errors
151    ///
152    /// Returns the provider failure with confirmed progress, or `InvalidState`
153    /// if execution has already started. Repeated execution preserves the
154    /// historical state and does not invoke the provider again.
155    pub async fn execute(&mut self) -> Result<WriteOutcome, AsyncWriteAllOperationFailure> {
156        if self.state != AsyncWriteAllOperationState::Ready {
157            return Err(AsyncWriteAllOperationFailure::new(
158                invalid_state(&self.path, &self.filesystem),
159                self.recovery.state,
160                self.recovery.written_bytes,
161            ));
162        }
163        let Self {
164            filesystem,
165            path,
166            bytes,
167            options,
168            state,
169            writer,
170            recovery,
171        } = self;
172        let bytes = std::mem::take(bytes);
173        let mut guard = WriteAllCancellationGuard::start(state, writer, recovery);
174        let result = execute_write(filesystem, path, &bytes, options, guard.writer_mut()).await;
175        guard.finish(&result);
176        result
177    }
178}
179/// Runs provider stages while keeping the session in the recovery slot.
180/// # Parameters
181/// - `filesystem`: Filesystem whose provider stages execute this write.
182/// - `path`: Target path used for error context and provider requests.
183/// - `bytes`: Payload retained for the whole-file write.
184/// - `options`: Write policy applied to the provider request.
185/// - `slot`: Recovery slot retaining the opened or rejected writer.
186async fn execute_write(
187    filesystem: &AsyncFileSystem,
188    path: &Path,
189    bytes: &[u8],
190    options: &WriteOptions,
191    slot: &mut Option<AsyncWriterRecovery>,
192) -> Result<WriteOutcome, AsyncWriteAllOperationFailure> {
193    if slot.is_none() {
194        match filesystem.open_writer(path, options.clone()).await {
195            Ok(writer) => *slot = Some(AsyncWriterRecovery::Opened(Box::new(writer))),
196            Err(failure) => {
197                let (error, stage, recovery) = failure.into_parts();
198                *slot = recovery.map(AsyncWriterRecovery::Rejected);
199                let state = match stage {
200                    OpenFailureStage::Preflight => WriteFailureState::NotPublished,
201                    OpenFailureStage::ProviderOpen => open_failure_state(&error),
202                    OpenFailureStage::OutcomeValidation => WriteFailureState::Indeterminate,
203                };
204                return Err(AsyncWriteAllOperationFailure::new(error, state, 0));
205            }
206        }
207    }
208    let writer = slot
209        .as_mut()
210        .and_then(AsyncWriterRecovery::opened_mut)
211        .expect("writer is retained after open");
212    if let Err(error) = writer.write_fully_async(bytes).await {
213        let error = contextual(filesystem, error, path);
214        let state = state_for(error.has_indeterminate_effect(), writer.state());
215        return Err(AsyncWriteAllOperationFailure::new(error, state, writer.written_bytes()));
216    }
217    if let Err(error) = writer.flush_async().await {
218        let error = contextual(filesystem, error, path);
219        let state = state_for(error.has_indeterminate_effect(), writer.state());
220        return Err(AsyncWriteAllOperationFailure::new(error, state, writer.written_bytes()));
221    }
222    match writer.commit_async().await {
223        Ok(outcome) => Ok(outcome),
224        Err(failure) => {
225            let (error, state) = failure.into_parts();
226            Err(AsyncWriteAllOperationFailure::new(error, state, writer.written_bytes()))
227        }
228    }
229}
230/// Restores filesystem and target context to a stream failure.
231/// # Parameters
232/// - `filesystem`: Filesystem whose provider stages execute this write.
233/// - `error`: Failure whose trusted filesystem context is being restored.
234/// - `path`: Target path used for error context and provider requests.
235fn contextual(filesystem: &AsyncFileSystem, error: IoError, path: &Path) -> FsError {
236    filesystem.core().enrich(
237        FsError::from_stream_io(error, FsOperation::Write, path),
238        Some(path),
239        FsOperation::Write,
240    )
241}
242/// Classifies a post-open stream failure using writer publication facts.
243/// # Parameters
244/// - `indeterminate`: Whether a completed stage left publication uncertain.
245/// - `state`: Publication state used to classify or retain this outcome.
246fn state_for(indeterminate: bool, state: WriterState) -> WriteFailureState {
247    if indeterminate {
248        WriteFailureState::Indeterminate
249    } else {
250        state.publication_failure_state()
251    }
252}
253/// Builds a repeated-execution error without changing historical facts.
254/// # Parameters
255/// - `path`: Target path used for error context and provider requests.
256/// - `filesystem`: Filesystem whose provider stages execute this write.
257fn invalid_state(path: &Path, filesystem: &AsyncFileSystem) -> FsError {
258    FsError::new(
259        FsErrorKind::InvalidState,
260        FsOperation::Write,
261        "async whole-file write cannot execute in its current state",
262    )
263    .with_path(path.clone())
264    .with_provider(filesystem.properties().info().provider_id())
265}
266
267impl Debug for AsyncWriteAllOperation {
268    /// Formats lifecycle facts without payload or provider session contents.
269    /// # Parameters
270    /// - `formatter`: Formatter receiving the diagnostic representation.
271    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
272        formatter
273            .debug_struct("AsyncWriteAllOperation")
274            .field("path", &self.path)
275            .field("state", &self.state)
276            .field("written_bytes", &self.recovery.written_bytes)
277            .field("has_recovery", &self.writer.is_some())
278            .finish()
279    }
280}