store_io_platform/lib.rs
1//! # store-io-platform
2//!
3//! The boundary between store-io's engine and the operating system.
4//!
5//! Everything above this crate (error classification, barriers, formats,
6//! provisioning, slots) is one shared code path. Below it, each platform
7//! backend (Linux, Windows, macOS) and the deterministic simulator implement
8//! two traits:
9//!
10//! - [`Platform`]: metadata operations (open, create, rename, directory
11//! flush, lock, allocate, full flush, probe), synchronous and off the hot
12//! path, plus a factory for per-thread [`Queue`]s.
13//! - [`Queue`]: data operations, completion-shaped. [`Queue::submit`] takes
14//! an [`IoOp`] that owns its buffer; the buffer comes back in a
15//! [`Completion`]. A synchronous backend performs the system call inside
16//! `submit` and completes immediately (no thread hop); the simulator and the
17//! io_uring / IOCP backends complete later, possibly out of order.
18//!
19//! Backends return raw operating-system codes ([`OsError`]) and never
20//! classify them; the engine decides what an error means (see
21//! `store_io_core::errno`).
22//!
23//! ## Contracts every implementation keeps
24//!
25//! 1. An operation's buffer is not touched by the caller between `submit` and
26//! the completion that returns it, and is never freed by the backend: it is
27//! returned in the completion, or in [`Rejected`] if `submit` refuses it.
28//! Only a failed completion may withhold it, for ever, when the kernel may
29//! still use it (an asynchronous backend that lost track of its kernel).
30//! 2. A file handle passed in an operation stays open until that operation's
31//! completion has been reaped. The engine guarantees this by keeping the
32//! handle alive while operations are in flight; a backend may copy the raw
33//! descriptor.
34//! 3. `submit` returning `Err` means the operation never reached the kernel or
35//! device (the media is untouched).
36//! 4. A completion's `result` is the raw outcome: `Ok(n)` bytes transferred,
37//! which may be short, or `Err(code)`.
38//! 5. No call ever waits with a timeout. [`Queue::wait`] blocks until the
39//! requested completions exist.
40
41#![deny(warnings)]
42#![forbid(unsafe_code)]
43
44use core::fmt;
45use std::path::Path;
46
47pub use store_io_buf::IoBuf;
48pub use store_io_core::error::OsError;
49pub use store_io_core::evidence::Evidence;
50
51/// Result carrying a raw operating-system error.
52pub type RawResult<T> = Result<T, OsError>;
53
54/// A single path component: 1 to 255 bytes, no separators, not `.` or `..`,
55/// no NUL. Validated once at construction so backends never see a path that
56/// could escape its directory.
57#[derive(Clone, PartialEq, Eq, Hash)]
58pub struct FileName(String);
59
60/// The name is not a valid single path component.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub struct InvalidFileName;
63
64impl fmt::Display for InvalidFileName {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 f.write_str("not a single path component (1-255 bytes, no separators, not . or .., no NUL)")
67 }
68}
69
70impl std::error::Error for InvalidFileName {}
71
72impl FileName {
73 /// Validates a file name.
74 ///
75 /// # Errors
76 ///
77 /// [`InvalidFileName`] for an empty, overlong, `.`/`..`, or separator- or
78 /// NUL-containing name.
79 ///
80 /// # Examples
81 ///
82 /// ```
83 /// use store_io_platform::FileName;
84 /// assert!(FileName::new("store.sio").is_ok());
85 /// assert!(FileName::new("../etc").is_err());
86 /// assert!(FileName::new("a/b").is_err());
87 /// ```
88 pub fn new(name: &str) -> Result<Self, InvalidFileName> {
89 let bad = name.is_empty()
90 || name.len() > 255
91 || name == "."
92 || name == ".."
93 || name
94 .bytes()
95 .any(|b| b == b'/' || b == b'\\' || b == 0 || b == b':');
96 if bad {
97 Err(InvalidFileName)
98 } else {
99 Ok(Self(name.to_owned()))
100 }
101 }
102
103 /// The name.
104 #[must_use]
105 pub fn as_str(&self) -> &str {
106 &self.0
107 }
108}
109
110impl fmt::Debug for FileName {
111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 fmt::Debug::fmt(&self.0, f)
113 }
114}
115
116/// How a file is opened.
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum FileMode {
119 /// Direct (unbuffered) reads and writes.
120 ReadWrite,
121 /// Direct reads only; the handle has no write rights.
122 ReadOnly,
123}
124
125/// How space is released.
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum ReleaseHow {
128 /// Deallocate (punch a hole / mark sparse and zero): space returns to the
129 /// filesystem; the range must be provisioned again before use.
130 Deallocate,
131 /// Trim in place: allocation kept, contents undefined.
132 TrimInPlace,
133}
134
135/// Facts about a byte range of a file.
136#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
137pub struct RangeState {
138 /// Some extent in the range is allocated but unwritten.
139 pub unwritten: store_io_core::evidence::Tri,
140 /// Some extent in the range is shared with another file (reflink).
141 pub shared: store_io_core::evidence::Tri,
142 /// Pages of the range resident in the OS page cache, if knowable.
143 pub cached_pages: Option<u64>,
144 /// Valid data length covers the range (Windows), if knowable.
145 pub valid_data: store_io_core::evidence::Tri,
146}
147
148/// Per-queue configuration.
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150pub struct QueueConfig {
151 /// Maximum operations in flight.
152 pub depth: u32,
153 /// A hint that the caller submits several independent operations before
154 /// it waits. A backend that would otherwise run them one by one inside
155 /// `submit` (the Linux synchronous tier) may then run them concurrently
156 /// on worker threads. `false` (the default) keeps every operation on the
157 /// calling thread: the Linux backend then performs each inside `submit`
158 /// on either tier, since a caller that waits for every operation gains
159 /// nothing from a ring (D-104).
160 pub parallel: bool,
161 /// Worker threads for the backend's shared pool, used only if this queue
162 /// is the one that starts it (0 = the backend's default; a backend may
163 /// cap it). A pool already running is never resized; the backend reports
164 /// its size.
165 pub pool_threads: u32,
166 /// Who uses the queue: one thread for its whole life, or any thread that
167 /// borrows it (D-081, D-083). A backend may set the queue up differently
168 /// for each (a thread-owned io_uring ring); others ignore it.
169 pub owner: Owner,
170}
171
172impl Default for QueueConfig {
173 fn default() -> Self {
174 Self {
175 depth: 64,
176 parallel: false,
177 pool_threads: 0,
178 owner: Owner::Shared,
179 }
180 }
181}
182
183/// Who uses a queue ([`QueueConfig::owner`]).
184#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
185#[non_exhaustive]
186pub enum Owner {
187 /// Borrowed by any thread, one at a time (the blocking layers' lanes).
188 #[default]
189 Shared,
190 /// Used by one thread for its whole life (an engine-layer submitter).
191 Thread,
192}
193
194/// Which kernel interface the Linux backend's queues use (D-082). Other
195/// backends have one interface and ignore it.
196#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
197#[non_exhaustive]
198pub enum LinuxTier {
199 /// io_uring where the kernel accepts store-io's rings (probed once per
200 /// process), else the synchronous tier; the reason is reported.
201 #[default]
202 Auto,
203 /// One blocking system call per operation (T3), inline or on the submit
204 /// pool.
205 Sync,
206 /// io_uring rings (store-io's own binding, D-093): operations complete
207 /// asynchronously and never run on kernel worker threads. Refused where
208 /// the kernel refuses the rings.
209 Uring,
210}
211
212/// A kernel interface for I/O ([`IoPath`]).
213#[derive(Debug, Clone, Copy, PartialEq, Eq)]
214#[non_exhaustive]
215pub enum IoInterface {
216 /// Linux io_uring.
217 IoUring,
218 /// One blocking system call per operation (the Linux synchronous tier).
219 Synchronous,
220 /// Windows I/O completion ports.
221 Iocp,
222 /// The deterministic simulator.
223 Simulator,
224 /// Another backend's interface.
225 Other,
226}
227
228impl fmt::Display for IoInterface {
229 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
230 f.write_str(match self {
231 Self::IoUring => "io_uring",
232 Self::Synchronous => "synchronous",
233 Self::Iocp => "IOCP",
234 Self::Simulator => "simulator",
235 Self::Other => "other",
236 })
237 }
238}
239
240/// The kernel interface a platform's queues use, and why (reported in
241/// `StoreReport`).
242#[derive(Debug, Clone, PartialEq, Eq)]
243pub struct IoPath {
244 /// The interface.
245 pub interface: IoInterface,
246 /// Why it was chosen.
247 pub reason: String,
248}
249
250/// Ends a [`Queue::wait`] from another thread (D-083): the queue's current
251/// wait, or its next one if none is in progress, returns, possibly having
252/// added nothing. A wake never creates, loses or repeats a completion.
253pub trait Wake: Send + Sync + Clone + 'static {
254 /// Wakes the queue's waiter. Cheap and never blocks.
255 fn wake(&self);
256}
257
258/// A data operation. Owns its buffer until it completes.
259#[derive(Debug)]
260pub enum IoOp<'a, F> {
261 /// Write the buffer's bytes at `offset`. `dsync` asks for durability at
262 /// completion (Linux `RWF_DSYNC`; FUA in the simulator).
263 Write {
264 /// Target file.
265 file: &'a F,
266 /// Byte offset.
267 offset: u64,
268 /// The data; its length is the transfer size.
269 buf: IoBuf,
270 /// Durable at completion.
271 dsync: bool,
272 },
273 /// Read `buf.len()` bytes at `offset` into the buffer.
274 Read {
275 /// Source file.
276 file: &'a F,
277 /// Byte offset.
278 offset: u64,
279 /// Destination.
280 buf: IoBuf,
281 },
282 /// Flush the device cache for this file's data (`fdatasync`,
283 /// `NtFlushBuffersFileEx(DATA_SYNC_ONLY)`, `F_FULLFSYNC`).
284 FlushData {
285 /// File whose data (and the device cache) is flushed.
286 file: &'a F,
287 },
288}
289
290/// A finished operation.
291#[derive(Debug)]
292pub struct Completion {
293 /// The tag passed to [`Queue::submit`].
294 pub tag: u64,
295 /// The operation's buffer, returned (`None` for flushes).
296 pub buf: Option<IoBuf>,
297 /// Bytes transferred (possibly short), or the raw error.
298 pub result: RawResult<usize>,
299}
300
301/// An operation `submit` refused; it never reached the kernel or device.
302#[derive(Debug)]
303pub struct Rejected {
304 /// The operation's buffer, returned to the caller.
305 pub buf: Option<IoBuf>,
306 /// The raw error, if the refusal came from the OS (a full queue has none).
307 pub raw: Option<OsError>,
308}
309
310/// Completions collected by [`Queue::reap`] / [`Queue::wait`].
311///
312/// Allocated once with a fixed capacity; reaping never grows it, so the hot
313/// path never allocates.
314#[derive(Debug)]
315pub struct CompletionBuf {
316 items: Vec<Completion>,
317 cap: usize,
318}
319
320impl CompletionBuf {
321 /// Creates a buffer for up to `cap` completions.
322 #[must_use]
323 pub fn with_capacity(cap: usize) -> Self {
324 Self {
325 items: Vec::with_capacity(cap),
326 cap,
327 }
328 }
329
330 /// Room left before the buffer is full.
331 #[must_use]
332 pub fn room(&self) -> usize {
333 self.cap - self.items.len()
334 }
335
336 /// Adds a completion; returns it back if the buffer is full.
337 pub fn push(&mut self, c: Completion) -> Result<(), Completion> {
338 if self.items.len() == self.cap {
339 return Err(c);
340 }
341 self.items.push(c);
342 Ok(())
343 }
344
345 /// Removes and returns every collected completion, in arrival order.
346 pub fn drain(&mut self) -> std::vec::Drain<'_, Completion> {
347 self.items.drain(..)
348 }
349
350 /// Number of collected completions.
351 #[must_use]
352 pub fn len(&self) -> usize {
353 self.items.len()
354 }
355
356 /// Whether nothing is collected.
357 #[must_use]
358 pub fn is_empty(&self) -> bool {
359 self.items.is_empty()
360 }
361}
362
363/// A per-thread submission queue. Not `Sync`: one thread submits and reaps.
364pub trait Queue {
365 /// The platform's file handle type.
366 type File;
367 /// The queue's waker ([`Self::waker`]).
368 type Waker: Wake;
369
370 /// Submits an operation tagged with a caller value.
371 ///
372 /// # Errors
373 ///
374 /// [`Rejected`] when the operation was not submitted (queue full or an OS
375 /// refusal before any I/O); its buffer is returned.
376 fn submit(&mut self, op: IoOp<'_, Self::File>, tag: u64) -> Result<(), Rejected>;
377
378 /// Moves finished completions into `out` without blocking; returns how
379 /// many were added.
380 fn reap(&mut self, out: &mut CompletionBuf) -> usize;
381
382 /// Blocks until at least `min` completions have been added to `out`, or
383 /// `out` is full, or nothing is left in flight, or the queue's waker
384 /// fired ([`Self::waker`]; the wait may then have added nothing); returns
385 /// how many were added. Never times out, and never waits for more than
386 /// is in flight.
387 ///
388 /// # Errors
389 ///
390 /// The raw error if waiting itself failed (not an operation error).
391 fn wait(&mut self, min: usize, out: &mut CompletionBuf) -> RawResult<usize>;
392
393 /// Operations submitted and not yet reaped.
394 fn in_flight(&self) -> usize;
395
396 /// Whether [`Self::perform`] would perform an operation now: this queue
397 /// runs every operation inside [`Self::submit`] and holds nothing. The
398 /// default: never.
399 fn performs(&self) -> bool {
400 false
401 }
402
403 /// Performs `op` now, on the calling thread, when [`Self::performs`]:
404 /// its buffer and result, exactly as its completion would carry them
405 /// (the same checks first, the same faults), with no completion left
406 /// behind. Otherwise the operation comes back (`Ok(Err(op))`) for
407 /// [`Self::submit`]. The default never performs.
408 ///
409 /// # Errors
410 ///
411 /// [`Rejected`] as [`Self::submit`]: refused before any I/O.
412 #[allow(clippy::type_complexity)]
413 fn perform<'a>(
414 &mut self,
415 op: IoOp<'a, Self::File>,
416 ) -> Result<Result<(Option<IoBuf>, RawResult<usize>), IoOp<'a, Self::File>>, Rejected> {
417 Ok(Err(op))
418 }
419
420 /// A handle another thread uses to end this queue's wait (D-083).
421 fn waker(&self) -> Self::Waker;
422
423 /// Worker threads that run this queue's operations concurrently, when
424 /// the backend runs them on a pool ([`QueueConfig::parallel`]); `None`
425 /// when they run inside `submit` or in the kernel.
426 fn workers(&self) -> Option<usize> {
427 None
428 }
429}
430
431/// A platform backend.
432pub trait Platform: Send + Sync + 'static {
433 /// Open file handle (closed on drop).
434 type File: Send + Sync;
435 /// Open directory handle.
436 type Dir: Send + Sync;
437 /// Held ownership lock (released on drop, after in-flight I/O on the
438 /// locked file has completed).
439 type Lock: Send + Sync;
440 /// Per-thread queue.
441 type Queue: Queue<File = Self::File>;
442
443 /// Opens a directory; with `create`, creates it if missing and syncs its
444 /// parent (the directory holding its entry), also when it already exists
445 /// (an earlier attempt may have died before the sync). For an existing
446 /// directory, a parent that cannot be synced on that volume (no
447 /// directory flush: unsupported; read-only on macOS; on Windows not
448 /// openable for it or write-protected) is not an error. A directory this
449 /// call made is removed again if its sync fails (POSIX: also its open),
450 /// when it is still the one made.
451 ///
452 /// # Errors
453 ///
454 /// The raw error.
455 fn open_dir(&self, path: &Path, create: bool) -> RawResult<Self::Dir>;
456
457 /// Creates a new file exclusively (fails if it exists), mode 0600.
458 ///
459 /// # Errors
460 ///
461 /// The raw error; the file does not exist afterwards unless creation
462 /// itself succeeded.
463 fn create_file(&self, dir: &Self::Dir, name: &FileName) -> RawResult<Self::File>;
464
465 /// Opens an existing file for direct I/O.
466 ///
467 /// # Errors
468 ///
469 /// The raw error.
470 fn open_file(&self, dir: &Self::Dir, name: &FileName, mode: FileMode) -> RawResult<Self::File>;
471
472 /// Atomically replaces `to` with `from` in the same directory. The file
473 /// handle is the open `from` (Windows renames by handle).
474 ///
475 /// # Errors
476 ///
477 /// The raw error. After a failure the rename may or may not have
478 /// happened; the engine treats it as durability-unknown.
479 fn rename_replace(
480 &self,
481 dir: &Self::Dir,
482 from: &FileName,
483 to: &FileName,
484 file: &Self::File,
485 ) -> RawResult<()>;
486
487 /// Renames `from` to `to` in the same directory, refusing if `to`
488 /// exists (the platform's "already exists" error, nothing renamed): a
489 /// rename that can never replace a file another process created after
490 /// the caller looked. Atomic where the system has such a rename (Linux
491 /// `RENAME_NOREPLACE`, Windows); elsewhere a hard link named `to` made
492 /// to the file, the directory flushed, then `from` removed, so a crash
493 /// may leave both names on the file (never neither). The file handle is
494 /// the open `from` (Windows renames by handle).
495 ///
496 /// # Errors
497 ///
498 /// The raw error. After any other failure the file may be under `from`,
499 /// under `to`, or (the link fallback) under both; the engine treats it
500 /// as durability-unknown.
501 fn rename_noreplace(
502 &self,
503 dir: &Self::Dir,
504 from: &FileName,
505 to: &FileName,
506 file: &Self::File,
507 ) -> RawResult<()>;
508
509 /// Removes a file.
510 ///
511 /// # Errors
512 ///
513 /// The raw error.
514 fn unlink(&self, dir: &Self::Dir, name: &FileName) -> RawResult<()>;
515
516 /// Makes the directory's entries durable. An unsupported directory flush
517 /// is an error, never success.
518 ///
519 /// # Errors
520 ///
521 /// The raw error.
522 fn sync_dir(&self, dir: &Self::Dir) -> RawResult<()>;
523
524 /// A coarse monotonic clock in milliseconds (resolution 1-16 ms) that
525 /// never decreases. Cold: read only by queries such as
526 /// `oldest_outstanding`, never on the I/O path.
527 fn monotonic_ms(&self) -> u64;
528
529 /// A queue as [`Platform::queue`] makes it, with `file` registered with
530 /// it where the backend can (D-078, D-107: an io_uring direct descriptor
531 /// on a thread-owned ring, used by reads only), so an operation on `file`
532 /// may skip the per-operation file lookup in the kernel. Best effort: a
533 /// backend that
534 /// cannot or will not register returns a plain queue (the default), and
535 /// an operation on any other file works as on a plain queue. The queue
536 /// keeps the file it registered open for as long as it lives.
537 ///
538 /// # Errors
539 ///
540 /// As [`Platform::queue`] (a refused registration is not an error).
541 fn queue_registered(&self, cfg: QueueConfig, file: &Self::File) -> RawResult<Self::Queue> {
542 let _ = file;
543 self.queue(cfg)
544 }
545
546 /// Whether flushes may run concurrently on separate handles of one file
547 /// (D-124). Both must hold: a flush through any handle persists every
548 /// write that completed through **any** handle of the file before the
549 /// flush began (file systems flush the file, not the handle); and a
550 /// flush reports every write-back failure since the previous flush **on
551 /// the same handle**, independently of flushes on other handles (Linux
552 /// 4.16 and later: the error sequence is kept per open file
553 /// description, and a handle opened after an unseen error still sees
554 /// it). False by default: one flush in flight.
555 fn flush_errors_per_handle(&self) -> bool {
556 false
557 }
558
559 /// A second handle on the very file `file` is (never another file that
560 /// has since taken its name), read-write, with an open file description
561 /// of its own and no lock: what a store's extra flush slots flush
562 /// through (D-124). `None` where the platform cannot (the default).
563 fn reopen(&self, file: &Self::File) -> Option<Self::File> {
564 let _ = file;
565 None
566 }
567
568 /// The kernel interface this platform's queues use, and why.
569 fn io_path(&self) -> IoPath {
570 IoPath {
571 interface: IoInterface::Other,
572 reason: "the backend's only interface".to_owned(),
573 }
574 }
575
576 /// Takes the exclusive ownership lock on an open file. At most one lock
577 /// (exclusive or shared) may be held per handle: on Linux a second lock
578 /// on the same handle shares the first's open file description, and
579 /// releasing either releases both.
580 ///
581 /// # Errors
582 ///
583 /// The raw error (another holder reports the platform's "would block").
584 fn lock_exclusive(&self, file: &Self::File) -> RawResult<Self::Lock>;
585
586 /// Takes the shared (reader) ownership lock on an open file, which may
587 /// be read-only. Shared holders coexist; a shared holder and an exclusive
588 /// holder exclude each other. At most one lock per handle (see
589 /// [`Self::lock_exclusive`]).
590 ///
591 /// # Errors
592 ///
593 /// The raw error (an exclusive holder reports the platform's "would
594 /// block").
595 fn lock_shared(&self, file: &Self::File) -> RawResult<Self::Lock>;
596
597 /// Sets the file's size to exactly `len` bytes, truncating or extending
598 /// with zeros. The data transfers stay block-aligned; only the size
599 /// moves. A metadata change: durable after [`Self::flush_all`].
600 ///
601 /// # Errors
602 ///
603 /// The raw error.
604 fn set_len(&self, file: &Self::File, len: u64) -> RawResult<()>;
605
606 /// Allocates real blocks up to `len` bytes, so the file size becomes
607 /// `len`. A file already at least `len` long is left as it is: this never
608 /// shrinks a file (that is [`Self::set_len`]).
609 /// Never leaves unwritten extents' contents readable as other files' data.
610 ///
611 /// # Errors
612 ///
613 /// The raw error (out of space reports the platform's ENOSPC equivalent).
614 fn allocate(&self, file: &Self::File, len: u64) -> RawResult<()>;
615
616 /// Allocates real blocks for `[offset, offset + len)`, inside the file:
617 /// its size never changes, and bytes already written stay as they are.
618 /// Blocks it allocates read as zeros until written (an unwritten extent
619 /// on Linux), never another file's data. For space a write will need
620 /// later without writing it now (format 2's capped regions): that holds
621 /// on a file system that overwrites in place; one that copies on write
622 /// (btrfs, ZFS) or a range sharing blocks with another file (a reflink)
623 /// may still allocate when the range is written. A length of 0 inside
624 /// the file or at its end does nothing.
625 ///
626 /// # Errors
627 ///
628 /// The raw error: out of space as the platform's ENOSPC equivalent; a
629 /// range past the end of the file as EINVAL's (Windows:
630 /// `ERROR_INVALID_PARAMETER`); a read-only handle (`EBADF`,
631 /// `ERROR_ACCESS_DENIED`); a file system that cannot allocate inside a
632 /// file (Linux `EOPNOTSUPP`: ext4 without extents, NFS before 4.2, many
633 /// FUSE file systems; macOS `ENOTSUP`, always: `F_PREALLOCATE` only
634 /// extends a file) or a file whose space a write may still need to
635 /// allocate (Windows: sparse, compressed or integrity-stream files,
636 /// `ERROR_NOT_SUPPORTED`) as unsupported.
637 fn allocate_range(&self, file: &Self::File, offset: u64, len: u64) -> RawResult<()>;
638
639 /// Current file size.
640 ///
641 /// # Errors
642 ///
643 /// The raw error.
644 fn size(&self, file: &Self::File) -> RawResult<u64>;
645
646 /// Releases a range.
647 ///
648 /// # Errors
649 ///
650 /// The raw error.
651 fn release_range(
652 &self,
653 file: &Self::File,
654 offset: u64,
655 len: u64,
656 how: ReleaseHow,
657 ) -> RawResult<()>;
658
659 /// Reports extent and cache state for a range.
660 ///
661 /// # Errors
662 ///
663 /// The raw error.
664 fn range_state(&self, file: &Self::File, offset: u64, len: u64) -> RawResult<RangeState>;
665
666 /// Makes data and metadata durable (fsync / FlushFileBuffers / F_FULLFSYNC).
667 ///
668 /// # Errors
669 ///
670 /// The raw error.
671 fn flush_all(&self, file: &Self::File) -> RawResult<()>;
672
673 /// Gathers raw evidence about the file's filesystem, stack and device.
674 ///
675 /// # Errors
676 ///
677 /// The raw error if nothing could be learned at all; partial evidence is
678 /// returned with `missing` set.
679 fn probe(&self, dir: &Self::Dir, file: &Self::File) -> RawResult<Evidence>;
680
681 /// Creates a queue for the calling thread.
682 ///
683 /// # Errors
684 ///
685 /// The raw error.
686 fn queue(&self, cfg: QueueConfig) -> RawResult<Self::Queue>;
687}
688
689#[cfg(test)]
690mod tests {
691 use super::*;
692
693 #[test]
694 fn test_file_name_rejects_escapes_and_separators() {
695 for bad in ["", ".", "..", "a/b", "a\\b", "c:x", "nul\0"] {
696 assert!(FileName::new(bad).is_err(), "{bad:?}");
697 }
698 assert!(FileName::new(&"x".repeat(256)).is_err());
699 assert_eq!(
700 FileName::new("store.sio").map(|n| n.as_str().to_owned()),
701 Ok("store.sio".to_owned())
702 );
703 }
704
705 #[test]
706 fn test_completion_buf_never_grows() {
707 let mut b = CompletionBuf::with_capacity(1);
708 assert!(
709 b.push(Completion {
710 tag: 1,
711 buf: None,
712 result: Ok(0)
713 })
714 .is_ok()
715 );
716 assert!(
717 b.push(Completion {
718 tag: 2,
719 buf: None,
720 result: Ok(0)
721 })
722 .is_err()
723 );
724 assert_eq!(b.room(), 0);
725 assert_eq!(b.drain().map(|c| c.tag).collect::<Vec<_>>(), vec![1]);
726 assert!(b.is_empty());
727 }
728}