Diffinery

homeflare/celldpublic

545 lines · 19.2 KBRaw History
1//! ltx.rs — LTX (Lite Transaction) file reader/writer + CRC64-ISO checksums.
2//!
3//! Ported from [email protected] `ltx.go`, `checksum.go`, `encoder.go`, `decoder.go`
4//! and [email protected] `v3.go`. `reference/ltx-format.md` describes the
5//! authoritative byte layout.
6//!
7//! The reader decodes a complete LTX file with either v0.5.2 LZ4 blocks or the
8//! older LZ4 frames. It verifies the CRC64-ISO file checksum and the rolling
9//! snapshot checksum. The v0.5.2 writer emits exact upstream bytes, while the
10//! default writer preserves the legacy layout during the staged rollout.
11
12use crate::error::{Error, Result};
13use crate::{Checksum, Pos, CHECKSUM_FLAG, TXID};
14use std::time::SystemTime;
15
16// ── Constants ([email protected] ltx.go:18-55) ──────────────────────────────────────
17
18/// First 4 bytes of every LTX file.
19pub const MAGIC: &[u8; 4] = b"LTX1";
20/// Current LTX file format version.
21pub const VERSION: i32 = 3;
22pub const HEADER_SIZE: usize = 100;
23pub const PAGE_HEADER_SIZE: usize = 6;
24pub const TRAILER_SIZE: usize = 16;
25pub const CHECKSUM_SIZE: usize = 8;
26
27/// Header flag: checksums are not tracked for this file.
28pub const HEADER_FLAG_NO_CHECKSUM: u32 = 1 << 1;
29pub const HEADER_FLAG_MASK: u32 = HEADER_FLAG_NO_CHECKSUM;
30
31/// A four-byte compressed-size field follows the page header, and the page
32/// uses raw LZ4 block compression. Files written before ltx v0.5.2 omit this
33/// flag and contain one LZ4 frame per page.
34pub const PAGE_HEADER_FLAG_SIZE: u16 = 1 << 0;
35pub const PAGE_HEADER_FLAG_MASK: u16 = PAGE_HEADER_FLAG_SIZE;
36
37/// SQLite PENDING_BYTE offset; the lock page derives from it.
38pub const PENDING_BYTE: i64 = 0x4000_0000;
39
40fn corrupt(msg: impl Into<String>) -> Error {
41 // Wrap a format error as LTXCorrupted, matching litestream's classification
42 // of malformed LTX content (litestream.go ErrLTXCorrupted).
43 let _ = msg;
44 Error::LTXCorrupted
45}
46
47/// Returns the lock page number for a given page size (ltx.go:494).
48///
49/// `page_size` is expected to be a validated SQLite page size (a power of two in
50/// `[512, 65536]`); for any such value the result is identical to Go's
51/// `LockPgno` (`PENDING_BYTE / page_size + 1`). A `page_size` of `0` — which
52/// only reaches here via an unvalidated/adversarial header — would make the
53/// underlying integer divide panic in both Go and Rust, so we guard it and
54/// return `0` (never a real page number) instead of dividing. All in-crate
55/// callers validate the header first, mirroring Go's `DecodeHeader`-before-
56/// `LockPgno` ordering, so this guard is reached only by a direct external call.
57pub fn lock_pgno(page_size: u32) -> u32 {
58 if page_size == 0 {
59 return 0;
60 }
61 (PENDING_BYTE / page_size as i64) as u32 + 1
62}
63
64// ── CRC64-ISO (checksum.go:177 `crc64.MakeTable(crc64.ISO)`) ──────────────────
65
66/// Streaming CRC64-ISO hasher matching Go's `hash/crc64` digest semantics
67/// (CRC-64/GO-ISO). `crc-fast` keeps the exact streaming result while using
68/// SIMD folding on the architectures that celld ships.
69#[derive(Clone)]
70pub struct Crc64 {
71 digest: crc_fast::Digest,
72}
73
74impl Default for Crc64 {
75 fn default() -> Self {
76 Self::new()
77 }
78}
79
80impl Crc64 {
81 pub fn new() -> Self {
82 Self {
83 digest: crc_fast::Digest::new(crc_fast::CrcAlgorithm::Crc64GoIso),
84 }
85 }
86
87 pub fn update(&mut self, data: &[u8]) {
88 self.digest.update(data);
89 }
90
91 pub fn sum64(&self) -> u64 {
92 self.digest.finalize()
93 }
94}
95
96/// CRC64 checksum of a single page combined with its page number, with the
97/// ChecksumFlag set (checksum.go:106-116). Input is `BE_u32(pgno) ++ data`.
98pub fn checksum_page(pgno: u32, data: &[u8]) -> Checksum {
99 let mut h = Crc64::new();
100 h.update(&pgno.to_be_bytes());
101 h.update(data);
102 CHECKSUM_FLAG | h.sum64()
103}
104
105// ── Header / PageHeader / Trailer ─────────────────────────────────────────────
106
107/// LTX file header (100 bytes). Ported from [email protected] ltx.go:179-326.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
109pub struct Header {
110 pub version: i32,
111 pub flags: u32,
112 pub page_size: u32,
113 pub commit: u32,
114 pub min_txid: TXID,
115 pub max_txid: TXID,
116 pub timestamp: i64,
117 pub pre_apply_checksum: Checksum,
118 pub wal_offset: i64,
119 pub wal_size: i64,
120 pub wal_salt1: u32,
121 pub wal_salt2: u32,
122 pub node_id: u64,
123}
124
125impl Header {
126 /// True if this header begins a complete database snapshot (MinTXID == 1).
127 pub fn is_snapshot(&self) -> bool {
128 self.min_txid == TXID(1)
129 }
130
131 /// True if checksum tracking is disabled for this file.
132 pub fn no_checksum(&self) -> bool {
133 self.flags & HEADER_FLAG_NO_CHECKSUM != 0
134 }
135
136 /// Decodes a header from a 100-byte slice (ltx.go:302-326). All big-endian.
137 pub fn parse(b: &[u8]) -> Result<Header> {
138 if b.len() < HEADER_SIZE {
139 return Err(corrupt("short header"));
140 }
141 if &b[0..4] != MAGIC {
142 return Err(corrupt("bad magic"));
143 }
144 Ok(Header {
145 version: VERSION,
146 flags: u32_be(&b[4..]),
147 page_size: u32_be(&b[8..]),
148 commit: u32_be(&b[12..]),
149 min_txid: TXID(u64_be(&b[16..])),
150 max_txid: TXID(u64_be(&b[24..])),
151 timestamp: u64_be(&b[32..]) as i64,
152 pre_apply_checksum: u64_be(&b[40..]),
153 wal_offset: u64_be(&b[48..]) as i64,
154 wal_size: u64_be(&b[56..]) as i64,
155 wal_salt1: u32_be(&b[64..]),
156 wal_salt2: u32_be(&b[68..]),
157 node_id: u64_be(&b[72..]),
158 })
159 }
160
161 /// Encodes the header to 100 bytes (ltx.go:283-299).
162 pub fn marshal(&self) -> [u8; HEADER_SIZE] {
163 let mut b = [0u8; HEADER_SIZE];
164 b[0..4].copy_from_slice(MAGIC);
165 b[4..8].copy_from_slice(&self.flags.to_be_bytes());
166 b[8..12].copy_from_slice(&self.page_size.to_be_bytes());
167 b[12..16].copy_from_slice(&self.commit.to_be_bytes());
168 b[16..24].copy_from_slice(&self.min_txid.0.to_be_bytes());
169 b[24..32].copy_from_slice(&self.max_txid.0.to_be_bytes());
170 b[32..40].copy_from_slice(&(self.timestamp as u64).to_be_bytes());
171 b[40..48].copy_from_slice(&self.pre_apply_checksum.to_be_bytes());
172 b[48..56].copy_from_slice(&(self.wal_offset as u64).to_be_bytes());
173 b[56..64].copy_from_slice(&(self.wal_size as u64).to_be_bytes());
174 b[64..68].copy_from_slice(&self.wal_salt1.to_be_bytes());
175 b[68..72].copy_from_slice(&self.wal_salt2.to_be_bytes());
176 b[72..80].copy_from_slice(&self.node_id.to_be_bytes());
177 b
178 }
179
180 /// Validates header invariants (ltx.go:208-267).
181 pub fn validate(&self) -> Result<()> {
182 if self.version != VERSION {
183 return Err(corrupt("invalid version"));
184 }
185 if self.flags != (self.flags & HEADER_FLAG_MASK) {
186 return Err(corrupt("invalid flags"));
187 }
188 if !is_valid_page_size(self.page_size) {
189 return Err(corrupt("invalid page size"));
190 }
191 if self.min_txid == TXID(0) {
192 return Err(corrupt("minimum transaction id required"));
193 }
194 if self.max_txid == TXID(0) {
195 return Err(corrupt("maximum transaction id required"));
196 }
197 if self.min_txid > self.max_txid {
198 return Err(corrupt("transaction ids out of order"));
199 }
200 if self.wal_offset < 0 {
201 return Err(corrupt("wal offset cannot be negative"));
202 }
203 if self.wal_size < 0 {
204 return Err(corrupt("wal size cannot be negative"));
205 }
206 if (self.wal_salt1 != 0 || self.wal_salt2 != 0) && self.wal_offset == 0 {
207 return Err(corrupt("wal offset required if salt exists"));
208 }
209 if self.wal_offset == 0 && self.wal_size != 0 {
210 return Err(corrupt("wal offset required if wal size exists"));
211 }
212 if self.is_snapshot() {
213 if self.pre_apply_checksum != 0 {
214 return Err(corrupt("pre-apply checksum must be zero on snapshots"));
215 }
216 } else if self.no_checksum() {
217 if self.pre_apply_checksum != 0 {
218 return Err(corrupt("pre-apply checksum not allowed"));
219 }
220 } else {
221 if self.pre_apply_checksum == 0 {
222 return Err(corrupt("pre-apply checksum required on non-snapshot files"));
223 }
224 if self.pre_apply_checksum & CHECKSUM_FLAG == 0 {
225 return Err(corrupt("invalid pre-apply checksum format"));
226 }
227 }
228 Ok(())
229 }
230}
231
232/// Per-page header (6 bytes). Ported from ltx.go:408-447.
233#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
234pub struct PageHeader {
235 pub pgno: u32,
236 pub flags: u16,
237}
238
239impl PageHeader {
240 pub fn is_zero(&self) -> bool {
241 self.pgno == 0 && self.flags == 0
242 }
243
244 pub fn parse(b: &[u8]) -> Result<PageHeader> {
245 if b.len() < PAGE_HEADER_SIZE {
246 return Err(corrupt("short page header"));
247 }
248 Ok(PageHeader {
249 pgno: u32_be(&b[0..]),
250 flags: u16_be(&b[4..]),
251 })
252 }
253
254 pub fn marshal(&self) -> [u8; PAGE_HEADER_SIZE] {
255 let mut b = [0u8; PAGE_HEADER_SIZE];
256 b[0..4].copy_from_slice(&self.pgno.to_be_bytes());
257 b[4..6].copy_from_slice(&self.flags.to_be_bytes());
258 b
259 }
260
261 pub fn validate(&self) -> Result<()> {
262 if self.pgno == 0 {
263 return Err(corrupt("page number required"));
264 }
265 if self.flags != (self.flags & PAGE_HEADER_FLAG_MASK) {
266 return Err(corrupt("invalid page header flags"));
267 }
268 Ok(())
269 }
270}
271
272/// File trailer (16 bytes). Ported from ltx.go:348-393.
273#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
274pub struct Trailer {
275 pub post_apply_checksum: Checksum,
276 pub file_checksum: Checksum,
277}
278
279impl Trailer {
280 /// Validates the checksum fields against the header checksum mode.
281 pub fn validate(&self, header: Header) -> Result<()> {
282 if header.no_checksum() {
283 if self.post_apply_checksum != 0 {
284 return Err(corrupt("post-apply checksum not allowed"));
285 }
286 } else if self.post_apply_checksum == 0 || self.post_apply_checksum & CHECKSUM_FLAG == 0 {
287 return Err(corrupt("invalid post-apply checksum"));
288 }
289
290 if self.file_checksum == 0 || self.file_checksum & CHECKSUM_FLAG == 0 {
291 return Err(corrupt("invalid file checksum"));
292 }
293 Ok(())
294 }
295
296 pub fn parse(b: &[u8]) -> Result<Trailer> {
297 if b.len() < TRAILER_SIZE {
298 return Err(corrupt("short trailer"));
299 }
300 Ok(Trailer {
301 post_apply_checksum: u64_be(&b[0..]),
302 file_checksum: u64_be(&b[8..]),
303 })
304 }
305
306 pub fn marshal(&self) -> [u8; TRAILER_SIZE] {
307 let mut b = [0u8; TRAILER_SIZE];
308 b[0..8].copy_from_slice(&self.post_apply_checksum.to_be_bytes());
309 b[8..16].copy_from_slice(&self.file_checksum.to_be_bytes());
310 b
311 }
312}
313
314/// True if `sz` is a power of two in [512, 65536] (ltx.go:399-406).
315pub fn is_valid_page_size(sz: u32) -> bool {
316 let mut i = 512u32;
317 while i <= 65536 {
318 if sz == i {
319 return true;
320 }
321 i *= 2;
322 }
323 false
324}
325
326/// Formats an LTX filename for a transaction range (ltx.go:487-489).
327pub fn format_filename(min_txid: TXID, max_txid: TXID) -> String {
328 format!("{}-{}.ltx", min_txid, max_txid)
329}
330
331/// Parses a `<min>-<max>.ltx` filename (ltx.go:450-459).
332pub fn parse_filename(name: &str) -> Result<(TXID, TXID)> {
333 let stem = name
334 .strip_suffix(".ltx")
335 .ok_or_else(|| corrupt("invalid ltx filename"))?;
336 let (a, b) = stem
337 .split_once('-')
338 .ok_or_else(|| corrupt("invalid ltx filename"))?;
339 if a.len() != 16 || b.len() != 16 {
340 return Err(corrupt("invalid ltx filename"));
341 }
342 let min = u64::from_str_radix(a, 16).map_err(|_| corrupt("invalid ltx filename"))?;
343 let max = u64::from_str_radix(b, 16).map_err(|_| corrupt("invalid ltx filename"))?;
344 Ok((TXID(min), TXID(max)))
345}
346
347// ── FileInfo ──────────────────────────────────────────────────────────────────
348
349/// Metadata about an LTX file on a replica. Ported from [email protected] ltx.go:571-596.
350///
351/// `pre_apply_checksum`/`post_apply_checksum` are populated when known (e.g. by
352/// decoding) and are zero when a file is discovered by a bare directory/bucket
353/// listing. Listings use the file mtime or object-store LastModified time, and
354/// write results use the LTX header timestamp.
355#[derive(Debug, Clone, PartialEq, Eq, Default)]
356pub struct FileInfo {
357 pub level: i32,
358 pub min_txid: TXID,
359 pub max_txid: TXID,
360 pub pre_apply_checksum: Checksum,
361 pub post_apply_checksum: Checksum,
362 pub size: i64,
363 pub created_at: Option<SystemTime>,
364}
365
366impl FileInfo {
367 /// Replication position *after* this file is applied (ltx.go:591-596).
368 pub fn pos(&self) -> Pos {
369 Pos::new(self.max_txid, self.post_apply_checksum)
370 }
371
372 /// Replication position *before* this file is applied (ltx.go:583-588).
373 pub fn pre_apply_pos(&self) -> Pos {
374 Pos::new(
375 TXID(self.min_txid.0.saturating_sub(1)),
376 self.pre_apply_checksum,
377 )
378 }
379}
380
381// ── Decoder ──────────────────────────────────────────────────────────────────
382
383/// The verified result of decoding a complete LTX file.
384#[derive(Debug, Clone)]
385pub struct DecodedFile {
386 pub header: Header,
387 pub trailer: Trailer,
388 /// Page numbers in file (write) order.
389 pub pgnos: Vec<u32>,
390}
391
392type DecodedPages = Vec<(u32, Vec<u8>)>;
393
394/// Decodes and fully verifies an in-memory LTX file: header, LZ4-framed pages,
395/// page index, trailer, the CRC64-ISO file checksum, and — for snapshots — the
396/// rolling post-apply checksum. Returns `Error::ChecksumMismatch` /
397/// `Error::LTXCorrupted` on any inconsistency.
398///
399/// Ported from the read+verify path in decoder.go:68-219.
400pub fn decode_file(bytes: &[u8]) -> Result<DecodedFile> {
401 decode_file_inner(bytes, false).map(|(file, _)| file)
402}
403
404/// Decodes a complete LTX file and retains each decompressed page.
405pub(crate) fn decode_file_with_pages(bytes: &[u8]) -> Result<(DecodedFile, DecodedPages)> {
406 decode_file_inner(bytes, true)
407}
408
409fn decode_file_inner(bytes: &[u8], retain_pages: bool) -> Result<(DecodedFile, DecodedPages)> {
410 let mut decoder = crate::codec::Decoder::new(std::io::Cursor::new(bytes));
411 decoder.decode_header()?;
412 let header = decoder.header;
413 let mut page_numbers = Vec::new();
414 let mut pages = Vec::new();
415 let mut data = vec![0; header.page_size as usize];
416
417 while let Some(page) = decoder.decode_page(&mut data)? {
418 page_numbers.push(page.pgno);
419 if retain_pages {
420 pages.push((page.pgno, data.clone()));
421 }
422 }
423 decoder.close()?;
424
425 Ok((
426 DecodedFile {
427 header,
428 trailer: decoder.trailer,
429 pgnos: page_numbers,
430 },
431 pages,
432 ))
433}
434
435/// Decodes and verifies a complete LTX file, returning each page's
436/// `(pgno, decompressed_data)` in write order.
437///
438/// The decoder retains the pages from its verification pass, so it does not
439/// decompress the file a second time.
440pub fn decode_file_pages(bytes: &[u8]) -> Result<Vec<(u32, Vec<u8>)>> {
441 decode_file_with_pages(bytes).map(|(_, pages)| pages)
442}
443
444/// Reconstructs the full SQLite database image from a **snapshot** LTX file
445/// (every page `1..=commit`, with the lock page zero-filled).
446///
447/// Ported from `Decoder.DecodeDatabaseTo` in [email protected] decoder.go:223-268. The
448/// CRC64 of this image must equal the live database's CRC64. Errors if the file
449/// is not a snapshot or a page is missing.
450pub fn decode_database_image(bytes: &[u8]) -> Result<Vec<u8>> {
451 // Verify the whole file before `lock_pgno` or `commit` is used. This rejects
452 // a zero page size and keeps the reconstruction panic-free on bad input.
453 let (decoded, pages) = decode_file_with_pages(bytes)?;
454 let header = decoded.header;
455 if !header.is_snapshot() {
456 return Err(corrupt(
457 "cannot decode non-snapshot LTX file to SQLite database",
458 ));
459 }
460 let page_size = header.page_size as usize;
461 let lock = lock_pgno(header.page_size);
462
463 // Materialize the pages, keyed by page number.
464 let mut by_pgno: std::collections::HashMap<u32, Vec<u8>> = std::collections::HashMap::new();
465 for (pgno, data) in pages {
466 by_pgno.insert(pgno, data);
467 }
468
469 let mut image = Vec::with_capacity(header.commit as usize * page_size);
470 for pgno in 1..=header.commit {
471 if pgno == lock {
472 image.extend(std::iter::repeat_n(0u8, page_size));
473 continue;
474 }
475 let data = by_pgno
476 .get(&pgno)
477 .ok_or_else(|| corrupt("missing page in snapshot"))?;
478 image.extend_from_slice(data);
479 }
480 Ok(image)
481}
482
483// ── Encoder (round-trip; byte-fidelity vs the real binary is D1's job) ────────
484
485/// Encodes a complete LTX file with the legacy LZ4 frame representation.
486///
487/// This function preserves the current celld write format during the staged
488/// v0.5.2 reader rollout. [`decode_file`] accepts this representation and the
489/// v0.5.2 block representation.
490pub fn encode_file(
491 header: &Header,
492 pages: &[(u32, Vec<u8>)],
493 post_apply_checksum: Checksum,
494) -> Result<Vec<u8>> {
495 encode_file_with_mode(header, pages, post_apply_checksum, false)
496}
497
498/// Encodes a complete LTX file with the byte-exact v0.5.2 block
499/// representation.
500pub fn encode_file_v0_5_2(
501 header: &Header,
502 pages: &[(u32, Vec<u8>)],
503 post_apply_checksum: Checksum,
504) -> Result<Vec<u8>> {
505 encode_file_with_mode(header, pages, post_apply_checksum, true)
506}
507
508fn encode_file_with_mode(
509 header: &Header,
510 pages: &[(u32, Vec<u8>)],
511 post_apply_checksum: Checksum,
512 use_v0_5_2: bool,
513) -> Result<Vec<u8>> {
514 let mut encoder = if use_v0_5_2 {
515 crate::codec::Encoder::new_block(Vec::new())
516 } else {
517 crate::codec::Encoder::new_legacy(Vec::new())
518 };
519 encoder.encode_header(*header)?;
520 for (page_number, data) in pages {
521 encoder.encode_page(
522 PageHeader {
523 pgno: *page_number,
524 flags: 0,
525 },
526 data,
527 )?;
528 }
529 encoder.close(post_apply_checksum)?;
530 Ok(encoder.writer)
531}
532
533// ── small byte / varint helpers ──────────────────────────────────────────────
534
535fn u16_be(b: &[u8]) -> u16 {
536 u16::from_be_bytes([b[0], b[1]])
537}
538fn u32_be(b: &[u8]) -> u32 {
539 u32::from_be_bytes([b[0], b[1], b[2], b[3]])
540}
541fn u64_be(b: &[u8]) -> u64 {
542 u64::from_be_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]])
543}
544
545// ── Tests ─────────────────────────────────────────────────────────────────────