Skip to main content

store_io_engine/
directory.rs

1//! Directory mode: whole files replaced atomically.
2//!
3//! A [`Directory`] holds small objects as ordinary files (a manifest, a
4//! `CURRENT` pointer, a configuration). [`Directory::replace`] swaps a file's
5//! contents so that after any crash it holds exactly the old bytes or exactly
6//! the new ones:
7//!
8//! 1. write the new bytes to a temporary file in the same directory (direct
9//!    I/O), set its exact length, and flush it, data and metadata;
10//! 2. rename it over the target (replace-if-exists, POSIX semantics);
11//! 3. flush the directory, so the rename itself is durable.
12//!
13//! Success is reported only after all three. A failure before the rename
14//! leaves the target untouched. Any failure from the rename on is
15//! "durability unknown": the handle is poisoned and refuses every later
16//! change, because the directory may now name either version. A directory
17//! flush the platform cannot do is an error, never a success.
18//!
19//! The device is probed once, with the first file the handle opens, and the
20//! durability class decides as it does for a store: unsafe or unverified
21//! devices are refused unless the caller's [`Trust`] says otherwise.
22
23use std::path::Path;
24use std::sync::{Mutex, OnceLock, PoisonError};
25
26use store_io_buf::{BufPool, PoolConfig};
27use store_io_core::align::align_up;
28use store_io_core::class::DurabilityClass;
29use store_io_core::decide::{ClassDecision, Trust, decide};
30use store_io_core::error::{
31    CorruptionKind, Error, ErrorContext, FirstCause, Named, NotWrittenCause, Op, OsError,
32};
33use store_io_platform::{FileMode, FileName, IoOp, Platform, QueueConfig};
34
35use crate::exec::{QueueSet, Ran, run};
36use crate::io::not_written;
37
38/// Block granularity of directory-mode transfers.
39const BLOCK: u64 = 4096;
40/// Largest single transfer.
41const CHUNK: usize = 1 << 20;
42/// Suffix of the temporary file a replace writes first.
43const TEMP_SUFFIX: &str = ".sio-tmp";
44/// The file whose exclusive lock a change holds, so one change at a time
45/// runs in the directory across handles and processes (the temporary name
46/// is then the changer's alone).
47const LOCK_NAME: &str = ".sio-lock";
48/// Longest object name: room for [`TEMP_SUFFIX`] within a file name.
49const NAME_MAX: usize = 255 - TEMP_SUFFIX.len();
50
51fn io(op: Op, raw: OsError) -> Error {
52    Error::Io {
53        op,
54        raw,
55        ctx: ErrorContext::default(),
56    }
57}
58
59fn name_of(name: &str) -> Result<FileName, Error> {
60    FileName::new(name)
61        .map_err(|_| not_written(NotWrittenCause::InvalidName, ErrorContext::default()))
62}
63
64/// An object's name: a file name that leaves room for the temporary suffix
65/// and never resolves to one of the directory's own files (a temporary
66/// file or the lock, which a change would otherwise remove or overwrite),
67/// to the directory itself, or to another file through a platform's
68/// aliases (short names, devices, trimmed trailing characters). Names that
69/// differ only in case, or in ignorable code points, may still be one file
70/// on a case-insensitive file system, as `A` and `a` always were. Refused,
71/// on every platform alike so names stay portable:
72///
73/// - longer than [`NAME_MAX`];
74/// - empty or ending in `.` or a space once ignorable code points are
75///   dropped (Windows drops trailing dots and spaces: `x.` is `x`, `...` is
76///   the directory itself; and `.\u{200C}` is `.`, `\u{200C}` nothing, on
77///   file systems that drop ignorables);
78/// - shaped like a Windows short name (`SIO-LO~1`, `X~1.SIO`), which can
79///   alias any long name;
80/// - a Windows device name (`NUL`, `COM1`, `CON.txt`, ...);
81/// - the lock file or a temporary file's name, compared as a
82///   case-insensitive file system compares names: case folded (Unicode
83///   included: `ſ` is `s` and `K` (Kelvin) is `k` there) and ignorable code
84///   points dropped (HFS+, and Linux case-folding directories, skip them:
85///   `.sio\u{200C}-lock` is `.sio-lock` there). Elsewhere in a name they
86///   are kept: a word with a zero-width non-joiner is a name like any
87///   other.
88fn object_name(name: &str) -> Result<FileName, Error> {
89    // Ignorable code points dropped, as case-insensitive file systems drop
90    // them when comparing names.
91    let folded: String = name
92        .chars()
93        .filter(|&c| !ignorable(c))
94        .map(|c| match c {
95            '\u{17F}' => 's',
96            '\u{212A}' => 'k',
97            c => c.to_ascii_lowercase(),
98        })
99        .collect();
100    // Empty or ending in `.` or a space once folded (`x.`, `...`,
101    // `.\u{200C}`): the directory itself, its parent, or a name Windows
102    // trims.
103    let trimmed = folded.is_empty() || folded.ends_with(['.', ' ']);
104    let own = folded.ends_with(TEMP_SUFFIX) || folded == LOCK_NAME;
105    let too_long = name.len() > NAME_MAX;
106    let alias = short_name_shaped(name) || device_name(name);
107    if too_long || alias || trimmed || own {
108        return Err(not_written(
109            NotWrittenCause::InvalidName,
110            ErrorContext::default(),
111        ));
112    }
113    name_of(name)
114}
115
116/// Whether `name` has the shape of a Windows 8.3 short name: a base of at
117/// most 8 characters ending in `~` and digits (what comes before may hold
118/// `~` itself: `A~BCDE~1`, `~$DOCU~1`), then optionally `.` and at most 3
119/// characters.
120fn short_name_shaped(name: &str) -> bool {
121    let (base, ext) = name.split_once('.').unwrap_or((name, ""));
122    let Some((_, digits)) = base.rsplit_once('~') else {
123        return false;
124    };
125    !digits.is_empty()
126        && digits.bytes().all(|b| b.is_ascii_digit())
127        && base.chars().count() <= 8
128        && ext.chars().count() <= 3
129        && !ext.contains('.')
130}
131
132/// Whether case-insensitive file systems ignore `c` when comparing names:
133/// Unicode's Default_Ignorable_Code_Point (Linux case-folding directories
134/// drop all of them; HFS+ a subset).
135fn ignorable(c: char) -> bool {
136    matches!(
137        c,
138        '\u{AD}'
139            | '\u{34F}'
140            | '\u{61C}'
141            | '\u{115F}'..='\u{1160}'
142            | '\u{17B4}'..='\u{17B5}'
143            | '\u{180B}'..='\u{180F}'
144            | '\u{200B}'..='\u{200F}'
145            | '\u{202A}'..='\u{202E}'
146            | '\u{2060}'..='\u{206F}'
147            | '\u{3164}'
148            | '\u{FE00}'..='\u{FE0F}'
149            | '\u{FEFF}'
150            | '\u{FFA0}'
151            | '\u{FFF0}'..='\u{FFF8}'
152            | '\u{1BCA0}'..='\u{1BCA3}'
153            | '\u{1D173}'..='\u{1D17A}'
154            | '\u{E0000}'..='\u{E0FFF}'
155    )
156}
157
158/// Whether `name` is a Windows device name, with or without an extension
159/// (older Windows treats `NUL.txt` as the device too), in any case.
160fn device_name(name: &str) -> bool {
161    let stem = name.split('.').next().unwrap_or(name).trim_end();
162    let upper = stem.to_ascii_uppercase();
163    let numbered = |prefix: &str| {
164        upper.strip_prefix(prefix).is_some_and(|n| {
165            matches!(
166                n,
167                "0" | "1"
168                    | "2"
169                    | "3"
170                    | "4"
171                    | "5"
172                    | "6"
173                    | "7"
174                    | "8"
175                    | "9"
176                    | "\u{B9}"
177                    | "\u{B2}"
178                    | "\u{B3}"
179            )
180        })
181    };
182    matches!(
183        upper.as_str(),
184        "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
185    ) || numbered("COM")
186        || numbered("LPT")
187}
188
189/// A directory of small objects, each replaced atomically.
190pub struct Directory<P: Platform> {
191    platform: P,
192    dir: P::Dir,
193    trust: Trust,
194    decision: OnceLock<ClassDecision>,
195    poisoned: OnceLock<FirstCause>,
196    pool: BufPool,
197    queue: QueueSet<P::Queue>,
198    /// Serialises this handle's replaces and removes; across handles and
199    /// processes, the lock on [`LOCK_NAME`] serialises replaces.
200    change: Mutex<()>,
201    /// This handle's own open of [`LOCK_NAME`] (opened on first change):
202    /// each replace locks it, so the lock is this handle's open file
203    /// description, and a lock taken there excludes every other handle.
204    /// Kept for the handle's life: the lock file must not be deleted while
205    /// a handle is open.
206    lock_file: OnceLock<P::File>,
207    /// The directory flush probed at open failed: every change is refused
208    /// before any write, since its rename could never be made durable.
209    dir_flush: Option<OsError>,
210    /// The largest object written or read ([`Self::with_max_object`]).
211    max_object: u64,
212}
213
214impl<P: Platform> core::fmt::Debug for Directory<P> {
215    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
216        f.debug_struct("Directory")
217            .field("class", &self.class())
218            .field("poisoned", &self.poisoned.get().is_some())
219            .finish()
220    }
221}
222
223impl<P: Platform> Directory<P> {
224    /// The largest object a handle writes or reads by default
225    /// ([`Self::with_max_object`]): 16 MiB.
226    pub const DEFAULT_MAX_OBJECT: u64 = 16 << 20;
227
228    /// Opens the directory at `path`, creating it (and syncing its parent)
229    /// when `create` is true. `trust` is applied when the device is probed.
230    /// It also tries a directory flush: if that fails, the handle still
231    /// reads, but every `replace`, `remove` and `sync` is refused before any
232    /// write, since no change could be made durable.
233    ///
234    /// # Errors
235    ///
236    /// `NotFound` if it does not exist and `create` is false; `Io`.
237    pub fn open(platform: P, path: &Path, create: bool, trust: Trust) -> Result<Self, Error> {
238        let dir = platform.open_dir(path, create).map_err(|raw| {
239            if store_io_core::errno::is_not_found(raw) {
240                Error::NotFound { what: Named::Store }
241            } else {
242                io(Op::Open, raw)
243            }
244        })?;
245        let queue = platform
246            .queue(QueueConfig {
247                depth: 8,
248                ..QueueConfig::default()
249            })
250            .map_err(|raw| io(Op::Queue, raw))?;
251        let pool = BufPool::new(&PoolConfig::uniform(4096, 4096, CHUNK, 4))
252            .map_err(|_| not_written(NotWrittenCause::PoolExhausted, ErrorContext::default()))?;
253        // Every change depends on a directory flush; learn now, before any
254        // write, whether this directory can do one.
255        let dir_flush = platform.sync_dir(&dir).err();
256        Ok(Self {
257            platform,
258            dir,
259            trust,
260            decision: OnceLock::new(),
261            poisoned: OnceLock::new(),
262            pool,
263            queue: QueueSet::new(vec![queue], 8),
264            change: Mutex::new(()),
265            lock_file: OnceLock::new(),
266            dir_flush,
267            max_object: Self::DEFAULT_MAX_OBJECT,
268        })
269    }
270
271    /// The handle with `max` as its largest object, written or read
272    /// (default [`Self::DEFAULT_MAX_OBJECT`]): a larger `replace` is refused
273    /// before anything is written, and a file found larger is refused by
274    /// `read` before anything is allocated (a damaged, replaced or sparse
275    /// file of any length costs its reader nothing then).
276    #[must_use]
277    pub fn with_max_object(mut self, max: u64) -> Self {
278        self.max_object = max;
279        self
280    }
281
282    /// The largest object this handle writes or reads.
283    #[must_use]
284    pub fn max_object(&self) -> u64 {
285        self.max_object
286    }
287
288    /// The durability class of the directory's device, once a file has been
289    /// opened through this handle.
290    #[must_use]
291    pub fn class(&self) -> Option<DurabilityClass> {
292        self.decision.get().map(|d| d.class)
293    }
294
295    /// The class decision (evidence, reasons, label), once probed.
296    #[must_use]
297    pub fn decision(&self) -> Option<&ClassDecision> {
298        self.decision.get()
299    }
300
301    /// Probes the device with `file` the first time, and refuses unsafe or
302    /// unverified devices as the trust settings require.
303    fn admit(&self, file: &P::File) -> Result<(), Error> {
304        if self.decision.get().is_none() {
305            let ev = self
306                .platform
307                .probe(&self.dir, file)
308                .map_err(|raw| io(Op::Probe, raw))?;
309            let _first = self.decision.set(decide(&ev, &self.trust));
310        }
311        match self.decision.get() {
312            Some(d) => crate::store::refuse(d),
313            None => Err(not_written(
314                NotWrittenCause::NotReady,
315                ErrorContext::default(),
316            )),
317        }
318    }
319
320    fn poison(&self, op: Op, raw: Option<OsError>) -> Error {
321        let _first_kept = self.poisoned.set(FirstCause { op: Some(op), raw });
322        Error::DurabilityUnknown {
323            op,
324            raw,
325            ctx: ErrorContext::default(),
326        }
327    }
328
329    fn writable(&self) -> Result<(), Error> {
330        if let Some(first) = self.poisoned.get() {
331            return Err(Error::Poisoned { first: *first });
332        }
333        match self.dir_flush {
334            None => Ok(()),
335            Some(raw) if store_io_core::errno::is_unsupported(raw) => Err(Error::Unsupported {
336                what: store_io_core::error::Capability::DirectoryFlush,
337            }),
338            Some(raw) => Err(io(Op::SyncDir, raw)),
339        }
340    }
341
342    /// Replaces the file `name` with `data`, atomically and durably: after
343    /// any crash the file holds exactly the old or exactly the new bytes, and
344    /// once this returns, exactly the new ones. One replace runs at a time in
345    /// the directory: while another handle or process is replacing, this
346    /// fails `Locked` with nothing written (the caller retries). Every
347    /// writer must take the lock for that to hold: a process of a version
348    /// before 0.5 does not. The lock is the file `.sio-lock` in the
349    /// directory, created on first use and kept; delete it only while no
350    /// `Directory` is open on the directory (an open handle keeps locking
351    /// the file it opened, so a new one beside it splits the writers).
352    ///
353    /// # Errors
354    ///
355    /// `Locked` while another handle or process replaces in the directory;
356    /// `Io(Lock)` if the file system cannot lock at all.
357    /// `NotWritten(InvalidName)` for a name that could resolve to another
358    /// file: longer than 247 bytes; shaped like a Windows short name (`~`
359    /// and digits) or a Windows device name; and, compared as a
360    /// case-insensitive file system compares names (case folded, ignorable
361    /// code points dropped), empty, ending in `.` or a space, or the
362    /// directory's own `.sio-lock` or a name ending in `.sio-tmp`.
363    /// `Unsupported(DirectoryFlush)` or `Io(SyncDir)` when the directory
364    /// cannot be flushed (found at open; nothing is written).
365    /// `NotWritten(TooLarge)` for `data` longer than [`Self::max_object`].
366    /// `NotWritten`, `UnsafeDevice`, `Unverified`, `NoSpace` or `Io` before
367    /// anything reached the device (the target is untouched).
368    /// `DurabilityUnknown` if a write, the length update or the flush of the
369    /// new bytes failed (the target is untouched) or anything from the rename
370    /// on failed (the directory may name either version); the handle is then
371    /// poisoned and later changes fail with `Poisoned`.
372    pub fn replace(&self, name: &str, data: &[u8]) -> Result<(), Error> {
373        self.writable()?;
374        if data.len() as u64 > self.max_object {
375            return Err(not_written(
376                NotWrittenCause::TooLarge,
377                ErrorContext::default(),
378            ));
379        }
380        let target = object_name(name)?;
381        let temp = name_of(&format!("{name}{TEMP_SUFFIX}"))?;
382        let _one_at_a_time = self.change.lock().unwrap_or_else(PoisonError::into_inner);
383        // Poisoned while this call waited for the handle's lock.
384        self.writable()?;
385        // One changer in the directory, across handles and processes: the
386        // temporary name below is ours alone.
387        let _owner = self.change_lock()?;
388        // A leftover from an interrupted replace is never the live version.
389        let _absent_or_removed = self.platform.unlink(&self.dir, &temp);
390        let file = self
391            .platform
392            .create_file(&self.dir, &temp)
393            .map_err(|raw| io(Op::Create, raw))?;
394        if let Err(e) = self.admit(&file).and_then(|()| self.fill(&file, data)) {
395            drop(file);
396            let _cleanup = self.platform.unlink(&self.dir, &temp);
397            return Err(e);
398        }
399        // The commit point: not after a poison seen here (a failed `sync`
400        // on this handle poisons without the change lock, so one landing
401        // after this check still commits; then the two calls overlapped,
402        // and this replace's own directory flush decides its result).
403        if let Some(first) = self.poisoned.get() {
404            drop(file);
405            let _cleanup = self.platform.unlink(&self.dir, &temp);
406            return Err(Error::Poisoned { first: *first });
407        }
408        // From here on the directory may name either version.
409        let renamed = self
410            .platform
411            .rename_replace(&self.dir, &temp, &target, &file);
412        drop(file);
413        renamed.map_err(|raw| self.poison(Op::Rename, Some(raw)))?;
414        self.platform
415            .sync_dir(&self.dir)
416            .map_err(|raw| self.poison(Op::SyncDir, Some(raw)))
417    }
418
419    /// Takes the directory's change lock: an exclusive lock, through this
420    /// handle's own open of [`LOCK_NAME`] (created on first use and kept,
421    /// an empty file), held until the returned guard drops. `Locked` only
422    /// when another holder has it.
423    fn change_lock(&self) -> Result<P::Lock, Error> {
424        let file = match self.lock_file.get() {
425            Some(f) => f,
426            None => {
427                let name = name_of(LOCK_NAME)?;
428                let open = || {
429                    self.platform
430                        .open_file(&self.dir, &name, FileMode::ReadWrite)
431                };
432                let f = match open() {
433                    Ok(f) => f,
434                    Err(raw) if store_io_core::errno::is_not_found(raw) => {
435                        match self.platform.create_file(&self.dir, &name) {
436                            Ok(f) => f,
437                            // Created by another handle meanwhile.
438                            Err(raw) if store_io_core::errno::is_already_exists(raw) => {
439                                open().map_err(|raw| io(Op::Open, raw))?
440                            }
441                            Err(raw) => return Err(io(Op::Create, raw)),
442                        }
443                    }
444                    Err(raw) => return Err(io(Op::Open, raw)),
445                };
446                // Only this handle's change mutex holder gets here.
447                let _first = self.lock_file.set(f);
448                self.lock_file.get().ok_or_else(|| {
449                    not_written(NotWrittenCause::NotReady, ErrorContext::default())
450                })?
451            }
452        };
453        self.platform.lock_exclusive(file).map_err(|raw| {
454            if store_io_core::errno::is_lock_held(raw) {
455                Error::Locked
456            } else {
457                io(Op::Lock, raw)
458            }
459        })
460    }
461
462    /// Writes `data` to a fresh file, sets its exact length and flushes it.
463    fn fill(&self, file: &P::File, data: &[u8]) -> Result<(), Error> {
464        let c = ErrorContext::default();
465        let len = data.len() as u64;
466        let padded =
467            align_up(len, BLOCK).ok_or_else(|| not_written(NotWrittenCause::TooLarge, c))?;
468        self.platform
469            .allocate(file, padded)
470            .map_err(|raw| crate::store::space_err(Op::Allocate, raw, 0))?;
471        let mut lane = self.queue.get(0);
472        for (i, piece) in data.chunks(CHUNK).enumerate() {
473            let piece_len = align_up(piece.len() as u64, BLOCK).unwrap_or(BLOCK) as usize;
474            let mut buf = self
475                .pool
476                .take(piece_len)
477                .map_err(|_| not_written(NotWrittenCause::PoolExhausted, c))?;
478            let dst = buf.as_mut_slice();
479            dst[..piece.len()].copy_from_slice(piece);
480            dst[piece.len()..].fill(0);
481            let ran = run(
482                &mut lane,
483                IoOp::Write {
484                    file,
485                    offset: (i * CHUNK) as u64,
486                    buf,
487                    dsync: false,
488                },
489            )
490            .map_err(|(_b, raw)| {
491                raw.map_or_else(
492                    || not_written(NotWrittenCause::QueueFull, c),
493                    |r| io(Op::Write, r),
494                )
495            })?;
496            let result = match ran {
497                Ran::Done { result, .. } => result,
498                Ran::Abandoned(raw) => Err(raw),
499            };
500            // A failed or short write, or a failed flush, poisons the handle
501            // (fail-stop), even though the target itself is untouched.
502            match result {
503                Ok(n) if n == piece_len => {}
504                Ok(_) => return Err(self.poison(Op::Write, None)),
505                Err(raw) => return Err(self.poison(Op::Write, Some(raw))),
506            }
507        }
508        drop(lane);
509        // Fail-stop: a metadata update the device refused after the writes
510        // poisons the handle, as a failed write does.
511        self.platform
512            .set_len(file, len)
513            .map_err(|raw| self.poison(Op::Allocate, Some(raw)))?;
514        self.platform
515            .flush_all(file)
516            .map_err(|raw| self.poison(Op::FlushAll, Some(raw)))
517    }
518
519    /// Reads the whole file `name` (direct I/O: never the OS page cache).
520    ///
521    /// # Errors
522    ///
523    /// `NotFound`; `Corruption(MediaError)` for an unreadable range;
524    /// `NotWritten(InvalidName)` as for [`Self::replace`];
525    /// `NotWritten(TooLarge)` for a file longer than [`Self::max_object`]
526    /// (nothing allocated); `Io`.
527    pub fn read(&self, name: &str) -> Result<Vec<u8>, Error> {
528        let c = ErrorContext::default();
529        let file = self
530            .platform
531            .open_file(&self.dir, &object_name(name)?, FileMode::ReadOnly)
532            .map_err(|raw| {
533                if store_io_core::errno::is_not_found(raw) {
534                    Error::NotFound { what: Named::Slot }
535                } else {
536                    io(Op::Open, raw)
537                }
538            })?;
539        let len = self.platform.size(&file).map_err(|raw| io(Op::Open, raw))?;
540        // Before anything is allocated: the file's length is untrusted.
541        if len > self.max_object {
542            return Err(not_written(NotWrittenCause::TooLarge, c));
543        }
544        let len = usize::try_from(len).map_err(|_| not_written(NotWrittenCause::TooLarge, c))?;
545        let mut out = vec![0u8; len];
546        let mut lane = self.queue.get(0);
547        let mut at = 0usize;
548        while at < len {
549            let want = (len - at).min(CHUNK);
550            let padded = align_up(want as u64, BLOCK).unwrap_or(BLOCK) as usize;
551            let buf = self
552                .pool
553                .take(padded)
554                .map_err(|_| not_written(NotWrittenCause::PoolExhausted, c))?;
555            let ran = run(
556                &mut lane,
557                IoOp::Read {
558                    file: &file,
559                    offset: at as u64,
560                    buf,
561                },
562            )
563            .map_err(|(_b, raw)| {
564                raw.map_or_else(
565                    || not_written(NotWrittenCause::QueueFull, c),
566                    |r| io(Op::Read, r),
567                )
568            })?;
569            let (got, result) = match ran {
570                Ran::Done { buf, result } => (buf, result),
571                // A failed wait: a failure of the queue, not of the media.
572                Ran::Abandoned(raw) => return Err(io(Op::Read, raw)),
573            };
574            let n = result.map_err(|raw| {
575                if store_io_core::errno::is_media_error(raw) {
576                    Error::Corruption {
577                        kind: CorruptionKind::MediaError,
578                        ctx: c,
579                    }
580                } else {
581                    io(Op::Read, raw)
582                }
583            })?;
584            let Some(buf) = got else {
585                return Err(not_written(NotWrittenCause::QueueFull, c));
586            };
587            let got = n.min(want);
588            out[at..at + got].copy_from_slice(&buf.as_slice()[..got]);
589            if got < want {
590                // The file shrank under us: report what is there.
591                out.truncate(at + got);
592                break;
593            }
594            at += got;
595        }
596        Ok(out)
597    }
598
599    /// Removes the file `name` durably (unlink, then flush the directory).
600    ///
601    /// # Errors
602    ///
603    /// `Unsupported(DirectoryFlush)` or `Io(SyncDir)` when the directory
604    /// cannot be flushed (nothing changed); `NotFound` (nothing changed);
605    /// `DurabilityUnknown` if the unlink or the directory flush failed (the
606    /// handle is poisoned); `Poisoned`; `NotWritten(InvalidName)` as for
607    /// [`Self::replace`]. A remove takes no lock: it touches no temporary
608    /// file, and a replace and a remove of one name racing each other end
609    /// in either order.
610    pub fn remove(&self, name: &str) -> Result<(), Error> {
611        self.writable()?;
612        let target = object_name(name)?;
613        let _one_at_a_time = self.change.lock().unwrap_or_else(PoisonError::into_inner);
614        self.writable()?;
615        match self.platform.unlink(&self.dir, &target) {
616            Ok(()) => {}
617            Err(raw) if store_io_core::errno::is_not_found(raw) => {
618                return Err(Error::NotFound { what: Named::Slot });
619            }
620            Err(raw) => return Err(self.poison(Op::Unlink, Some(raw))),
621        }
622        self.platform
623            .sync_dir(&self.dir)
624            .map_err(|raw| self.poison(Op::SyncDir, Some(raw)))
625    }
626
627    /// Flushes the directory: every create, rename and unlink in it so far
628    /// becomes durable.
629    ///
630    /// # Errors
631    ///
632    /// `Unsupported(DirectoryFlush)` or `Io(SyncDir)` when the directory
633    /// cannot be flushed; `DurabilityUnknown` (the handle is poisoned);
634    /// `Poisoned`.
635    pub fn sync(&self) -> Result<(), Error> {
636        self.writable()?;
637        self.platform
638            .sync_dir(&self.dir)
639            .map_err(|raw| self.poison(Op::SyncDir, Some(raw)))
640    }
641}