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