qubit_fs/error/fs_error.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//! Concrete filesystem error type.
9
10use std::error::Error;
11use std::fmt::Debug;
12use std::fmt::Display;
13use std::fmt::Formatter;
14use std::fmt::Result as FmtResult;
15use std::io;
16
17use crate::error::FsEffectState;
18use crate::error::FsErrorKind;
19use crate::error::FsOperation;
20use crate::metadata::FileSystemCapability;
21use crate::path::Path;
22
23/// Provider-neutral filesystem error with operation and path context.
24///
25/// [`Debug`] and [`Display`] never expand the retained source error because a
26/// lower-level SDK or transport diagnostic may contain credentials. `Debug`
27/// reports only whether a source exists; explicit diagnostic code may inspect
28/// it through [`Error::source`]. The message supplied by constructors must
29/// already be scrubbed of secret material.
30///
31/// # Examples
32///
33/// ```
34/// use qubit_fs::Path;
35/// use qubit_fs::error::FsError;
36/// use qubit_fs::error::FsErrorKind;
37/// use qubit_fs::error::FsOperation;
38///
39/// let path = Path::parse("/reports/latest.csv")?;
40/// let error = FsError::new(FsErrorKind::NotFound, FsOperation::Stat, "object missing")
41/// .with_path(path.clone());
42/// assert_eq!(FsErrorKind::NotFound, error.kind());
43/// assert_eq!(Some(&path), error.path());
44///
45/// # Ok::<(), qubit_fs::FsError>(())
46/// ```
47#[must_use = "inspect the filesystem error instead of silently discarding it"]
48pub struct FsError {
49 /// Error category.
50 kind: FsErrorKind,
51 /// Operation that produced the error.
52 operation: FsOperation,
53 /// Concrete path where the operation failed.
54 path: Option<Box<Path>>,
55 /// Secondary path involved in the operation.
56 target: Option<Box<Path>>,
57 /// Concrete source entry where a structured operation failed.
58 failure_path: Option<Box<Path>>,
59 /// Concrete destination entry where a structured operation failed.
60 failure_target: Option<Box<Path>>,
61 /// Provider id or alias involved in the operation.
62 provider: Option<Box<str>>,
63 /// Capability needed to satisfy the request, when applicable.
64 required_capability: Option<FileSystemCapability>,
65 /// Strongest known external effect of the failed operation.
66 effect_state: Option<FsEffectState>,
67 /// Human-readable, non-sensitive error message.
68 message: Box<str>,
69 /// Lower-level source error, excluded from automatic formatting.
70 source: Option<Box<dyn Error + Send + Sync + 'static>>,
71}
72
73impl FsError {
74 /// Creates a filesystem error without path or provider context.
75 ///
76 /// # Parameters
77 /// - `kind`: Provider-neutral error category.
78 /// - `operation`: Operation that produced the error.
79 /// - `message`: Human-readable diagnostic message that must not contain
80 /// credentials or other secret material.
81 ///
82 /// # Returns
83 /// New filesystem error.
84 #[inline]
85 pub fn new(kind: FsErrorKind, operation: FsOperation, message: &str) -> Self {
86 Self {
87 kind,
88 operation,
89 path: None,
90 target: None,
91 failure_path: None,
92 failure_target: None,
93 provider: None,
94 required_capability: None,
95 effect_state: None,
96 message: message.into(),
97 source: None,
98 }
99 }
100
101 /// Creates a filesystem error that wraps a lower-level source error.
102 ///
103 /// # Type Parameters
104 ///
105 /// - `E`: Concrete error type preserved as the underlying error source.
106 ///
107 /// # Parameters
108 /// - `kind`: Provider-neutral error category.
109 /// - `operation`: Operation that produced the error.
110 /// - `message`: Human-readable diagnostic message that must not contain
111 /// credentials or other secret material.
112 /// - `source`: Lower-level error to preserve. Its formatting may contain
113 /// secrets and is therefore never expanded by this type's `Debug` or
114 /// `Display` implementation.
115 ///
116 /// # Returns
117 /// New filesystem error with source context.
118 #[inline]
119 pub fn with_source<E>(kind: FsErrorKind, operation: FsOperation, message: &str, source: E) -> Self
120 where
121 E: Error + Send + Sync + 'static,
122 {
123 Self {
124 source: Some(Box::new(source)),
125 ..Self::new(kind, operation, message)
126 }
127 }
128
129 /// Creates an invalid-path error.
130 ///
131 /// # Parameters
132 /// - `operation`: Operation that rejected the path.
133 /// - `message`: Human-readable reason.
134 ///
135 /// # Returns
136 /// Invalid-path filesystem error.
137 #[inline]
138 pub fn invalid_path(operation: FsOperation, message: &str) -> Self {
139 Self::new(FsErrorKind::InvalidPath, operation, message)
140 }
141
142 /// Wraps a byte-stream error with filesystem operation context.
143 ///
144 /// # Parameters
145 /// - `error`: Lower-level stream error.
146 /// - `operation`: Filesystem operation in progress when it occurred.
147 ///
148 /// # Returns
149 /// A filesystem error retaining `error` as its source.
150 #[inline]
151 pub fn from_io(error: io::Error, operation: FsOperation) -> Self {
152 let kind = match error.kind() {
153 io::ErrorKind::NotFound => FsErrorKind::NotFound,
154 io::ErrorKind::AlreadyExists => FsErrorKind::AlreadyExists,
155 io::ErrorKind::DirectoryNotEmpty => FsErrorKind::Conflict,
156 io::ErrorKind::NotADirectory => FsErrorKind::NotDirectory,
157 io::ErrorKind::IsADirectory => FsErrorKind::IsDirectory,
158 io::ErrorKind::PermissionDenied => FsErrorKind::PermissionDenied,
159 io::ErrorKind::InvalidInput => FsErrorKind::InvalidOptions,
160 io::ErrorKind::Unsupported => FsErrorKind::UnsupportedOperation,
161 io::ErrorKind::TimedOut => FsErrorKind::Timeout,
162 io::ErrorKind::Interrupted => FsErrorKind::Interrupted,
163 io::ErrorKind::StorageFull => FsErrorKind::QuotaExceeded,
164 io::ErrorKind::QuotaExceeded => FsErrorKind::QuotaExceeded,
165 io::ErrorKind::OutOfMemory => FsErrorKind::ResourceLimitExceeded,
166 io::ErrorKind::InvalidData => FsErrorKind::DataCorruption,
167 _ => FsErrorKind::Io,
168 };
169 Self::with_source(kind, operation, "stream I/O failed", error)
170 }
171
172 /// Restores a filesystem error transported through an I/O boundary.
173 ///
174 /// Provider streams may embed an [`FsError`] inside [`io::Error`]. This
175 /// helper recovers that typed error when present; ordinary I/O errors use
176 /// [`Self::from_io`] classification instead. An untyped `InvalidData`
177 /// remains generic I/O because stream adapters also use it for contract
178 /// violations; providers report verified corruption with an embedded typed
179 /// error.
180 ///
181 /// # Parameters
182 ///
183 /// * `error` - Stream error returned by a reader or writer.
184 /// * `operation` - Public filesystem operation consuming the stream.
185 /// * `path` - Resource path supplied to that public operation.
186 ///
187 /// # Returns
188 ///
189 /// A typed filesystem error with the public operation and path rebound.
190 #[allow(dead_code)]
191 #[inline]
192 pub(crate) fn from_stream_io(error: io::Error, operation: FsOperation, path: &Path) -> Self {
193 match error.downcast::<Self>() {
194 Ok(error) => error.with_operation(operation).with_path(path.clone()),
195 Err(error) if error.kind() == io::ErrorKind::InvalidData => {
196 Self::with_source(FsErrorKind::Io, operation, "stream I/O contract failed", error)
197 .with_path(path.clone())
198 }
199 Err(error) => Self::from_io(error, operation).with_path(path.clone()),
200 }
201 }
202
203 /// Returns the provider-neutral error category.
204 ///
205 /// # Returns
206 /// Error category.
207 #[inline]
208 #[must_use]
209 pub fn kind(&self) -> FsErrorKind {
210 self.kind
211 }
212
213 /// Returns the operation that produced this error.
214 ///
215 /// # Returns
216 /// The provider-neutral operation identifier.
217 #[inline]
218 #[must_use]
219 pub fn operation(&self) -> FsOperation {
220 self.operation
221 }
222
223 /// Returns the primary path associated with this error.
224 ///
225 /// # Returns
226 /// `Some` when a primary path was attached, or `None` otherwise.
227 #[inline]
228 pub fn path(&self) -> Option<&Path> {
229 self.path.as_deref()
230 }
231
232 /// Returns the secondary target path associated with this error.
233 ///
234 /// # Returns
235 /// `Some` when a target path was attached, or `None` otherwise.
236 #[inline]
237 pub fn target(&self) -> Option<&Path> {
238 self.target.as_deref()
239 }
240
241 /// Returns the concrete source entry where the operation failed.
242 ///
243 /// # Returns
244 /// `Some` when a structured source path was attached for copy, rename, or
245 /// similar multi-path operations, or `None` otherwise.
246 #[inline]
247 pub fn failure_path(&self) -> Option<&Path> {
248 self.failure_path.as_deref()
249 }
250
251 /// Returns the concrete destination entry where the operation failed.
252 ///
253 /// # Returns
254 /// `Some` when a structured destination path was attached for copy, rename,
255 /// or similar multi-path operations, or `None` otherwise.
256 #[inline]
257 pub fn failure_target(&self) -> Option<&Path> {
258 self.failure_target.as_deref()
259 }
260
261 /// Returns the provider associated with this error.
262 ///
263 /// # Returns
264 /// `Some` when a canonical provider id was attached, or `None` otherwise.
265 #[inline]
266 pub fn provider(&self) -> Option<&str> {
267 self.provider.as_deref()
268 }
269
270 /// Returns the required capability associated with this error.
271 ///
272 /// # Returns
273 /// `Some` when the error describes unsupported functionality or an unmet
274 /// semantic requirement, or `None` otherwise.
275 #[inline]
276 pub fn required_capability(&self) -> Option<FileSystemCapability> {
277 self.required_capability
278 }
279
280 /// Returns the strongest known external effect of the failed operation.
281 ///
282 /// # Returns
283 ///
284 /// `Some` when a provider proved an effect state, or `None` when the error
285 /// carries no effect-state claim.
286 #[inline]
287 pub fn effect_state(&self) -> Option<FsEffectState> {
288 self.effect_state
289 }
290
291 /// Returns whether the operation's external effect cannot be determined.
292 #[inline]
293 #[must_use]
294 pub fn has_indeterminate_effect(&self) -> bool {
295 self.kind == FsErrorKind::Indeterminate || self.effect_state == Some(FsEffectState::Indeterminate)
296 }
297
298 /// Adds primary path context.
299 ///
300 /// # Parameters
301 /// - `path`: Concrete path where the operation failed. For a two-path
302 /// operation this may be either request path; use [`Self::target`] to
303 /// identify the destination.
304 ///
305 /// # Returns
306 /// Updated filesystem error.
307 #[inline]
308 pub fn with_path(mut self, path: impl Into<Path>) -> Self {
309 self.path = Some(Box::new(path.into()));
310 self
311 }
312
313 /// Rebinds the error to the public operation that was requested.
314 ///
315 /// This is useful for convenience operations implemented through another
316 /// primitive, such as `exists` implemented through `stat`, while retaining
317 /// all path, provider, capability, and source context.
318 ///
319 /// # Parameters
320 /// - `operation`: Public operation whose failure is being returned.
321 ///
322 /// # Returns
323 /// Updated filesystem error.
324 #[inline]
325 pub fn with_operation(mut self, operation: FsOperation) -> Self {
326 self.operation = operation;
327 self
328 }
329
330 /// Adds secondary target path context.
331 ///
332 /// # Parameters
333 /// - `target`: Destination path of a two-path operation.
334 ///
335 /// # Returns
336 /// Updated filesystem error.
337 #[inline]
338 pub fn with_target(mut self, target: impl Into<Path>) -> Self {
339 self.target = Some(Box::new(target.into()));
340 self
341 }
342
343 /// Adds the concrete source entry where a structured operation failed.
344 ///
345 /// # Parameters
346 /// - `path`: Concrete source entry where the operation failed.
347 ///
348 /// # Returns
349 /// Updated error with the failure source path attached.
350 #[inline]
351 pub fn with_failure_path(mut self, path: impl Into<Path>) -> Self {
352 self.failure_path = Some(Box::new(path.into()));
353 self
354 }
355
356 /// Adds the concrete destination entry where a structured operation failed.
357 ///
358 /// # Parameters
359 /// - `target`: Concrete destination entry where the operation failed.
360 ///
361 /// # Returns
362 /// Updated error with the failure destination path attached.
363 #[inline]
364 pub fn with_failure_target(mut self, target: impl Into<Path>) -> Self {
365 self.failure_target = Some(Box::new(target.into()));
366 self
367 }
368
369 /// Adds provider context.
370 ///
371 /// # Parameters
372 /// - `provider`: Canonical provider id involved in the operation.
373 ///
374 /// # Returns
375 /// Updated filesystem error.
376 #[inline]
377 pub fn with_provider(mut self, provider: impl Display) -> Self {
378 self.provider = Some(provider.to_string().into());
379 self
380 }
381
382 /// Adds the capability required by an unsupported or unmet request.
383 ///
384 /// # Parameters
385 /// - `capability`: Stable capability required by the request.
386 ///
387 /// # Returns
388 /// Updated filesystem error.
389 #[inline]
390 pub fn with_required_capability(mut self, capability: FileSystemCapability) -> Self {
391 self.required_capability = Some(capability);
392 self
393 }
394
395 /// Adds the strongest known external effect of the failed operation.
396 ///
397 /// # Parameters
398 ///
399 /// * `effect_state` - Provider-neutral effect state proven by the provider.
400 ///
401 /// # Returns
402 ///
403 /// Updated filesystem error.
404 #[inline]
405 pub fn with_effect_state(mut self, effect_state: FsEffectState) -> Self {
406 self.effect_state = Some(effect_state);
407 self
408 }
409
410 /// Converts this filesystem error into a byte-stream error.
411 ///
412 /// The complete [`FsError`] is retained as the [`io::Error`] source so
413 /// callers crossing the open/stream boundary do not lose provider,
414 /// operation, or path context.
415 ///
416 /// # Returns
417 /// An I/O error with a corresponding standard category.
418 #[inline]
419 #[must_use]
420 pub fn into_io_error(self) -> io::Error {
421 let kind = match self.kind {
422 FsErrorKind::NotFound => io::ErrorKind::NotFound,
423 FsErrorKind::AlreadyExists => io::ErrorKind::AlreadyExists,
424 FsErrorKind::NotDirectory => io::ErrorKind::NotADirectory,
425 FsErrorKind::IsDirectory => io::ErrorKind::IsADirectory,
426 FsErrorKind::PermissionDenied | FsErrorKind::AuthenticationFailed => io::ErrorKind::PermissionDenied,
427 FsErrorKind::InvalidPath
428 | FsErrorKind::InvalidUri
429 | FsErrorKind::InvalidOptions
430 | FsErrorKind::InvalidState => io::ErrorKind::InvalidInput,
431 FsErrorKind::UnsupportedOperation | FsErrorKind::UnsupportedCapability => io::ErrorKind::Unsupported,
432 FsErrorKind::Timeout => io::ErrorKind::TimedOut,
433 FsErrorKind::Interrupted => io::ErrorKind::Interrupted,
434 FsErrorKind::Cancelled => io::ErrorKind::Other,
435 FsErrorKind::QuotaExceeded => io::ErrorKind::StorageFull,
436 FsErrorKind::DataCorruption => io::ErrorKind::InvalidData,
437 _ => io::ErrorKind::Other,
438 };
439 io::Error::new(kind, self)
440 }
441
442 /// Replaces untrusted session locations with a known cleanup request.
443 ///
444 /// # Parameters
445 ///
446 /// - `operation`: Filesystem operation used for validation or error
447 /// context.
448 /// - `path`: Logical path of the resource involved in this operation.
449 /// - `provider`: Provider identifier attached to contextual errors.
450 pub(crate) fn with_trusted_cleanup_context(
451 mut self,
452 operation: FsOperation,
453 path: Option<&Path>,
454 provider: &str,
455 ) -> Self {
456 self.operation = operation;
457 self.path = path.cloned().map(Box::new);
458 self.target = None;
459 self.failure_path = None;
460 self.failure_target = None;
461 self.provider = Some(provider.into());
462 self
463 }
464
465 /// Adds missing path, target, and provider context without overwriting
466 /// provider-supplied details.
467 ///
468 /// Core resource wrappers use this when an error crosses an abstraction
469 /// boundary. It preserves a provider's more specific context while making
470 /// generic validation and stream failures actionable to callers.
471 ///
472 /// # Parameters
473 /// - `path`: Fallback primary path for the requested operation.
474 /// - `target`: Fallback secondary path, when the operation has one.
475 /// - `provider`: Fallback canonical provider id.
476 ///
477 /// # Returns
478 /// Updated error with every previously absent context field filled.
479 #[inline]
480 pub(crate) fn with_missing_context(mut self, path: &Path, target: Option<&Path>, provider: &str) -> Self {
481 if self.path.is_none() {
482 self.path = Some(Box::new(path.clone()));
483 }
484 if self.target.is_none() {
485 self.target = target.cloned().map(Box::new);
486 }
487 if self.provider.is_none() {
488 self.provider = Some(provider.into());
489 }
490 self
491 }
492
493 /// Adds provider context only when an error does not already carry it.
494 ///
495 /// This is used by operations that have no meaningful logical path, such
496 /// as provider capability checks performed before temporary resource
497 /// creation.
498 ///
499 /// # Parameters
500 ///
501 /// - `provider`: Provider identifier attached to contextual errors.
502 #[inline]
503 pub(crate) fn with_missing_provider(mut self, provider: &str) -> Self {
504 if self.provider.is_none() {
505 self.provider = Some(provider.into());
506 }
507 self
508 }
509}
510
511impl Debug for FsError {
512 /// Formats safe error facts without expanding the underlying source.
513 ///
514 /// # Parameters
515 ///
516 /// - `formatter`: Formatter receiving the safe error representation.
517 #[inline]
518 fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
519 formatter
520 .debug_struct("FsError")
521 .field("kind", &self.kind)
522 .field("operation", &self.operation)
523 .field("path", &self.path.as_deref())
524 .field("target", &self.target.as_deref())
525 .field("failure_path", &self.failure_path.as_deref())
526 .field("failure_target", &self.failure_target.as_deref())
527 .field("provider", &self.provider)
528 .field("required_capability", &self.required_capability)
529 .field("effect_state", &self.effect_state)
530 .field("message", &self.message)
531 .field("source_present", &self.source.is_some())
532 .finish()
533 }
534}
535
536impl Display for FsError {
537 /// Formats the operation, category, and non-secret diagnostic message.
538 ///
539 /// # Parameters
540 ///
541 /// - `formatter`: Formatter receiving the non-secret error message.
542 #[inline]
543 fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
544 write!(
545 formatter,
546 "{:?} failed with {:?}: {}",
547 self.operation, self.kind, self.message,
548 )
549 }
550}
551
552impl Error for FsError {
553 /// Returns the preserved lower-level error, if one was attached.
554 ///
555 /// # Parameters
556 ///
557 /// - `self`: Filesystem error whose lower-level source is requested.
558 #[inline]
559 fn source(&self) -> Option<&(dyn Error + 'static)> {
560 self.source.as_deref().map(|source| source as &(dyn Error + 'static))
561 }
562}