fsys 0.4.0

Adaptive file and directory IO for Rust — fast, hardware-aware, multi-strategy.
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! Error type for the `fsys` crate.
//!
//! All fallible operations in `fsys` return [`Result<T>`], which is a type
//! alias for [`std::result::Result<T, Error>`]. The [`Error`] enum is the
//! single error type produced by the library; consumers match on its
//! variants rather than juggling boxed trait objects.
//!
//! Error codes use the prefix `FS-` per the wider Hive error registry.
//! Codes are stable once assigned: the integer associated with each variant
//! is part of the public contract and will not change between versions.

use std::fmt;
use std::path::PathBuf;

/// Convenient `Result` alias that fixes the error type to [`Error`].
///
/// # Examples
///
/// ```
/// use fsys::Result;
///
/// fn always_ok() -> Result<u32> {
///     Ok(42)
/// }
///
/// assert_eq!(always_ok().ok(), Some(42));
/// ```
pub type Result<T> = std::result::Result<T, Error>;

/// The single error type produced by the `fsys` crate.
///
/// Every variant carries enough context to identify what was attempted,
/// where it failed, and what the caller can do next. Display output never
/// includes raw buffer contents; file paths are considered safe to surface
/// because callers already supplied them.
#[derive(Debug)]
#[non_exhaustive]
#[must_use = "errors should be inspected, propagated, or logged"]
pub enum Error {
    /// A platform IO syscall returned an error.
    ///
    /// Wraps the underlying [`std::io::Error`]. Callers needing the
    /// original `io::ErrorKind` can pattern-match the inner value.
    ///
    /// **Code:** `FS-00001`. Caller action: inspect the inner kind; this
    /// is typically a transient condition such as `Interrupted` or a
    /// configuration problem such as `PermissionDenied`.
    Io(std::io::Error),

    /// A supplied path could not be used.
    ///
    /// **Code:** `FS-00002`. Caller action: correct the path. Common
    /// causes include empty segments, embedded NUL bytes, or characters
    /// disallowed on the active platform.
    InvalidPath {
        /// The offending path, as supplied by the caller.
        path: PathBuf,
        /// Human-readable explanation of why the path was rejected.
        reason: String,
    },

    /// A hardware probe failed.
    ///
    /// **Code:** `FS-00003`. Caller action: treat as advisory. The crate
    /// continues to operate with conservative defaults (queue depth 1,
    /// drive kind unknown, no PLP); only call sites that need real
    /// hardware information should treat this as fatal.
    HardwareProbeFailed {
        /// Detail string describing which probe failed and why.
        detail: String,
    },

    /// The requested feature is not available on the active platform.
    ///
    /// **Code:** `FS-00004`. Caller action: select an alternative
    /// strategy, fall back to a portable path, or recompile with the
    /// appropriate feature flag.
    UnsupportedPlatform {
        /// Detail string describing what was requested and why this
        /// platform cannot serve it.
        detail: String,
    },

    /// The requested durability method is not implemented in this release.
    ///
    /// **Code:** `FS-00005`. Caller action: select an available method
    /// ([`crate::Method::Sync`], [`crate::Method::Data`],
    /// [`crate::Method::Direct`], or [`crate::Method::Auto`]).
    /// `Method::Mmap` is planned for `0.5.0`; `Method::Journal` for `0.7.0`.
    UnsupportedMethod {
        /// The name of the method that was requested.
        method: &'static str,
    },

    /// A Direct IO operation could not satisfy its alignment requirements.
    ///
    /// **Code:** `FS-00006`. Caller action: this is an internal alignment
    /// failure. File a bug if you encounter this — fsys is responsible for
    /// managing alignment transparently on behalf of the caller.
    AlignmentRequired {
        /// Human-readable description of the violated requirement.
        detail: &'static str,
    },

    /// The atomic write-replace sequence failed part-way through.
    ///
    /// **Code:** `FS-00007`. Caller action: inspect `step` to determine
    /// how far the operation progressed. If `step` is `"write"` or
    /// earlier, the original file is unmodified. If `step` is `"rename"`,
    /// the original file may or may not have been replaced. A stale temp
    /// file may remain adjacent to the destination; it is safe to delete.
    AtomicReplaceFailed {
        /// The step that failed (e.g. `"open"`, `"write"`, `"flush"`,
        /// `"rename"`, `"sync_parent"`).
        step: &'static str,
        /// The underlying IO error from the failed step.
        source: std::io::Error,
    },

