qubit-fs 0.2.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
// facade tests.
//! Concrete filesystem error type.

use std::error::Error;
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;
use std::io;

use crate::error::FsEffectState;
use crate::error::FsErrorKind;
use crate::error::FsOperation;
use crate::metadata::FileSystemCapability;
use crate::path::Path;

/// Provider-neutral filesystem error with operation and path context.
///
/// [`Debug`] and [`Display`] never expand the retained source error because a
/// lower-level SDK or transport diagnostic may contain credentials. `Debug`
/// reports only whether a source exists; explicit diagnostic code may inspect
/// it through [`Error::source`]. The message supplied by constructors must
/// already be scrubbed of secret material.
///
/// # Examples
///
/// ```
/// use qubit_fs::Path;
/// use qubit_fs::error::FsError;
/// use qubit_fs::error::FsErrorKind;
/// use qubit_fs::error::FsOperation;
///
/// let path = Path::parse("/reports/latest.csv")?;
/// let error = FsError::new(FsErrorKind::NotFound, FsOperation::Stat, "object missing")
///     .with_path(path.clone());
/// assert_eq!(FsErrorKind::NotFound, error.kind());
/// assert_eq!(Some(&path), error.path());
/// # Ok::<(), qubit_fs::FsError>(())
/// ```
pub struct FsError {
    /// Error category.
    kind: FsErrorKind,
    /// Operation that produced the error.
    operation: FsOperation,
    /// Concrete path where the operation failed.
    path: Option<Box<Path>>,
    /// Secondary path involved in the operation.
    target: Option<Box<Path>>,
    /// Concrete source entry where a structured operation failed.
    failure_path: Option<Box<Path>>,
    /// Concrete destination entry where a structured operation failed.
    failure_target: Option<Box<Path>>,
    /// Provider id or alias involved in the operation.
    provider: Option<Box<str>>,
    /// Capability needed to satisfy the request, when applicable.
    required_capability: Option<FileSystemCapability>,
    /// Strongest known external effect of the failed operation.
    effect_state: Option<FsEffectState>,
    /// Human-readable, non-sensitive error message.
    message: Box<str>,
    /// Lower-level source error, excluded from automatic formatting.
    source: Option<Box<dyn Error + Send + Sync + 'static>>,
}

impl FsError {
    /// Creates a filesystem error without path or provider context.
    ///
    /// # Parameters
    /// - `kind`: Provider-neutral error category.
    /// - `operation`: Operation that produced the error.
    /// - `message`: Human-readable diagnostic message that must not contain
    ///   credentials or other secret material.
    ///
    /// # Returns
    /// New filesystem error.
    #[inline]
    #[must_use]
    pub fn new(kind: FsErrorKind, operation: FsOperation, message: &str) -> Self {
        Self {
            kind,
            operation,
            path: None,
            target: None,
            failure_path: None,
            failure_target: None,
            provider: None,
            required_capability: None,
            effect_state: None,
            message: message.into(),
            source: None,
        }
    }

    /// Creates a filesystem error that wraps a lower-level source error.
    ///
    /// # Parameters
    /// - `kind`: Provider-neutral error category.
    /// - `operation`: Operation that produced the error.
    /// - `message`: Human-readable diagnostic message that must not contain
    ///   credentials or other secret material.
    /// - `source`: Lower-level error to preserve. Its formatting may contain
    ///   secrets and is therefore never expanded by this type's `Debug` or
    ///   `Display` implementation.
    ///
    /// # Returns
    /// New filesystem error with source context.
    #[inline]
    pub fn with_source<E>(kind: FsErrorKind, operation: FsOperation, message: &str, source: E) -> Self
    where
        E: Error + Send + Sync + 'static,
    {
        Self {
            source: Some(Box::new(source)),
            ..Self::new(kind, operation, message)
        }
    }

    /// Adds primary path context.
    ///
    /// # Parameters
    /// - `path`: Concrete path where the operation failed. For a two-path
    ///   operation this may be either request path; use [`Self::target`] to
    ///   identify the destination.
    ///
    /// # Returns
    /// Updated filesystem error.
    #[inline]
    #[must_use]
    pub fn with_path(mut self, path: impl Into<Path>) -> Self {
        self.path = Some(Box::new(path.into()));
        self
    }

