Skip to main content

qubit_fs/
file_system_properties.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// facade.
9
10//! Immutable filesystem property snapshots used by facades.
11
12use crate::error::FsError;
13use crate::error::FsErrorKind;
14use crate::error::FsOperation;
15use crate::error::FsResult;
16use crate::metadata::FileSystemCapabilities;
17use crate::metadata::FileSystemCapability;
18use crate::metadata::FileSystemInfo;
19use crate::metadata::FileSystemLimits;
20use crate::metadata::SymlinkPolicy;
21use crate::path::Path;
22use crate::path::PathConstraints;
23use crate::path::PathForm;
24use crate::path::PathSemantics;
25use crate::spi::ProviderOperation;
26use crate::spi::ProviderProperties;
27
28/// Immutable construction-time properties cached by a filesystem facade.
29///
30/// A facade exposes the provider's validated identity, limits, path rules, and
31/// effective capabilities through one stable snapshot. The capability set may
32/// include facts derived by the facade; it is therefore not necessarily a
33/// byte-for-byte copy of the provider declaration.
34///
35/// # Examples
36///
37/// ```
38/// use qubit_fs::metadata::{FileSystemCapabilities, FileSystemId, FileSystemInfo,
39///     FileSystemLimit, FileSystemLimits, SymlinkPolicy};
40/// use qubit_fs::path::{PathConstraints, PathForm, PathSemantics};
41/// use qubit_fs::metadata::FileSystemProperties;
42///
43/// let properties = FileSystemProperties::new(
44///     FileSystemInfo::new(FileSystemId::new("example")?, "example", PathSemantics::Hierarchical),
45///     FileSystemCapabilities::new(),
46///     FileSystemLimits::unknown().with_max_path_text_bytes(FileSystemLimit::Maximum(4096)),
47///     PathConstraints::absolute(),
48///     SymlinkPolicy::Reject,
49/// )?;
50/// assert_eq!(properties.info().provider_id(), "example");
51/// assert_eq!(properties.limits().max_path_text_bytes(), FileSystemLimit::Maximum(4096));
52/// assert_eq!(properties.path_constraints().form(), PathForm::Absolute);
53/// # Ok::<(), qubit_fs::FsError>(())
54/// ```
55#[derive(Clone, Debug)]
56pub struct FileSystemProperties {
57    /// Stable filesystem information.
58    info: FileSystemInfo,
59    /// Stable advertised capabilities.
60    capabilities: FileSystemCapabilities,
61    /// Stable provider limits.
62    limits: FileSystemLimits,
63    /// Accepted logical path forms.
64    path_constraints: PathConstraints,
65    /// Provider-declared symbolic-link traversal policy.
66    symlink_policy: SymlinkPolicy,
67}
68
69impl FileSystemProperties {
70    /// Builds and validates an immutable filesystem property snapshot.
71    ///
72    /// This method performs no I/O.
73    ///
74    /// # Parameters
75    /// - `info`: Stable provider identity and path semantics.
76    /// - `capabilities`: Capabilities explicitly advertised by the provider.
77    /// - `limits`: Provider resource and operation limits.
78    /// - `path_constraints`: Accepted absolute and relative path forms.
79    /// - `symlink_policy`: Provider-declared symbolic-link traversal policy.
80    ///
81    /// # Returns
82    /// A validated immutable property snapshot.
83    ///
84    /// # Errors
85    /// Returns an invalid-options error when the provider identity is invalid,
86    /// advertised capabilities violate dependencies, or path configuration is
87    /// internally inconsistent. Finite path-text, component-text, range-read,
88    /// and list-page limits must be positive. A zero write-session limit is
89    /// valid and permits only empty write sessions.
90    #[inline]
91    pub fn new(
92        info: FileSystemInfo,
93        capabilities: FileSystemCapabilities,
94        limits: FileSystemLimits,
95        path_constraints: PathConstraints,
96        symlink_policy: SymlinkPolicy,
97    ) -> FsResult<Self> {
98        let properties = Self {
99            info,
100            capabilities,
101            limits,
102            path_constraints,
103            symlink_policy,
104        };
105        properties.validate()?;
106        Ok(properties)
107    }
108
109    /// Derives the application-visible property snapshot from one validated
110    /// provider snapshot.
111    ///
112    /// The facade adds conditional copy support only when the provider exposes
113    /// metadata, reader, and writer entry points together with corresponding
114    /// read and write capabilities. This method performs no I/O.
115    ///
116    /// # Parameters
117    /// - `provider`: Validated provider operations, guarantees, and limits.
118    ///
119    /// # Returns
120    /// A validated application-visible property snapshot.
121    ///
122    /// # Errors
123    /// Returns an invalid-options error when the derived snapshot violates a
124    /// shared property invariant.
125    pub(crate) fn from_provider(provider: &ProviderProperties) -> FsResult<Self> {
126        let mut capabilities = provider.declared_capabilities();
127        let operations = provider.operations();
128        let streamed_copy = operations.supports(ProviderOperation::Stat)
129            && operations.supports(ProviderOperation::OpenReader)
130            && operations.supports(ProviderOperation::OpenWriter)
131            && capabilities.supports(FileSystemCapability::Read)
132            && capabilities.supports(FileSystemCapability::Write);
133        if streamed_copy && !capabilities.supports(FileSystemCapability::Copy) {
134            capabilities = capabilities.with_conditional(FileSystemCapability::Copy);
135        }
136        Self::new(
137            provider.info().clone(),
138            capabilities,
139            *provider.limits(),
140            provider.path_constraints().clone(),
141            provider.symlink_policy(),
142        )
143    }
144
145    /// Returns the stable filesystem identity and configuration.
146    ///
147    /// # Returns
148    /// The immutable provider information snapshot.
149    #[inline]
150    #[must_use]
151    pub const fn info(&self) -> &FileSystemInfo {
152        &self.info
153    }
154
155    /// Returns the effective application-visible capabilities.
156    ///
157    /// The snapshot contains provider-declared capabilities plus capabilities
158    /// derived by the facade, such as conditional streamed copy support.
159    ///
160    /// # Returns
161    /// Capabilities available to callers of the facade.
162    #[inline]
163    #[must_use]
164    pub const fn capabilities(&self) -> FileSystemCapabilities {
165        self.capabilities
166    }
167
168    /// Returns the stable filesystem limits.
169    ///
170    /// # Returns
171    /// The immutable provider limit snapshot.
172    #[inline]
173    #[must_use]
174    pub const fn limits(&self) -> &FileSystemLimits {
175        &self.limits
176    }
177
178    /// Returns the immutable accepted path constraints.
179    ///
180    /// # Returns
181    /// The accepted logical path forms.
182    #[inline]
183    #[must_use]
184    pub const fn path_constraints(&self) -> &PathConstraints {
185        &self.path_constraints
186    }
187
188    /// Returns the provider-declared symbolic-link traversal policy.
189    #[inline]
190    #[must_use = "the filesystem symbolic-link policy must be used"]
191    pub const fn symlink_policy(&self) -> SymlinkPolicy {
192        self.symlink_policy
193    }
194
195    /// Validates a logical path against the provider's semantics, form, and
196    /// byte limits without performing I/O.
197    ///
198    /// # Parameters
199    /// - `path`: Logical path to validate against this filesystem's contract.
200    /// - `operation`: Operation associated with the path for error context.
201    ///
202    /// # Errors
203    /// Returns an enriched invalid-path or resource-limit error when the path
204    /// does not satisfy this filesystem's declared contract.
205    pub fn validate_path(&self, path: &Path, operation: FsOperation) -> FsResult<()> {
206        let result = if path.semantics() != self.info.path_semantics() {
207            Err(FsError::invalid_path(
208                operation,
209                "path semantics do not match this filesystem",
210            ))
211        } else {
212            self.path_constraints
213                .validate(path)
214                .and_then(|()| self.limits.validate_path(path, self.info.path_semantics(), operation))
215        };
216        result.map_err(|error| {
217            error
218                .with_operation(operation)
219                .with_missing_context(path, None, self.info.provider_id())
220        })
221    }
222
223    /// Defensively validates a provider-supplied snapshot at the facade
224    /// boundary.
225    ///
226    /// It performs no I/O and is intentionally crate-private.
227    ///
228    /// # Returns
229    /// `Ok(())` when all property invariants hold.
230    ///
231    /// # Errors
232    /// Returns an invalid-options error when the snapshot violates core value
233    /// invariants.
234    pub(crate) fn validate(&self) -> FsResult<()> {
235        if self.info.provider_id().is_empty() || self.info.provider_id().chars().any(char::is_control) {
236            return Err(invalid_properties(
237                "provider id must be non-empty and contain no controls",
238            ));
239        }
240        if let Some((_capability, _dependency)) = self.capabilities.missing_dependency() {
241            return Err(invalid_properties("advertised capability dependency is missing"));
242        }
243        if [
244            self.limits.max_path_text_bytes(),
245            self.limits.max_component_text_bytes(),
246            self.limits.max_list_page_entries(),
247        ]
248        .into_iter()
249        .any(|limit| matches!(limit, crate::metadata::FileSystemLimit::Maximum(0)))
250        {
251            return Err(invalid_properties(
252                "finite path, component, and list-page limits must have a positive value",
253            ));
254        }
255        if self.info.path_semantics() != PathSemantics::Hierarchical
256            && self.path_constraints.form() == PathForm::Absolute
257        {
258            return Err(invalid_properties(
259                "literal path semantics cannot require hierarchical absolute paths",
260            ));
261        }
262        Ok(())
263    }
264}
265
266/// Builds the shared property-validation failure.
267///
268/// # Parameters
269/// - `message`: Static explanation of the violated property invariant.
270///
271/// # Returns
272/// An invalid-options error scoped to provider configuration.
273fn invalid_properties(message: &'static str) -> FsError {
274    FsError::new(FsErrorKind::InvalidOptions, FsOperation::ValidateProperties, message)
275}