    /// A directory creation or removal operation failed part-way through.
    ///
    /// **Code:** `FS-00008`. Caller action: the filesystem is in a
    /// partially modified state. Inspect `failed_step` to identify which
    /// sub-operation triggered the error, and `completed_steps` to know
    /// what succeeded before the failure. No rollback is performed; the
    /// caller decides whether to retry, clean up, or accept the partial
    /// state.
    PartialDirectoryOp {
        /// The operation that failed (e.g. `"create /a/b/c"`).
        failed_step: String,
        /// Operations that succeeded before the failure.
        completed_steps: Vec<String>,
    },

    /// A batch operation was submitted to a [`crate::Handle`] that is
    /// being dropped.
    ///
    /// **Code:** `FS-00009`. Caller action: the handle is shutting down;
    /// rebuild a new handle if more IO is needed. This error is only
    /// produced when a batch submit races with `Handle::drop` — it is
    /// effectively unreachable when handle ownership is single-threaded
    /// or properly fenced.
    ShutdownInProgress,

    /// The group-lane queue is full and a non-blocking submission was
    /// rejected.
    ///
    /// **Code:** `FS-00010`. **Reserved variant — never emitted in
    /// `0.4.0`.** The default backpressure mode in `0.4.0` is blocking
    /// submission (callers wait when the queue is full); this variant
    /// is reserved for a future opt-in error-mode (`Builder::backpressure
    /// (BackpressureMode::Error)`) that has not landed yet. Match it to
    /// satisfy exhaustiveness even though it cannot occur today.
    QueueFull,
}

impl Error {
    /// Returns the stable `FS-XXXXX` code identifying this variant.
    ///
    /// Codes are stable across releases. They never change for an
    /// existing variant; new variants receive new codes.
    ///
    /// # Examples
    ///
    /// ```
    /// use fsys::Error;
    /// use std::io;
    ///
    /// let err = Error::Io(io::Error::from(io::ErrorKind::NotFound));
    /// assert_eq!(err.code(), "FS-00001");
    /// ```
    #[must_use]
    pub fn code(&self) -> &'static str {
        match self {
            Error::Io(_) => "FS-00001",
            Error::InvalidPath { .. } => "FS-00002",
            Error::HardwareProbeFailed { .. } => "FS-00003",
            Error::UnsupportedPlatform { .. } => "FS-00004",
            Error::UnsupportedMethod { .. } => "FS-00005",
            Error::AlignmentRequired { .. } => "FS-00006",
            Error::AtomicReplaceFailed { .. } => "FS-00007",
            Error::PartialDirectoryOp { .. } => "FS-00008",
            Error::ShutdownInProgress => "FS-00009",
            Error::QueueFull => "FS-00010",
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Io(e) => write!(f, "[{}] io error: {}", self.code(), e),
            Error::InvalidPath { path, reason } => write!(
                f,
                "[{}] invalid path {:?}: {}",
                self.code(),
                path.display(),
                reason
            ),
            Error::HardwareProbeFailed { detail } => {
                write!(f, "[{}] hardware probe failed: {}", self.code(), detail)
            }
            Error::UnsupportedPlatform { detail } => {
                write!(f, "[{}] unsupported platform: {}", self.code(), detail)
            }
            Error::UnsupportedMethod { method } => {
                write!(
                    f,
                    "[{}] method '{}' is not implemented in this release",
                    self.code(),
                    method
                )
            }
            Error::AlignmentRequired { detail } => {
                write!(
                    f,
                    "[{}] alignment requirement failed: {}",
                    self.code(),
                    detail
                )
            }
            Error::AtomicReplaceFailed { step, source } => {
                write!(
                    f,
                    "[{}] atomic write-replace failed at step '{}': {}",
                    self.code(),
                    step,
                    source
                )
            }
            Error::PartialDirectoryOp {
                failed_step,
                completed_steps,
            } => {
                write!(
                    f,
                    "[{}] directory op failed at '{}' after {} completed step(s)",
                    self.code(),
                    failed_step,
                    completed_steps.len()
                )
            }
            Error::ShutdownInProgress => {
                write!(
                    f,
                    "[{}] handle is shutting down; batch submission rejected",
                    self.code()
                )
            }
            Error::QueueFull => {
                write!(
                    f,
                    "[{}] group-lane queue is full (reserved variant; never emitted in 0.4.0)",
                    self.code()
                )
            }
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Io(e) => Some(e),
            Error::AtomicReplaceFailed { source, .. } => Some(source),
            Error::InvalidPath { .. }
            | Error::HardwareProbeFailed { .. }
            | Error::UnsupportedPlatform { .. }
            | Error::UnsupportedMethod { .. }
            | Error::AlignmentRequired { .. }
            | Error::PartialDirectoryOp { .. }
            | Error::ShutdownInProgress
            | Error::QueueFull => None,
        }
    }
}

