Skip to main content

qubit_fs_local/registry/
local_file_system_provider.rs

1// =============================================================================
2//    Copyright (c) 2025 - 2026 Haixing Hu.
3//
4//    SPDX-License-Identifier: Apache-2.0
5//
6//    Licensed under the Apache License, Version 2.0.
7// =============================================================================
8//! Registry provider for host and rooted local filesystems.
9
10use std::path::Path;
11use std::sync::OnceLock;
12
13use qubit_fs::Path as FsPath;
14use qubit_fs::error::FsError;
15use qubit_fs::error::FsErrorKind;
16use qubit_fs::error::FsOperation;
17use qubit_fs::metadata::FileSystemId;
18use qubit_fs::path::Uri;
19use qubit_fs_registry::FileSystemConfig;
20use qubit_fs_registry::FileSystemResolution;
21use qubit_fs_registry::FileSystemSpec;
22use qubit_spi::ProviderDescriptor;
23use qubit_spi::ProviderId;
24use qubit_spi::ProviderMetadata;
25use qubit_spi::ServiceProvider;
26use qubit_spi::error::ProviderFailure;
27
28use super::internal::LocalProviderMode;
29use super::local_file_uri_path;
30use crate::LocalFileSystems;
31use crate::LocalResourcePolicy;
32use crate::LocalTempCleanupControl;
33use crate::constants::FILE_SCHEME;
34use crate::constants::LOCAL_PROVIDER_ID;
35
36/// Creates local filesystem resolutions for accepted `file:` configurations.
37///
38/// # Examples
39///
40/// ```
41/// # #[cfg(feature = "registry")]
42/// use qubit_fs::path::ConnectionUri;
43/// # #[cfg(feature = "registry")]
44/// use qubit_fs_registry::{FileSystemConfig, FileSystemRegistry};
45/// # #[cfg(feature = "registry")]
46/// use qubit_fs_local::{LocalFileSystemProvider, LocalResourcePolicy};
47/// # #[cfg(feature = "registry")]
48/// let registry = FileSystemRegistry::default();
49/// # #[cfg(feature = "registry")]
50/// registry.register(LocalFileSystemProvider::host(LocalResourcePolicy::standard()))?;
51/// # #[cfg(feature = "registry")]
52/// let config = FileSystemConfig::new(ConnectionUri::parse("file:///reports/summary.csv")?);
53/// # #[cfg(feature = "registry")]
54/// let resolution = registry.resolve_config(&config)?;
55/// # #[cfg(feature = "registry")]
56/// assert_eq!(resolution.path().as_str(), "/reports/summary.csv");
57/// # #[cfg(feature = "registry")]
58/// assert_eq!(resolution.file_system().properties().info().provider_id(), "local-file");
59/// # #[cfg(feature = "registry")]
60/// # Ok::<(), Box<dyn std::error::Error>>(())
61/// ```
62#[must_use]
63pub struct LocalFileSystemProvider {
64    /// Authority mode used for every configuration resolved by this provider.
65    mode: LocalProviderMode,
66    /// Descriptor used to register and validate this provider instance.
67    descriptor: Option<ProviderDescriptor>,
68    /// Immutable resource policy selected by the embedding application.
69    policy: LocalResourcePolicy,
70    /// Shared cleanup limits used by resolutions and retained rooted sessions.
71    temp_cleanup_control: OnceLock<LocalTempCleanupControl>,
72}
73
74impl Clone for LocalFileSystemProvider {
75    /// Clones the provider while preserving its mode, descriptor, policy, and
76    /// current shared cleanup configuration.
77    fn clone(&self) -> Self {
78        Self {
79            mode: self.mode.clone(),
80            descriptor: self.descriptor.clone(),
81            policy: self.policy,
82            temp_cleanup_control: OnceLock::from(self.temp_cleanup_control()),
83        }
84    }
85}
86
87impl LocalFileSystemProvider {
88    /// Creates a host-wide local provider.
89    ///
90    /// # Parameters
91    ///
92    /// - `policy`: Resource ceilings applied to local filesystem operations.
93    ///
94    /// # Returns
95    ///
96    /// A provider that resolves absolute `file:` paths against the process
97    /// host filesystem.
98    ///
99    /// # Examples
100    ///
101    /// ```
102    /// # #[cfg(feature = "registry")]
103    /// use qubit_fs::path::ConnectionUri;
104    /// # #[cfg(feature = "registry")]
105    /// use qubit_fs_registry::{FileSystemConfig, FileSystemRegistry};
106    /// # #[cfg(feature = "registry")]
107    /// use qubit_fs_local::{LocalFileSystemProvider, LocalResourcePolicy};
108    /// # #[cfg(feature = "registry")]
109    /// let registry = FileSystemRegistry::default();
110    /// # #[cfg(feature = "registry")]
111    /// registry.register(LocalFileSystemProvider::host(LocalResourcePolicy::standard()))?;
112    /// # #[cfg(feature = "registry")]
113    /// let config = FileSystemConfig::new(ConnectionUri::parse("file:///reports/summary.csv")?);
114    /// # #[cfg(feature = "registry")]
115    /// let resolution = registry.resolve_config(&config)?;
116    /// # #[cfg(feature = "registry")]
117    /// assert_eq!(resolution.path().as_str(), "/reports/summary.csv");
118    /// # #[cfg(feature = "registry")]
119    /// assert_eq!(resolution.file_system().properties().info().provider_id(), "local-file");
120    /// # #[cfg(feature = "registry")]
121    /// # Ok::<(), Box<dyn std::error::Error>>(())
122    /// ```
123    pub const fn host(policy: LocalResourcePolicy) -> Self {
124        Self {
125            mode: LocalProviderMode::Host,
126            descriptor: None,
127            policy,
128            temp_cleanup_control: OnceLock::new(),
129        }
130    }
131
132    /// Creates a provider restricted to `root` with the supplied stable
133    /// identity.
134    ///
135    /// # Parameters
136    ///
137    /// - `id`: Stable identity exposed by each resolved rooted filesystem.
138    /// - `root`: Native directory retained as the provider authority.
139    ///
140    /// # Returns
141    ///
142    /// A provider that resolves accepted paths below the opened `root`.
143    /// The default descriptor is `local-file` with the `file` URI alias.
144    ///
145    /// # Errors
146    ///
147    /// Returns an error when `root` cannot be opened as the provider's native
148    /// authority. No provider is returned in that case, so it cannot be
149    /// registered or considered by a later fallback resolution.
150    #[inline]
151    pub fn rooted(id: FileSystemId, root: &Path, policy: LocalResourcePolicy) -> Result<Self, FsError> {
152        Self::rooted_with_descriptor(default_descriptor(), id, root, policy)
153    }
154
155    /// Creates a rooted provider with caller-specified registration metadata.
156    ///
157    /// The descriptor ID is also exposed by the configured filesystem, so
158    /// multiple rooted local providers can coexist in one registry when they
159    /// use distinct IDs and aliases. The supplied descriptor is retained as
160    /// provided, including its aliases; this constructor does not add the
161    /// default `file` alias.
162    ///
163    /// # Parameters
164    ///
165    /// - `descriptor`: Registration identity and URI aliases to retain.
166    /// - `id`: Stable filesystem identity exposed by resolved instances.
167    /// - `root`: Native directory retained as provider authority.
168    /// - `policy`: Recursive resource and lifecycle policy.
169    ///
170    /// # Returns
171    ///
172    /// A provider retaining the opened rooted authority and descriptor.
173    ///
174    /// # Errors
175    ///
176    /// Returns an error when the root cannot be opened or the provider
177    /// identity cannot be assembled.
178    pub fn rooted_with_descriptor(
179        descriptor: ProviderDescriptor,
180        id: FileSystemId,
181        root: &Path,
182        policy: LocalResourcePolicy,
183    ) -> Result<Self, FsError> {
184        let temp_cleanup_control = LocalTempCleanupControl::new(None);
185        LocalFileSystems::rooted_with_provider_id_and_temp_cleanup(
186            id,
187            descriptor.id(),
188            root,
189            policy,
190            temp_cleanup_control.clone(),
191        )
192        .map(|file_system| Self {
193            mode: LocalProviderMode::Rooted { file_system },
194            descriptor: Some(descriptor),
195            policy,
196            temp_cleanup_control: OnceLock::from(temp_cleanup_control),
197        })
198    }
199
200    /// Returns a clone of the shared temporary cleanup configuration.
201    ///
202    /// Host resolutions, rooted resources, and provider clones use this shared
203    /// control. Retain the returned handle to adjust the budget for subsequent
204    /// cleanup attempts. An attempt already in progress uses its starting
205    /// snapshot; setting `None` explicitly selects unbounded cleanup. This
206    /// accessor does not restore cleanup authority for an indeterminate source.
207    #[must_use]
208    pub fn temp_cleanup_control(&self) -> LocalTempCleanupControl {
209        self.temp_cleanup_control
210            .get_or_init(|| LocalTempCleanupControl::new(None))
211            .clone()
212    }
213
214    /// Validates and decodes a registry configuration into a logical path and
215    /// URI.
216    ///
217    /// # Parameters
218    ///
219    /// - `config`: Registry configuration supplied to this provider.
220    ///
221    /// # Returns
222    ///
223    /// The decoded absolute logical path and its parsed `file:` URI.
224    ///
225    /// # Errors
226    ///
227    /// Returns an unsupported failure for non-`file` schemes before checking
228    /// provider-specific configuration, or an invalid-configuration failure
229    /// for malformed `file:` configurations.
230    fn decode_config(config: &FileSystemConfig) -> Result<(FsPath, Uri), ProviderFailure<FsError>> {
231        if config.uri().scheme() != FILE_SCHEME {
232            return Err(unsupported_scheme(
233                "local filesystem provider requires the file URI scheme",
234            ));
235        }
236        let uri = config
237            .uri()
238            .try_to_uri()
239            .map_err(ProviderFailure::invalid_configuration)?;
240        if !config.options().is_empty() || !config.metadata().is_empty() || config.credential().is_some() {
241            return Err(invalid_options(
242                "local filesystem provider does not support provider options, metadata, or credentials",
243            ));
244        }
245        if uri.authority().is_some_and(|authority| !authority.is_empty()) {
246            return Err(invalid_options(
247                "local filesystem provider does not support remote URI authorities",
248            ));
249        }
250        if uri.query().is_some() {
251            return Err(invalid_options(
252                "local filesystem provider does not support URI queries",
253            ));
254        }
255        let path = local_file_uri_path::decode(uri.path())?;
256        if !path.is_absolute() {
257            return Err(invalid_path("local file URI path must be absolute"));
258        }
259        let canonical = local_file_uri_path::canonical_uri(&path)?;
260        Ok((path, canonical))
261    }
262}
263
264impl ProviderMetadata for LocalFileSystemProvider {
265    /// Returns the stable local-provider descriptor and the `file` alias.
266    ///
267    /// # Returns
268    ///
269    /// The retained registration descriptor. Host providers and rooted
270    /// providers created by [`Self::rooted`] use the default `local-file`
271    /// descriptor with the `file` alias; [`Self::rooted_with_descriptor`]
272    /// preserves the caller-supplied descriptor unchanged.
273    #[inline]
274    fn descriptor(&self) -> ProviderDescriptor {
275        self.descriptor.clone().unwrap_or_else(default_descriptor)
276    }
277}
278
279/// Builds the default local provider descriptor from shared identities.
280///
281/// # Returns
282///
283/// The static `local-file` descriptor with the `file` URI alias.
284#[inline]
285fn default_descriptor() -> ProviderDescriptor {
286    ProviderDescriptor::new(ProviderId::new(LOCAL_PROVIDER_ID).expect("static provider identity is valid"))
287        .with_aliases([FILE_SCHEME])
288        .expect("static provider alias is valid")
289}
290
291impl ServiceProvider<FileSystemSpec> for LocalFileSystemProvider {
292    /// Resolves one accepted `file:` configuration to a concrete facade.
293    ///
294    /// # Parameters
295    ///
296    /// - `config`: Provider configuration to validate and resolve.
297    ///
298    /// # Returns
299    ///
300    /// A concrete filesystem, decoded logical path, and canonical URI.
301    ///
302    /// # Errors
303    ///
304    /// Returns an invalid-configuration failure for unsupported configuration
305    /// shapes or an initialization failure when the selected local filesystem
306    /// cannot be opened or assembled.
307    fn create_configured(&self, config: &FileSystemConfig) -> Result<FileSystemResolution, ProviderFailure<FsError>> {
308        let (path, uri) = Self::decode_config(config)?;
309        let file_system = match &self.mode {
310            LocalProviderMode::Host => {
311                LocalFileSystems::host_with_temp_cleanup(self.policy, self.temp_cleanup_control())
312            }
313            LocalProviderMode::Rooted { file_system } => Ok(file_system.clone()),
314        }
315        .map_err(ProviderFailure::initialization_failed)?;
316        FileSystemResolution::try_new(file_system, path, uri).map_err(ProviderFailure::initialization_failed)
317    }
318}
319
320/// Builds an invalid-options provider failure.
321///
322/// # Parameters
323///
324/// - `message`: Static detail explaining the rejected configuration shape.
325///
326/// # Returns
327///
328/// An invalid-configuration failure carrying an `InvalidOptions` filesystem
329/// error.
330#[inline]
331fn invalid_options(message: &'static str) -> ProviderFailure<FsError> {
332    ProviderFailure::invalid_configuration(FsError::new(
333        FsErrorKind::InvalidOptions,
334        FsOperation::Provider,
335        message,
336    ))
337}
338
339/// Builds an unsupported-scheme provider failure.
340///
341/// # Parameters
342///
343/// - `message`: Static detail explaining why the URI scheme is unsupported.
344///
345/// # Returns
346///
347/// An unsupported failure carrying an `UnsupportedOperation` filesystem
348/// error, allowing an `OnAbsence` provider chain to continue.
349#[inline]
350fn unsupported_scheme(message: &'static str) -> ProviderFailure<FsError> {
351    ProviderFailure::unsupported(FsError::new(
352        FsErrorKind::UnsupportedOperation,
353        FsOperation::Provider,
354        message,
355    ))
356}
357
358/// Builds an invalid-path provider failure.
359///
360/// # Parameters
361///
362/// - `message`: Static detail explaining why the path is invalid.
363///
364/// # Returns
365///
366/// An invalid-configuration failure carrying an `InvalidPath` filesystem
367/// error.
368#[inline]
369pub(super) fn invalid_path(message: &'static str) -> ProviderFailure<FsError> {
370    ProviderFailure::invalid_configuration(FsError::new(FsErrorKind::InvalidPath, FsOperation::Provider, message))
371}