    /// Rebinds the error to the public operation that was requested.
    ///
    /// This is useful for convenience operations implemented through another
    /// primitive, such as `exists` implemented through `stat`, while retaining
    /// all path, provider, capability, and source context.
    ///
    /// # Parameters
    /// - `operation`: Public operation whose failure is being returned.
    ///
    /// # Returns
    /// Updated filesystem error.
    #[inline]
    #[must_use]
    pub fn with_operation(mut self, operation: FsOperation) -> Self {
        self.operation = operation;
        self
    }

    /// Adds secondary target path context.
    ///
    /// # Parameters
    /// - `target`: Destination path of a two-path operation.
    ///
    /// # Returns
    /// Updated filesystem error.
    #[inline]
    #[must_use]
    pub fn with_target(mut self, target: impl Into<Path>) -> Self {
        self.target = Some(Box::new(target.into()));
        self
    }

    /// Adds the concrete source entry where a structured operation failed.
    #[inline]
    #[must_use]
    pub fn with_failure_path(mut self, path: impl Into<Path>) -> Self {
        self.failure_path = Some(Box::new(path.into()));
        self
    }

    /// Adds the concrete destination entry where a structured operation failed.
    #[inline]
    #[must_use]
    pub fn with_failure_target(mut self, target: impl Into<Path>) -> Self {
        self.failure_target = Some(Box::new(target.into()));
        self
    }

    /// Adds provider context.
    ///
    /// # Parameters
    /// - `provider`: Canonical provider id involved in the operation.
    ///
    /// # Returns
    /// Updated filesystem error.
    #[inline]
    #[must_use]
    pub fn with_provider(mut self, provider: impl Display) -> Self {
        self.provider = Some(provider.to_string().into());
        self
    }

    /// Adds the capability required by an unsupported or unmet request.
    ///
    /// # Parameters
    /// - `capability`: Stable capability required by the request.
    ///
    /// # Returns
    /// Updated filesystem error.
    #[inline]
    #[must_use]
    pub fn with_required_capability(mut self, capability: FileSystemCapability) -> Self {
        self.required_capability = Some(capability);
        self
    }

    /// Adds the strongest known external effect of the failed operation.
    ///
    /// # Parameters
    ///
    /// * `effect_state` - Provider-neutral effect state proven by the provider.
    ///
    /// # Returns
    ///
    /// Updated filesystem error.
    #[inline]
    #[must_use]
    pub fn with_effect_state(mut self, effect_state: FsEffectState) -> Self {
        self.effect_state = Some(effect_state);
        self
    }

    /// Replaces untrusted session locations with a known cleanup request.
    ///
    /// Used only for quarantined sessions whose opening identity was invalid.
    /// Diagnostic entry and target paths cannot be trusted in this case. The
    /// original category, effect evidence, message, and source remain intact.
    pub(crate) fn with_trusted_cleanup_context(
        mut self,
        operation: FsOperation,
        path: Option<&Path>,
        provider: &str,
    ) -> Self {
        self.operation = operation;
        self.path = path.cloned().map(Box::new);
        self.target = None;
        self.failure_path = None;
        self.failure_target = None;
        self.provider = Some(provider.into());
        self
    }

    /// Adds missing path, target, and provider context without overwriting
    /// provider-supplied details.
    ///
    /// Core resource wrappers use this when an error crosses an abstraction
    /// boundary. It preserves a provider's more specific context while making
    /// generic validation and stream failures actionable to callers.
    ///
    /// # Parameters
    /// - `path`: Fallback primary path for the requested operation.
    /// - `target`: Fallback secondary path, when the operation has one.
    /// - `provider`: Fallback canonical provider id.
    ///
    /// # Returns
    /// Updated error with every previously absent context field filled.
    #[inline]
    #[must_use]
    pub(crate) fn with_missing_context(mut self, path: &Path, target: Option<&Path>, provider: &str) -> Self {
        if self.path.is_none() {
            self.path = Some(Box::new(path.clone()));
        }
        if self.target.is_none() {
            self.target = target.cloned().map(Box::new);
        }
        if self.provider.is_none() {
            self.provider = Some(provider.into());
        }
        self
    }

    /// Adds provider context only when an error does not already carry it.
    ///
    /// This is used by operations that have no meaningful logical path, such
    /// as provider capability checks performed before temporary resource
    /// creation.
    #[inline]
    #[must_use]
    pub(crate) fn with_missing_provider(mut self, provider: &str) -> Self {
        if self.provider.is_none() {
            self.provider = Some(provider.into());
        }
        self
    }

