obj-core 1.1.0

Storage engine internals for the obj embedded document database (pager, WAL, B-tree, codec, catalog).
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
//! Platform layer (L0).
//!
//! This module owns the file-system primitives the pager and WAL
//! build on: opening a database file, positioned reads and writes at
//! fixed page boundaries, length queries, truncation, removal, and the
//! durability primitive [`FileHandle::sync_data`].
//!
//! # `unsafe` policy
//!
//! Power-of-ten Rule 8 confines `unsafe` to this submodule (and to
//! `libobj`). All positioned-I/O and durability calls go through the
//! `rustix` crate, which provides audited safe wrappers. The
//! cross-process locking submodule [`lock`] reaches for `libc::fcntl`
//! / `LockFileEx` directly because `rustix` does not expose POSIX
//! OFD-lock variants; every `unsafe` block in that submodule
//! carries a `// SAFETY:` comment per Rule 8. This `mod.rs` itself
//! contains no `unsafe` blocks and is `#![deny(unsafe_code)]`; the
//! lint is scoped to the file rather than the module tree so the
//! `lock` submodule can re-introduce its (audited) `unsafe`
//! blocks.

#![deny(unsafe_code)]

#[cfg(any(test, feature = "fault-injection"))]
pub mod fault;

pub mod lock;

pub use crate::platform::lock::{ReaderLock, WriterLock};

use std::fs::{File, OpenOptions};
use std::io;
use std::path::Path;

// Positioned-I/O extension trait differs per platform: the Unix
// `FileExt` exposes `read_exact_at` / `write_all_at` directly, while
// the Windows `FileExt` only exposes single-shot `seek_read` /
// `seek_write`. We import each as `_` so the methods are in scope and
// fall back to a hand-rolled retry loop on Windows.
#[cfg(unix)]
use std::os::unix::fs::FileExt as _;
// #75: on unix, newly-created DB/backup files get owner-only
// permissions (0600) via `OpenOptionsExt::mode` so a database that
// may hold plaintext (unencrypted) data is not world-readable at
// rest. The mode is the pre-umask request; the effective mode is
// `0600 & !umask`. Non-unix targets keep the platform default.
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt as _;
#[cfg(windows)]
use std::os::windows::fs::FileExt as _;

/// #75: owner read+write only (`rw-------`). Applied to freshly
/// created database and backup files on unix targets.
#[cfg(unix)]
const OWNER_ONLY_MODE: u32 = 0o600;

use crate::error::{Error, Result};

/// Maximum number of retry attempts for transient Windows I/O errors
/// (`ERROR_LOCK_VIOLATION` / `ERROR_SHARING_VIOLATION`). Mirrors
/// `SQLite`'s `winRetryIoerr` (10 attempts, linear backoff).
/// Power-of-ten Rule 2: every retry loop carries an explicit bound
/// and a recoverable `Err` on exhaustion.
#[cfg(windows)]
const WIN_TRANSIENT_RETRY_LIMIT: u32 = 10;

/// File-backend abstraction the pager and WAL build on.
///
/// `FileBackend` is the common subset of [`FileHandle`] operations
/// that fault-injection harnesses and the production type both expose
/// (Rule 9). Production code never holds `dyn FileBackend`; both
/// [`crate::pager::Pager`] and [`crate::wal::Wal`] are generic over
/// `F: FileBackend` so the dispatch stays monomorphised.
///
/// New methods added to this trait MUST mirror an existing
/// [`FileHandle`] method exactly. Adding a method that does not exist
/// on the production type would let the harness perform syscalls
/// production code cannot — a forbidden divergence (the harness
/// must be a strict superset of legal behaviour, never a separate
/// kingdom).
pub trait FileBackend: Sized {
    /// Length of the file in bytes. See [`FileHandle::len`].
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] on syscall failure.
    fn len(&self) -> Result<u64>;

    /// `true` iff the file has zero length.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] on syscall failure.
    fn is_empty(&self) -> Result<bool> {
        Ok(self.len()? == 0)
    }

    /// Positioned read. See [`FileHandle::read_exact_at`].
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] on syscall failure or harness-injected
    /// short read.
    fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> Result<()>;

    /// Positioned write. See [`FileHandle::write_all_at`].
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] on syscall failure.
    fn write_all_at(&self, buf: &[u8], offset: u64) -> Result<()>;

    /// Truncate or extend the file. See [`FileHandle::set_len`].
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] on syscall failure.
    fn set_len(&self, new_len: u64) -> Result<()>;

    /// See [`FileHandle::sync_data`].
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] on syscall failure.
    fn sync_data(&self, mode: SyncMode) -> Result<()>;

    /// See [`FileHandle::sync_all`].
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] on syscall failure.
    fn sync_all(&self) -> Result<()>;
}

