Skip to main content

ledger_engine/
blocks.rs

1//! Block storage for ledgers: random access to any ledger without
2//! decompressing the whole archive.
3//!
4//! Compressing each ledger separately is expensive: zstd loses the repetition
5//! between neighbouring ledgers (measured on the validation archive: 32% larger
6//! than a whole segment). Compressing a whole segment loses random access.
7//! The compromise is a block of `block_ledgers` consecutive ledgers, optionally
8//! with a zstd dictionary: reading a ledger means decompressing one block.
9//!
10//! Segment file `blk-<first>.xwlb`: magic `XWLB\0\1`, then blocks:
11//! `u32 compressed length | compressed`. A decompressed block: `u32 n`, n pairs
12//! `(u32 sequence, u32 length)`, then the records back to back.
13//!
14//! Index `blk-<first>.xwlb.idx`: magic `XWLI\0\1`, then for each block
15//! `u32 first sequence | u32 n | u64 offset | u32 compressed length`. The index
16//! is kept in memory: for a million ledgers in blocks of 16 it is under 2 MB.
17//!
18//! The reader keeps the last few decompressed blocks: the history of an
19//! active account touches consecutive ledgers, and decompressing a block
20//! (32 ledgers, a few megabytes) costs more than searching within it.
21//!
22//! The dictionary, if any, is `dict.zdict` in the same directory. Blocks cannot
23//! be read without it, so it is written before the first block.
24//!
25//! A block goes into the index only after the block itself is on disk (fsync),
26//! so a segment tail torn by a crash has no index entry and is never read.
27
28use std::collections::VecDeque;
29use std::fs::{self, File, OpenOptions};
30use std::io::{Read, Seek, SeekFrom, Write};
31use std::os::unix::fs::FileExt;
32use std::path::{Path, PathBuf};
33use std::sync::{Arc, Mutex, RwLock};
34
35const MAGIC: &[u8; 6] = b"XWLB\x00\x01";
36const IDX_MAGIC: &[u8; 6] = b"XWLI\x00\x01";
37const IDX_ENTRY: usize = 4 + 4 + 8 + 4;
38/// How many decompressed blocks the reader keeps.
39const CACHE_BLOCKS: usize = 16;
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42struct BlockRef {
43    first: u32,
44    count: u32,
45    offset: u64,
46    len: u32,
47}
48
49fn io(e: std::io::Error) -> String {
50    e.to_string()
51}
52
53/// Writer: collects ledgers into a block and flushes the block when it is full.
54#[derive(Debug)]
55pub struct BlockWriter {
56    file: File,
57    index: File,
58    offset: u64,
59    level: i32,
60    dict: Option<Vec<u8>>,
61    block_ledgers: u32,
62    pending: Vec<(u32, Vec<u8>)>,
63}
64
65impl BlockWriter {
66    /// A new segment starting at ledger `first`.
67    pub fn create(
68        dir: &Path,
69        first: u32,
70        block_ledgers: u32,
71        level: i32,
72        dict: Option<Vec<u8>>,
73    ) -> Result<BlockWriter, String> {
74        fs::create_dir_all(dir).map_err(io)?;
75        if let Some(d) = &dict {
76            fs::write(dir.join("dict.zdict"), d).map_err(io)?;
77        }
78        let path = dir.join(format!("blk-{first:010}.xwlb"));
79        let idx_path = path.with_extension("xwlb.idx");
80        // A segment with the same start but not a single block in the index is
81        // left over from a crash right after creation, so it can be replaced.
82        if let Ok(m) = fs::metadata(&idx_path)
83            && m.len() < (IDX_MAGIC.len() + IDX_ENTRY) as u64
84        {
85            fs::remove_file(&path).map_err(io)?;
86            fs::remove_file(&idx_path).map_err(io)?;
87        }
88        let mut file = OpenOptions::new()
89            .create_new(true)
90            .write(true)
91            .open(&path)
92            .map_err(io)?;
93        file.write_all(MAGIC).map_err(io)?;
94        let mut index = OpenOptions::new()
95            .create_new(true)
96            .write(true)
97            .open(idx_path)
98            .map_err(io)?;
99        index.write_all(IDX_MAGIC).map_err(io)?;
100        Ok(BlockWriter {
101            file,
102            index,
103            offset: MAGIC.len() as u64,
104            level,
105            dict,
106            block_ledgers: block_ledgers.max(1),
107            pending: Vec::new(),
108        })
109    }
110
111    pub fn append(&mut self, sequence: u32, ledger: Vec<u8>) -> Result<(), String> {
112        if let Some((last, _)) = self.pending.last()
113            && sequence != last + 1
114        {
115            return Err(format!("ledgers out of sequence: {last} → {sequence}"));
116        }
117        self.pending.push((sequence, ledger));
118        if self.pending.len() as u32 >= self.block_ledgers {
119            self.flush()?;
120        }
121        Ok(())
122    }
123
124    /// Flushes an incomplete block, at the end of a run or before closing.
125    pub fn flush(&mut self) -> Result<(), String> {
126        if self.pending.is_empty() {
127            return Ok(());
128        }
129        let n = self.pending.len() as u32;
130        let total: usize = self.pending.iter().map(|(_, l)| l.len() + 8).sum();
131        let mut raw = Vec::with_capacity(4 + total);
132        raw.extend_from_slice(&n.to_le_bytes());
133        for (seq, l) in &self.pending {
134            raw.extend_from_slice(&seq.to_le_bytes());
135            raw.extend_from_slice(&(l.len() as u32).to_le_bytes());
136        }
137        for (_, l) in &self.pending {
138            raw.extend_from_slice(l);
139        }
140        let zst = match &self.dict {
141            Some(d) => zstd::bulk::Compressor::with_dictionary(self.level, d)
142                .and_then(|mut c| c.compress(&raw))
143                .map_err(io)?,
144            None => zstd::bulk::compress(&raw, self.level).map_err(io)?,
145        };
146        self.file
147            .write_all(&(zst.len() as u32).to_le_bytes())
148            .map_err(io)?;
149        self.file.write_all(&zst).map_err(io)?;
150        self.file.sync_data().map_err(io)?;
151        let entry = BlockRef {
152            first: self.pending[0].0,
153            count: n,
154            offset: self.offset + 4,
155            len: zst.len() as u32,
156        };
157        let mut e = Vec::with_capacity(IDX_ENTRY);
158        e.extend_from_slice(&entry.first.to_le_bytes());
159        e.extend_from_slice(&entry.count.to_le_bytes());
160        e.extend_from_slice(&entry.offset.to_le_bytes());
161        e.extend_from_slice(&entry.len.to_le_bytes());
162        self.index.write_all(&e).map_err(io)?;
163        self.index.sync_data().map_err(io)?;
164        self.offset += 4 + zst.len() as u64;
165        self.pending.clear();
166        Ok(())
167    }
168
169    /// How many ledgers are waiting in the incomplete block.
170    pub fn buffered(&self) -> usize {
171        self.pending.len()
172    }
173
174    /// Flushes the remainder and syncs data to disk.
175    pub fn finish(mut self) -> Result<(), String> {
176        self.flush()?;
177        self.file.sync_all().map_err(io)?;
178        self.index.sync_all().map_err(io)
179    }
180}
181
182/// A block segment: the file and its index in memory.
183#[derive(Debug)]
184struct Segment {
185    path: PathBuf,
186    file: File,
187    blocks: Vec<BlockRef>,
188}
189
190/// Reads by ledger sequence.
191///
192/// The reader knows the segments as of the last directory scan; new
193/// blocks appended by the loader become visible after `refresh`. `get`
194/// calls it itself when the ledger is past the known end.
195#[derive(Debug)]
196pub struct BlockReader {
197    dir: PathBuf,
198    segments: RwLock<Arc<Vec<Arc<Segment>>>>,
199    dict: Option<Vec<u8>>,
200    /// Decompressed blocks keyed by first ledger, most recent first.
201    cache: Mutex<VecDeque<(u32, Arc<Vec<u8>>)>>,
202}
203
204fn scan(dir: &Path) -> Result<Vec<Arc<Segment>>, String> {
205    let mut segments = Vec::new();
206    for e in fs::read_dir(dir).map_err(io)? {
207        let path = e.map_err(io)?.path();
208        if path.extension().is_none_or(|x| x != "xwlb") {
209            continue;
210        }
211        let mut idx = Vec::new();
212        File::open(path.with_extension("xwlb.idx"))
213            .and_then(|mut f| f.read_to_end(&mut idx))
214            .map_err(io)?;
215        if !idx.starts_with(IDX_MAGIC) {
216            return Err(format!("{}: not a block index", path.display()));
217        }
218        let blocks = idx[IDX_MAGIC.len()..]
219            .as_chunks::<IDX_ENTRY>()
220            .0
221            .iter()
222            .map(|c| BlockRef {
223                first: u32::from_le_bytes([c[0], c[1], c[2], c[3]]),
224                count: u32::from_le_bytes([c[4], c[5], c[6], c[7]]),
225                offset: u64::from_le_bytes([c[8], c[9], c[10], c[11], c[12], c[13], c[14], c[15]]),
226                len: u32::from_le_bytes([c[16], c[17], c[18], c[19]]),
227            })
228            .collect::<Vec<_>>();
229        let mut file = File::open(&path).map_err(io)?;
230        let mut magic = [0u8; 6];
231        file.read_exact(&mut magic).map_err(io)?;
232        if &magic != MAGIC {
233            return Err(format!("{}: not a block segment", path.display()));
234        }
235        file.seek(SeekFrom::Start(0)).map_err(io)?;
236        segments.push(Arc::new(Segment { path, file, blocks }));
237    }
238    segments.sort_by_key(|s| s.blocks.first().map_or(u32::MAX, |r| r.first));
239    Ok(segments)
240}
241
242impl BlockReader {
243    pub fn open(dir: &Path) -> Result<BlockReader, String> {
244        let dict = match fs::read(dir.join("dict.zdict")) {
245            Ok(d) => Some(d),
246            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
247            Err(e) => return Err(e.to_string()),
248        };
249        Ok(BlockReader {
250            dir: dir.to_path_buf(),
251            segments: RwLock::new(Arc::new(scan(dir)?)),
252            dict,
253            cache: Mutex::new(VecDeque::new()),
254        })
255    }
256
257    fn segments(&self) -> Arc<Vec<Arc<Segment>>> {
258        self.segments
259            .read()
260            .unwrap_or_else(|p| p.into_inner())
261            .clone()
262    }
263
264    /// Rescans the directory for new blocks and segments.
265    pub fn refresh(&self) -> Result<(), String> {
266        let fresh = Arc::new(scan(&self.dir)?);
267        *self.segments.write().unwrap_or_else(|p| p.into_inner()) = fresh;
268        Ok(())
269    }
270
271    /// First ledger in the blocks.
272    pub fn first(&self) -> Option<u32> {
273        self.segments()
274            .iter()
275            .filter_map(|s| s.blocks.first().map(|r| r.first))
276            .min()
277    }
278
279    /// Last ledger in the blocks.
280    pub fn last(&self) -> Option<u32> {
281        self.segments()
282            .iter()
283            .filter_map(|s| s.blocks.last().map(|r| r.first + r.count - 1))
284            .max()
285    }
286
287    fn find(&self, sequence: u32) -> Option<(Arc<Segment>, BlockRef)> {
288        for s in self.segments().iter() {
289            let i = s.blocks.partition_point(|b| b.first + b.count <= sequence);
290            if let Some(b) = s.blocks.get(i)
291                && b.first <= sequence
292            {
293                return Some((s.clone(), *b));
294            }
295        }
296        None
297    }
298
299    /// Serialized ledger by sequence; `None` if there is no such ledger.
300    pub fn get(&self, sequence: u32) -> Result<Option<Vec<u8>>, String> {
301        let found = match self.find(sequence) {
302            Some(f) => Some(f),
303            None if self.last().is_none_or(|l| sequence > l) => {
304                self.refresh()?;
305                self.find(sequence)
306            }
307            None => None,
308        };
309        let Some((segment, b)) = found else {
310            return Ok(None);
311        };
312        let raw = self.block(&segment.file, b)?;
313        let n = u32::from_le_bytes(raw[..4].try_into().map_err(|_| "block")?) as usize;
314        let mut at = 4 + n * 8;
315        for i in 0..n {
316            let h = &raw[4 + i * 8..12 + i * 8];
317            let seq = u32::from_le_bytes([h[0], h[1], h[2], h[3]]);
318            let len = u32::from_le_bytes([h[4], h[5], h[6], h[7]]) as usize;
319            if seq == sequence {
320                return raw
321                    .get(at..at + len)
322                    .map(|s| Some(s.to_vec()))
323                    .ok_or_else(|| "block truncated".into());
324            }
325            at += len;
326        }
327        Err(format!("ledger {sequence} missing from its block"))
328    }
329
330    /// A decompressed block, from the cache or from disk.
331    fn block(&self, file: &File, b: BlockRef) -> Result<Arc<Vec<u8>>, String> {
332        let cached = |c: &VecDeque<(u32, Arc<Vec<u8>>)>| {
333            c.iter()
334                .find(|(f, _)| *f == b.first)
335                .map(|(_, r)| r.clone())
336        };
337        if let Some(r) = cached(&self.cache.lock().unwrap_or_else(|p| p.into_inner())) {
338            return Ok(r);
339        }
340        let mut zst = vec![0u8; b.len as usize];
341        file.read_exact_at(&mut zst, b.offset).map_err(io)?;
342        let raw = Arc::new(match &self.dict {
343            Some(d) => zstd::bulk::Decompressor::with_dictionary(d)
344                .and_then(|mut z| z.decompress(&zst, 512 << 20))
345                .map_err(io)?,
346            None => zstd::stream::decode_all(&zst[..]).map_err(io)?,
347        });
348        let mut c = self.cache.lock().unwrap_or_else(|p| p.into_inner());
349        if cached(&c).is_none() {
350            c.push_front((b.first, raw.clone()));
351            c.truncate(CACHE_BLOCKS);
352        }
353        Ok(raw)
354    }
355
356    /// Bytes taken by segments, indexes and the dictionary.
357    pub fn bytes_on_disk(&self, dir: &Path) -> u64 {
358        let mut total = fs::metadata(dir.join("dict.zdict")).map_or(0, |m| m.len());
359        for s in self.segments().iter() {
360            total += fs::metadata(&s.path).map_or(0, |m| m.len());
361            total += fs::metadata(s.path.with_extension("xwlb.idx")).map_or(0, |m| m.len());
362        }
363        total
364    }
365}
366
367/// A zstd dictionary trained on sample ledgers.
368pub fn train_dictionary(samples: &[Vec<u8>], size: usize) -> Result<Vec<u8>, String> {
369    zstd::dict::from_samples(samples, size).map_err(io)
370}
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375
376    fn ledger(seq: u32) -> Vec<u8> {
377        let mut v = format!("ledger {seq} ").into_bytes();
378        v.extend(std::iter::repeat_n((seq % 251) as u8, (seq % 300) as usize));
379        v
380    }
381
382    fn roundtrip(block: u32, dict: bool) {
383        let dir = tempfile::tempdir().unwrap();
384        let d = dict.then(|| {
385            let samples: Vec<_> = (0..200).map(ledger).collect();
386            train_dictionary(&samples, 4096).unwrap()
387        });
388        let mut w = BlockWriter::create(dir.path(), 1000, block, 3, d).unwrap();
389        for s in 1000..1100 {
390            w.append(s, ledger(s)).unwrap();
391        }
392        w.finish().unwrap();
393        let r = BlockReader::open(dir.path()).unwrap();
394        for s in 1000..1100 {
395            assert_eq!(
396                r.get(s).unwrap().unwrap(),
397                ledger(s),
398                "block {block} dictionary {dict} ledger {s}"
399            );
400        }
401        assert!(r.get(999).unwrap().is_none());
402        assert!(r.get(1100).unwrap().is_none());
403        assert_eq!((r.first(), r.last()), (Some(1000), Some(1099)));
404    }
405
406    #[test]
407    fn random_access_roundtrips() {
408        for block in [1, 7, 16, 100, 1000] {
409            roundtrip(block, false);
410        }
411        roundtrip(16, true);
412    }
413
414    #[test]
415    fn empty_leftover_segment_is_replaced() {
416        let dir = tempfile::tempdir().unwrap();
417        drop(BlockWriter::create(dir.path(), 5, 4, 3, None).unwrap());
418        let mut w = BlockWriter::create(dir.path(), 5, 4, 3, None).unwrap();
419        w.append(5, vec![5]).unwrap();
420        w.finish().unwrap();
421        assert!(BlockWriter::create(dir.path(), 5, 4, 3, None).is_err());
422        assert_eq!(BlockReader::open(dir.path()).unwrap().last(), Some(5));
423    }
424
425    #[test]
426    fn gaps_are_refused() {
427        let dir = tempfile::tempdir().unwrap();
428        let mut w = BlockWriter::create(dir.path(), 1, 16, 3, None).unwrap();
429        w.append(1, vec![1]).unwrap();
430        assert!(w.append(3, vec![3]).is_err());
431    }
432}