impl From<std::io::Error> for Error {
    fn from(value: std::io::Error) -> Self {
        Error::Io(value)
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// BatchError
// ──────────────────────────────────────────────────────────────────────────────

/// The error type returned by batch operations
/// (`Handle::write_batch`, `Handle::delete_batch`, `Handle::copy_batch`,
/// and `Batch::commit`).
///
/// `BatchError` reports per-batch failure semantics under decision #5
/// of the `0.4.0` design (independent ops, not transactions). When a
/// batch op fails — whether by returning an `Err` or by panicking — the
/// dispatcher stops processing the current batch, sends the response,
/// and moves on to the next batch in the queue. Subsequent ops in the
/// failing batch are **not attempted**. Ops that succeeded before the
/// failure **are** durable; fsys does **not** roll them back.
///
/// To recover from a `BatchError`, inspect:
/// - [`failed_at`](BatchError::failed_at): the index of the op that
///   failed.
/// - [`completed`](BatchError::completed): the number of ops that
///   completed successfully *before* the failure (always equal to
///   `failed_at` in `0.4.0`; the field is preserved as a structural
///   guarantee for future phases that might allow continuation).
/// - [`source`](BatchError::source): the underlying [`Error`] that
///   describes the failure.
///
/// Callers needing all-or-nothing semantics must layer their own
/// transactional logic on top of fsys, or wait for `Method::Journal`
/// in `0.7.0`.
#[derive(Debug)]
#[non_exhaustive]
#[must_use = "errors should be inspected, propagated, or logged"]
pub struct BatchError {
    /// The zero-based index of the op that failed within its batch.
    pub failed_at: usize,
    /// The number of ops that completed successfully before the failure.
    pub completed: usize,
    /// The underlying error.
    ///
    /// Boxed because `Error` is `non_exhaustive` and may grow large; the
    /// box keeps `BatchError` itself small even when the inner error
    /// carries large payloads (e.g. paths, detail strings, captured
    /// `std::io::Error`s).
    pub source: Box<Error>,
}

impl BatchError {
    /// Returns the inner [`Error`] as a borrowed reference.
    ///
    /// Convenience wrapper over `&*self.source`.
    pub fn inner(&self) -> &Error {
        &self.source
    }

    /// Consumes this `BatchError` and returns the boxed inner [`Error`].
    pub fn into_inner(self) -> Box<Error> {
        self.source
    }
}

impl fmt::Display for BatchError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "batch failed at op {} after {} successful op(s): {}",
            self.failed_at, self.completed, self.source
        )
    }
}

