qubit-fs 0.3.2

Provider-neutral synchronous and asynchronous filesystem abstraction for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Directory listing options.

use std::time::Duration;
use std::time::Instant;

use crate::directory::ListFilter;
use crate::error::FsError;
use crate::error::FsErrorKind;
use crate::error::FsOperation;
use crate::error::FsResult;
use crate::metadata::SymlinkPolicy;
use crate::path::PathSemantics;
use crate::path::RelativePath;

/// Options controlling directory or prefix listing.
///
/// Options are validated by [`crate::FileSystem::list`] before a provider
/// session is opened. A page-size hint is bounded by the provider's declared
/// limit; `max_depth` and `max_entries` are caller-side safety bounds.
///
/// # Examples
///
/// ```
/// use qubit_fs::directory::{ListFilter, ListOptions};
///
/// let options = ListOptions::default()
///     .with_page_size(Some(100))
///     .with_max_depth(Some(2))
///     .with_max_entries(Some(500))
///     .with_filter(Some(ListFilter::Subtree("reports".to_owned())));
/// assert_eq!(options.page_size(), Some(100));
/// assert_eq!(options.max_depth(), Some(2));
/// assert_eq!(options.max_entries(), Some(500));
/// assert!(options.validate().is_ok());
/// ```
#[non_exhaustive]
#[derive(Clone, Debug, Eq, PartialEq, Default)]
pub struct ListOptions {
    /// Whether listing should recurse into child containers.
    ///
    /// Without a filter, `false` limits descendant entries to immediate
    /// children. A provider may also return the listed root itself.
    /// Applications that recursively enumerate returned directories must
    /// skip an entry equal to that root. A [`ListFilter::Subtree`] and
    /// `max_depth` retain their documented selection and depth rules.
    recursive: bool,
    /// Optional symbolic-link policy overriding the filesystem default.
    symlink_policy: Option<SymlinkPolicy>,
    /// Whether every returned entry must include metadata.
    ///
    /// When enabled, an entry without metadata fails the stream; metadata is
    /// not best-effort.
    include_metadata: bool,
    /// Optional provider page size hint.
    page_size: Option<usize>,
    /// Optional lexical prefix filter relative to the requested list root.
    ///
    /// [`ListFilter::Subtree`] uses canonical `/`-separated relative paths.
    /// Listing `/root` with `Subtree("nested")` selects `/root/nested` and
    /// its descendants, including deeper entries when `recursive` is false.
    /// `max_depth` can limit the returned descendant depth relative to `/root`.
    filter: Option<ListFilter>,
    /// Maximum returned descendant depth relative to the list root.
    max_depth: Option<usize>,
    /// Maximum number of entries returned to the caller.
    max_entries: Option<usize>,
    /// Maximum elapsed duration from stream creation.
    deadline: Option<Duration>,
}

impl ListOptions {
    /// Returns defaults for a flat object-key listing.
    #[must_use]
    pub fn object_keys() -> Self {
        Self {
            recursive: true,
            filter: Some(ListFilter::LiteralPrefix(String::new())),
            ..Self::default()
        }
    }

    /// Returns whether traversal recurses into child containers.
    ///
    /// Without a filter, `false` limits descendant entries to immediate
    /// children. A provider may also return the listed root itself.
    /// Applications that recursively enumerate returned directories must
    /// skip an entry equal to that root. A subtree filter and `max_depth`
    /// retain their documented selection and depth rules.
    #[inline]
    #[must_use]
    pub const fn recursive(&self) -> bool {
        self.recursive
    }

    /// Returns the optional symbolic-link policy override.
    ///
    /// # Returns
    /// `Some` with the configured override, or `None` when the filesystem
    /// default policy applies.
    #[inline]
    pub const fn symlink_policy_override(&self) -> Option<SymlinkPolicy> {
        self.symlink_policy
    }

    /// Returns whether metadata is required for entries.
    ///
    /// When `true`, missing metadata makes the listing fail.
    #[inline]
    #[must_use]
    pub const fn include_metadata(&self) -> bool {
        self.include_metadata
    }

    /// Returns the optional page-size hint.
    ///
    /// # Returns
    /// `Some` with the provider page-size hint, or `None` when no hint is set.
    #[inline]
    pub const fn page_size(&self) -> Option<usize> {
        self.page_size
    }

