| 1 | //! wal.rs — SQLite WAL header/frame parsing + cumulative SQLite checksums. |
| 2 | //! |
| 3 | //! Ported from [email protected] wal_reader.go:14-295 (read path) and the |
| 4 | //! `WALChecksum` helper in [email protected] litestream.go:110-119 (re-exported |
| 5 | //! from the crate root as [`crate::wal_checksum`]). |
| 6 | //! |
| 7 | //! A [`WalReader`] wraps a byte buffer and parses SQLite WAL frames, verifying |
| 8 | //! salt and cumulative-checksum integrity as it reads. It does **not** enforce |
| 9 | //! transaction boundaries (it may return uncommitted frames); honoring commit |
| 10 | //! records is the caller's responsibility (see [`WalReader::page_map`]). |
| 11 | //! |
| 12 | //! ## Byte format (read straight from the SQLite WAL spec; see wal_reader.go) |
| 13 | //! |
| 14 | //! WAL header (32 bytes, all fields big-endian at fixed offsets): |
| 15 | //! ```text |
| 16 | //! [0..4] magic 0x377f0682 => checksums LITTLE-endian |
| 17 | //! 0x377f0683 => checksums BIG-endian |
| 18 | //! [4..8] version must equal 3007000 |
| 19 | //! [8..12] page size |
| 20 | //! [12..16] checkpoint sequence number |
| 21 | //! [16..20] salt-1 |
| 22 | //! [20..24] salt-2 |
| 23 | //! [24..28] checksum-1 (cumulative checksum of bytes [0..24]) |
| 24 | //! [28..32] checksum-2 |
| 25 | //! ``` |
| 26 | //! |
| 27 | //! WAL frame header (24 bytes, all fields big-endian): |
| 28 | //! ```text |
| 29 | //! [0..4] page number |
| 30 | //! [4..8] commit size in pages for a commit record, else 0 |
| 31 | //! [8..12] salt-1 (must match the header salt-1) |
| 32 | //! [12..16] salt-2 (must match the header salt-2) |
| 33 | //! [16..20] checksum-1 (cumulative checksum through this frame's data) |
| 34 | //! [20..24] checksum-2 |
| 35 | //! ``` |
| 36 | //! |
| 37 | //! A frame is `pageSize + 24` bytes. The cumulative checksum is seeded with the |
| 38 | //! header checksum and rolled forward over each frame's 8-byte header prefix and |
| 39 | //! then its page data, in the byte order chosen by the magic. |
| 40 | |
| 41 | use std::collections::{HashMap, HashSet}; |
| 42 | |
| 43 | use crate::{wal_checksum, WAL_FRAME_HEADER_SIZE, WAL_HEADER_SIZE}; |
| 44 | |
| 45 | /// Required WAL format version (`3007000`), as found at header offset 4. |
| 46 | /// |
| 47 | /// Ported from [email protected] wal_reader.go:118. |
| 48 | const WAL_VERSION: u32 = 3_007_000; |
| 49 | |
| 50 | /// WAL header magic indicating checksums are computed **little-endian**. |
| 51 | /// |
| 52 | /// Ported from [email protected] wal_reader.go:101. |
| 53 | const WAL_MAGIC_LITTLE_ENDIAN: u32 = 0x377f_0682; |
| 54 | |
| 55 | /// WAL header magic indicating checksums are computed **big-endian**. |
| 56 | /// |
| 57 | /// Ported from [email protected] wal_reader.go:103. |
| 58 | const WAL_MAGIC_BIG_ENDIAN: u32 = 0x377f_0683; |
| 59 | |
| 60 | // ── Errors ──────────────────────────────────────────────────────────────────── |
| 61 | |
| 62 | /// Errors returned by [`WalReader`]. |
| 63 | /// |
| 64 | /// The Go reader leans on `io.EOF` as a control-flow sentinel: it signals the |
| 65 | /// clean end of the *valid* WAL, but also a short/partial read, a salt mismatch, |
| 66 | /// or a checksum mismatch — all of which mean "stop reading here, the rest of the |
| 67 | /// file is not a valid continuation." We model that single sentinel as |
| 68 | /// [`WalError::Eof`] so callers can branch on it exactly like Go's |
| 69 | /// `errors.Is(err, io.EOF)` (see [`WalError::is_eof`]). Non-EOF variants carry |
| 70 | /// the same human-readable messages as the Go `fmt.Errorf` strings so the ported |
| 71 | /// tests can assert them byte-for-byte. |
| 72 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 73 | pub enum WalError { |
| 74 | /// End of the valid WAL. |
| 75 | /// |
| 76 | /// Mirrors every `return ..., io.EOF` in wal_reader.go: a partial header, a |
| 77 | /// failed header checksum, a short frame read, a salt mismatch, or a frame |
| 78 | /// checksum mismatch. In all of these the WAL has no further valid frames. |
| 79 | Eof, |
| 80 | |
| 81 | /// `invalid wal header magic: <hex>` — the magic was neither |
| 82 | /// `0x377f0682` nor `0x377f0683`. |
| 83 | /// |
| 84 | /// Ported from [email protected] wal_reader.go:106. |
| 85 | InvalidMagic(u32), |
| 86 | |
| 87 | /// `unsupported wal version: <n>` — header version field was not `3007000`. |
| 88 | /// |
| 89 | /// Ported from [email protected] wal_reader.go:119. |
| 90 | UnsupportedVersion(u32), |
| 91 | |
| 92 | /// `WALReader.ReadFrame(): buffer size (<n>) must match page size (<m>)`. |
| 93 | /// |
| 94 | /// Ported from [email protected] wal_reader.go:139. |
| 95 | BufferSize { |
| 96 | /// Length of the buffer the caller supplied. |
| 97 | got: usize, |
| 98 | /// The WAL's page size. |
| 99 | want: u32, |
| 100 | }, |
| 101 | |
| 102 | /// `offset (<n>) must be greater than the wal header size (<m>)` — passed to |
| 103 | /// [`WalReader::new_with_offset`] with an offset at or before the header. |
| 104 | /// |
| 105 | /// Ported from [email protected] wal_reader.go:48. |
| 106 | OffsetTooSmall { |
| 107 | /// The requested offset. |
| 108 | offset: i64, |
| 109 | /// The WAL header size. |
| 110 | header_size: i64, |
| 111 | }, |
| 112 | |
| 113 | /// `unaligned wal offset <n> for page size <m>` — the offset does not land on |
| 114 | /// a frame boundary. |
| 115 | /// |
| 116 | /// Ported from [email protected] wal_reader.go:64. |
| 117 | UnalignedOffset { |
| 118 | /// The requested offset. |
| 119 | offset: i64, |
| 120 | /// The WAL's page size. |
| 121 | page_size: u32, |
| 122 | }, |
| 123 | |
| 124 | /// The previous frame at the seek offset could not be re-read (its salt or |
| 125 | /// checksum did not match). **Load-bearing**: `DB.sync` catches this and |
| 126 | /// falls back to a full snapshot (db.go:1571-1577). |
| 127 | /// |
| 128 | /// Ported from `PrevFrameMismatchError` in [email protected] |
| 129 | /// wal_reader.go:284-294. |
| 130 | PrevFrameMismatch, |
| 131 | } |
| 132 | |
| 133 | impl WalError { |
| 134 | /// Returns `true` for the [`WalError::Eof`] sentinel. |
| 135 | /// |
| 136 | /// This is the analog of Go's `errors.Is(err, io.EOF)`, which the upstream |
| 137 | /// callers (`PageMap`, the test suite) use to detect the end of the WAL. |
| 138 | #[inline] |
| 139 | pub fn is_eof(&self) -> bool { |
| 140 | matches!(self, WalError::Eof) |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | impl std::fmt::Display for WalError { |
| 145 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 146 | match self { |
| 147 | // Matches the Go string "EOF" (io.EOF.Error()). |
| 148 | WalError::Eof => f.write_str("EOF"), |
| 149 | // Go: fmt.Errorf("invalid wal header magic: %x", magic) — lowercase |
| 150 | // hex, no leading zeros (matches Go's %x for a uint32). |
| 151 | WalError::InvalidMagic(magic) => write!(f, "invalid wal header magic: {magic:x}"), |
| 152 | WalError::UnsupportedVersion(v) => write!(f, "unsupported wal version: {v}"), |
| 153 | WalError::BufferSize { got, want } => write!( |
| 154 | f, |
| 155 | "WALReader.ReadFrame(): buffer size ({got}) must match page size ({want})" |
| 156 | ), |
| 157 | WalError::OffsetTooSmall { |
| 158 | offset, |
| 159 | header_size, |
| 160 | } => write!( |
| 161 | f, |
| 162 | "offset ({offset}) must be greater than the wal header size ({header_size})" |
| 163 | ), |
| 164 | WalError::UnalignedOffset { offset, page_size } => { |
| 165 | write!(f, "unaligned wal offset {offset} for page size {page_size}") |
| 166 | } |
| 167 | WalError::PrevFrameMismatch => f.write_str("previous frame mismatch"), |
| 168 | } |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | impl std::error::Error for WalError {} |
| 173 | |
| 174 | impl From<WalError> for crate::Error { |
| 175 | /// Lifts a [`WalError`] into the crate-wide error type for callers that work |
| 176 | /// in terms of [`crate::Error`]. EOF and the structured WAL errors become |
| 177 | /// `Error::Other` carrying the same message. |
| 178 | fn from(e: WalError) -> Self { |
| 179 | crate::Error::Other(Box::new(e)) |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | /// `WalReader`'s `Result` alias. |
| 184 | type WalResult<T> = std::result::Result<T, WalError>; |
| 185 | |
| 186 | // ── WalReader ─────────────────────────────────────────────────────────────── |
| 187 | |
| 188 | /// Reads SQLite WAL frames from an in-memory byte buffer, verifying salts and |
| 189 | /// the cumulative SQLite checksum as it goes. |
| 190 | /// |
| 191 | /// This is the faithful analog of Go's `WALReader` (wal_reader.go:19-31). Go |
| 192 | /// wraps an `io.ReaderAt`; the upstream tests always back that with a |
| 193 | /// `bytes.Reader` over the whole WAL, so we wrap a borrowed `&[u8]` and emulate |
| 194 | /// `ReadAt` semantics directly: a read whose requested length runs past the end |
| 195 | /// of the buffer yields fewer bytes, which the algorithm treats as `io.EOF` |
| 196 | /// exactly as Go does. |
| 197 | /// |
| 198 | /// Ported from [email protected] wal_reader.go:19-187. |
| 199 | #[derive(Debug)] |
| 200 | pub struct WalReader<'a> { |
| 201 | /// Backing WAL bytes (the whole file, as the Go `io.ReaderAt`). |
| 202 | data: &'a [u8], |
| 203 | /// Index of the *next* frame to read (0-based). Go field `frameN`. |
| 204 | frame_n: i64, |
| 205 | |
| 206 | /// `true` when checksums are big-endian (magic `0x377f0683`), |
| 207 | /// `false` when little-endian (magic `0x377f0682`). Go field `bo`. |
| 208 | big_endian: bool, |
| 209 | /// Page size from the header. Go field `pageSize`. |
| 210 | page_size: u32, |
| 211 | /// Header salt-1 / salt-2; frames must match these. Go fields `salt1/salt2`. |
| 212 | salt1: u32, |
| 213 | salt2: u32, |
| 214 | /// Running cumulative checksum. Seeded from the header checksum, then rolled |
| 215 | /// forward frame by frame. Go fields `chksum1/chksum2`. |
| 216 | chksum1: u32, |
| 217 | chksum2: u32, |
| 218 | } |
| 219 | |
| 220 | impl<'a> WalReader<'a> { |
| 221 | /// Creates a new reader over `data`, parsing the WAL header immediately. |
| 222 | /// |
| 223 | /// Returns [`WalError::Eof`] if the buffer is too short to hold a header or |
| 224 | /// the header checksum does not validate (a partial WAL-header write during |
| 225 | /// checkpointing). Returns [`WalError::InvalidMagic`] / |
| 226 | /// [`WalError::UnsupportedVersion`] for a malformed header. |
| 227 | /// |
| 228 | /// Ported from `NewWALReader` in [email protected] wal_reader.go:34-40. |
| 229 | pub fn new(data: &'a [u8]) -> WalResult<Self> { |
| 230 | let mut r = WalReader { |
| 231 | data, |
| 232 | frame_n: 0, |
| 233 | big_endian: false, |
| 234 | page_size: 0, |
| 235 | salt1: 0, |
| 236 | salt2: 0, |
| 237 | chksum1: 0, |
| 238 | chksum2: 0, |
| 239 | }; |
| 240 | r.read_header()?; |
| 241 | Ok(r) |
| 242 | } |
| 243 | |
| 244 | /// Creates a new reader positioned at `offset`, loading the running checksum |
| 245 | /// from the *previous* frame so reading can resume mid-WAL. |
| 246 | /// |
| 247 | /// `salt1`/`salt2` are the expected salts of the segment being resumed; they |
| 248 | /// override the header salts in case the start of the file was overwritten by |
| 249 | /// a later transaction. Returns: |
| 250 | /// - [`WalError::OffsetTooSmall`] if `offset <= WAL_HEADER_SIZE` (we must be |
| 251 | /// able to read a previous frame), |
| 252 | /// - [`WalError::UnalignedOffset`] if `offset` is not on a frame boundary, |
| 253 | /// - [`WalError::PrevFrameMismatch`] if the previous frame cannot be re-read |
| 254 | /// (salt/checksum mismatch) — the caller falls back to a full snapshot. |
| 255 | /// |
| 256 | /// Ported from `NewWALReaderWithOffset` in [email protected] |
| 257 | /// wal_reader.go:42-75. |
| 258 | pub fn new_with_offset(data: &'a [u8], offset: i64, salt1: u32, salt2: u32) -> WalResult<Self> { |
| 259 | // Must not start on the first page — we need to read the previous frame. |
| 260 | if offset <= WAL_HEADER_SIZE as i64 { |
| 261 | return Err(WalError::OffsetTooSmall { |
| 262 | offset, |
| 263 | header_size: WAL_HEADER_SIZE as i64, |
| 264 | }); |
| 265 | } |
| 266 | |
| 267 | let mut r = WalReader { |
| 268 | data, |
| 269 | frame_n: 0, |
| 270 | big_endian: false, |
| 271 | page_size: 0, |
| 272 | salt1: 0, |
| 273 | salt2: 0, |
| 274 | chksum1: 0, |
| 275 | chksum2: 0, |
| 276 | }; |
| 277 | |
| 278 | // Read header to determine page size & byte order. |
| 279 | r.read_header()?; |
| 280 | |
| 281 | // Override salts in case the beginning of the file was overwritten. |
| 282 | r.salt1 = salt1; |
| 283 | r.salt2 = salt2; |
| 284 | |
| 285 | // Ensure the offset lands on a frame start. |
| 286 | let frame_size = r.page_size as i64 + WAL_FRAME_HEADER_SIZE as i64; |
| 287 | if (offset - WAL_HEADER_SIZE as i64) % frame_size != 0 { |
| 288 | return Err(WalError::UnalignedOffset { |
| 289 | offset, |
| 290 | page_size: r.page_size, |
| 291 | }); |
| 292 | } |
| 293 | r.frame_n = (offset - WAL_HEADER_SIZE as i64) / frame_size; |
| 294 | |
| 295 | // Read the previous frame to load the running checksum. Any failure here |
| 296 | // (salt/checksum mismatch surfaces as WalError::Eof from read_frame_inner) |
| 297 | // means the previous frame doesn't match what we expect → mismatch. |
| 298 | r.frame_n -= 1; |
| 299 | let mut buf = vec![0u8; r.page_size as usize]; |
| 300 | if r.read_frame_inner(&mut buf, false).is_err() { |
| 301 | return Err(WalError::PrevFrameMismatch); |
| 302 | } |
| 303 | |
| 304 | Ok(r) |
| 305 | } |
| 306 | |
| 307 | /// Returns the page size from the header. |
| 308 | /// |
| 309 | /// Ported from `PageSize` in [email protected] wal_reader.go:78. |
| 310 | #[inline] |
| 311 | pub fn page_size(&self) -> u32 { |
| 312 | self.page_size |
| 313 | } |
| 314 | |
| 315 | /// Returns the header salt pair `(salt1, salt2)`. |
| 316 | #[inline] |
| 317 | pub fn salt(&self) -> (u32, u32) { |
| 318 | (self.salt1, self.salt2) |
| 319 | } |
| 320 | |
| 321 | /// Returns the file offset of the last frame read, or `0` if no frame has |
| 322 | /// been read yet. |
| 323 | /// |
| 324 | /// Ported from `Offset` in [email protected] wal_reader.go:82-87. |
| 325 | pub fn offset(&self) -> i64 { |
| 326 | if self.frame_n == 0 { |
| 327 | return 0; |
| 328 | } |
| 329 | WAL_HEADER_SIZE as i64 |
| 330 | + ((self.frame_n - 1) * (WAL_FRAME_HEADER_SIZE as i64 + self.page_size as i64)) |
| 331 | } |
| 332 | |
| 333 | /// Reads `n` bytes at absolute `offset`, returning `None` (the `io.EOF` |
| 334 | /// case) when fewer than `n` bytes are available — exactly the behavior of |
| 335 | /// Go's `io.ReaderAt.ReadAt` over a `bytes.Reader` short read, which the |
| 336 | /// upstream code converts to `io.EOF`. |
| 337 | fn read_at(&self, offset: i64, n: usize) -> Option<&'a [u8]> { |
| 338 | if offset < 0 { |
| 339 | return None; |
| 340 | } |
| 341 | let start = offset as usize; |
| 342 | let end = start.checked_add(n)?; |
| 343 | if end > self.data.len() { |
| 344 | return None; |
| 345 | } |
| 346 | Some(&self.data[start..end]) |
| 347 | } |
| 348 | |
| 349 | /// Reads and validates the WAL header into `self`. |
| 350 | /// |
| 351 | /// Ported from `readHeader` in [email protected] wal_reader.go:90-129. |
| 352 | fn read_header(&mut self) -> WalResult<()> { |
| 353 | // If we have a partial WAL, mark WAL as done (io.EOF). |
| 354 | let hdr = match self.read_at(0, WAL_HEADER_SIZE) { |
| 355 | Some(b) => b, |
| 356 | None => return Err(WalError::Eof), |
| 357 | }; |
| 358 | |
| 359 | // Determine byte order of checksums from the magic (always read |
| 360 | // big-endian, like Go's binary.BigEndian.Uint32(hdr[0:])). |
| 361 | let magic = be_u32(&hdr[0..]); |
| 362 | self.big_endian = match magic { |
| 363 | WAL_MAGIC_LITTLE_ENDIAN => false, |
| 364 | WAL_MAGIC_BIG_ENDIAN => true, |
| 365 | _ => return Err(WalError::InvalidMagic(magic)), |
| 366 | }; |
| 367 | |
| 368 | // If the header checksum doesn't match then we may have failed with a |
| 369 | // partial WAL header write during checkpointing => io.EOF. |
| 370 | let chksum1 = be_u32(&hdr[24..]); |
| 371 | let chksum2 = be_u32(&hdr[28..]); |
| 372 | let (v0, v1) = wal_checksum(self.big_endian, 0, 0, &hdr[..24]); |
| 373 | if v0 != chksum1 || v1 != chksum2 { |
| 374 | return Err(WalError::Eof); |
| 375 | } |
| 376 | |
| 377 | // Verify version is correct. |
| 378 | let version = be_u32(&hdr[4..]); |
| 379 | if version != WAL_VERSION { |
| 380 | return Err(WalError::UnsupportedVersion(version)); |
| 381 | } |
| 382 | |
| 383 | self.page_size = be_u32(&hdr[8..]); |
| 384 | self.salt1 = be_u32(&hdr[16..]); |
| 385 | self.salt2 = be_u32(&hdr[20..]); |
| 386 | self.chksum1 = chksum1; |
| 387 | self.chksum2 = chksum2; |
| 388 | |
| 389 | Ok(()) |
| 390 | } |
| 391 | |
| 392 | /// Reads the next frame into `data` and returns `(pgno, commit)`. |
| 393 | /// |
| 394 | /// Returns [`WalError::Eof`] at the end of the valid WAL (including on a |
| 395 | /// salt or checksum mismatch, which terminate the valid region). `data` must |
| 396 | /// be exactly `page_size` bytes or [`WalError::BufferSize`] is returned. |
| 397 | /// |
| 398 | /// Ported from `ReadFrame` in [email protected] wal_reader.go:131-135. |
| 399 | pub fn read_frame(&mut self, data: &mut [u8]) -> WalResult<(u32, u32)> { |
| 400 | self.read_frame_inner(data, true) |
| 401 | } |
| 402 | |
| 403 | /// Frame-read core shared by [`Self::read_frame`] and the offset constructor. |
| 404 | /// |
| 405 | /// When `verify_checksum` is `false`, the running checksum is *set* from the |
| 406 | /// frame's stored checksum rather than verified against a rolling value — |
| 407 | /// used when seeking to an offset without checksumming from the beginning. |
| 408 | /// |
| 409 | /// Ported from `readFrame` in [email protected] wal_reader.go:137-187. |
| 410 | fn read_frame_inner( |
| 411 | &mut self, |
| 412 | data: &mut [u8], |
| 413 | verify_checksum: bool, |
| 414 | ) -> WalResult<(u32, u32)> { |
| 415 | if data.len() != self.page_size as usize { |
| 416 | return Err(WalError::BufferSize { |
| 417 | got: data.len(), |
| 418 | want: self.page_size, |
| 419 | }); |
| 420 | } |
| 421 | |
| 422 | let frame_size = self.page_size as i64 + WAL_FRAME_HEADER_SIZE as i64; |
| 423 | let offset = WAL_HEADER_SIZE as i64 + (self.frame_n * frame_size); |
| 424 | |
| 425 | // Read WAL frame header. A short read is io.EOF. |
| 426 | let hdr = match self.read_at(offset, WAL_FRAME_HEADER_SIZE) { |
| 427 | Some(b) => b, |
| 428 | None => return Err(WalError::Eof), |
| 429 | }; |
| 430 | |
| 431 | // Read WAL page data. A short read is io.EOF. |
| 432 | let page = match self.read_at(offset + WAL_FRAME_HEADER_SIZE as i64, data.len()) { |
| 433 | Some(b) => b, |
| 434 | None => return Err(WalError::Eof), |
| 435 | }; |
| 436 | data.copy_from_slice(page); |
| 437 | |
| 438 | // Verify salt matches the salt in the header; otherwise end of valid WAL. |
| 439 | let salt1 = be_u32(&hdr[8..]); |
| 440 | let salt2 = be_u32(&hdr[12..]); |
| 441 | if self.salt1 != salt1 || self.salt2 != salt2 { |
| 442 | return Err(WalError::Eof); |
| 443 | } |
| 444 | |
| 445 | // Verify the cumulative checksum. If verification is disabled, it is |
| 446 | // because we are jumping to an offset and not checksumming from the |
| 447 | // beginning, so we simply adopt the frame's stored checksum. |
| 448 | let chksum1 = be_u32(&hdr[16..]); |
| 449 | let chksum2 = be_u32(&hdr[20..]); |
| 450 | if verify_checksum { |
| 451 | let (c0, c1) = wal_checksum(self.big_endian, self.chksum1, self.chksum2, &hdr[..8]); |
| 452 | let (c0, c1) = wal_checksum(self.big_endian, c0, c1, data); |
| 453 | self.chksum1 = c0; |
| 454 | self.chksum2 = c1; |
| 455 | if self.chksum1 != chksum1 || self.chksum2 != chksum2 { |
| 456 | return Err(WalError::Eof); |
| 457 | } |
| 458 | } else { |
| 459 | self.chksum1 = chksum1; |
| 460 | self.chksum2 = chksum2; |
| 461 | } |
| 462 | |
| 463 | let pgno = be_u32(&hdr[0..]); |
| 464 | let commit = be_u32(&hdr[4..]); |
| 465 | |
| 466 | self.frame_n += 1; |
| 467 | |
| 468 | Ok((pgno, commit)) |
| 469 | } |
| 470 | |
| 471 | /// Reads all committed frames to end-of-file and returns a map of page |
| 472 | /// number → byte offset of the latest committed version of that page, the |
| 473 | /// max offset of the WAL segment read, and the final database size in pages. |
| 474 | /// |
| 475 | /// Pages above the final commit size are dropped (handles a DB that shrank, |
| 476 | /// e.g. via `VACUUM`, between transactions). |
| 477 | /// |
| 478 | /// Ported from `PageMap` in [email protected] wal_reader.go:189-244. |
| 479 | pub fn page_map(&mut self) -> WalResult<(HashMap<u32, i64>, i64, u32)> { |
| 480 | let mut m: HashMap<u32, i64> = HashMap::new(); |
| 481 | let mut tx_map: HashMap<u32, i64> = HashMap::new(); |
| 482 | let mut commit: u32 = 0; |
| 483 | let mut data = vec![0u8; self.page_size as usize]; |
| 484 | |
| 485 | loop { |
| 486 | let (pgno, fcommit) = match self.read_frame(&mut data) { |
| 487 | Ok(v) => v, |
| 488 | Err(e) if e.is_eof() => break, |
| 489 | Err(e) => return Err(e), |
| 490 | }; |
| 491 | |
| 492 | // Update latest offset for this page within the current transaction. |
| 493 | // Not promoted to the full map until the txn commits. |
| 494 | let offset = self.offset(); |
| 495 | tx_map.insert(pgno, offset); |
| 496 | |
| 497 | // On a commit record, transfer the txn offsets into the full map and |
| 498 | // record the new DB size. |
| 499 | if fcommit != 0 { |
| 500 | for (p, o) in tx_map.drain() { |
| 501 | m.insert(p, o); |
| 502 | } |
| 503 | commit = fcommit; |
| 504 | } |
| 505 | } |
| 506 | |
| 507 | // Remove pages that exceed the final commit size (DB shrank mid-WAL). |
| 508 | m.retain(|&pgno, _| pgno <= commit); |
| 509 | |
| 510 | // No complete transactions => original (zero) offset. |
| 511 | if m.is_empty() { |
| 512 | return Ok((m, 0, 0)); |
| 513 | } |
| 514 | |
| 515 | // Highest page offset, extended to the end of that frame. |
| 516 | let mut end: i64 = 0; |
| 517 | for &offset in m.values() { |
| 518 | if end == 0 || offset > end { |
| 519 | end = offset; |
| 520 | } |
| 521 | } |
| 522 | end += WAL_FRAME_HEADER_SIZE as i64 + self.page_size as i64; |
| 523 | |
| 524 | Ok((m, end, commit)) |
| 525 | } |
| 526 | |
| 527 | /// Returns the set of unique frame salt pairs in the WAL, scanning until the |
| 528 | /// `until` salt pair is seen or end-of-file is reached. |
| 529 | /// |
| 530 | /// Unlike frame reading, this does **not** verify checksums or that frame |
| 531 | /// salts match the header — it deliberately collects *every* distinct salt, |
| 532 | /// including those from superseded transactions. |
| 533 | /// |
| 534 | /// Ported from `FrameSaltsUntil` in [email protected] wal_reader.go:246-270. |
| 535 | pub fn frame_salts_until(&self, until: (u32, u32)) -> HashSet<(u32, u32)> { |
| 536 | let mut m = HashSet::new(); |
| 537 | let step = WAL_FRAME_HEADER_SIZE as i64 + self.page_size as i64; |
| 538 | let mut offset = WAL_HEADER_SIZE as i64; |
| 539 | // The loop ends either when a frame-header read runs short (the Go |
| 540 | // `n != len(hdr)` => break) or when we reach the `until` salt below. |
| 541 | while let Some(hdr) = self.read_at(offset, WAL_FRAME_HEADER_SIZE) { |
| 542 | let salt1 = be_u32(&hdr[8..]); |
| 543 | let salt2 = be_u32(&hdr[12..]); |
| 544 | |
| 545 | // Track unique salts. |
| 546 | m.insert((salt1, salt2)); |
| 547 | |
| 548 | // Stop once we've seen the salt we were asked to read up to. |
| 549 | if salt1 == until.0 && salt2 == until.1 { |
| 550 | break; |
| 551 | } |
| 552 | |
| 553 | offset += step; |
| 554 | } |
| 555 | m |
| 556 | } |
| 557 | } |
| 558 | |
| 559 | /// Reads a big-endian `u32` from the first four bytes of `b`. |
| 560 | /// |
| 561 | /// All WAL header/frame scalar fields are big-endian regardless of the checksum |
| 562 | /// byte order (Go uses `binary.BigEndian.Uint32`). Panics if `b.len() < 4`, |
| 563 | /// which never happens for the fixed-offset accesses in this module. |
| 564 | #[inline] |
| 565 | fn be_u32(b: &[u8]) -> u32 { |
| 566 | u32::from_be_bytes([b[0], b[1], b[2], b[3]]) |
| 567 | } |
| 568 | |
| 569 | #[cfg(test)] |
| 570 | mod tests { |
| 571 | use super::*; |
| 572 | use std::path::PathBuf; |
| 573 | |
| 574 | /// Loads a WAL test vector from the **read-only** upstream Go testdata tree |
| 575 | /// (`reference/litestream-go/testdata/wal-reader/<name>/wal`). These are the |
| 576 | /// exact fixtures the ported Go tests (`wal_reader_test.go`) consume. |
| 577 | fn read_testdata(name: &str) -> Vec<u8> { |
| 578 | let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR")); |
| 579 | p.push("reference/litestream-go/testdata/wal-reader"); |
| 580 | p.push(name); |
| 581 | p.push("wal"); |
| 582 | std::fs::read(&p).unwrap_or_else(|e| panic!("read {}: {e}", p.display())) |
| 583 | } |
| 584 | |
| 585 | /// Loads the immutable golden SQLite WAL fixture. |
| 586 | fn read_golden_wal() -> Vec<u8> { |
| 587 | let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR")); |
| 588 | p.push("tests/fixtures/golden/sample.wal"); |
| 589 | std::fs::read(&p).unwrap_or_else(|e| panic!("read {}: {e}", p.display())) |
| 590 | } |
| 591 | |
| 592 | // ── Port of TestWALReader/OK (wal_reader_test.go:16-75) ──────────────────── |
| 593 | #[test] |
| 594 | fn test_wal_reader_ok() { |
| 595 | let mut buf = vec![0u8; 4096]; |
| 596 | let b = read_testdata("ok"); |
| 597 | |
| 598 | let mut r = WalReader::new(&b).expect("new reader"); |
| 599 | assert_eq!(r.page_size(), 4096, "PageSize"); |
| 600 | assert_eq!(r.offset(), 0, "Offset"); |
| 601 | |
| 602 | // First frame. |
| 603 | let (pgno, commit) = r.read_frame(&mut buf).expect("frame 1"); |
| 604 | assert_eq!(pgno, 1, "pgno"); |
| 605 | assert_eq!(commit, 0, "commit"); |
| 606 | assert_eq!(&buf[..], &b[56..4152], "page data mismatch"); |
| 607 | assert_eq!(r.offset(), 32, "Offset"); |
| 608 | |
| 609 | // Second frame: end of transaction. |
| 610 | let (pgno, commit) = r.read_frame(&mut buf).expect("frame 2"); |
| 611 | assert_eq!(pgno, 2, "pgno"); |
| 612 | assert_eq!(commit, 2, "commit"); |
| 613 | assert_eq!(&buf[..], &b[4176..8272], "page data mismatch"); |
| 614 | assert_eq!(r.offset(), 4152, "Offset"); |
| 615 | |
| 616 | // Third frame. |
| 617 | let (pgno, commit) = r.read_frame(&mut buf).expect("frame 3"); |
| 618 | assert_eq!(pgno, 2, "pgno"); |
| 619 | assert_eq!(commit, 2, "commit"); |
| 620 | assert_eq!(&buf[..], &b[8296..12392], "page data mismatch"); |
| 621 | assert_eq!(r.offset(), 8272, "Offset"); |
| 622 | |
| 623 | // End of WAL. |
| 624 | let err = r.read_frame(&mut buf).expect_err("expected EOF"); |
| 625 | assert!(err.is_eof(), "unexpected error: {err}"); |
| 626 | } |
| 627 | |
| 628 | // ── Port of TestWALReader/SaltMismatch (wal_reader_test.go:77-109) ───────── |
| 629 | #[test] |
| 630 | fn test_wal_reader_salt_mismatch() { |
| 631 | let mut buf = vec![0u8; 4096]; |
| 632 | let b = read_testdata("salt-mismatch"); |
| 633 | |
| 634 | let mut r = WalReader::new(&b).expect("new reader"); |
| 635 | assert_eq!(r.page_size(), 4096); |
| 636 | assert_eq!(r.offset(), 0); |
| 637 | |
| 638 | // First frame is valid. |
| 639 | let (pgno, commit) = r.read_frame(&mut buf).expect("frame 1"); |
| 640 | assert_eq!(pgno, 1); |
| 641 | assert_eq!(commit, 0); |
| 642 | assert_eq!(&buf[..], &b[56..4152], "page data mismatch"); |
| 643 | |
| 644 | // Second frame: salt altered so it doesn't match header => EOF. |
| 645 | let err = r.read_frame(&mut buf).expect_err("expected EOF"); |
| 646 | assert!(err.is_eof(), "unexpected error: {err}"); |
| 647 | } |
| 648 | |
| 649 | // ── Port of TestWALReader/FrameChecksumMismatch (wal_reader_test.go:111-143) ─ |
| 650 | #[test] |
| 651 | fn test_wal_reader_frame_checksum_mismatch() { |
| 652 | let mut buf = vec![0u8; 4096]; |
| 653 | let b = read_testdata("frame-checksum-mismatch"); |
| 654 | |
| 655 | let mut r = WalReader::new(&b).expect("new reader"); |
| 656 | assert_eq!(r.page_size(), 4096); |
| 657 | assert_eq!(r.offset(), 0); |
| 658 | |
| 659 | // First frame is valid. |
| 660 | let (pgno, commit) = r.read_frame(&mut buf).expect("frame 1"); |
| 661 | assert_eq!(pgno, 1); |
| 662 | assert_eq!(commit, 0); |
| 663 | assert_eq!(&buf[..], &b[56..4152], "page data mismatch"); |
| 664 | |
| 665 | // Second frame: checksum altered => EOF. |
| 666 | let err = r.read_frame(&mut buf).expect_err("expected EOF"); |
| 667 | assert!(err.is_eof(), "unexpected error: {err}"); |
| 668 | } |
| 669 | |
| 670 | // ── Port of TestWALReader/ZeroLength (wal_reader_test.go:145-150) ────────── |
| 671 | #[test] |
| 672 | fn test_wal_reader_zero_length() { |
| 673 | let err = WalReader::new(&[]).expect_err("expected EOF"); |
| 674 | assert!(err.is_eof(), "unexpected error: {err}"); |
| 675 | } |
| 676 | |
| 677 | // ── Port of TestWALReader/PartialHeader (wal_reader_test.go:152-157) ─────── |
| 678 | #[test] |
| 679 | fn test_wal_reader_partial_header() { |
| 680 | let err = WalReader::new(&[0u8; 10]).expect_err("expected EOF"); |
| 681 | assert!(err.is_eof(), "unexpected error: {err}"); |
| 682 | } |
| 683 | |
| 684 | // ── Port of TestWALReader/BadMagic (wal_reader_test.go:159-164) ──────────── |
| 685 | #[test] |
| 686 | fn test_wal_reader_bad_magic() { |
| 687 | // All-zero 32-byte header => magic 0. |
| 688 | let err = WalReader::new(&[0u8; 32]).expect_err("expected error"); |
| 689 | assert_eq!(err.to_string(), "invalid wal header magic: 0"); |
| 690 | } |
| 691 | |
| 692 | // ── Port of TestWALReader/BadHeaderChecksum (wal_reader_test.go:166-176) ─── |
| 693 | #[test] |
| 694 | fn test_wal_reader_bad_header_checksum() { |
| 695 | // Valid big-endian magic, zero checksum fields => header checksum fails. |
| 696 | let data: [u8; 32] = [ |
| 697 | 0x37, 0x7f, 0x06, 0x83, 0x00, 0x00, 0x00, 0x00, // |
| 698 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // |
| 699 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // |
| 700 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, |
| 701 | ]; |
| 702 | let err = WalReader::new(&data).expect_err("expected EOF"); |
| 703 | assert!(err.is_eof(), "unexpected error: {err}"); |
| 704 | } |
| 705 | |
| 706 | // ── Port of TestWALReader/BadHeaderVersion (wal_reader_test.go:178-188) ──── |
| 707 | #[test] |
| 708 | fn test_wal_reader_bad_header_version() { |
| 709 | // Valid magic + version 1 + a header checksum that actually validates |
| 710 | // over bytes [0..24] (these checksum bytes are taken verbatim from the |
| 711 | // upstream Go test vector). |
| 712 | let data: [u8; 32] = [ |
| 713 | 0x37, 0x7f, 0x06, 0x83, 0x00, 0x00, 0x00, 0x01, // |
| 714 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // |
| 715 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // |
| 716 | 0x15, 0x7b, 0x20, 0x92, 0xbb, 0xf8, 0x34, 0x1d, |
| 717 | ]; |
| 718 | let err = WalReader::new(&data).expect_err("expected error"); |
| 719 | assert_eq!(err.to_string(), "unsupported wal version: 1"); |
| 720 | } |
| 721 | |
| 722 | // ── Port of TestWALReader/ErrBufferSize (wal_reader_test.go:190-204) ─────── |
| 723 | #[test] |
| 724 | fn test_wal_reader_err_buffer_size() { |
| 725 | let b = read_testdata("ok"); |
| 726 | let mut r = WalReader::new(&b).expect("new reader"); |
| 727 | let mut small = vec![0u8; 512]; |
| 728 | let err = r |
| 729 | .read_frame(&mut small) |
| 730 | .expect_err("expected buffer-size error"); |
| 731 | assert_eq!( |
| 732 | err.to_string(), |
| 733 | "WALReader.ReadFrame(): buffer size (512) must match page size (4096)" |
| 734 | ); |
| 735 | } |
| 736 | |
| 737 | // ── Port of TestWALReader/ErrPartialFrameHeader (wal_reader_test.go:206-218) ─ |
| 738 | #[test] |
| 739 | fn test_wal_reader_err_partial_frame_header() { |
| 740 | let b = read_testdata("ok"); |
| 741 | // Truncate to 40 bytes: header (32) + 8 bytes of frame header. |
| 742 | let mut r = WalReader::new(&b[..40]).expect("new reader"); |
| 743 | let mut buf = vec![0u8; 4096]; |
| 744 | let err = r.read_frame(&mut buf).expect_err("expected EOF"); |
| 745 | assert!(err.is_eof(), "unexpected error: {err}"); |
| 746 | } |
| 747 | |
| 748 | // ── Port of TestWALReader/ErrFrameHeaderOnly (wal_reader_test.go:220-232) ── |
| 749 | #[test] |
| 750 | fn test_wal_reader_err_frame_header_only() { |
| 751 | let b = read_testdata("ok"); |
| 752 | // Truncate to 56 bytes: header (32) + full frame header (24), no page. |
| 753 | let mut r = WalReader::new(&b[..56]).expect("new reader"); |
| 754 | let mut buf = vec![0u8; 4096]; |
| 755 | let err = r.read_frame(&mut buf).expect_err("expected EOF"); |
| 756 | assert!(err.is_eof(), "unexpected error: {err}"); |
| 757 | } |
| 758 | |
| 759 | // ── Port of TestWALReader/ErrPartialFrameData (wal_reader_test.go:234-246) ── |
| 760 | #[test] |
| 761 | fn test_wal_reader_err_partial_frame_data() { |
| 762 | let b = read_testdata("ok"); |
| 763 | // Truncate to 1000 bytes: full frame header but only partial page data. |
| 764 | let mut r = WalReader::new(&b[..1000]).expect("new reader"); |
| 765 | let mut buf = vec![0u8; 4096]; |
| 766 | let err = r.read_frame(&mut buf).expect_err("expected EOF"); |
| 767 | assert!(err.is_eof(), "unexpected error: {err}"); |
| 768 | } |
| 769 | |
| 770 | // ── new_with_offset (port of NewWALReaderWithOffset, wal_reader.go:42-75) ── |
| 771 | // |
| 772 | // Resuming at a frame boundary must load the running checksum from the |
| 773 | // previous frame and continue reading the rest of the WAL identically to a |
| 774 | // fresh full read. We cross-check against a from-start read of the same WAL. |
| 775 | #[test] |
| 776 | fn test_wal_reader_new_with_offset_resumes() { |
| 777 | let b = read_testdata("ok"); |
| 778 | let page_size = 4096i64; |
| 779 | let frame_size = WAL_FRAME_HEADER_SIZE as i64 + page_size; |
| 780 | |
| 781 | // Header salts (offsets 16/20) are the segment's expected salts. |
| 782 | let salt1 = be_u32(&b[16..]); |
| 783 | let salt2 = be_u32(&b[20..]); |
| 784 | |
| 785 | // Resume at the SECOND frame: offset = 32 + 1*frame_size. This requires |
| 786 | // re-reading frame 0 to seed the checksum. |
| 787 | let offset = WAL_HEADER_SIZE as i64 + frame_size; |
| 788 | let mut r = WalReader::new_with_offset(&b, offset, salt1, salt2) |
| 789 | .expect("new_with_offset at frame 1"); |
| 790 | |
| 791 | // The next frame read should be frame index 1 (the second frame), whose |
| 792 | // page/commit match what a full read returns for that frame. |
| 793 | let mut buf = vec![0u8; page_size as usize]; |
| 794 | let (pgno, commit) = r.read_frame(&mut buf).expect("resume frame"); |
| 795 | assert_eq!(pgno, 2, "second frame pgno"); |
| 796 | assert_eq!(commit, 2, "second frame commit"); |
| 797 | assert_eq!(&buf[..], &b[4176..8272], "resumed page data matches"); |
| 798 | } |
| 799 | |
| 800 | #[test] |
| 801 | fn test_wal_reader_new_with_offset_too_small() { |
| 802 | let b = read_testdata("ok"); |
| 803 | let salt1 = be_u32(&b[16..]); |
| 804 | let salt2 = be_u32(&b[20..]); |
| 805 | // Offset at the header is rejected (need a previous frame to re-read). |
| 806 | let err = WalReader::new_with_offset(&b, WAL_HEADER_SIZE as i64, salt1, salt2) |
| 807 | .expect_err("expected offset-too-small"); |
| 808 | assert_eq!( |
| 809 | err, |
| 810 | WalError::OffsetTooSmall { |
| 811 | offset: WAL_HEADER_SIZE as i64, |
| 812 | header_size: WAL_HEADER_SIZE as i64 |
| 813 | } |
| 814 | ); |
| 815 | } |
| 816 | |
| 817 | #[test] |
| 818 | fn test_wal_reader_new_with_offset_unaligned() { |
| 819 | let b = read_testdata("ok"); |
| 820 | let salt1 = be_u32(&b[16..]); |
| 821 | let salt2 = be_u32(&b[20..]); |
| 822 | // An offset off the frame grid is rejected. |
| 823 | let err = WalReader::new_with_offset(&b, WAL_HEADER_SIZE as i64 + 7, salt1, salt2) |
| 824 | .expect_err("expected unaligned"); |
| 825 | assert!( |
| 826 | matches!(err, WalError::UnalignedOffset { .. }), |
| 827 | "unexpected error: {err}" |
| 828 | ); |
| 829 | } |
| 830 | |
| 831 | #[test] |
| 832 | fn test_wal_reader_new_with_offset_prev_frame_mismatch() { |
| 833 | let b = read_testdata("ok"); |
| 834 | let frame_size = WAL_FRAME_HEADER_SIZE as i64 + 4096; |
| 835 | let offset = WAL_HEADER_SIZE as i64 + frame_size; |
| 836 | // Wrong expected salts → the previous frame won't validate → mismatch |
| 837 | // (the load-bearing snapshot-fallback signal for DB.sync). |
| 838 | let err = WalReader::new_with_offset(&b, offset, 0xdead_beef, 0xfeed_face) |
| 839 | .expect_err("expected prev-frame mismatch"); |
| 840 | assert_eq!(err, WalError::PrevFrameMismatch); |
| 841 | } |
| 842 | |
| 843 | // ── Port of TestWALReader_FrameSaltsUntil/OK (wal_reader_test.go:249-278) ── |
| 844 | #[test] |
| 845 | fn test_wal_reader_frame_salts_until_ok() { |
| 846 | let b = read_testdata("frame-salts"); |
| 847 | let r = WalReader::new(&b).expect("new reader"); |
| 848 | |
| 849 | // No frame carries salt (0,0), so the scan runs to EOF and collects all |
| 850 | // three distinct salt pairs present in the file. |
| 851 | let m = r.frame_salts_until((0x0000_0000, 0x0000_0000)); |
| 852 | assert_eq!(m.len(), 3, "len(m)"); |
| 853 | assert!(m.contains(&(0x1b9a_294b, 0x37f9_1916)), "salt 0 not found"); |
| 854 | assert!(m.contains(&(0x1b9a_294a, 0x031f_195e)), "salt 1 not found"); |
| 855 | assert!(m.contains(&(0x1b9a_2949, 0x13b3_dd67)), "salt 2 not found"); |
| 856 | } |
| 857 | |
| 858 | // ── GOLDEN (byte-exact): real SQLite WAL from tests/fixtures/golden ──────── |
| 859 | // |
| 860 | // sample.wal: 16,512 bytes, page size 4096, magic 0x377f0682 (little-endian |
| 861 | // checksums), per tests/fixtures/golden/MANIFEST.md. A checksum failure here |
| 862 | // means the port is wrong, NOT the fixture (AGENTS.md rule 3). |
| 863 | #[test] |
| 864 | fn test_golden_sample_wal() { |
| 865 | let b = read_golden_wal(); |
| 866 | assert_eq!(b.len(), 16_512, "fixture size changed unexpectedly"); |
| 867 | |
| 868 | let mut r = WalReader::new(&b).expect("new reader over golden WAL"); |
| 869 | |
| 870 | // Page size from the header. |
| 871 | assert_eq!(r.page_size(), 4096, "golden WAL page size"); |
| 872 | |
| 873 | // Salt values straight from the header bytes (offsets 16/20). |
| 874 | assert_eq!( |
| 875 | r.salt(), |
| 876 | (0x9bf2_9a02, 0x6867_0130), |
| 877 | "golden WAL header salts" |
| 878 | ); |
| 879 | |
| 880 | // Every frame must read cleanly and pass the cumulative SQLite checksum. |
| 881 | // read_frame returns EOF the instant a checksum (or salt) check fails, so |
| 882 | // a successful read of a frame == that frame's checksum verified. |
| 883 | let mut buf = vec![0u8; r.page_size() as usize]; |
| 884 | let mut frame_count = 0u64; |
| 885 | loop { |
| 886 | match r.read_frame(&mut buf) { |
| 887 | Ok((pgno, _commit)) => { |
| 888 | assert!(pgno >= 1, "page numbers are 1-based"); |
| 889 | frame_count += 1; |
| 890 | } |
| 891 | Err(e) if e.is_eof() => break, |
| 892 | Err(e) => panic!("unexpected non-EOF error reading golden WAL: {e}"), |
| 893 | } |
| 894 | } |
| 895 | |
| 896 | // A real WAL with data => a nonzero frame count, every frame checksummed. |
| 897 | assert!( |
| 898 | frame_count > 0, |
| 899 | "expected a nonzero frame count in the golden WAL" |
| 900 | ); |
| 901 | |
| 902 | // Cross-check the geometry: with all frames valid to EOF, the file must |
| 903 | // be exactly header + frame_count whole frames (no trailing partial). |
| 904 | let frame_size = WAL_FRAME_HEADER_SIZE as i64 + r.page_size() as i64; |
| 905 | assert_eq!( |
| 906 | WAL_HEADER_SIZE as i64 + frame_count as i64 * frame_size, |
| 907 | b.len() as i64, |
| 908 | "golden WAL is not an exact header + N*frame layout" |
| 909 | ); |
| 910 | } |
| 911 | } |