impl std::error::Error for BatchError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&*self.source)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io;

    #[test]
    fn test_error_code_io_returns_fs00001() {
        let err = Error::Io(io::Error::from(io::ErrorKind::NotFound));
        assert_eq!(err.code(), "FS-00001");
    }

    #[test]
    fn test_error_code_invalid_path_returns_fs00002() {
        let err = Error::InvalidPath {
            path: PathBuf::from("bad"),
            reason: "empty segment".into(),
        };
        assert_eq!(err.code(), "FS-00002");
    }

    #[test]
    fn test_error_code_hardware_probe_returns_fs00003() {
        let err = Error::HardwareProbeFailed {
            detail: "nvme ioctl unavailable".into(),
        };
        assert_eq!(err.code(), "FS-00003");
    }

    #[test]
    fn test_error_code_unsupported_platform_returns_fs00004() {
        let err = Error::UnsupportedPlatform {
            detail: "io_uring requires Linux 5.1+".into(),
        };
        assert_eq!(err.code(), "FS-00004");
    }

    #[test]
    fn test_error_display_unsupported_platform_includes_detail() {
        let err = Error::UnsupportedPlatform {
            detail: "io_uring not available".into(),
        };
        let s = err.to_string();
        assert!(s.starts_with("[FS-00004]"));
        assert!(s.contains("io_uring not available"));
    }

    #[test]
    fn test_error_display_io_includes_code_and_kind() {
        let err = Error::Io(io::Error::from(io::ErrorKind::NotFound));
        let s = err.to_string();
        assert!(s.starts_with("[FS-00001]"));
        assert!(s.contains("io error"));
    }

    #[test]
    fn test_error_display_invalid_path_does_not_panic_on_unicode() {
        let err = Error::InvalidPath {
            path: PathBuf::from("名前/test"),
            reason: "rejected".into(),
        };
        let s = err.to_string();
        assert!(s.contains("FS-00002"));
    }

    #[test]
    fn test_error_source_io_returns_inner() {
        let inner = io::Error::from(io::ErrorKind::PermissionDenied);
        let err = Error::Io(inner);
        assert!(std::error::Error::source(&err).is_some());
    }

    #[test]
    fn test_error_source_invalid_path_returns_none() {
        let err = Error::InvalidPath {
            path: PathBuf::from("x"),
            reason: "y".into(),
        };
        assert!(std::error::Error::source(&err).is_none());
    }

    #[test]
    fn test_error_from_io_error_converts() {
        let io_err = io::Error::from(io::ErrorKind::Other);
        let err: Error = io_err.into();
        assert_eq!(err.code(), "FS-00001");
    }

    #[test]
    fn test_result_alias_compiles_for_ok_and_err_paths() {
        fn returns_ok() -> Result<u8> {
            Ok(1)
        }
        fn returns_err() -> Result<u8> {
            Err(Error::HardwareProbeFailed {
                detail: "test".into(),
            })
        }
        assert_eq!(returns_ok().ok(), Some(1));
        assert!(returns_err().is_err());
    }

    #[test]
    fn test_error_code_unsupported_method_returns_fs00005() {
        let err = Error::UnsupportedMethod { method: "Mmap" };
        assert_eq!(err.code(), "FS-00005");
    }

    #[test]
    fn test_error_display_unsupported_method_includes_name() {
        let err = Error::UnsupportedMethod { method: "Journal" };
        let s = err.to_string();
        assert!(s.starts_with("[FS-00005]"));
        assert!(s.contains("Journal"));
    }

    #[test]
    fn test_error_code_alignment_required_returns_fs00006() {
        let err = Error::AlignmentRequired {
            detail: "size not a multiple of sector size",
        };
        assert_eq!(err.code(), "FS-00006");
    }

    #[test]
    fn test_error_display_alignment_required_includes_detail() {
        let err = Error::AlignmentRequired {
            detail: "buffer not aligned to 4096",
        };
        let s = err.to_string();
        assert!(s.starts_with("[FS-00006]"));
        assert!(s.contains("4096"));
    }

    #[test]
    fn test_error_code_atomic_replace_failed_returns_fs00007() {
        let err = Error::AtomicReplaceFailed {
            step: "rename",
            source: io::Error::from(io::ErrorKind::PermissionDenied),
        };
        assert_eq!(err.code(), "FS-00007");
    }

    #[test]
    fn test_error_display_atomic_replace_includes_step() {
        let err = Error::AtomicReplaceFailed {
            step: "flush",
            source: io::Error::from(io::ErrorKind::Other),
        };
        let s = err.to_string();
        assert!(s.starts_with("[FS-00007]"));
        assert!(s.contains("flush"));
    }

    #[test]
    fn test_error_source_atomic_replace_returns_inner() {
        let err = Error::AtomicReplaceFailed {
            step: "write",
            source: io::Error::from(io::ErrorKind::NotFound),
        };
        assert!(std::error::Error::source(&err).is_some());
    }

    #[test]
    fn test_error_code_partial_dir_op_returns_fs00008() {
        let err = Error::PartialDirectoryOp {
            failed_step: "create /a/b".into(),
            completed_steps: vec!["create /a".into()],
        };
        assert_eq!(err.code(), "FS-00008");
    }

    #[test]
    fn test_error_display_partial_dir_op_includes_step() {
        let err = Error::PartialDirectoryOp {
            failed_step: "create /a/b/c".into(),
            completed_steps: vec!["create /a".into(), "create /a/b".into()],
        };
        let s = err.to_string();
        assert!(s.starts_with("[FS-00008]"));
        assert!(s.contains("/a/b/c"));
    }

    #[test]
    fn test_error_source_partial_dir_op_returns_none() {
        let err = Error::PartialDirectoryOp {
            failed_step: "create /x".into(),
            completed_steps: vec![],
        };
        assert!(std::error::Error::source(&err).is_none());
    }

    // ── 0.4.0 additions ──────────────────────────────────────────────────

    #[test]
    fn test_error_code_shutdown_in_progress_returns_fs00009() {
        let err = Error::ShutdownInProgress;
        assert_eq!(err.code(), "FS-00009");
    }

    #[test]
    fn test_error_display_shutdown_in_progress_includes_code() {
        let err = Error::ShutdownInProgress;
        let s = err.to_string();
        assert!(s.starts_with("[FS-00009]"));
        assert!(s.contains("shutting down"));
    }

    #[test]
    fn test_error_source_shutdown_in_progress_returns_none() {
        let err = Error::ShutdownInProgress;
        assert!(std::error::Error::source(&err).is_none());
    }

    #[test]
    fn test_error_code_queue_full_returns_fs00010() {
        let err = Error::QueueFull;
        assert_eq!(err.code(), "FS-00010");
    }

    #[test]
    fn test_error_display_queue_full_marked_reserved() {
        let err = Error::QueueFull;
        let s = err.to_string();
        assert!(s.starts_with("[FS-00010]"));
        assert!(s.to_ascii_lowercase().contains("reserved"));
    }

    #[test]
    fn test_error_source_queue_full_returns_none() {
        let err = Error::QueueFull;
        assert!(std::error::Error::source(&err).is_none());
    }

    #[test]
    fn test_batch_error_fields_round_trip() {
        let inner = Error::Io(io::Error::from(io::ErrorKind::NotFound));
        let be = BatchError {
            failed_at: 3,
            completed: 3,
            source: Box::new(inner),
        };
        assert_eq!(be.failed_at, 3);
        assert_eq!(be.completed, 3);
        assert_eq!(be.inner().code(), "FS-00001");
    }

    #[test]
    fn test_batch_error_display_includes_indices_and_inner() {
        let inner = Error::HardwareProbeFailed {
            detail: "probe stub".into(),
        };
        let be = BatchError {
            failed_at: 7,
            completed: 7,
            source: Box::new(inner),
        };
        let s = be.to_string();
        assert!(s.contains("op 7"));
        assert!(s.contains("7 successful"));
        assert!(s.contains("FS-00003"));
    }

    #[test]
    fn test_batch_error_implements_std_error_with_inner_source() {
        let inner = Error::Io(io::Error::from(io::ErrorKind::PermissionDenied));
        let be = BatchError {
            failed_at: 0,
            completed: 0,
            source: Box::new(inner),
        };
        let dyn_err: &dyn std::error::Error = &be;
        assert!(dyn_err.source().is_some());
    }

    #[test]
    fn test_batch_error_into_inner_returns_boxed_error() {
        let inner = Error::ShutdownInProgress;
        let be = BatchError {
            failed_at: 0,
            completed: 0,
            source: Box::new(inner),
        };
        let unboxed: Box<Error> = be.into_inner();
        assert_eq!(unboxed.code(), "FS-00009");
    }
}