qubit_fs/temp/async_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//! Runtime-neutral asynchronous temporary-file facade handle.
9
10use std::pin::Pin;
11
12use crate::AsyncFileSystem;
13use crate::error::FsError;
14use crate::error::FsErrorKind;
15use crate::error::FsOperation;
16use crate::error::FsResult;
17use crate::metadata::AchievedAtomicity;
18use crate::metadata::AtomicityRequirement;
19use crate::path::Path;
20use crate::path::PathComponent;
21use crate::path::RelativePath;
22use crate::spi::AsyncTempResourceSpi;
23use crate::spi::PersistRequest;
24use crate::spi::SpiFuture;
25use crate::temp::PersistFailure;
26use crate::temp::PersistFailureState;
27use crate::temp::PersistOptions;
28use crate::temp::PersistOutcome;
29use crate::temp::TempResourceState;
30use crate::temp::internal::TempLifecycle;
31
32/// A facade-owned asynchronous temporary file.
33///
34/// # Examples
35///
36/// This example uses an isolated in-memory provider fixture.
37///
38/// ```rust
39/// # mod support { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/common/rustdoc_support.rs")); }
40/// # use support::*;
41/// # let (filesystem, _) = async_recording_spi::async_recording_file_system(Default::default());
42/// # poll_support::ready(async {
43/// use qubit_fs::temp::TempOptions;
44/// use qubit_fs::temp::TempResourceState;
45///
46/// let mut temporary = filesystem.create_temp_file(TempOptions::default()).await?;
47/// temporary.cleanup().await?;
48/// assert_eq!(TempResourceState::Cleaned, temporary.state());
49/// # Ok::<(), Box<dyn std::error::Error>>(())
50/// # }).unwrap();
51/// ```
52pub struct AsyncTempFile {
53 /// Facade that owns validation and persistence policy.
54 file_system: AsyncFileSystem,
55 /// Provider-local temporary path.
56 path: Path,
57 /// Pinned provider lifecycle session.
58 session: Pin<Box<dyn AsyncTempResourceSpi>>,
59 /// Current cleanup and publication lifecycle state.
60 lifecycle: TempLifecycle,
61 /// Human-readable resource kind used in lifecycle diagnostics.
62 resource_name: &'static str,
63}
64
65impl AsyncTempFile {
66 /// Binds a validated provider temporary session to its owning facade.
67 ///
68 /// # Parameters
69 /// - `file_system`: Facade that owns validation and persistence policy.
70 /// - `path`: Validated provider-local temporary path.
71 /// - `session`: Provider lifecycle session.
72 /// - `resource_name`: Human-readable resource kind used in lifecycle
73 /// diagnostics.
74 ///
75 /// # Returns
76 /// An owned asynchronous temporary-file handle.
77 pub(crate) fn new(
78 file_system: AsyncFileSystem,
79 path: Path,
80 session: Box<dyn AsyncTempResourceSpi>,
81 resource_name: &'static str,
82 ) -> Self {
83 Self {
84 file_system,
85 path,
86 session: Box::into_pin(session),
87 lifecycle: TempLifecycle::new(),
88 resource_name,
89 }
90 }
91
92 /// Returns the provider-local temporary path.
93 ///
94 /// # Returns
95 /// The validated path supplied by the provider.
96 #[inline]
97 #[must_use]
98 pub const fn path(&self) -> &Path {
99 &self.path
100 }
101
102 /// Returns the current ownership lifecycle state.
103 ///
104 /// # Returns
105 /// The handle's current cleanup and publication state.
106 #[inline]
107 pub const fn state(&self) -> TempResourceState {
108 self.lifecycle.state()
109 }
110
111 /// Returns one lexically safe child path.
112 ///
113 /// # Returns
114 /// The path formed by appending `component` to this temporary file path.
115 ///
116 /// # Parameters
117 /// - `component`: Validated component appended to the temporary path.
118 #[inline]
119 #[must_use]
120 pub fn child(&self, component: &PathComponent) -> Path {
121 self.path.child(component)
122 }
123
124 /// Returns one lexically safe descendant path.
125 ///
126 /// # Returns
127 /// The path formed by joining `relative` to this temporary file path.
128 ///
129 /// # Parameters
130 /// - `relative`: Validated relative path joined below the temporary path.
131 #[inline]
132 #[must_use]
133 pub fn descendant(&self, relative: &RelativePath) -> Path {
134 self.path.join(relative)
135 }
136
137 /// Asynchronously confirms cleanup of this temporary resource.
138 ///
139 /// Dropping an unpolled cleanup future changes nothing. Cancelling cleanup
140 /// after it returns `Pending` leaves source authority indeterminate while
141 /// preserving whether the target was already known to be published or not
142 /// published. Later `persist` or `keep` calls are rejected and retain that
143 /// distinction in their failure snapshot. This does not authorize another
144 /// source mutation.
145 ///
146 /// # Returns
147 /// A future resolving after provider cleanup is confirmed.
148 ///
149 /// # Errors
150 /// Resolves to an invalid-state error when cleanup is no longer legal, or
151 /// to the provider cleanup failure.
152 #[inline]
153 pub fn cleanup(&mut self) -> SpiFuture<'_, FsResult<()>> {
154 self.lifecycle("cannot be cleaned now", FsOperation::CleanupTemp, |session| {
155 session.cleanup()
156 })
157 }
158
159 /// Asynchronously publishes this temporary resource to a generated target.
160 ///
161 /// # Returns
162 /// A future resolving to the provider's confirmed publication outcome.
163 ///
164 /// # Errors
165 /// Resolves to an invalid-state error when the resource is no longer owned,
166 /// or to the provider ownership-transfer failure. An invalid-state failure
167 /// retains any previously confirmed publication target and recovery state.
168 #[inline]
169 pub fn keep(&mut self) -> SpiFuture<'_, Result<PersistOutcome, PersistFailure>> {
170 if self.lifecycle.state() != TempResourceState::Owned {
171 let error = self.invalid_state(FsOperation::KeepTemp, "cannot be kept now");
172 return Box::pin(async move {
173 Err(PersistFailure::new(error, self.lifecycle.failure_state())
174 .with_publication_target(self.lifecycle.publication_target()))
175 });
176 }
177 Box::pin(async move {
178 self.lifecycle.begin_pending();
179 match self.session.as_mut().keep().await {
180 Ok(outcome) => {
181 if let Err(error) = self.file_system.validate_temp_keep_target(&self.path, outcome.target()) {
182 return Err(PersistFailure::new(error, PersistFailureState::Indeterminate));
183 }
184 self.path = outcome.target().clone();
185 self.lifecycle.record_success(true, outcome.target().clone());
186 Ok(outcome)
187 }
188 Err(failure) => {
189 let (error, state) = failure.into_parts();
190 self.lifecycle.record_failure(state, error.target().cloned(), true);
191 let target = self.path.clone();
192 Err(PersistFailure::new(
193 error.with_operation(FsOperation::KeepTemp).with_missing_context(
194 &self.path,
195 Some(&target),
196 self.file_system.properties().info().provider_id(),
197 ),
198 state,
199 )
200 .with_publication_target(self.lifecycle.publication_target()))
201 }
202 }
203 })
204 }
205
206 /// Asynchronously persists this resource to a validated destination.
207 ///
208 /// # Parameters
209 /// - `target`: Validated destination path.
210 /// - `options`: Persistence atomicity and publication requirements.
211 ///
212 /// # Returns
213 /// A future resolving to the confirmed persistence outcome.
214 ///
215 /// # Errors
216 /// Resolves to a typed failure for invalid lifecycle state, failed local
217 /// preflight, provider failure, or provider contract violation. Rejected
218 /// repeated calls preserve the previously confirmed publication facts.
219 pub fn persist<'a>(
220 &'a mut self,
221 target: &'a Path,
222 options: PersistOptions,
223 ) -> SpiFuture<'a, Result<PersistOutcome, PersistFailure>> {
224 if self.lifecycle.state() != TempResourceState::Owned {
225 let error = self
226 .invalid_state(FsOperation::PersistTemp, "cannot be persisted now")
227 .with_target(target.clone());
228 return Box::pin(async move {
229 Err(PersistFailure::new(error, self.lifecycle.failure_state())
230 .with_publication_target(self.lifecycle.publication_target()))
231 });
232 }
233 if let Err(error) = self.file_system.preflight_temp_persist(&self.path, target, &options) {
234 return Box::pin(async move { Err(PersistFailure::new(error, PersistFailureState::NotPublished)) });
235 }
236 Box::pin(async move {
237 self.lifecycle.begin_pending();
238 let atomicity = options.atomicity();
239 let result = self
240 .session
241 .as_mut()
242 .persist(PersistRequest::new(target, options))
243 .await;
244 match &result {
245 Ok(outcome)
246 if outcome.target() == target
247 && !(atomicity == AtomicityRequirement::Required
248 && outcome.atomicity() != AchievedAtomicity::Atomic) =>
249 {
250 self.lifecycle.record_success(false, outcome.target().clone());
251 }
252 Ok(outcome) if outcome.target() != target => {
253 self.lifecycle
254 .record_failure(PersistFailureState::Indeterminate, Some(target.clone()), false);
255 }
256 Ok(_) => self.lifecycle.record_failure(
257 PersistFailureState::PublishedSourceIndeterminate,
258 Some(target.clone()),
259 false,
260 ),
261 Err(failure) => self
262 .lifecycle
263 .record_failure(failure.state(), Some(target.clone()), false),
264 }
265 match result {
266 Ok(outcome) if outcome.target() != target => Err(PersistFailure::new(
267 FsError::new(
268 FsErrorKind::ProviderContractViolation,
269 FsOperation::PersistTemp,
270 "provider reported a persistence target different from the request",
271 )
272 .with_path(self.path.clone())
273 .with_target(target.clone())
274 .with_provider(self.file_system.properties().info().provider_id()),
275 PersistFailureState::Indeterminate,
276 )),
277 Ok(outcome)
278 if atomicity == AtomicityRequirement::Required
279 && outcome.atomicity() != AchievedAtomicity::Atomic =>
280 {
281 Err(PersistFailure::new(
282 FsError::new(
283 FsErrorKind::ProviderContractViolation,
284 FsOperation::PersistTemp,
285 "provider reported non-atomic success for atomic-required persist",
286 )
287 .with_path(self.path.clone())
288 .with_target(target.clone())
289 .with_provider(self.file_system.properties().info().provider_id()),
290 PersistFailureState::PublishedSourceIndeterminate,
291 )
292 .with_publication_target(self.lifecycle.publication_target()))
293 }
294 Err(failure) => {
295 let (error, state) = failure.into_parts();
296 Err(PersistFailure::new(self.contextual_persist_error(error, target), state)
297 .with_publication_target(self.lifecycle.publication_target()))
298 }
299 Ok(outcome) => Ok(outcome),
300 }
301 })
302 }
303
304 /// Runs one lifecycle operation while retaining an indeterminate
305 /// cancellation state.
306 ///
307 /// # Type Parameters
308 /// - `F`: One-shot provider lifecycle operation.
309 ///
310 /// # Parameters
311 /// - `action`: Resource-specific action text used when the lifecycle state
312 /// rejects the operation.
313 /// - `operation`: Filesystem operation recorded in generated errors.
314 /// - `call`: Provider operation invoked after local state validation.
315 ///
316 /// # Returns
317 /// A future resolving to the provider lifecycle result.
318 ///
319 /// # Errors
320 /// Resolves to an invalid-state error or the provider lifecycle failure.
321 fn lifecycle<'a, F>(
322 &'a mut self,
323 action: &'static str,
324 operation: FsOperation,
325 call: F,
326 ) -> SpiFuture<'a, FsResult<()>>
327 where
328 F: FnOnce(Pin<&'a mut dyn AsyncTempResourceSpi>) -> SpiFuture<'a, FsResult<()>> + Send + 'a,
329 {
330 if !matches!(
331 self.lifecycle.state(),
332 TempResourceState::Owned | TempResourceState::CleanupRequired
333 ) {
334 let error = self.invalid_state(operation, action);
335 return Box::pin(async move { Err(error) });
336 }
337 Box::pin(async move {
338 let previous_lifecycle = self.lifecycle.clone();
339 self.lifecycle.begin_cleanup_pending();
340 let result = call(self.session.as_mut()).await;
341 self.lifecycle = previous_lifecycle;
342 match &result {
343 Ok(()) => self.lifecycle.record_cleanup_success(),
344 Err(error) => self.lifecycle.record_cleanup_error(error),
345 }
346 result.map_err(|error| {
347 error.with_operation(operation).with_missing_context(
348 &self.path,
349 None,
350 self.file_system.properties().info().provider_id(),
351 )
352 })
353 })
354 }
355
356 /// Builds an invalid-state error for this handle.
357 ///
358 /// # Parameters
359 /// - `operation`: Rejected lifecycle operation.
360 /// - `action`: Stable action text describing the rejected operation.
361 ///
362 /// # Returns
363 /// A contextual invalid-state error containing the temporary path and
364 /// provider.
365 fn invalid_state(&self, operation: FsOperation, action: &str) -> FsError {
366 let message = format!("{} {}", self.resource_name, action);
367 FsError::new(FsErrorKind::InvalidState, operation, &message)
368 .with_path(self.path.clone())
369 .with_provider(self.file_system.properties().info().provider_id())
370 }
371
372 /// Adds only missing facade facts to a provider persistence error.
373 ///
374 /// # Parameters
375 /// - `error`: Provider persistence error.
376 /// - `target`: Requested persistence target.
377 ///
378 /// # Returns
379 /// The error enriched with missing operation, path, target, and provider
380 /// context.
381 fn contextual_persist_error(&self, error: FsError, target: &Path) -> FsError {
382 error.with_operation(FsOperation::PersistTemp).with_missing_context(
383 &self.path,
384 Some(target),
385 self.file_system.properties().info().provider_id(),
386 )
387 }
388}
389
390impl Drop for AsyncTempFile {
391 /// Invokes provider-local cancellation when this handle still owns it.
392 ///
393 /// This nonblocking hook does not start asynchronous cleanup or confirm
394 /// that remote cleanup completed.
395 fn drop(&mut self) {
396 if matches!(
397 self.lifecycle.state(),
398 TempResourceState::Owned | TempResourceState::CleanupRequired
399 ) {
400 self.session.as_mut().cancel_on_drop();
401 }
402 }
403}