    /// Returns the optional subtree prefix set through the legacy prefix API.
    ///
    /// # Returns
    /// `Some` with the configured subtree prefix, or `None` when no subtree
    /// prefix filter is configured.
    #[inline]
    pub fn prefix(&self) -> Option<&str> {
        match self.filter.as_ref() {
            Some(ListFilter::Subtree(prefix)) => Some(prefix),
            _ => None,
        }
    }

    /// Returns the explicit listing filter.
    ///
    /// # Returns
    /// `Some` with the configured filter, or `None` when listing is unfiltered.
    pub fn filter(&self) -> Option<&ListFilter> {
        self.filter.as_ref()
    }

    /// Returns the optional maximum descendant depth.
    ///
    /// # Returns
    /// `Some` with the maximum descendant depth, or `None` when no depth limit
    /// is configured.
    #[inline]
    pub const fn max_depth(&self) -> Option<usize> {
        self.max_depth
    }

    /// Returns the optional maximum returned entry count.
    ///
    /// # Returns
    /// `Some` with the maximum entry count, or `None` when no count limit is
    /// configured.
    #[inline]
    pub const fn max_entries(&self) -> Option<usize> {
        self.max_entries
    }

    /// Returns the optional maximum elapsed duration from stream creation.
    ///
    /// # Returns
    /// `Some` with the elapsed-time limit, or `None` when no deadline is set.
    #[inline]
    pub const fn deadline(&self) -> Option<Duration> {
        self.deadline
    }

    /// Returns a copy with recursive traversal replaced.
    ///
    /// # Parameters
    /// - `recursive`: Whether traversal should recurse into child containers.
    #[inline]
    #[must_use]
    pub const fn with_recursive(mut self, recursive: bool) -> Self {
        self.recursive = recursive;
        self
    }

    /// Returns a copy with the symbolic-link policy override replaced.
    ///
    /// # Parameters
    /// - `policy`: Symbolic-link policy to use instead of the filesystem
    ///   default.
    #[inline]
    #[must_use]
    pub const fn with_symlink_policy(mut self, policy: SymlinkPolicy) -> Self {
        self.symlink_policy = Some(policy);
        self
    }

    /// Returns a copy with metadata inclusion replaced.
    ///
    /// # Parameters
    /// - `include`: Whether metadata is required for every returned entry. When
    ///   enabled, missing metadata makes the listing fail.
    #[inline]
    #[must_use]
    pub const fn with_include_metadata(mut self, include: bool) -> Self {
        self.include_metadata = include;
        self
    }

    /// Returns a copy with the page-size hint replaced.
    ///
    /// # Parameters
    /// - `page_size`: Provider page-size hint, or `None` to leave it
    ///   unspecified.
    #[inline]
    #[must_use]
    pub const fn with_page_size(mut self, page_size: Option<usize>) -> Self {
        self.page_size = page_size;
        self
    }

    /// Returns a copy with the subtree prefix replaced through the legacy API.
    ///
    /// # Parameters
    /// - `prefix`: Relative subtree path to select, or `None` to clear the
    ///   filter.
    #[inline]
    #[must_use]
    pub fn with_prefix(mut self, prefix: Option<String>) -> Self {
        self.filter = prefix.map(ListFilter::Subtree);
        self
    }

    /// Replaces the explicit listing filter.
    ///
    /// # Parameters
    /// - `filter`: Filter to apply, or `None` to list without a filter.
    #[inline]
    #[must_use]
    pub fn with_filter(mut self, filter: Option<ListFilter>) -> Self {
        self.filter = filter;
        self
    }

    /// Returns a copy with the maximum descendant depth replaced.
    ///
    /// # Parameters
    /// - `max_depth`: Maximum descendant depth, or `None` for no depth limit.
    #[inline]
    #[must_use]
    pub const fn with_max_depth(mut self, max_depth: Option<usize>) -> Self {
        self.max_depth = max_depth;
        self
    }

    /// Returns a copy with the maximum returned entry count replaced.
    ///
    /// # Parameters
    /// - `max_entries`: Maximum returned entry count, or `None` for no count
    ///   limit.
    #[inline]
    #[must_use]
    pub const fn with_max_entries(mut self, max_entries: Option<usize>) -> Self {
        self.max_entries = max_entries;
        self
    }

    /// Returns a copy with the maximum elapsed duration replaced.
    ///
    /// # Parameters
    /// - `deadline`: Maximum elapsed duration, or `None` for no deadline.
    #[inline]
    #[must_use]
    pub const fn with_deadline(mut self, deadline: Option<Duration>) -> Self {
        self.deadline = deadline;
        self
    }