/// Durability mode for [`FileHandle::sync_data`].
///
/// `SyncMode` is the user-visible knob that selects the cross-platform
/// fsync primitive `obj` calls after a WAL commit. The contract for
/// each variant is documented in `docs/format.md` § `SyncMode`.
///
/// The default is [`SyncMode::Full`]: a `commit` that returns
/// `Ok(())` is durable across a system-wide power loss. `Normal` is
/// the throughput-tuned middle ground; `Off` skips the syscall and is
/// only safe for tests and benchmarks.
///
/// Power-of-ten Rule 5: a three-state enum is far cheaper to audit
/// than three `bool` knobs, and the variants are exhaustive at every
/// `match`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub enum SyncMode {
    /// Strongest durability. Survives system-wide power loss.
    ///
    /// Maps to `fcntl(F_FULLFSYNC)` on macOS (forces the drive cache
    /// to flush), `FlushFileBuffers` on Windows, and `fdatasync` on
    /// Linux / BSDs. macOS's plain `fsync` is **not** sufficient
    /// here — it does not flush the drive cache; `F_FULLFSYNC` does.
    /// This is the standard wisdom for safety-critical macOS storage.
    #[default]
    Full,

    /// Process-crash and kernel-panic durability; may lose data on a
    /// sudden power loss if the drive's write cache has not been
    /// flushed by the time the OS acknowledges the call.
    ///
    /// Maps to `fsync` on Unix and `FlushFileBuffers` on Windows. On
    /// Windows there is no weaker primitive than `FlushFileBuffers`,
    /// so `Normal` and `Full` are equivalent there.
    Normal,

    /// No durability call. The OS may write the data eventually, but
    /// `obj` does not ask it to. Use only for tests and benchmarks
    /// where data loss is acceptable.
    Off,
}

/// A handle to a database file capable of positioned reads and writes
/// at page boundaries.
///
/// `FileHandle` is intentionally minimal — it exposes only the
/// operations the pager (L1) and WAL (L2) need. Higher layers must
/// never reach past it into `std::fs` directly; routing every syscall
/// through this type is how the project keeps Rule 8 enforceable.
#[derive(Debug)]
pub struct FileHandle {
    file: File,
}

impl FileHandle {
    /// Open `path` for read-write access, creating it if it does not
    /// exist. The new file is empty; the caller is responsible for
    /// writing the file header.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] if the file cannot be opened or created
    /// (permission denied, missing parent directory, etc.).
    pub fn open_or_create<P: AsRef<Path>>(path: P) -> Result<Self> {
        let mut opts = OpenOptions::new();
        opts.read(true).write(true).create(true).truncate(false);
        // #75: request owner-only permissions on unix. `mode` only
        // affects files this call CREATES; an existing file keeps its
        // current permissions.
        #[cfg(unix)]
        opts.mode(OWNER_ONLY_MODE);
        let file = opts.open(path)?;
        Ok(Self { file })
    }

    /// Open `path` for read-write access, failing if the file
    /// already exists (`O_CREAT | O_EXCL` on POSIX, `CREATE_NEW` on
    /// Windows). Used by M11 #92 hot-backup to guarantee the
    /// destination is never overwritten.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] if the file already exists, the parent
    /// directory does not exist, or any other syscall failure
    /// occurs.
    pub fn create_new<P: AsRef<Path>>(path: P) -> Result<Self> {
        let mut opts = OpenOptions::new();
        opts.read(true).write(true).create_new(true);
        // #75: owner-only permissions on unix for the always-fresh
        // backup destination.
        #[cfg(unix)]
        opts.mode(OWNER_ONLY_MODE);
        let file = opts.open(path)?;
        Ok(Self { file })
    }

    /// Length of the file in bytes.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] if the metadata syscall fails.
    pub fn len(&self) -> Result<u64> {
        let meta = self.file.metadata()?;
        Ok(meta.len())
    }

