Skip to main content

qubit_fs/temp/
temp_resource.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2026 Haixing Hu.
4 *
5 *    SPDX-License-Identifier: Apache-2.0
6 *
7 *    Licensed under the Apache License, Version 2.0.
8 *
9 ******************************************************************************/
10//! Common temporary resource handle trait.
11
12use std::fmt::Debug;
13use std::sync::Arc;
14
15use crate::{
16    FileMetadata,
17    FileResource,
18    FileSystem,
19    FsPath,
20    FsResult,
21};
22
23/// Common lifecycle contract for filesystem-owned temporary resources.
24///
25/// `TempResource` captures the behavior shared by temporary files and
26/// temporary directories: both are owned by a filesystem, have a provider-local
27/// path, can be queried as ordinary resources, and carry cleanup responsibility
28/// until they are explicitly cleaned, persisted, or kept.
29pub trait TempResource: Debug + Send + Sync {
30    /// Returns the filesystem that owns this temporary resource.
31    ///
32    /// # Returns
33    /// Shared filesystem instance that owns the temporary path.
34    fn fs(&self) -> Arc<dyn FileSystem>;
35
36    /// Returns the provider-local temporary path.
37    ///
38    /// # Returns
39    /// Provider-local path of this temporary resource.
40    fn path(&self) -> &FsPath;
41
42    /// Converts this temporary handle to an ordinary bound file resource.
43    ///
44    /// # Returns
45    /// A [`FileResource`] bound to the same filesystem and path.
46    fn resource(&self) -> FileResource {
47        FileResource::new(self.fs(), self.path().clone())
48    }
49
50    /// Checks whether the temporary resource currently exists.
51    ///
52    /// # Returns
53    /// `true` if the owning filesystem confirms that the resource exists.
54    ///
55    /// # Errors
56    /// Returns [`crate::FsError`] if the owning filesystem cannot determine
57    /// existence.
58    fn exists(&self) -> FsResult<bool> {
59        self.fs().as_ref().exists(self.path())
60    }
61
62    /// Reads metadata for the temporary resource.
63    ///
64    /// # Returns
65    /// Metadata reported by the owning filesystem.
66    ///
67    /// # Errors
68    /// Returns [`crate::FsError`] if metadata cannot be read.
69    fn metadata(&self) -> FsResult<FileMetadata> {
70        self.fs().as_ref().path_metadata(self.path())
71    }
72
73    /// Explicitly cleans up the temporary resource.
74    ///
75    /// # Errors
76    /// Returns [`crate::FsError`] when cleanup fails.
77    fn cleanup(self: Box<Self>) -> FsResult<()>;
78
79    /// Keeps the temporary resource and disables automatic cleanup.
80    ///
81    /// # Returns
82    /// Path of the retained temporary resource.
83    ///
84    /// # Errors
85    /// Returns [`crate::FsError`] when the provider cannot release cleanup
86    /// responsibility.
87    fn keep(self: Box<Self>) -> FsResult<FsPath>;
88}