    /// Validates pagination and canonical provider-facing prefix values.
    ///
    /// # Errors
    ///
    /// Returns `FsError` with `InvalidOptions` when the page size is zero, a
    /// literal prefix contains NUL, a subtree prefix is not canonical, or the
    /// deadline exceeds the platform monotonic-clock range.
    pub fn validate(&self) -> FsResult<()> {
        self.validate_common()?;
        if let Some(ListFilter::Subtree(prefix)) = self.filter.as_ref() {
            let parsed = RelativePath::parse(prefix).map_err(|_| {
                FsError::new(
                    FsErrorKind::InvalidOptions,
                    FsOperation::List,
                    "list subtree must be a canonical relative path",
                )
            })?;
            if parsed.as_str() != prefix {
                return Err(FsError::new(
                    FsErrorKind::InvalidOptions,
                    FsOperation::List,
                    "list subtree must be a canonical relative path",
                ));
            }
        }
        Ok(())
    }

    /// Validates options against the filesystem path semantics.
    ///
    /// # Parameters
    /// - `semantics`: Provider path semantics used to validate the filter.
    ///
    /// # Errors
    /// Returns `FsError` with `InvalidOptions` when the page size is zero, a
    /// literal prefix contains NUL, the deadline exceeds the platform
    /// monotonic-clock range, or the filter is invalid or incompatible with
    /// `semantics`.
    pub fn validate_for(&self, semantics: PathSemantics) -> FsResult<()> {
        self.validate_common()?;
        self.validate_filter(semantics)
    }

    /// Validates options that do not depend on path semantics.
    fn validate_common(&self) -> FsResult<()> {
        if self.page_size == Some(0) {
            return Err(FsError::new(
                FsErrorKind::InvalidOptions,
                FsOperation::List,
                "list page size must be greater than zero",
            ));
        }
        if matches!(self.filter.as_ref(), Some(ListFilter::LiteralPrefix(prefix)) if prefix.contains('\0')) {
            return Err(FsError::new(
                FsErrorKind::InvalidOptions,
                FsOperation::List,
                "literal prefix contains NUL",
            ));
        }
        if self
            .deadline
            .is_some_and(|deadline| Instant::now().checked_add(deadline).is_none())
        {
            return Err(FsError::new(
                FsErrorKind::InvalidOptions,
                FsOperation::List,
                "list deadline exceeds the platform monotonic-clock range",
            ));
        }
        Ok(())
    }

    /// Validates the selected filter against provider path semantics.
    ///
    /// # Parameters
    ///
    /// - `semantics`: Path interpretation rules declared by the provider.
    fn validate_filter(&self, semantics: PathSemantics) -> FsResult<()> {
        match (semantics, self.filter.as_ref()) {
            (PathSemantics::Hierarchical, Some(ListFilter::Subtree(prefix))) => {
                let parsed = RelativePath::parse(prefix).map_err(|_| {
                    FsError::new(
                        FsErrorKind::InvalidOptions,
                        FsOperation::List,
                        "list subtree must be a canonical relative path",
                    )
                })?;
                if parsed.as_str() != prefix {
                    return Err(FsError::new(
                        FsErrorKind::InvalidOptions,
                        FsOperation::List,
                        "list subtree must be a canonical relative path",
                    ));
                }
            }
            (PathSemantics::Hierarchical, Some(ListFilter::LiteralPrefix(_))) => {
                return Err(FsError::new(
                    FsErrorKind::InvalidOptions,
                    FsOperation::List,
                    "literal prefix requires flat path semantics",
                ));
            }
            (PathSemantics::ObjectKey | PathSemantics::ProviderSpecific, Some(ListFilter::Subtree(_))) => {
                return Err(FsError::new(
                    FsErrorKind::InvalidOptions,
                    FsOperation::List,
                    "subtree filter requires hierarchical path semantics",
                ));
            }
            _ => {}
        }
        if matches!(semantics, PathSemantics::ObjectKey | PathSemantics::ProviderSpecific)
            && (!self.recursive || self.max_depth.is_some())
        {
            return Err(FsError::new(
                FsErrorKind::InvalidOptions,
                FsOperation::List,
                "flat listing requires recursive traversal without max_depth",
            ));
        }
        Ok(())
    }
}