Skip to main content

qubit_fs/write/
rejected_async_writer.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//! Explicit cleanup authority for a rejected write session.
9
10use std::fmt::Debug;
11use std::fmt::Formatter;
12use std::fmt::Result as FmtResult;
13use std::pin::Pin;
14
15use crate::error::FsError;
16use crate::error::FsErrorKind;
17use crate::error::FsOperation;
18use crate::error::FsResult;
19use crate::error::RecoveryCleanupState;
20use crate::facade::internal::RecoveryCleanupGuard;
21use crate::path::Path;
22use crate::spi::AsyncFileWriteSession;
23use crate::spi::SpiFuture;
24use crate::write::WriteAbortOutcome;
25
26/// Isolated cleanup ownership after a provider returned an invalid identity.
27///
28/// This handle cannot write or publish. Cleanup acts only on resources owned by
29/// its session, never on a diagnostic path. Drop performs no explicit cleanup
30/// or cancellation hook; retain this handle until cleanup is confirmed.
31///
32/// ```compile_fail
33/// use qubit_fs::write::RejectedAsyncWriter;
34/// fn cannot_publish(mut recovery: RejectedAsyncWriter) {
35///     recovery.commit();
36/// }
37/// ```
38///
39/// # Examples
40///
41/// ```rust
42/// # mod support { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/common/rustdoc_support.rs")); }
43/// # use support::*;
44/// # let (filesystem, _) = async_recording_spi::async_recording_file_system(
45/// #     async_recording_spi::AsyncRecordingConfig {
46/// #         invalid_opened_identity: true,
47/// #         ..Default::default()
48/// #     },
49/// # );
50/// # poll_support::ready(async {
51/// use qubit_fs::Path;
52/// use qubit_fs::write::AsyncWriterRecovery;
53/// use qubit_fs::write::WriteOptions;
54///
55/// let mut operation = filesystem.begin_write_all(
56///     Path::parse("/report")?, b"bytes".to_vec(), WriteOptions::default(),
57/// )?;
58/// let failure = operation
59///     .execute()
60///     .await
61///     .expect_err("invalid provider identity");
62/// let mut recovery = operation.take_recovery().expect("retained rejected session");
63///
64/// if let AsyncWriterRecovery::Rejected(writer) = &mut recovery {
65///     assert!(writer.abort_async().await.is_ok());
66/// }
67/// drop(failure);
68/// # Ok::<(), Box<dyn std::error::Error>>(())
69/// # }).unwrap();
70/// ```
71#[must_use = "explicitly clean or retain the isolated recovery session"]
72pub struct RejectedAsyncWriter {
73    /// The actual provider session, retained independently of cleanup futures.
74    session: Pin<Box<dyn AsyncFileWriteSession>>,
75    /// Last observed cleanup state, never a publication snapshot.
76    state: RecoveryCleanupState,
77    /// Trusted configured provider identifier.
78    provider: Box<str>,
79    /// Requested path, never the unvalidated provider identity.
80    path: Option<Path>,
81}
82impl RejectedAsyncWriter {
83    /// Takes ownership of a rejected session and trusted request context.
84    /// # Parameters
85    /// - `session`: Provider session whose ownership transfers to this wrapper.
86    /// - `provider`: Trusted provider identity attached to cleanup errors.
87    /// - `path`: Target path used for error context and provider requests.
88    pub(crate) fn new(session: Box<dyn AsyncFileWriteSession>, provider: &str, path: Option<Path>) -> Self {
89        Self {
90            session: Box::into_pin(session),
91            state: RecoveryCleanupState::Pending,
92            provider: provider.into(),
93            path,
94        }
95    }
96    /// Returns cleanup progress; errors and cancellation do not release
97    /// ownership.
98    #[must_use]
99    #[inline]
100    pub const fn cleanup_state(&self) -> RecoveryCleanupState {
101        self.state
102    }
103
104    /// Explicitly cleans resources actually owned by this isolated session.
105    ///
106    /// A failed attempt retains the session for explicit retry or
107    /// reconciliation. No work occurs until polled. Dropping a polled,
108    /// unfinished future records Indeterminate; dropping an unpolled future
109    /// leaves the state unchanged. Cleanup completion is independent of
110    /// destination publication certainty:
111    /// `Ok(WriteAbortOutcome::Indeterminate)` confirms cleanup while
112    /// leaving the destination state unknown.
113    ///
114    /// # Errors
115    /// Returns InvalidState after confirmed cleanup, or the contextual provider
116    /// error without replacing the original opening failure.
117    pub fn abort_async(&mut self) -> SpiFuture<'_, FsResult<WriteAbortOutcome>> {
118        Box::pin(async move {
119            if self.state == RecoveryCleanupState::Completed {
120                return Err(self.contextual_error(FsError::new(
121                    FsErrorKind::InvalidState,
122                    FsOperation::AbortWriter,
123                    "isolated session cleanup already completed",
124                )));
125            }
126            let mut guard = RecoveryCleanupGuard::start(&mut self.state);
127            let result = self.session.as_mut().abort_async().await;
128            guard.finish(result.is_ok());
129            drop(guard);
130            result.map_err(|error| self.contextual_error(error))
131        })
132    }
133    /// Adds only trusted request context to a cleanup error.
134    /// # Parameters
135    /// - `error`: Failure whose trusted filesystem context is being restored.
136    fn contextual_error(&self, error: FsError) -> FsError {
137        error.with_trusted_cleanup_context(FsOperation::AbortWriter, self.path.as_ref(), &self.provider)
138    }
139}
140impl Debug for RejectedAsyncWriter {
141    /// Omits the session and unvalidated provider identity.
142    /// # Parameters
143    /// - `f`: Formatter receiving the diagnostic representation.
144    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
145        f.debug_struct("RejectedAsyncWriter")
146            .field("cleanup_state", &self.state)
147            .finish_non_exhaustive()
148    }
149}