reth_db/static_file/
mod.rs1use 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#[derive(Debug, Clone)]
23pub struct StaticFileEntry {
24 pub file_range: SegmentRangeInclusive,
26 pub block_range: SegmentRangeInclusive,
28 pub header: SegmentHeader,
30}
31
32type SortedStaticFiles = StaticFileMap<Vec<StaticFileEntry>>;
35
36pub 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 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 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
84pub fn read_static_file_header(path: &Path) -> Result<SegmentHeader, NippyJarError> {
86 Ok(NippyJar::<SegmentHeader>::load(path)?.user_header().clone())
87}
88
89pub 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}