    /// `true` if the file is zero-length (i.e. just created).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] if the metadata syscall fails.
    pub fn is_empty(&self) -> Result<bool> {
        Ok(self.len()? == 0)
    }

    /// Positioned read. Fills `buf` from byte offset `offset`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] on syscall failure or on short read
    /// (e.g. file shorter than `offset + buf.len()`).
    pub fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> Result<()> {
        read_exact_at_impl(&self.file, buf, offset).map_err(Error::from)
    }

    /// Positioned write. Writes `buf` to byte offset `offset`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] on syscall failure or on short write.
    pub fn write_all_at(&self, buf: &[u8], offset: u64) -> Result<()> {
        write_all_at_impl(&self.file, buf, offset).map_err(Error::from)
    }

    /// Truncate or extend the file to `new_len` bytes.
    ///
    /// Used by the pager when the freelist is exhausted and a fresh
    /// page must be appended.
    ///
    /// On Windows this call wraps `SetEndOfFile`, which can transiently
    /// return `ERROR_LOCK_VIOLATION` when Windows Defender holds a
    /// short byte-range lock on the extending region. We retry under
    /// the same bounded scheme as positioned reads and writes (up to
    /// 10 attempts with linear backoff capped at 250 ms). On Unix the
    /// call is forwarded unchanged.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] on syscall failure.
    pub fn set_len(&self, new_len: u64) -> Result<()> {
        #[cfg(windows)]
        {
            set_len_with_retry(&self.file, new_len).map_err(Error::from)
        }
        #[cfg(not(windows))]
        {
            self.file.set_len(new_len).map_err(Error::from)
        }
    }

    /// Force file contents and metadata to disk. Used at close.
    ///
    /// Power-of-ten Rule 7: the underlying call returns
    /// `io::Result<()>` and is propagated explicitly.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] on syscall failure.
    pub fn sync_all(&self) -> Result<()> {
        self.file.sync_all().map_err(Error::from)
    }

    /// Force file data (and on `Full`, the drive cache) to persistent
    /// storage according to `mode`. See [`SyncMode`] for the exact
    /// per-variant durability promise.
    ///
    /// On `SyncMode::Off` this call is a no-op.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] on syscall failure.
    pub fn sync_data(&self, mode: SyncMode) -> Result<()> {
        match mode {
            SyncMode::Off => Ok(()),
            SyncMode::Normal => sync_data_normal(&self.file),
            SyncMode::Full => sync_data_full(&self.file),
        }
    }
}

impl FileBackend for FileHandle {
    fn len(&self) -> Result<u64> {
        FileHandle::len(self)
    }
    fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> Result<()> {
        FileHandle::read_exact_at(self, buf, offset)
    }
    fn write_all_at(&self, buf: &[u8], offset: u64) -> Result<()> {
        FileHandle::write_all_at(self, buf, offset)
    }
    fn set_len(&self, new_len: u64) -> Result<()> {
        FileHandle::set_len(self, new_len)
    }
    fn sync_data(&self, mode: SyncMode) -> Result<()> {
        FileHandle::sync_data(self, mode)
    }
    fn sync_all(&self) -> Result<()> {
        FileHandle::sync_all(self)
    }
}

// --------------------------------------------------------------------
// Per-platform positioned-I/O primitives. Unix's `FileExt` exposes
// `read_exact_at` / `write_all_at` natively; Windows only offers the
// single-shot `seek_read` / `seek_write`, so we retry until the
// requested span is satisfied or the call fails.
// --------------------------------------------------------------------

#[cfg(unix)]
fn read_exact_at_impl(file: &File, buf: &mut [u8], offset: u64) -> io::Result<()> {
    file.read_exact_at(buf, offset)
}

#[cfg(unix)]
fn write_all_at_impl(file: &File, buf: &[u8], offset: u64) -> io::Result<()> {
    file.write_all_at(buf, offset)
}

#[cfg(windows)]
fn read_exact_at_impl(file: &File, mut buf: &mut [u8], mut offset: u64) -> io::Result<()> {
    let mut attempt: u32 = 0;
    while !buf.is_empty() {
        match file.seek_read(buf, offset) {
            Ok(0) => {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "failed to fill whole buffer",
                ));
            }
            Ok(n) => {
                // Forward progress: any short read that returned data
                // is not contention, so reset the transient counter.
                attempt = 0;
                let tmp = buf;
                buf = &mut tmp[n..];
                offset += n as u64;
            }
            Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
            Err(e) if is_transient_io_error(&e) => {
                if attempt >= WIN_TRANSIENT_RETRY_LIMIT - 1 {
                    return Err(e);
                }
                windows_io_backoff(attempt + 1);
                attempt += 1;
            }
            Err(e) => return Err(e),
        }
    }
    Ok(())
}

