| 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. |
| 71 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 72 | pub enum WalError { |
| 73 | /// End of the valid WAL. |
| 74 | /// |
| 75 | /// Mirrors every `return ..., io.EOF` in wal_reader.go: a partial header, a |
| 76 | /// failed header checksum, a short frame read, a salt mismatch, or a frame |
| 77 | /// checksum mismatch. In all of these the WAL has no further valid frames. |
| 78 | Eof, |
| 79 | |
| 80 | /// `invalid wal header magic: <hex>` — the magic was neither |
| 81 | /// `0x377f0682` nor `0x377f0683`. |
| 82 | /// |
| 83 | /// Ported from [email protected] wal_reader.go:106. |
| 84 | InvalidMagic(u32), |
| 85 | |
| 86 | /// `unsupported wal version: <n>` — header version field was not `3007000`. |
| 87 | /// |
| 88 | /// Ported from [email protected] wal_reader.go:119. |
| 89 | UnsupportedVersion(u32), |
| 90 | |
| 91 | /// `WALReader.ReadFrame(): buffer size (<n>) must match page size (<m>)`. |
| 92 | /// |
| 93 | /// Ported from [email protected] wal_reader.go:139. |
| 94 | BufferSize { |
| 95 | /// Length of the buffer the caller supplied. |
| 96 | got: usize, |
| 97 | /// The WAL's page size. |
| 98 | want: u32, |
| 99 | }, |
| 100 | |
| 101 | /// `offset (<n>) must be greater than the wal header size (<m>)` — passed to |
| 102 | /// [`WalReader::new_with_offset`] with an offset at or before the header. |
| 103 | /// |
| 104 | /// Ported from [email protected] wal_reader.go:48. |
| 105 | OffsetTooSmall { |
| 106 | /// The requested offset. |
| 107 | offset: i64, |
| 108 | /// The WAL header size. |
| 109 | header_size: i64, |
| 110 | }, |
| 111 | |
| 112 | /// `unaligned wal offset <n> for page size <m>` — the offset does not land on |
| 113 | /// a frame boundary. |
| 114 | /// |
| 115 | /// Ported from [email protected] wal_reader.go:64. |
| 116 | UnalignedOffset { |
| 117 | /// The requested offset. |
| 118 | offset: i64, |
| 119 | /// The WAL's page size. |
| 120 | page_size: u32, |
| 121 | }, |
| 122 | |
| 123 | /// The previous frame at the seek offset could not be re-read (its salt or |
| 124 | /// checksum did not match). **Load-bearing**: `DB.sync` catches this and |
| 125 | /// falls back to a full snapshot (db.go:1571-1577). |
| 126 | /// |
| 127 | /// Ported from `PrevFrameMismatchError` in [email protected] |
| 128 | /// wal_reader.go:284-294. |
| 129 | PrevFrameMismatch, |
| 130 | } |
| 131 | |
| 132 | impl WalError { |
| 133 | /// Returns `true` for the [`WalError::Eof`] sentinel. |
| 134 | /// |
| 135 | /// This is the analog of Go's `errors.Is(err, io.EOF)`, which upstream |
| 136 | /// callers such as `PageMap` use to detect the end of the WAL. |
| 137 | #[inline] |
| 138 | pub fn is_eof(&self) -> bool { |
| 139 | matches!(self, WalError::Eof) |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | impl std::fmt::Display for WalError { |
| 144 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 145 | match self { |
| 146 | // Matches the Go string "EOF" (io.EOF.Error()). |
| 147 | WalError::Eof => f.write_str("EOF"), |
| 148 | // Go: fmt.Errorf("invalid wal header magic: %x", magic) — lowercase |
| 149 | // hex, no leading zeros (matches Go's %x for a uint32). |
| 150 | WalError::InvalidMagic(magic) => write!(f, "invalid wal header magic: {magic:x}"), |
| 151 | WalError::UnsupportedVersion(v) => write!(f, "unsupported wal version: {v}"), |
| 152 | WalError::BufferSize { got, want } => write!( |
| 153 | f, |
| 154 | "WALReader.ReadFrame(): buffer size ({got}) must match page size ({want})" |
| 155 | ), |
| 156 | WalError::OffsetTooSmall { |
| 157 | offset, |
| 158 | header_size, |
| 159 | } => write!( |
| 160 | f, |
| 161 | "offset ({offset}) must be greater than the wal header size ({header_size})" |
| 162 | ), |
| 163 | WalError::UnalignedOffset { offset, page_size } => { |
| 164 | write!(f, "unaligned wal offset {offset} for page size {page_size}") |
| 165 | } |
| 166 | WalError::PrevFrameMismatch => f.write_str("previous frame mismatch"), |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | impl std::error::Error for WalError {} |
| 172 | |
| 173 | impl From<WalError> for crate::Error { |
| 174 | /// Lifts a [`WalError`] into the crate-wide error type for callers that work |
| 175 | /// in terms of [`crate::Error`]. EOF and the structured WAL errors become |
| 176 | /// `Error::Other` carrying the same message. |
| 177 | fn from(e: WalError) -> Self { |
| 178 | crate::Error::Other(Box::new(e)) |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | /// `WalReader`'s `Result` alias. |
| 183 | type WalResult<T> = std::result::Result<T, WalError>; |
| 184 | |
| 185 | // ── WalReader ─────────────────────────────────────────────────────────────── |
| 186 | |
| 187 | /// Reads SQLite WAL frames from an in-memory byte buffer, verifying salts and |
| 188 | /// the cumulative SQLite checksum as it goes. |
| 189 | /// |
| 190 | /// This is the faithful analog of Go's `WALReader` (wal_reader.go:19-31). Go |
| 191 | /// wraps an `io.ReaderAt`; this implementation wraps a borrowed `&[u8]` and emulates |
| 192 | /// `ReadAt` semantics directly: a read whose requested length runs past the end |
| 193 | /// of the buffer yields fewer bytes, which the algorithm treats as `io.EOF` |
| 194 | /// exactly as Go does. |
| 195 | /// |
| 196 | /// Ported from [email protected] wal_reader.go:19-187. |
| 197 | #[derive(Debug)] |
| 198 | pub struct WalReader<'a> { |
| 199 | /// Backing WAL bytes: the whole file (as the Go `io.ReaderAt`) when |
| 200 | /// `tail_base` is 0, otherwise the 32-byte header followed by the file's |
| 201 | /// bytes from `tail_base` onward — the shape a tail read produces without |
| 202 | /// a file-sized buffer between the header and the tail. |
| 203 | data: &'a [u8], |
| 204 | /// The file offset of `data[WAL_HEADER_SIZE..]`, or 0 for a whole-file |
| 205 | /// image. See [`WalReader::new_with_offset_over_tail`]. |
| 206 | tail_base: usize, |
| 207 | /// Index of the *next* frame to read (0-based). Go field `frameN`. |
| 208 | frame_n: i64, |
| 209 | |
| 210 | /// `true` when checksums are big-endian (magic `0x377f0683`), |
| 211 | /// `false` when little-endian (magic `0x377f0682`). Go field `bo`. |
| 212 | big_endian: bool, |
| 213 | /// Page size from the header. Go field `pageSize`. |
| 214 | page_size: u32, |
| 215 | /// Header salt-1 / salt-2; frames must match these. Go fields `salt1/salt2`. |
| 216 | salt1: u32, |
| 217 | salt2: u32, |
| 218 | /// Running cumulative checksum. Seeded from the header checksum, then rolled |
| 219 | /// forward frame by frame. Go fields `chksum1/chksum2`. |
| 220 | chksum1: u32, |
| 221 | chksum2: u32, |
| 222 | } |
| 223 | |
| 224 | impl<'a> WalReader<'a> { |
| 225 | /// Creates a new reader over `data`, parsing the WAL header immediately. |
| 226 | /// |
| 227 | /// Returns [`WalError::Eof`] if the buffer is too short to hold a header or |
| 228 | /// the header checksum does not validate (a partial WAL-header write during |
| 229 | /// checkpointing). Returns [`WalError::InvalidMagic`] / |
| 230 | /// [`WalError::UnsupportedVersion`] for a malformed header. |
| 231 | /// |
| 232 | /// Ported from `NewWALReader` in [email protected] wal_reader.go:34-40. |
| 233 | pub fn new(data: &'a [u8]) -> WalResult<Self> { |
| 234 | let mut r = WalReader { |
| 235 | data, |
| 236 | tail_base: 0, |
| 237 | frame_n: 0, |
| 238 | big_endian: false, |
| 239 | page_size: 0, |
| 240 | salt1: 0, |
| 241 | salt2: 0, |
| 242 | chksum1: 0, |
| 243 | chksum2: 0, |
| 244 | }; |
| 245 | r.read_header()?; |
| 246 | Ok(r) |
| 247 | } |
| 248 | |
| 249 | /// Creates a new reader positioned at `offset`, loading the running checksum |
| 250 | /// from the *previous* frame so reading can resume mid-WAL. |
| 251 | /// |
| 252 | /// `salt1`/`salt2` are the expected salts of the segment being resumed; they |
| 253 | /// override the header salts in case the start of the file was overwritten by |
| 254 | /// a later transaction. Returns: |
| 255 | /// - [`WalError::OffsetTooSmall`] if `offset <= WAL_HEADER_SIZE` (we must be |
| 256 | /// able to read a previous frame), |
| 257 | /// - [`WalError::UnalignedOffset`] if `offset` is not on a frame boundary, |
| 258 | /// - [`WalError::PrevFrameMismatch`] if the previous frame cannot be re-read |
| 259 | /// (salt/checksum mismatch) — the caller falls back to a full snapshot. |
| 260 | /// |
| 261 | /// Ported from `NewWALReaderWithOffset` in [email protected] |
| 262 | /// wal_reader.go:42-75. |
| 263 | pub fn new_with_offset(data: &'a [u8], offset: i64, salt1: u32, salt2: u32) -> WalResult<Self> { |
| 264 | // Must not start on the first page — we need to read the previous frame. |
| 265 | if offset <= WAL_HEADER_SIZE as i64 { |
| 266 | return Err(WalError::OffsetTooSmall { |
| 267 | offset, |
| 268 | header_size: WAL_HEADER_SIZE as i64, |
| 269 | }); |
| 270 | } |
| 271 | let mut r = Self::new_with_offset_inner(data, 0)?; |
| 272 | r.seek_to_offset(offset, salt1, salt2)?; |
| 273 | Ok(r) |
| 274 | } |
| 275 | |
| 276 | /// A reader over `data` with its header parsed and its tail base set; |
| 277 | /// the two offset constructors share it and then seek. |
| 278 | fn new_with_offset_inner(data: &'a [u8], tail_base: usize) -> WalResult<Self> { |
| 279 | let mut r = WalReader { |
| 280 | data, |
| 281 | tail_base, |
| 282 | frame_n: 0, |
| 283 | big_endian: false, |
| 284 | page_size: 0, |
| 285 | salt1: 0, |
| 286 | salt2: 0, |
| 287 | chksum1: 0, |
| 288 | chksum2: 0, |
| 289 | }; |
| 290 | // Read header to determine page size & byte order. |
| 291 | r.read_header()?; |
| 292 | Ok(r) |
| 293 | } |
| 294 | |
| 295 | /// Positions the reader at `offset` and seeds its running checksum from |
| 296 | /// the previous frame (wal_reader.go:42-75): the salts override the |
| 297 | /// header's in case the beginning of the file was overwritten, the offset |
| 298 | /// must land on a frame start, and a previous frame that does not match |
| 299 | /// is [`WalError::PrevFrameMismatch`] — the caller falls back to a full |
| 300 | /// snapshot. |
| 301 | fn seek_to_offset(&mut self, offset: i64, salt1: u32, salt2: u32) -> WalResult<()> { |
| 302 | self.salt1 = salt1; |
| 303 | self.salt2 = salt2; |
| 304 | |
| 305 | let frame_size = self.page_size as i64 + WAL_FRAME_HEADER_SIZE as i64; |
| 306 | if (offset - WAL_HEADER_SIZE as i64) % frame_size != 0 { |
| 307 | return Err(WalError::UnalignedOffset { |
| 308 | offset, |
| 309 | page_size: self.page_size, |
| 310 | }); |
| 311 | } |
| 312 | self.frame_n = (offset - WAL_HEADER_SIZE as i64) / frame_size; |
| 313 | |
| 314 | // Read the previous frame to load the running checksum. Any failure here |
| 315 | // (salt/checksum mismatch surfaces as WalError::Eof from read_frame_inner) |
| 316 | // means the previous frame doesn't match what we expect → mismatch. |
| 317 | self.frame_n -= 1; |
| 318 | let mut buf = vec![0u8; self.page_size as usize]; |
| 319 | if self.read_frame_inner(&mut buf, false).is_err() { |
| 320 | return Err(WalError::PrevFrameMismatch); |
| 321 | } |
| 322 | Ok(()) |
| 323 | } |
| 324 | |
| 325 | /// Returns the page size from the header. |
| 326 | /// |
| 327 | /// Ported from `PageSize` in [email protected] wal_reader.go:78. |
| 328 | #[inline] |
| 329 | pub fn page_size(&self) -> u32 { |
| 330 | self.page_size |
| 331 | } |
| 332 | |
| 333 | /// Returns the header salt pair `(salt1, salt2)`. |
| 334 | #[inline] |
| 335 | pub fn salt(&self) -> (u32, u32) { |
| 336 | (self.salt1, self.salt2) |
| 337 | } |
| 338 | |
| 339 | /// Returns the file offset of the last frame read, or `0` if no frame has |
| 340 | /// been read yet. |
| 341 | /// |
| 342 | /// Ported from `Offset` in [email protected] wal_reader.go:82-87. |
| 343 | pub fn offset(&self) -> i64 { |
| 344 | if self.frame_n == 0 { |
| 345 | return 0; |
| 346 | } |
| 347 | WAL_HEADER_SIZE as i64 |
| 348 | + ((self.frame_n - 1) * (WAL_FRAME_HEADER_SIZE as i64 + self.page_size as i64)) |
| 349 | } |
| 350 | |
| 351 | /// Reads `n` bytes at absolute `offset`, returning `None` (the `io.EOF` |
| 352 | /// case) when fewer than `n` bytes are available — exactly the behavior of |
| 353 | /// Go's `io.ReaderAt.ReadAt` over a `bytes.Reader` short read, which the |
| 354 | /// upstream code converts to `io.EOF`. |
| 355 | fn read_at(&self, offset: i64, n: usize) -> Option<&'a [u8]> { |
| 356 | if offset < 0 { |
| 357 | return None; |
| 358 | } |
| 359 | let offset = offset as usize; |
| 360 | let start = if self.tail_base == 0 || offset < WAL_HEADER_SIZE { |
| 361 | offset |
| 362 | } else { |
| 363 | // A tail image holds nothing between the header and the tail; |
| 364 | // an offset in that gap is a short read, exactly as a whole-file |
| 365 | // image shorter than the offset would be. |
| 366 | WAL_HEADER_SIZE + offset.checked_sub(self.tail_base)? |
| 367 | }; |
| 368 | let end = start.checked_add(n)?; |
| 369 | if end > self.data.len() { |
| 370 | return None; |
| 371 | } |
| 372 | Some(&self.data[start..end]) |
| 373 | } |
| 374 | |
| 375 | /// A reader positioned at `offset` over a tail image: `data` is the |
| 376 | /// 32-byte WAL header followed by the file's bytes from `tail_base` |
| 377 | /// onward, so a sync that resumes at `offset` reads a buffer the size of |
| 378 | /// the tail rather than of the file. `offset` must lie in the tail, and |
| 379 | /// the previous frame (which the offset reader re-reads to seed its |
| 380 | /// checksum) must too — the caller starts the tail one frame early. |
| 381 | pub fn new_with_offset_over_tail( |
| 382 | data: &'a [u8], |
| 383 | tail_base: i64, |
| 384 | offset: i64, |
| 385 | salt1: u32, |
| 386 | salt2: u32, |
| 387 | ) -> WalResult<Self> { |
| 388 | if tail_base < WAL_HEADER_SIZE as i64 || offset < tail_base { |
| 389 | return Err(WalError::OffsetTooSmall { |
| 390 | offset, |
| 391 | header_size: WAL_HEADER_SIZE as i64, |
| 392 | }); |
| 393 | } |
| 394 | let mut r = Self::new_with_offset_inner(data, tail_base as usize)?; |
| 395 | r.seek_to_offset(offset, salt1, salt2)?; |
| 396 | Ok(r) |
| 397 | } |
| 398 | |
| 399 | /// Reads and validates the WAL header into `self`. |
| 400 | /// |
| 401 | /// Ported from `readHeader` in [email protected] wal_reader.go:90-129. |
| 402 | fn read_header(&mut self) -> WalResult<()> { |
| 403 | // If we have a partial WAL, mark WAL as done (io.EOF). |
| 404 | let hdr = match self.read_at(0, WAL_HEADER_SIZE) { |
| 405 | Some(b) => b, |
| 406 | None => return Err(WalError::Eof), |
| 407 | }; |
| 408 | |
| 409 | // Determine byte order of checksums from the magic (always read |
| 410 | // big-endian, like Go's binary.BigEndian.Uint32(hdr[0:])). |
| 411 | let magic = be_u32(&hdr[0..]); |
| 412 | self.big_endian = match magic { |
| 413 | WAL_MAGIC_LITTLE_ENDIAN => false, |
| 414 | WAL_MAGIC_BIG_ENDIAN => true, |
| 415 | _ => return Err(WalError::InvalidMagic(magic)), |
| 416 | }; |
| 417 | |
| 418 | // If the header checksum doesn't match then we may have failed with a |
| 419 | // partial WAL header write during checkpointing => io.EOF. |
| 420 | let chksum1 = be_u32(&hdr[24..]); |
| 421 | let chksum2 = be_u32(&hdr[28..]); |
| 422 | let (v0, v1) = wal_checksum(self.big_endian, 0, 0, &hdr[..24]); |
| 423 | if v0 != chksum1 || v1 != chksum2 { |
| 424 | return Err(WalError::Eof); |
| 425 | } |
| 426 | |
| 427 | // Verify version is correct. |
| 428 | let version = be_u32(&hdr[4..]); |
| 429 | if version != WAL_VERSION { |
| 430 | return Err(WalError::UnsupportedVersion(version)); |
| 431 | } |
| 432 | |
| 433 | self.page_size = be_u32(&hdr[8..]); |
| 434 | self.salt1 = be_u32(&hdr[16..]); |
| 435 | self.salt2 = be_u32(&hdr[20..]); |
| 436 | self.chksum1 = chksum1; |
| 437 | self.chksum2 = chksum2; |
| 438 | |
| 439 | Ok(()) |
| 440 | } |
| 441 | |
| 442 | /// Reads the next frame into `data` and returns `(pgno, commit)`. |
| 443 | /// |
| 444 | /// Returns [`WalError::Eof`] at the end of the valid WAL (including on a |
| 445 | /// salt or checksum mismatch, which terminate the valid region). `data` must |
| 446 | /// be exactly `page_size` bytes or [`WalError::BufferSize`] is returned. |
| 447 | /// |
| 448 | /// Ported from `ReadFrame` in [email protected] wal_reader.go:131-135. |
| 449 | pub fn read_frame(&mut self, data: &mut [u8]) -> WalResult<(u32, u32)> { |
| 450 | self.read_frame_inner(data, true) |
| 451 | } |
| 452 | |
| 453 | /// Frame-read core shared by [`Self::read_frame`] and the offset constructor. |
| 454 | /// |
| 455 | /// When `verify_checksum` is `false`, the running checksum is *set* from the |
| 456 | /// frame's stored checksum rather than verified against a rolling value — |
| 457 | /// used when seeking to an offset without checksumming from the beginning. |
| 458 | /// |
| 459 | /// Ported from `readFrame` in [email protected] wal_reader.go:137-187. |
| 460 | fn read_frame_inner( |
| 461 | &mut self, |
| 462 | data: &mut [u8], |
| 463 | verify_checksum: bool, |
| 464 | ) -> WalResult<(u32, u32)> { |
| 465 | if data.len() != self.page_size as usize { |
| 466 | return Err(WalError::BufferSize { |
| 467 | got: data.len(), |
| 468 | want: self.page_size, |
| 469 | }); |
| 470 | } |
| 471 | |
| 472 | let frame_size = self.page_size as i64 + WAL_FRAME_HEADER_SIZE as i64; |
| 473 | let offset = WAL_HEADER_SIZE as i64 + (self.frame_n * frame_size); |
| 474 | |
| 475 | // Read WAL frame header. A short read is io.EOF. |
| 476 | let hdr = match self.read_at(offset, WAL_FRAME_HEADER_SIZE) { |
| 477 | Some(b) => b, |
| 478 | None => return Err(WalError::Eof), |
| 479 | }; |
| 480 | |
| 481 | // Read WAL page data. A short read is io.EOF. |
| 482 | let page = match self.read_at(offset + WAL_FRAME_HEADER_SIZE as i64, data.len()) { |
| 483 | Some(b) => b, |
| 484 | None => return Err(WalError::Eof), |
| 485 | }; |
| 486 | data.copy_from_slice(page); |
| 487 | |
| 488 | // Verify salt matches the salt in the header; otherwise end of valid WAL. |
| 489 | let salt1 = be_u32(&hdr[8..]); |
| 490 | let salt2 = be_u32(&hdr[12..]); |
| 491 | if self.salt1 != salt1 || self.salt2 != salt2 { |
| 492 | return Err(WalError::Eof); |
| 493 | } |
| 494 | |
| 495 | // Verify the cumulative checksum. If verification is disabled, it is |
| 496 | // because we are jumping to an offset and not checksumming from the |
| 497 | // beginning, so we simply adopt the frame's stored checksum. |
| 498 | let chksum1 = be_u32(&hdr[16..]); |
| 499 | let chksum2 = be_u32(&hdr[20..]); |
| 500 | if verify_checksum { |
| 501 | let (c0, c1) = wal_checksum(self.big_endian, self.chksum1, self.chksum2, &hdr[..8]); |
| 502 | let (c0, c1) = wal_checksum(self.big_endian, c0, c1, data); |
| 503 | self.chksum1 = c0; |
| 504 | self.chksum2 = c1; |
| 505 | if self.chksum1 != chksum1 || self.chksum2 != chksum2 { |
| 506 | return Err(WalError::Eof); |
| 507 | } |
| 508 | } else { |
| 509 | self.chksum1 = chksum1; |
| 510 | self.chksum2 = chksum2; |
| 511 | } |
| 512 | |
| 513 | let pgno = be_u32(&hdr[0..]); |
| 514 | let commit = be_u32(&hdr[4..]); |
| 515 | |
| 516 | self.frame_n += 1; |
| 517 | |
| 518 | Ok((pgno, commit)) |
| 519 | } |
| 520 | |
| 521 | /// Reads all committed frames to end-of-file and returns a map of page |
| 522 | /// number → byte offset of the latest committed version of that page, the |
| 523 | /// max offset of the WAL segment read, and the final database size in pages. |
| 524 | /// |
| 525 | /// Pages above the final commit size are dropped (handles a DB that shrank, |
| 526 | /// e.g. via `VACUUM`, between transactions). |
| 527 | /// |
| 528 | /// Ported from `PageMap` in [email protected] wal_reader.go:189-244. |
| 529 | pub fn page_map(&mut self) -> WalResult<(HashMap<u32, i64>, i64, u32)> { |
| 530 | let mut m: HashMap<u32, i64> = HashMap::new(); |
| 531 | let mut tx_map: HashMap<u32, i64> = HashMap::new(); |
| 532 | let mut commit: u32 = 0; |
| 533 | let mut data = vec![0u8; self.page_size as usize]; |
| 534 | |
| 535 | loop { |
| 536 | let (pgno, fcommit) = match self.read_frame(&mut data) { |
| 537 | Ok(v) => v, |
| 538 | Err(e) if e.is_eof() => break, |
| 539 | Err(e) => return Err(e), |
| 540 | }; |
| 541 | |
| 542 | // Update latest offset for this page within the current transaction. |
| 543 | // Not promoted to the full map until the txn commits. |
| 544 | let offset = self.offset(); |
| 545 | tx_map.insert(pgno, offset); |
| 546 | |
| 547 | // On a commit record, transfer the txn offsets into the full map and |
| 548 | // record the new DB size. |
| 549 | if fcommit != 0 { |
| 550 | for (p, o) in tx_map.drain() { |
| 551 | m.insert(p, o); |
| 552 | } |
| 553 | commit = fcommit; |
| 554 | } |
| 555 | } |
| 556 | |
| 557 | // Remove pages that exceed the final commit size (DB shrank mid-WAL). |
| 558 | m.retain(|&pgno, _| pgno <= commit); |
| 559 | |
| 560 | // No complete transactions => original (zero) offset. |
| 561 | if m.is_empty() { |
| 562 | return Ok((m, 0, 0)); |
| 563 | } |
| 564 | |
| 565 | // Highest page offset, extended to the end of that frame. |
| 566 | let mut end: i64 = 0; |
| 567 | for &offset in m.values() { |
| 568 | if end == 0 || offset > end { |
| 569 | end = offset; |
| 570 | } |
| 571 | } |
| 572 | end += WAL_FRAME_HEADER_SIZE as i64 + self.page_size as i64; |
| 573 | |
| 574 | Ok((m, end, commit)) |
| 575 | } |
| 576 | |
| 577 | /// Returns the set of unique frame salt pairs in the WAL, scanning until the |
| 578 | /// `until` salt pair is seen or end-of-file is reached. |
| 579 | /// |
| 580 | /// Unlike frame reading, this does **not** verify checksums or that frame |
| 581 | /// salts match the header — it deliberately collects *every* distinct salt, |
| 582 | /// including those from superseded transactions. |
| 583 | /// |
| 584 | /// Ported from `FrameSaltsUntil` in [email protected] wal_reader.go:246-270. |
| 585 | pub fn frame_salts_until(&self, until: (u32, u32)) -> HashSet<(u32, u32)> { |
| 586 | let mut m = HashSet::new(); |
| 587 | let step = WAL_FRAME_HEADER_SIZE as i64 + self.page_size as i64; |
| 588 | let mut offset = WAL_HEADER_SIZE as i64; |
| 589 | // The loop ends either when a frame-header read runs short (the Go |
| 590 | // `n != len(hdr)` => break) or when we reach the `until` salt below. |
| 591 | while let Some(hdr) = self.read_at(offset, WAL_FRAME_HEADER_SIZE) { |
| 592 | let salt1 = be_u32(&hdr[8..]); |
| 593 | let salt2 = be_u32(&hdr[12..]); |
| 594 | |
| 595 | // Track unique salts. |
| 596 | m.insert((salt1, salt2)); |
| 597 | |
| 598 | // Stop once we've seen the salt we were asked to read up to. |
| 599 | if salt1 == until.0 && salt2 == until.1 { |
| 600 | break; |
| 601 | } |
| 602 | |
| 603 | offset += step; |
| 604 | } |
| 605 | m |
| 606 | } |
| 607 | } |
| 608 | |
| 609 | /// Reads a big-endian `u32` from the first four bytes of `b`. |
| 610 | /// |
| 611 | /// All WAL header/frame scalar fields are big-endian regardless of the checksum |
| 612 | /// byte order (Go uses `binary.BigEndian.Uint32`). Panics if `b.len() < 4`, |
| 613 | /// which never happens for the fixed-offset accesses in this module. |
| 614 | #[inline] |
| 615 | fn be_u32(b: &[u8]) -> u32 { |
| 616 | u32::from_be_bytes([b[0], b[1], b[2], b[3]]) |
| 617 | } |