qubit_fs/temp/temp_file.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//! Provider-backed temporary file lifecycle handle.
9
10use std::fmt::Debug;
11use std::fmt::Formatter;
12use std::fmt::Result as FmtResult;
13
14use crate::FileSystem;
15use crate::error::FsResult;
16use crate::path::Path;
17use crate::spi::TempResourceSpi;
18use crate::temp::PersistFailure;
19use crate::temp::PersistOptions;
20use crate::temp::PersistOutcome;
21use crate::temp::TempResourceState;
22use crate::temp::internal::SyncTempResource;
23
24/// Temporary file retaining the provider session until its lifecycle completes.
25///
26/// Dropping this synchronous handle while its state is
27/// [`TempResourceState::Owned`] or [`TempResourceState::CleanupRequired`] calls
28/// provider cleanup synchronously on the current thread. Cleanup may perform
29/// I/O and block, and any cleanup error is ignored. Call [`Self::cleanup`]
30/// explicitly when the result matters; if it fails and leaves the state as
31/// `CleanupRequired`, dropping the handle may make another best-effort cleanup
32/// attempt. The facade does not call cleanup on drop in the `Cleaned`,
33/// `Persisted`, `Kept`, or `Indeterminate` states.
34///
35/// This contract applies to synchronous handles. Async handles use their
36/// separate `cancel_on_drop` behavior, and rejected handles use their isolated
37/// recovery contract; neither implies synchronous cleanup by dropping this
38/// type.
39///
40/// # Examples
41///
42/// ```rust
43/// use qubit_fs::FileSystem;
44/// use qubit_fs::temp::{TempOptions, TempResourceState};
45///
46/// fn create_and_cleanup(filesystem: &FileSystem) -> Result<(), Box<dyn std::error::Error>> {
47/// let mut temporary = filesystem.create_temp_file(TempOptions::default())?;
48/// assert_eq!(TempResourceState::Owned, temporary.state());
49/// temporary.cleanup()?;
50/// assert_eq!(TempResourceState::Cleaned, temporary.state());
51/// Ok(())
52/// }
53/// ```
54pub struct TempFile {
55 /// Shared synchronous resource lifecycle.
56 core: SyncTempResource,
57}
58
59impl TempFile {
60 /// Creates the facade handle from validated provider parts.
61 ///
62 /// # Parameters
63 /// - `filesystem`: Facade that owns validation and persistence policy.
64 /// - `path`: Validated provider-local temporary file path.
65 /// - `session`: Provider lifecycle session for this file.
66 ///
67 /// # Returns
68 /// An owned temporary-file handle.
69 pub(crate) fn new(filesystem: FileSystem, path: Path, session: Box<dyn TempResourceSpi>) -> Self {
70 Self {
71 core: SyncTempResource::new(
72 filesystem,
73 path,
74 session,
75 "temporary file cannot perform this lifecycle operation",
76 ),
77 }
78 }
79
80 /// Returns the temporary logical path.
81 ///
82 /// # Returns
83 /// The provider-local path retained by this handle.
84 #[inline]
85 #[must_use]
86 pub const fn path(&self) -> &Path {
87 self.core.path()
88 }
89
90 /// Returns the resource lifecycle state.
91 ///
92 /// # Returns
93 /// The current ownership and cleanup state.
94 #[inline]
95 pub const fn state(&self) -> TempResourceState {
96 self.core.state()
97 }
98
99 /// Persists this temporary file to `target`.
100 ///
101 /// # Parameters
102 /// - `target`: Destination path validated by the owning filesystem.
103 /// - `options`: Atomicity and publication requirements.
104 ///
105 /// # Returns
106 /// The provider-confirmed publication outcome.
107 ///
108 /// # Errors
109 /// Returns a typed failure for invalid lifecycle state, failed preflight,
110 /// provider failure, or a provider contract violation.
111 #[allow(clippy::result_large_err)]
112 pub fn persist(&mut self, target: &Path, options: PersistOptions) -> Result<PersistOutcome, PersistFailure> {
113 self.core.persist(target, options)
114 }
115
116 /// Publishes this temporary file to the provider-generated target.
117 ///
118 /// # Returns
119 /// The provider-confirmed publication outcome and generated target.
120 ///
121 /// # Errors
122 /// Returns a typed failure when ownership is unavailable, provider
123 /// publication fails, or the provider returns an invalid target.
124 #[allow(clippy::result_large_err)]
125 pub fn keep(&mut self) -> Result<PersistOutcome, PersistFailure> {
126 self.core.keep()
127 }
128
129 /// Cleans the source and releases the session responsibility.
130 ///
131 /// Call this method when cleanup success or failure must be observed.
132 /// Unlike dropping an owned handle, this returns the provider result. If
133 /// cleanup fails while the state remains `CleanupRequired`, a later drop
134 /// may make another best-effort attempt.
135 ///
136 /// # Errors
137 /// Returns an invalid-state error when cleanup is no longer legal, or the
138 /// provider cleanup error when cleanup cannot be confirmed.
139 pub fn cleanup(&mut self) -> FsResult<()> {
140 self.core.cleanup()
141 }
142}
143
144impl Debug for TempFile {
145 /// Formats the handle path and lifecycle state without exposing provider
146 /// internals.
147 ///
148 /// # Parameters
149 /// - `f`: Formatter that receives the debug representation.
150 ///
151 /// # Returns
152 /// `Ok(())` when formatting succeeds, or the formatter's error.
153 #[inline]
154 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
155 f.debug_struct("TempFile")
156 .field("path", self.core.path())
157 .field("state", &self.core.state())
158 .finish_non_exhaustive()
159 }
160}