#[cfg(windows)]
fn write_all_at_impl(file: &File, mut buf: &[u8], mut offset: u64) -> io::Result<()> {
    let mut attempt: u32 = 0;
    while !buf.is_empty() {
        match file.seek_write(buf, offset) {
            Ok(0) => {
                return Err(io::Error::new(
                    io::ErrorKind::WriteZero,
                    "failed to write whole buffer",
                ));
            }
            Ok(n) => {
                attempt = 0;
                buf = &buf[n..];
                offset += n as u64;
            }
            Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
            Err(e) if is_transient_io_error(&e) => {
                if attempt >= WIN_TRANSIENT_RETRY_LIMIT - 1 {
                    return Err(e);
                }
                windows_io_backoff(attempt + 1);
                attempt += 1;
            }
            Err(e) => return Err(e),
        }
    }
    Ok(())
}

/// Windows-only: truncate or extend `file` to `new_len`, retrying
/// `ERROR_LOCK_VIOLATION` / `ERROR_SHARING_VIOLATION` up to
/// [`WIN_TRANSIENT_RETRY_LIMIT`] times with linear backoff. Mirrors
/// the retry shape used for positioned reads and writes.
#[cfg(windows)]
fn set_len_with_retry(file: &File, new_len: u64) -> io::Result<()> {
    retry_transient_io(|| file.set_len(new_len))
}

/// Generic Windows transient-I/O retry harness. The closure is called
/// at least once; on `ERROR_LOCK_VIOLATION` / `ERROR_SHARING_VIOLATION`
/// the harness sleeps with linear backoff and retries up to
/// [`WIN_TRANSIENT_RETRY_LIMIT`] times before surfacing the last
/// `io::Error`. Used by `set_len_with_retry`; also the unit-test
/// hook for the exhaustion path (no Defender / real lock needed).
#[cfg(windows)]
fn retry_transient_io<F>(mut op: F) -> io::Result<()>
where
    F: FnMut() -> io::Result<()>,
{
    let mut attempt: u32 = 0;
    loop {
        match op() {
            Ok(()) => return Ok(()),
            Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
            Err(e) if is_transient_io_error(&e) => {
                if attempt >= WIN_TRANSIENT_RETRY_LIMIT - 1 {
                    return Err(e);
                }
                windows_io_backoff(attempt + 1);
                attempt += 1;
            }
            Err(e) => return Err(e),
        }
    }
}

/// `true` iff `e` is a Windows transient I/O error that should be
/// retried: `ERROR_LOCK_VIOLATION` (33) or `ERROR_SHARING_VIOLATION`
/// (32). These are the codes Windows Defender's real-time scanner
/// emits when it briefly holds a byte-range lock on a file being
/// scanned; `SQLite`'s `winRetryIoerr` retries the same two codes.
#[cfg(windows)]
fn is_transient_io_error(e: &io::Error) -> bool {
    use windows_sys::Win32::Foundation::{ERROR_LOCK_VIOLATION, ERROR_SHARING_VIOLATION};
    // `raw_os_error` returns `Option<i32>`; the `windows-sys`
    // constants are `u32`. Both error codes are small positive
    // numbers, so `cast_signed` is well-defined and preserves the
    // bit pattern `from_raw_os_error` round-trips back to.
    match e.raw_os_error() {
        Some(code) => {
            code == ERROR_LOCK_VIOLATION.cast_signed()
                || code == ERROR_SHARING_VIOLATION.cast_signed()
        }
        None => false,
    }
}

/// Linear backoff between transient-I/O retries. Sleep
/// `min(attempt * 25, 250)` ms, mirroring `SQLite`'s `winRetryIoerr`.
/// The caller is responsible for bounding `attempt` via
/// [`WIN_TRANSIENT_RETRY_LIMIT`] (Power-of-ten Rule 2).
#[cfg(windows)]
fn windows_io_backoff(attempt: u32) {
    const STEP_MS: u64 = 25;
    const CAP_MS: u64 = 250;
    let delay = u64::from(attempt).saturating_mul(STEP_MS).min(CAP_MS);
    std::thread::sleep(std::time::Duration::from_millis(delay));
}

