Skip to main content

qubit_fs/metadata/
file_system_limits.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//! Stable configured filesystem limits.
9
10use crate::error::FsError;
11use crate::error::FsErrorKind;
12use crate::error::FsOperation;
13use crate::error::FsResult;
14use crate::metadata::FileSystemLimit;
15use crate::path::Path;
16use crate::path::PathSemantics;
17
18/// Stable limits declared by a configured filesystem provider.
19///
20/// # Examples
21///
22/// ```rust
23/// use qubit_fs::metadata::{FileSystemLimit, FileSystemLimits};
24///
25/// let limits = FileSystemLimits::unknown();
26/// assert_eq!(FileSystemLimit::Unknown, limits.max_path_text_bytes());
27/// ```
28#[derive(Clone, Copy, Debug, Eq, PartialEq)]
29pub struct FileSystemLimits {
30    /// Maximum encoded bytes accepted for a complete logical path.
31    max_path_text_bytes: FileSystemLimit,
32    /// Maximum encoded bytes accepted for one path component.
33    max_component_text_bytes: FileSystemLimit,
34    /// Maximum bytes accepted by one range-read request.
35    max_read_range_bytes: FileSystemLimit,
36    /// Maximum bytes accepted by one write session.
37    max_write_bytes: FileSystemLimit,
38    /// Maximum entries requested in one listing page.
39    max_list_page_entries: FileSystemLimit,
40}
41
42impl FileSystemLimits {
43    /// Creates a limit snapshot whose dimensions are all explicitly unknown.
44    #[inline]
45    #[must_use]
46    pub const fn unknown() -> Self {
47        Self {
48            max_path_text_bytes: FileSystemLimit::Unknown,
49            max_component_text_bytes: FileSystemLimit::Unknown,
50            max_read_range_bytes: FileSystemLimit::Unknown,
51            max_write_bytes: FileSystemLimit::Unknown,
52            max_list_page_entries: FileSystemLimit::Unknown,
53        }
54    }
55
56    /// Returns a copy with the path-text byte limit replaced by `limit`.
57    ///
58    /// # Parameters
59    /// - `limit`: New maximum for the encoded complete path, or its declared
60    ///   unknown, inapplicable, or unbounded state.
61    #[inline]
62    #[must_use]
63    pub const fn with_max_path_text_bytes(mut self, limit: FileSystemLimit) -> Self {
64        self.max_path_text_bytes = limit;
65        self
66    }
67
68    /// Returns a copy with the component-text byte limit replaced by `limit`.
69    ///
70    /// # Parameters
71    /// - `limit`: New maximum for one encoded path component.
72    #[inline]
73    #[must_use]
74    pub const fn with_max_component_text_bytes(mut self, limit: FileSystemLimit) -> Self {
75        self.max_component_text_bytes = limit;
76        self
77    }
78
79    /// Returns a copy with the range-read byte limit replaced by `limit`.
80    ///
81    /// # Parameters
82    /// - `limit`: New maximum length for one range-read request.
83    #[inline]
84    #[must_use]
85    pub const fn with_max_read_range_bytes(mut self, limit: FileSystemLimit) -> Self {
86        self.max_read_range_bytes = limit;
87        self
88    }
89
90    /// Returns a copy with the write-session byte limit replaced by `limit`.
91    ///
92    /// A finite maximum of zero is valid and permits only empty write
93    /// sessions when the limits are used to construct filesystem properties.
94    ///
95    /// # Parameters
96    /// - `limit`: New maximum total size for one write session.
97    #[inline]
98    #[must_use]
99    pub const fn with_max_write_bytes(mut self, limit: FileSystemLimit) -> Self {
100        self.max_write_bytes = limit;
101        self
102    }
103
104    /// Returns a copy with the native list-page entry limit replaced by
105    /// `limit`.
106    ///
107    /// # Parameters
108    /// - `limit`: New maximum number of entries requested in one native page.
109    #[inline]
110    #[must_use]
111    pub const fn with_max_list_page_entries(mut self, limit: FileSystemLimit) -> Self {
112        self.max_list_page_entries = limit;
113        self
114    }
115
116    /// Returns the maximum canonical [`crate::path::Path`] text length in UTF-8
117    /// bytes.
118    #[inline]
119    #[must_use]
120    pub const fn max_path_text_bytes(&self) -> FileSystemLimit {
121        self.max_path_text_bytes
122    }
123
124    /// Returns the maximum path-component text length in UTF-8 bytes.
125    #[inline]
126    #[must_use]
127    pub const fn max_component_text_bytes(&self) -> FileSystemLimit {
128        self.max_component_text_bytes
129    }
130
131    /// Returns the maximum byte count accepted by one logical range read.
132    #[inline]
133    #[must_use]
134    pub const fn max_read_range_bytes(&self) -> FileSystemLimit {
135        self.max_read_range_bytes
136    }
137
138    /// Returns the maximum total byte count accepted by one write session.
139    ///
140    /// A finite maximum of zero permits only empty write sessions.
141    #[inline]
142    #[must_use]
143    pub const fn max_write_bytes(&self) -> FileSystemLimit {
144        self.max_write_bytes
145    }
146
147    /// Returns the maximum entry count in one provider-native list page.
148    #[inline]
149    #[must_use]
150    pub const fn max_list_page_entries(&self) -> FileSystemLimit {
151        self.max_list_page_entries
152    }
153
154    /// Clamps a requested list-page size to the declared finite maximum.
155    ///
156    /// Unknown, unbounded, and inapplicable limits leave the hint unchanged.
157    /// A missing hint remains absent so the provider can select its natural
158    /// page size while still honoring its declared limit.
159    ///
160    /// # Parameters
161    /// - `requested`: Optional caller-supplied page-size hint.
162    ///
163    /// # Returns
164    /// The effective page-size hint forwarded to the provider.
165    #[inline]
166    #[must_use]
167    pub fn clamp_list_page_size(&self, requested: Option<usize>) -> Option<usize> {
168        let requested = requested?;
169        match self.max_list_page_entries {
170            FileSystemLimit::Maximum(maximum) => {
171                usize::try_from(maximum).map_or(Some(requested), |maximum| Some(requested.min(maximum)))
172            }
173            FileSystemLimit::Unknown | FileSystemLimit::NotApplicable | FileSystemLimit::Unbounded => Some(requested),
174        }
175    }
176
177    /// Validates a canonical filesystem path against provider path limits.
178    ///
179    /// Component limits are checked only for hierarchical path semantics.
180    ///
181    /// # Errors
182    /// Returns [`FsErrorKind::ResourceLimitExceeded`] when the complete path
183    /// text or a hierarchical component exceeds its declared finite maximum.
184    ///
185    /// # Parameters
186    /// - `path`: Canonical logical path whose encoded byte lengths are checked.
187    /// - `semantics`: Path model; component limits apply only to hierarchical
188    ///   paths.
189    /// - `operation`: Operation attached to a possible resource-limit error.
190    pub fn validate_path(&self, path: &Path, semantics: PathSemantics, operation: FsOperation) -> FsResult<()> {
191        if exceeds_usize(self.max_path_text_bytes, path.as_str().len()) {
192            return Err(limit_error(
193                operation,
194                "path text exceeds the provider byte limit",
195                path,
196            ));
197        }
198        if semantics == PathSemantics::Hierarchical
199            && path
200                .as_str()
201                .split('/')
202                .any(|component| !component.is_empty() && exceeds_usize(self.max_component_text_bytes, component.len()))
203        {
204            return Err(limit_error(
205                operation,
206                "path component exceeds the provider byte limit",
207                path,
208            ));
209        }
210        Ok(())
211    }
212
213    /// Validates a requested logical range-read length.
214    ///
215    /// A missing length cannot be preflighted and remains the provider's
216    /// responsibility during execution.
217    ///
218    /// # Errors
219    /// Returns [`FsErrorKind::ResourceLimitExceeded`] when `length` exceeds
220    /// the declared finite range-read maximum.
221    ///
222    /// # Parameters
223    /// - `path`: Path attached to a possible resource-limit error.
224    /// - `length`: Requested range length, or `None` when the length is not
225    ///   known before provider execution.
226    pub fn validate_read_range(&self, path: &Path, length: Option<u64>) -> FsResult<()> {
227        if length.is_some_and(|length| self.max_read_range_bytes.is_exceeded_by(length)) {
228            Err(limit_error(
229                FsOperation::OpenReader,
230                "requested range exceeds the provider byte limit",
231                path,
232            ))
233        } else {
234            Ok(())
235        }
236    }
237
238    /// Validates the total bytes supplied to one write session.
239    ///
240    /// # Errors
241    /// Returns [`FsErrorKind::ResourceLimitExceeded`] when `bytes` exceeds the
242    /// declared finite write-session maximum.
243    ///
244    /// # Parameters
245    /// - `path`: Path attached to a possible resource-limit error.
246    /// - `bytes`: Total number of bytes supplied to the write session.
247    pub fn validate_write_size(&self, path: &Path, bytes: usize) -> FsResult<()> {
248        if exceeds_usize(self.max_write_bytes, bytes) {
249            Err(limit_error(
250                FsOperation::Write,
251                "write session exceeds the provider byte limit",
252                path,
253            ))
254        } else {
255            Ok(())
256        }
257    }
258
259    /// Validates a streamed write-session byte length without narrowing it to
260    /// the native pointer-sized integer.
261    ///
262    /// # Errors
263    /// Returns [`FsErrorKind::ResourceLimitExceeded`] when `bytes` exceeds the
264    /// declared finite write-session maximum.
265    ///
266    /// # Parameters
267    /// - `path`: Path attached to a possible resource-limit error.
268    /// - `bytes`: Streamed write length represented without native-size
269    ///   narrowing.
270    pub(crate) fn validate_write_size_u64(&self, path: &Path, bytes: u64) -> FsResult<()> {
271        if self.max_write_bytes.is_exceeded_by(bytes) {
272            Err(limit_error(
273                FsOperation::Write,
274                "write session exceeds the provider byte limit",
275                path,
276            ))
277        } else {
278            Ok(())
279        }
280    }
281}
282
283/// Tests whether a `usize` count exceeds the declared filesystem limit.
284///
285/// Values that cannot be represented as `u64` exceed every finite maximum.
286///
287/// # Parameters
288/// - `limit`: Declared filesystem limit to apply.
289/// - `actual`: Native-size value being checked.
290///
291/// # Returns
292/// `true` when the value exceeds the finite maximum, including when conversion
293/// to `u64` fails.
294fn exceeds_usize(limit: FileSystemLimit, actual: usize) -> bool {
295    match u64::try_from(actual) {
296        Ok(actual) => limit.is_exceeded_by(actual),
297        Err(_) => matches!(limit, FileSystemLimit::Maximum(_)),
298    }
299}
300
301/// Builds a path-contextual resource-limit error for `operation`.
302///
303/// # Parameters
304/// - `operation`: Operation that encountered the limit.
305/// - `message`: Static explanation of the rejected resource size.
306/// - `path`: Path to attach as error context.
307///
308/// # Returns
309/// A resource-limit error carrying the operation, message, and path.
310fn limit_error(operation: FsOperation, message: &'static str, path: &Path) -> FsError {
311    FsError::new(FsErrorKind::ResourceLimitExceeded, operation, message).with_path(path.clone())
312}