Skip to main content

xs/store/
fsync.rs

1use std::fmt;
2use std::str::FromStr;
3use std::time::Duration;
4
5/// When the store fsyncs its journal.
6///
7/// Every append commits to the fjall journal before it returns. A commit is
8/// crash-consistent on its own: a process crash loses nothing. What an fsync
9/// adds is durability against power loss or a kernel crash. Without it the
10/// unsynced tail of the journal can be lost, and recovery yields a stable
11/// prefix of the stream.
12///
13/// Parse one from a string with [`FromStr`]:
14///
15/// ```
16/// use std::time::Duration;
17/// use xs::Fsync;
18///
19/// assert_eq!("always".parse::<Fsync>(), Ok(Fsync::Always));
20/// assert_eq!("interval:250".parse::<Fsync>(), Ok(Fsync::Interval(Duration::from_millis(250))));
21/// assert_eq!("never".parse::<Fsync>(), Ok(Fsync::Never));
22/// assert_eq!(Fsync::default(), Fsync::Interval(Duration::from_millis(1000)));
23/// ```
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum Fsync {
26    /// Fsync after every append, before `append` returns. Slowest, and the
27    /// only mode where a returned append survives power loss.
28    Always,
29    /// Fsync on a background tick every `Duration`, and only when something
30    /// was written since the last tick. Power loss can lose up to one
31    /// interval of appends. This is the default, at one second.
32    Interval(Duration),
33    /// Never fsync. The OS decides when the journal reaches disk.
34    Never,
35}
36
37impl Default for Fsync {
38    fn default() -> Self {
39        Fsync::Interval(Duration::from_millis(1000))
40    }
41}
42
43impl fmt::Display for Fsync {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        match self {
46            Fsync::Always => write!(f, "always"),
47            Fsync::Interval(d) => write!(f, "interval:{}", d.as_millis()),
48            Fsync::Never => write!(f, "never"),
49        }
50    }
51}
52
53impl FromStr for Fsync {
54    type Err = String;
55
56    /// Parses `always`, `interval:<ms>`, or `never`.
57    fn from_str(s: &str) -> Result<Self, Self::Err> {
58        match s {
59            "always" => Ok(Fsync::Always),
60            "never" => Ok(Fsync::Never),
61            _ if s.starts_with("interval:") => {
62                let ms = s["interval:".len()..]
63                    .parse::<u64>()
64                    .map_err(|_| "Invalid interval for 'interval' fsync policy".to_string())?;
65                if ms == 0 {
66                    return Err("Interval must be >= 1 ms for 'interval' fsync policy".to_string());
67                }
68                Ok(Fsync::Interval(Duration::from_millis(ms)))
69            }
70            _ => Err("Invalid fsync policy: expected always, interval:<ms>, or never".to_string()),
71        }
72    }
73}