// --------------------------------------------------------------------
// Per-platform sync primitives. Kept as small free functions so the
// platform switch is one match-arm per variant rather than threading
// `cfg` attributes through `FileHandle::sync_data`.
// --------------------------------------------------------------------

/// `Normal` durability — `fsync` on Unix, `FlushFileBuffers` on
/// Windows. Survives process / kernel crash but may lose data on a
/// sudden power loss if the drive cache has not been flushed.
fn sync_data_normal(file: &File) -> Result<()> {
    // `std::fs::File::sync_all` invokes `fsync(2)` on Unix and
    // `FlushFileBuffers` on Windows. Both flush the OS page cache;
    // neither, on macOS, flushes the drive cache (that is `Full`'s
    // job via `F_FULLFSYNC`). Using `sync_all` here keeps the
    // platform switch in one place and avoids reimplementing the
    // `fsync` syscall ourselves.
    file.sync_all().map_err(Error::from)
}

/// `Full` durability — flush the drive cache where the platform
/// distinguishes it from the OS cache. See [`SyncMode::Full`] for
/// the per-OS mapping.
#[cfg(target_vendor = "apple")]
fn sync_data_full(file: &File) -> Result<()> {
    // macOS: plain `fsync` does NOT flush the drive cache. The
    // documented way to do that is `fcntl(F_FULLFSYNC)`, which the
    // `rustix` crate exposes safely. See
    // <https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/fcntl.2.html>.
    rustix::fs::fcntl_fullfsync(file).map_err(|e| Error::Io(io::Error::from(e)))
}

/// `Full` durability on non-Apple Unix targets: `fdatasync(2)` is
/// sufficient (the on-disk data is flushed, metadata changes that do
/// not affect the data — like mtime — are not).
#[cfg(all(unix, not(target_vendor = "apple")))]
fn sync_data_full(file: &File) -> Result<()> {
    rustix::fs::fdatasync(file).map_err(|e| Error::Io(io::Error::from(e)))
}

/// `Full` durability on Windows: `FlushFileBuffers` is the strongest
/// primitive; `std::fs::File::sync_all` invokes it.
#[cfg(windows)]
fn sync_data_full(file: &File) -> Result<()> {
    file.sync_all().map_err(Error::from)
}

/// Delete the file at `path` if it exists.
///
/// Used by `Pager::close()` to remove the WAL sidecar after a clean
/// shutdown. Missing-file is intentionally **not** an error; the
/// post-condition is "no file at `path`", and that is satisfied either
/// by deletion or by absence.
///
/// # Errors
///
/// Returns [`Error::Io`] on any failure other than `NotFound`.
pub fn remove_file_if_exists<P: AsRef<Path>>(path: P) -> Result<()> {
    match std::fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(Error::Io(e)),
    }
}

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

#[cfg(test)]
mod tests {
    use super::{FileHandle, SyncMode};
    use tempfile::TempDir;

    fn write_and_sync(mode: SyncMode) {
        let dir = TempDir::new().expect("tempdir");
        let path = dir.path().join("sync.bin");
        let h = FileHandle::open_or_create(&path).expect("open");
        h.set_len(4096).expect("set_len");
        h.write_all_at(&[0xABu8; 4096], 0).expect("write");
        h.sync_data(mode).expect("sync_data must succeed");
    }

    #[test]
    fn sync_data_full_returns_ok() {
        write_and_sync(SyncMode::Full);
    }

    #[test]
    fn sync_data_normal_returns_ok() {
        write_and_sync(SyncMode::Normal);
    }

    #[test]
    fn sync_data_off_is_noop() {
        write_and_sync(SyncMode::Off);
    }

    #[test]
    fn default_is_full() {
        assert_eq!(SyncMode::default(), SyncMode::Full);
    }

    // --------------------------------------------------------------
    // Windows-only retry-helper tests. These are compiled and run
    // only on `cfg(windows)`; the macOS / Linux test runs ignore
    // them entirely. The helpers under test are themselves
    // `#[cfg(windows)]`, so the gating must match.
    // --------------------------------------------------------------

