Skip to main content

forgedb_wal/
writer.rs

1//! WAL Writer with configurable fsync policies
2use std::fs::{File, OpenOptions};
3use std::io::{self, Seek, SeekFrom, Write};
4use std::path::Path;
5use std::time::{Duration, Instant};
6
7use crate::FsyncPolicy;
8use crate::entry::WalEntry;
9
10/// WAL Writer
11pub struct WalWriter {
12    file: File,
13    fsync_policy: FsyncPolicy,
14    last_fsync: Instant,
15    bytes_since_fsync: usize,
16}
17
18impl WalWriter {
19    /// Create a new WAL writer
20    pub fn new<P: AsRef<Path>>(path: P, fsync_policy: FsyncPolicy) -> io::Result<Self> {
21        let file = OpenOptions::new()
22            .create(true)
23            .append(true)
24            .read(true)
25            .open(path)?;
26
27        Ok(WalWriter {
28            file,
29            fsync_policy,
30            last_fsync: Instant::now(),
31            bytes_since_fsync: 0,
32        })
33    }
34
35    /// Write an entry to the WAL
36    pub fn write(&mut self, entry: &WalEntry) -> io::Result<()> {
37        let bytes = entry.to_bytes();
38        self.file.write_all(&bytes)?;
39        self.bytes_since_fsync += bytes.len();
40
41        // Apply fsync policy
42        match self.fsync_policy {
43            FsyncPolicy::Always => {
44                self.file.sync_all()?;
45                self.last_fsync = Instant::now();
46                self.bytes_since_fsync = 0;
47            }
48            FsyncPolicy::Periodic(duration) => {
49                if self.last_fsync.elapsed() >= duration {
50                    self.file.sync_all()?;
51                    self.last_fsync = Instant::now();
52                    self.bytes_since_fsync = 0;
53                }
54            }
55            FsyncPolicy::Never => {
56                // No automatic fsync
57            }
58        }
59
60        Ok(())
61    }
62
63    /// Append an entry WITHOUT fsyncing, regardless of the fsync policy (#170
64    /// group commit).  Durability is deferred to an explicit [`flush`](Self::flush)
65    /// at the batch/transaction commit boundary — so a batch of N appends pays one
66    /// barrier instead of N.  Safe only for writes whose visibility is gated on a
67    /// later durable marker (e.g. MVCC-Tier-1 staged rows, which crash-recovery
68    /// drops unless the transaction journal committed): a crash before the flush
69    /// loses these appends, which is exactly correct for not-yet-committed data.
70    pub fn write_buffered(&mut self, entry: &WalEntry) -> io::Result<()> {
71        let bytes = entry.to_bytes();
72        self.file.write_all(&bytes)?;
73        self.bytes_since_fsync += bytes.len();
74        Ok(())
75    }
76
77    /// Manually flush the WAL to disk
78    pub fn flush(&mut self) -> io::Result<()> {
79        self.file.sync_all()?;
80        self.last_fsync = Instant::now();
81        self.bytes_since_fsync = 0;
82        Ok(())
83    }
84
85    /// Truncate the WAL (clear all entries)
86    pub fn truncate(&mut self) -> io::Result<()> {
87        self.file.set_len(0)?;
88        self.file.seek(SeekFrom::Start(0))?;
89        self.file.sync_all()?;
90        self.last_fsync = Instant::now();
91        self.bytes_since_fsync = 0;
92        Ok(())
93    }
94
95    /// Truncate the WAL to `offset` bytes, dropping any tail past it (MVCC Tier 1
96    /// transaction rollback).  A no-op if `offset` is already at or past the
97    /// current length.  The file is opened in append mode, so no cursor reset is
98    /// needed — the next write still appends at the (new, shorter) end.
99    pub fn truncate_to(&mut self, offset: u64) -> io::Result<()> {
100        let current = self.file.metadata()?.len();
101        if offset >= current {
102            return Ok(());
103        }
104        self.file.set_len(offset)?;
105        self.file.sync_all()?;
106        self.last_fsync = Instant::now();
107        self.bytes_since_fsync = 0;
108        Ok(())
109    }
110
111    /// Get the current fsync policy
112    pub fn fsync_policy(&self) -> FsyncPolicy {
113        self.fsync_policy
114    }
115
116    /// Get bytes written since last fsync
117    pub fn bytes_since_fsync(&self) -> usize {
118        self.bytes_since_fsync
119    }
120
121    /// Get time since last fsync
122    pub fn time_since_fsync(&self) -> Duration {
123        self.last_fsync.elapsed()
124    }
125}