    /// Creates an invalid-path error.
    ///
    /// # Parameters
    /// - `operation`: Operation that rejected the path.
    /// - `message`: Human-readable reason.
    ///
    /// # Returns
    /// Invalid-path filesystem error.
    #[inline]
    #[must_use]
    pub fn invalid_path(operation: FsOperation, message: &str) -> Self {
        Self::new(FsErrorKind::InvalidPath, operation, message)
    }

    /// Wraps a byte-stream error with filesystem operation context.
    ///
    /// # Parameters
    /// - `error`: Lower-level stream error.
    /// - `operation`: Filesystem operation in progress when it occurred.
    ///
    /// # Returns
    /// A filesystem error retaining `error` as its source.
    #[inline]
    #[must_use]
    pub fn from_io(error: io::Error, operation: FsOperation) -> Self {
        let kind = match error.kind() {
            io::ErrorKind::NotFound => FsErrorKind::NotFound,
            io::ErrorKind::AlreadyExists => FsErrorKind::AlreadyExists,
            io::ErrorKind::DirectoryNotEmpty => FsErrorKind::Conflict,
            io::ErrorKind::NotADirectory => FsErrorKind::NotDirectory,
            io::ErrorKind::IsADirectory => FsErrorKind::IsDirectory,
            io::ErrorKind::PermissionDenied => FsErrorKind::PermissionDenied,
            io::ErrorKind::InvalidInput => FsErrorKind::InvalidOptions,
            io::ErrorKind::Unsupported => FsErrorKind::UnsupportedOperation,
            io::ErrorKind::TimedOut => FsErrorKind::Timeout,
            io::ErrorKind::Interrupted => FsErrorKind::Interrupted,
            io::ErrorKind::StorageFull => FsErrorKind::QuotaExceeded,
            io::ErrorKind::InvalidData => FsErrorKind::DataCorruption,
            _ => FsErrorKind::Io,
        };
        Self::with_source(kind, operation, "stream I/O failed", error)
    }

    /// Restores a filesystem error transported through an I/O boundary.
    ///
    /// Provider streams may embed an [`FsError`] inside [`io::Error`]. This
    /// helper recovers that typed error when present; ordinary I/O errors use
    /// [`Self::from_io`] classification instead. An untyped `InvalidData`
    /// remains generic I/O because stream adapters also use it for contract
    /// violations; providers report verified corruption with an embedded typed
    /// error.
    ///
    /// # Parameters
    ///
    /// * `error` - Stream error returned by a reader or writer.
    /// * `operation` - Public filesystem operation consuming the stream.
    /// * `path` - Resource path supplied to that public operation.
    ///
    /// # Returns
    ///
    /// A typed filesystem error with the public operation and path rebound.
    #[allow(dead_code)]
    #[inline]
    pub(crate) fn from_stream_io(error: io::Error, operation: FsOperation, path: &Path) -> Self {
        match error.downcast::<Self>() {
            Ok(error) => error.with_operation(operation).with_path(path.clone()),
            Err(error) if error.kind() == io::ErrorKind::InvalidData => {
                Self::with_source(FsErrorKind::Io, operation, "stream I/O contract failed", error)
                    .with_path(path.clone())
            }
            Err(error) => Self::from_io(error, operation).with_path(path.clone()),
        }
    }

    /// Returns the provider-neutral error category.
    ///
    /// # Returns
    /// Error category.
    #[inline]
    #[must_use]
    pub fn kind(&self) -> FsErrorKind {
        self.kind
    }

    /// Returns the operation that produced this error.
    ///
    /// # Returns
    /// The provider-neutral operation identifier.
    #[inline]
    #[must_use]
    pub fn operation(&self) -> FsOperation {
        self.operation
    }

    /// Returns the primary path associated with this error.
    ///
    /// # Returns
    /// The path when one was attached.
    #[inline]
    #[must_use]
    pub fn path(&self) -> Option<&Path> {
        self.path.as_deref()
    }

    /// Returns the secondary target path associated with this error.
    ///
    /// # Returns
    /// The target path when one was attached.
    #[inline]
    #[must_use]
    pub fn target(&self) -> Option<&Path> {
        self.target.as_deref()
    }

