Skip to main content

reth_db/static_file/
mod.rs

1//! reth's static file database table import and access
2
3use reth_nippy_jar::{NippyJar, NippyJarError};
4use reth_static_file_types::{
5    SegmentHeader, SegmentRangeInclusive, StaticFileMap, StaticFileSegment,
6};
7use std::path::Path;
8use tracing::warn;
9
10pub use reth_nippy_jar::{CONFIG_FILE_EXTENSION, OFFSETS_FILE_EXTENSION};
11
12mod cursor;
13pub use cursor::StaticFileCursor;
14
15mod mask;
16pub use mask::*;
17
18mod masks;
19pub use masks::*;
20
21/// A static file found on disk.
22#[derive(Debug, Clone)]
23pub struct StaticFileEntry {
24    /// The block range the file is named after, which its segment index keys it by.
25    pub file_range: SegmentRangeInclusive,
26    /// The blocks the file holds, within `file_range`.
27    pub block_range: SegmentRangeInclusive,
28    /// The file's header.
29    pub header: SegmentHeader,
30}
31
32/// Alias type for a map of [`StaticFileSegment`] and lists of existing static files, sorted by
33/// the end of the blocks they hold.
34type SortedStaticFiles = StaticFileMap<Vec<StaticFileEntry>>;
35
36/// Given the `static_files` directory path, it returns a list over the existing `static_files`
37/// organized by [`StaticFileSegment`]. Each segment has a sorted list of block ranges and
38/// segment headers as presented in the file configuration.
39pub fn iter_static_files(path: &Path) -> Result<SortedStaticFiles, NippyJarError> {
40    if !path.exists() {
41        reth_fs_util::create_dir_all(path).map_err(|err| NippyJarError::Custom(err.to_string()))?;
42    }
43
44    let mut static_files = SortedStaticFiles::default();
45    let entries = reth_fs_util::read_dir(path)
46        .map_err(|err| NippyJarError::Custom(err.to_string()))?
47        .filter_map(Result::ok);
48    for entry in entries {
49        if entry.metadata().is_ok_and(|metadata| metadata.is_file()) &&
50            let Some((segment, file_range)) =
51                StaticFileSegment::parse_filename(&entry.file_name().to_string_lossy())
52        {
53            let data_path = entry.path();
54            // The config is written last on creation; without it the jar was never initialized
55            // and the writer recreates it.
56            if !data_path.with_extension(CONFIG_FILE_EXTENSION).exists() {
57                warn!(
58                    target: "reth::static_file",
59                    path = ?data_path,
60                    "Skipping uninitialized static file"
61                );
62                continue
63            }
64            let header = read_static_file_header(&data_path)?;
65
66            if let Some(block_range) = header.block_range() {
67                static_files.entry(segment).or_insert_with(Vec::new).push(StaticFileEntry {
68                    file_range,
69                    block_range,
70                    header,
71                });
72            }
73        }
74    }
75
76    // Sort by block end range.
77    for range_list in static_files.values_mut() {
78        range_list.sort_unstable_by_key(|entry| entry.block_range.end());
79    }
80
81    Ok(static_files)
82}
83
84/// Reads the segment header from the configuration of a single static file.
85pub fn read_static_file_header(path: &Path) -> Result<SegmentHeader, NippyJarError> {
86    Ok(NippyJar::<SegmentHeader>::load(path)?.user_header().clone())
87}
88
89/// Returns the last missing block at or below `tip`, or `None` if coverage reaches genesis.
90/// Ranges must be ordered by decreasing end block. Overlapping ranges are allowed.
91pub fn last_missing_block(
92    tip: u64,
93    ranges: impl Iterator<Item = SegmentRangeInclusive>,
94) -> Option<u64> {
95    let mut missing = tip;
96    for range in ranges {
97        if range.end() < missing {
98            break
99        }
100        if range.contains(missing) {
101            missing = range.start().checked_sub(1)?;
102        }
103    }
104    Some(missing)
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110
111    #[test]
112    fn skips_static_file_without_config() {
113        let dir = tempfile::tempdir().unwrap();
114        let segment = StaticFileSegment::Headers;
115        let path = dir.path().join(segment.filename(&SegmentRangeInclusive::new(0, 499_999)));
116        std::fs::write(&path, b"").unwrap();
117
118        assert!(iter_static_files(dir.path()).unwrap().is_empty());
119    }
120}