reth_db/static_file/
mod.rs

1//! reth's static file database table import and access
2
3use std::{collections::HashMap, path::Path};
4
5mod cursor;
6pub use cursor::StaticFileCursor;
7
8mod mask;
9pub use mask::*;
10use reth_nippy_jar::{NippyJar, NippyJarError};
11
12mod masks;
13pub use masks::*;
14use reth_static_file_types::{SegmentHeader, SegmentRangeInclusive, StaticFileSegment};
15
16/// Alias type for a map of [`StaticFileSegment`] and sorted lists of existing static file ranges.
17type SortedStaticFiles = HashMap<StaticFileSegment, Vec<(SegmentRangeInclusive, SegmentHeader)>>;
18
19/// Given the `static_files` directory path, it returns a list over the existing `static_files`
20/// organized by [`StaticFileSegment`]. Each segment has a sorted list of block ranges and
21/// segment headers as presented in the file configuration.
22pub fn iter_static_files(path: &Path) -> Result<SortedStaticFiles, NippyJarError> {
23    if !path.exists() {
24        reth_fs_util::create_dir_all(path).map_err(|err| NippyJarError::Custom(err.to_string()))?;
25    }
26
27    let mut static_files = SortedStaticFiles::default();
28    let entries = reth_fs_util::read_dir(path)
29        .map_err(|err| NippyJarError::Custom(err.to_string()))?
30        .filter_map(Result::ok);
31    for entry in entries {
32        if entry.metadata().is_ok_and(|metadata| metadata.is_file()) &&
33            let Some((segment, _)) =
34                StaticFileSegment::parse_filename(&entry.file_name().to_string_lossy())
35        {
36            let jar = NippyJar::<SegmentHeader>::load(&entry.path())?;
37
38            if let Some(block_range) = jar.user_header().block_range() {
39                static_files
40                    .entry(segment)
41                    .and_modify(|headers| headers.push((block_range, *jar.user_header())))
42                    .or_insert_with(|| vec![(block_range, *jar.user_header())]);
43            }
44        }
45    }
46
47    for range_list in static_files.values_mut() {
48        // Sort by block end range.
49        range_list.sort_by_key(|(block_range, _)| block_range.end());
50    }
51
52    Ok(static_files)
53}