Skip to main content

forgedb_wal/
reader.rs

1//! WAL Reader and replay logic
2use std::fs::File;
3use std::io::{self, Read, Seek, SeekFrom};
4use std::path::Path;
5
6use crate::entry::WalEntry;
7
8/// WAL Reader
9pub struct WalReader {
10    file: File,
11}
12
13impl WalReader {
14    /// Create a new WAL reader
15    pub fn new<P: AsRef<Path>>(path: P) -> io::Result<Self> {
16        let file = File::open(path)?;
17        Ok(WalReader { file })
18    }
19
20    /// Read all entries from the WAL
21    /// Stops at the first corrupted or incomplete entry
22    pub fn read_all(&mut self) -> io::Result<Vec<WalEntry>> {
23        self.file.seek(SeekFrom::Start(0))?;
24        let mut entries = Vec::new();
25        let mut buffer = Vec::new();
26
27        // Read entire file
28        self.file.read_to_end(&mut buffer)?;
29
30        let mut offset = 0;
31
32        while offset < buffer.len() {
33            match WalEntry::from_bytes(&buffer[offset..]) {
34                Ok((entry, size)) => {
35                    entries.push(entry);
36                    offset += size;
37                }
38                Err(_) => {
39                    // Stop at the first corrupted/incomplete entry. A truncated
40                    // tail is the common, benign case (a crash mid-write); we
41                    // return the entries recovered so far rather than erroring.
42                    // Callers needing to distinguish tail-truncation from
43                    // mid-file corruption should use `read_with_validation`.
44                    break;
45                }
46            }
47        }
48
49        Ok(entries)
50    }
51
52    /// Read entries and validate them without stopping at corruption
53    /// Returns both valid entries and information about corrupted regions
54    pub fn read_with_validation(&mut self) -> io::Result<(Vec<WalEntry>, Vec<CorruptionInfo>)> {
55        self.file.seek(SeekFrom::Start(0))?;
56        let mut entries = Vec::new();
57        let mut corruptions = Vec::new();
58        let mut buffer = Vec::new();
59
60        self.file.read_to_end(&mut buffer)?;
61
62        let mut offset = 0;
63
64        while offset < buffer.len() {
65            match WalEntry::from_bytes(&buffer[offset..]) {
66                Ok((entry, size)) => {
67                    entries.push(entry);
68                    offset += size;
69                }
70                Err(e) => {
71                    corruptions.push(CorruptionInfo {
72                        offset,
73                        error: e.to_string(),
74                    });
75                    // Try to skip past this corruption
76                    // Look for next valid entry by scanning for entry length markers
77                    offset += 1;
78                }
79            }
80        }
81
82        Ok((entries, corruptions))
83    }
84
85    /// Get the position in the file
86    pub fn position(&mut self) -> io::Result<u64> {
87        self.file.stream_position()
88    }
89
90    /// Seek to a specific position
91    pub fn seek(&mut self, pos: u64) -> io::Result<u64> {
92        self.file.seek(SeekFrom::Start(pos))
93    }
94
95    /// Read a single entry at the current position
96    pub fn read_one(&mut self) -> io::Result<Option<WalEntry>> {
97        let mut buffer = vec![0u8; 4];
98
99        // Try to read length prefix
100        match self.file.read_exact(&mut buffer) {
101            Ok(_) => {}
102            Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => {
103                return Ok(None);
104            }
105            Err(e) => return Err(e),
106        }
107
108        let length = u32::from_le_bytes(buffer.try_into().unwrap()) as usize;
109
110        // Guard against a corrupt length prefix triggering a huge allocation:
111        // the entry body cannot exceed the bytes remaining in the file.
112        let position = self.file.stream_position()?;
113        let file_len = self.file.metadata()?.len();
114        let remaining = file_len.saturating_sub(position);
115        if length as u64 > remaining {
116            return Err(io::Error::new(
117                io::ErrorKind::InvalidData,
118                "WAL entry length exceeds remaining file size",
119            ));
120        }
121
122        // Read the rest of the entry
123        let mut entry_buffer = vec![0u8; length];
124        self.file.read_exact(&mut entry_buffer)?;
125
126        // Prepend length for parsing
127        let mut full_buffer = Vec::new();
128        full_buffer.extend_from_slice(&(length as u32).to_le_bytes());
129        full_buffer.extend_from_slice(&entry_buffer);
130
131        let (entry, _) = WalEntry::from_bytes(&full_buffer)?;
132        Ok(Some(entry))
133    }
134}
135
136/// Information about a corrupted region in the WAL
137#[derive(Debug, Clone)]
138pub struct CorruptionInfo {
139    pub offset: usize,
140    pub error: String,
141}