    /// Returns the concrete source entry where the operation failed.
    ///
    /// # Returns
    /// The structured source path when one was attached for copy, rename, or
    /// similar multi-path operations.
    #[inline]
    #[must_use]
    pub fn failure_path(&self) -> Option<&Path> {
        self.failure_path.as_deref()
    }

    /// Returns the concrete destination entry where the operation failed.
    ///
    /// # Returns
    /// The structured destination path when one was attached for copy, rename,
    /// or similar multi-path operations.
    #[inline]
    #[must_use]
    pub fn failure_target(&self) -> Option<&Path> {
        self.failure_target.as_deref()
    }

    /// Returns the provider associated with this error.
    ///
    /// # Returns
    /// The canonical provider id when one was attached.
    #[inline]
    #[must_use]
    pub fn provider(&self) -> Option<&str> {
        self.provider.as_deref()
    }

    /// Returns the required capability associated with this error.
    ///
    /// # Returns
    /// The capability when the error describes unsupported functionality or
    /// an unmet semantic requirement.
    #[inline]
    #[must_use]
    pub fn required_capability(&self) -> Option<FileSystemCapability> {
        self.required_capability
    }

    /// Returns the strongest known external effect of the failed operation.
    ///
    /// # Returns
    ///
    /// `Some` when a provider proved an effect state, or `None` when the error
    /// carries no effect-state claim.
    #[inline]
    #[must_use]
    pub fn effect_state(&self) -> Option<FsEffectState> {
        self.effect_state
    }

    /// Returns whether the operation's external effect cannot be determined.
    #[inline]
    #[must_use]
    pub fn has_indeterminate_effect(&self) -> bool {
        self.kind == FsErrorKind::Indeterminate || self.effect_state == Some(FsEffectState::Indeterminate)
    }

    /// Converts this filesystem error into a byte-stream error.
    ///
    /// The complete [`FsError`] is retained as the [`io::Error`] source so
    /// callers crossing the open/stream boundary do not lose provider,
    /// operation, or path context.
    ///
    /// # Returns
    /// An I/O error with a corresponding standard category.
    #[inline]
    #[must_use]
    pub fn into_io_error(self) -> io::Error {
        let kind = match self.kind {
            FsErrorKind::NotFound => io::ErrorKind::NotFound,
            FsErrorKind::AlreadyExists => io::ErrorKind::AlreadyExists,
            FsErrorKind::NotDirectory => io::ErrorKind::NotADirectory,
            FsErrorKind::IsDirectory => io::ErrorKind::IsADirectory,
            FsErrorKind::PermissionDenied | FsErrorKind::AuthenticationFailed => io::ErrorKind::PermissionDenied,
            FsErrorKind::InvalidPath
            | FsErrorKind::InvalidUri
            | FsErrorKind::InvalidOptions
            | FsErrorKind::InvalidState => io::ErrorKind::InvalidInput,
            FsErrorKind::UnsupportedOperation | FsErrorKind::UnsupportedCapability => io::ErrorKind::Unsupported,
            FsErrorKind::Timeout => io::ErrorKind::TimedOut,
            FsErrorKind::Interrupted => io::ErrorKind::Interrupted,
            FsErrorKind::Cancelled => io::ErrorKind::Other,
            FsErrorKind::QuotaExceeded => io::ErrorKind::StorageFull,
            FsErrorKind::DataCorruption => io::ErrorKind::InvalidData,
            _ => io::ErrorKind::Other,
        };
        io::Error::new(kind, self)
    }
}

impl Debug for FsError {
    #[inline]
    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
        formatter
            .debug_struct("FsError")
            .field("kind", &self.kind)
            .field("operation", &self.operation)
            .field("path", &self.path.as_deref())
            .field("target", &self.target.as_deref())
            .field("failure_path", &self.failure_path.as_deref())
            .field("failure_target", &self.failure_target.as_deref())
            .field("provider", &self.provider)
            .field("required_capability", &self.required_capability)
            .field("effect_state", &self.effect_state)
            .field("message", &self.message)
            .field("source_present", &self.source.is_some())
            .finish()
    }
}

impl Display for FsError {
    #[inline]
    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
        write!(
            formatter,
            "{:?} failed with {:?}: {}",
            self.operation, self.kind, self.message,
        )
    }
}

impl Error for FsError {
    #[inline]
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.source.as_deref().map(|source| source as &(dyn Error + 'static))
    }
}