Skip to main content

qubit_fs/write/
rejected_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;
13
14use crate::error::FsError;
15use crate::error::FsErrorKind;
16use crate::error::FsOperation;
17use crate::error::FsResult;
18use crate::error::RecoveryCleanupState;
19use crate::facade::internal::RecoveryCleanupGuard;
20use crate::path::Path;
21use crate::spi::FileWriterSpi;
22use crate::write::WriteAbortOutcome;
23
24/// Isolated cleanup ownership after a provider returned an invalid identity.
25///
26/// This handle cannot write or publish. Cleanup acts only on resources owned by
27/// its session, never on a diagnostic path. Drop performs no explicit cleanup
28/// or cancellation hook; retain this handle until cleanup is confirmed.
29///
30/// ```compile_fail
31/// use qubit_fs::write::RejectedWriter;
32/// fn cannot_publish(mut recovery: RejectedWriter) {
33///     recovery.commit();
34/// }
35/// ```
36///
37/// # Examples
38///
39/// ```rust
40/// use qubit_fs::error::FsResult;
41/// use qubit_fs::write::RejectedWriter;
42/// use qubit_fs::write::WriteAbortOutcome;
43///
44/// fn clean_up(recovery: &mut RejectedWriter) -> FsResult<WriteAbortOutcome> {
45///     // Keep the handle available if cleanup returns an error.
46///     recovery.abort()
47/// }
48/// ```
49#[must_use = "explicitly clean or retain the isolated recovery session"]
50pub struct RejectedWriter {
51    /// The actual provider session, retained independently of cleanup futures.
52    session: Box<dyn FileWriterSpi>,
53    /// Last observed cleanup state, never a publication snapshot.
54    state: RecoveryCleanupState,
55    /// Trusted configured provider identifier.
56    provider: Box<str>,
57    /// Requested path, never the unvalidated provider identity.
58    path: Option<Path>,
59}
60impl RejectedWriter {
61    /// Takes ownership of a rejected session and trusted request context.
62    /// # Parameters
63    /// - `session`: Provider session whose ownership transfers to this wrapper.
64    /// - `provider`: Trusted provider identity attached to cleanup errors.
65    /// - `path`: Target path used for error context and provider requests.
66    pub(crate) fn new(session: Box<dyn FileWriterSpi>, provider: &str, path: Option<Path>) -> Self {
67        Self {
68            session,
69            state: RecoveryCleanupState::Pending,
70            provider: provider.into(),
71            path,
72        }
73    }
74    /// Returns cleanup progress; errors and cancellation do not release
75    /// ownership.
76    ///
77    /// # Returns
78    /// The latest cleanup state: `Pending` before cleanup, `Running` while an
79    /// attempt is active, `Completed` after confirmed cleanup, or
80    /// `Indeterminate` when cleanup did not finish conclusively. This cleanup
81    /// state is independent of destination publication certainty; an
82    /// `Ok(WriteAbortOutcome::Indeterminate)` confirms cleanup while leaving
83    /// destination publication unknown.
84    #[must_use]
85    #[inline]
86    pub const fn cleanup_state(&self) -> RecoveryCleanupState {
87        self.state
88    }
89
90    /// Explicitly cleans resources actually owned by this isolated session.
91    ///
92    /// A failed attempt retains the session for explicit retry or
93    /// reconciliation. This synchronous method may block in provider I/O.
94    ///
95    /// # Errors
96    /// Returns InvalidState after confirmed cleanup, or the contextual provider
97    /// error without replacing the original opening failure.
98    ///
99    /// # Returns
100    /// The outcome reported by the provider after cleanup completes.
101    pub fn abort(&mut self) -> FsResult<WriteAbortOutcome> {
102        if self.state == RecoveryCleanupState::Completed {
103            return Err(self.contextual_error(FsError::new(
104                FsErrorKind::InvalidState,
105                FsOperation::AbortWriter,
106                "isolated session cleanup already completed",
107            )));
108        }
109        let mut guard = RecoveryCleanupGuard::start(&mut self.state);
110        let result = self.session.abort();
111        guard.finish(result.is_ok());
112        drop(guard);
113        result.map_err(|error| self.contextual_error(error))
114    }
115    /// Adds only trusted request context to a cleanup error.
116    /// # Parameters
117    /// - `error`: Failure whose trusted filesystem context is being restored.
118    fn contextual_error(&self, error: FsError) -> FsError {
119        error.with_trusted_cleanup_context(FsOperation::AbortWriter, self.path.as_ref(), &self.provider)
120    }
121}
122impl Debug for RejectedWriter {
123    /// Omits the session and unvalidated provider identity.
124    /// # Parameters
125    /// - `f`: Formatter receiving the diagnostic representation.
126    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
127        f.debug_struct("RejectedWriter")
128            .field("cleanup_state", &self.state)
129            .finish_non_exhaustive()
130    }
131}