    #[cfg(windows)]
    #[test]
    fn is_transient_io_error_matches_lock_and_sharing_codes() {
        use super::is_transient_io_error;
        use std::io;
        use windows_sys::Win32::Foundation::{
            ERROR_ACCESS_DENIED, ERROR_LOCK_VIOLATION, ERROR_SHARING_VIOLATION,
        };

        let lock = io::Error::from_raw_os_error(ERROR_LOCK_VIOLATION.cast_signed());
        let share = io::Error::from_raw_os_error(ERROR_SHARING_VIOLATION.cast_signed());
        assert!(is_transient_io_error(&lock));
        assert!(is_transient_io_error(&share));

        // Non-transient OS error: `ERROR_ACCESS_DENIED` is a hard
        // failure, not a retry candidate.
        let denied = io::Error::from_raw_os_error(ERROR_ACCESS_DENIED.cast_signed());
        assert!(!is_transient_io_error(&denied));

        // Kind-only errors carry `raw_os_error() == None` and must
        // never be treated as transient.
        let not_found = io::Error::from(io::ErrorKind::NotFound);
        assert!(!is_transient_io_error(&not_found));
    }

    #[cfg(windows)]
    #[test]
    fn windows_io_backoff_is_bounded() {
        use super::windows_io_backoff;
        use std::time::Instant;

        // Each individual attempt must sleep at most ~250 ms. Allow
        // generous headroom for scheduler jitter on CI runners.
        let start = Instant::now();
        windows_io_backoff(1);
        assert!(start.elapsed() < std::time::Duration::from_secs(1));

        // Cap holds: attempt 100 still sleeps no more than ~250 ms.
        let start = Instant::now();
        windows_io_backoff(100);
        assert!(start.elapsed() < std::time::Duration::from_secs(1));
    }

    #[cfg(windows)]
    #[test]
    fn retry_transient_io_returns_first_success() {
        use super::retry_transient_io;
        use std::cell::Cell;
        use std::io;
        use windows_sys::Win32::Foundation::ERROR_LOCK_VIOLATION;

        // Two transient failures, then success. The harness must
        // see exactly three calls and return `Ok(())`.
        let calls = Cell::new(0u32);
        let result = retry_transient_io(|| {
            calls.set(calls.get() + 1);
            if calls.get() < 3 {
                Err(io::Error::from_raw_os_error(
                    ERROR_LOCK_VIOLATION.cast_signed(),
                ))
            } else {
                Ok(())
            }
        });
        result.expect("must recover after transient sequence");
        assert_eq!(calls.get(), 3);
    }

    #[cfg(windows)]
    #[test]
    fn retry_transient_io_exhausts_and_surfaces_last_error() {
        use super::{retry_transient_io, WIN_TRANSIENT_RETRY_LIMIT};
        use std::cell::Cell;
        use std::io;
        use windows_sys::Win32::Foundation::ERROR_LOCK_VIOLATION;

        // Always-transient: the harness must call the closure
        // exactly `WIN_TRANSIENT_RETRY_LIMIT` times and return the
        // last raw OS error unchanged.
        let calls = Cell::new(0u32);
        let err = retry_transient_io(|| -> io::Result<()> {
            calls.set(calls.get() + 1);
            Err(io::Error::from_raw_os_error(
                ERROR_LOCK_VIOLATION.cast_signed(),
            ))
        })
        .expect_err("must exhaust");
        assert_eq!(calls.get(), WIN_TRANSIENT_RETRY_LIMIT);
        assert_eq!(err.raw_os_error(), Some(ERROR_LOCK_VIOLATION.cast_signed()));
    }

    #[cfg(windows)]
    #[test]
    fn retry_transient_io_returns_non_transient_immediately() {
        use super::retry_transient_io;
        use std::cell::Cell;
        use std::io;
        use windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED;

        // Non-transient errors must not be retried. The closure
        // is called exactly once.
        let calls = Cell::new(0u32);
        let err = retry_transient_io(|| -> io::Result<()> {
            calls.set(calls.get() + 1);
            Err(io::Error::from_raw_os_error(
                ERROR_ACCESS_DENIED.cast_signed(),
            ))
        })
        .expect_err("must fail");
        assert_eq!(calls.get(), 1);
        assert_eq!(err.raw_os_error(), Some(ERROR_ACCESS_DENIED.cast_signed()));
    }
}