1use super::{manifest::*, verify::OutputVerifier};
2use eyre::Result;
3use serde::Serialize;
4use std::{collections::BTreeMap, io::Write, path::Path};
5use tracing::info;
6
7#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
9#[serde(rename_all = "camelCase")]
10pub struct DownloadPlan {
11 pub schema_version: u8,
13 pub chain_id: u64,
15 pub block: u64,
17 pub total_download_size: u64,
19 pub total_output_size: u64,
21 pub archives: Vec<DownloadPlanArchive>,
23}
24
25impl DownloadPlan {
26 const SCHEMA_VERSION: u8 = 1;
27
28 pub(crate) fn from_planned(manifest: &SnapshotManifest, planned: &PlannedDownloads) -> Self {
29 Self {
30 schema_version: Self::SCHEMA_VERSION,
31 chain_id: manifest.chain_id,
32 block: manifest.block,
33 total_download_size: planned.total_download_size,
34 total_output_size: planned.total_output_size,
35 archives: planned.archives.iter().map(DownloadPlanArchive::from_planned).collect(),
36 }
37 }
38
39 pub fn push_archive(&mut self, archive: DownloadPlanArchive) {
41 self.total_download_size = self.total_download_size.saturating_add(archive.download_size);
42 self.total_output_size = self.total_output_size.saturating_add(archive.output_size);
43 self.archives.push(archive);
44 }
45
46 pub fn write_json(&self, mut writer: impl Write) -> Result<()> {
48 serde_json::to_writer_pretty(&mut writer, self)?;
49 writeln!(writer)?;
50 Ok(())
51 }
52}
53
54#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
56#[serde(rename_all = "camelCase")]
57pub struct DownloadPlanArchive {
58 pub component: String,
60 pub file_name: String,
62 pub url: String,
64 pub download_size: u64,
66 pub output_size: u64,
68 #[serde(skip_serializing_if = "Option::is_none")]
70 pub blake3: Option<String>,
71}
72
73impl DownloadPlanArchive {
74 pub fn new(
76 component: impl Into<String>,
77 file_name: impl Into<String>,
78 url: impl Into<String>,
79 download_size: u64,
80 output_size: u64,
81 blake3: Option<String>,
82 ) -> Self {
83 Self {
84 component: component.into(),
85 file_name: file_name.into(),
86 url: url.into(),
87 download_size,
88 output_size,
89 blake3,
90 }
91 }
92
93 fn from_planned(planned: &PlannedArchive) -> Self {
94 Self::new(
95 planned.ty.key(),
96 planned.archive.file_name.clone(),
97 planned.archive.url.clone(),
98 planned.archive.size,
99 planned.archive.output_size(),
100 planned.archive.blake3.clone(),
101 )
102 }
103}
104
105#[derive(Debug, Clone)]
107pub(crate) struct PlannedArchive {
108 pub(crate) ty: SnapshotComponentType,
110 pub(crate) component: String,
112 pub(crate) archive: SnapshotArchive,
114}
115
116#[derive(Debug)]
118pub(crate) struct PlannedDownloads {
119 pub(crate) archives: Vec<PlannedArchive>,
121 pub(crate) total_download_size: u64,
123 pub(crate) total_output_size: u64,
125}
126
127impl PlannedDownloads {
128 pub(crate) const fn total_archives(&self) -> usize {
130 self.archives.len()
131 }
132}
133
134pub(crate) const fn archive_priority_rank(ty: SnapshotComponentType) -> u8 {
136 match ty {
137 SnapshotComponentType::State => 0,
138 SnapshotComponentType::RocksdbIndices => 1,
139 _ => 2,
140 }
141}
142
143#[derive(Debug, Default, Clone, Copy)]
145pub(crate) struct DownloadStartupSummary {
146 pub(crate) reusable: usize,
148 pub(crate) needs_download: usize,
150}
151
152pub(crate) fn summarize_download_startup(
154 all_downloads: &[PlannedArchive],
155 target_dir: &Path,
156) -> Result<DownloadStartupSummary> {
157 let mut summary = DownloadStartupSummary::default();
158 let verifier = OutputVerifier::new(target_dir);
159
160 for planned in all_downloads {
161 if verifier.verify(&planned.archive.output_files)? {
162 summary.reusable += 1;
163 } else {
164 summary.needs_download += 1;
165 }
166 }
167
168 Ok(summary)
169}
170
171fn selection_archive_distance(
173 selection: &ComponentSelection,
174 snapshot_block: u64,
175) -> Option<Option<u64>> {
176 match selection {
177 ComponentSelection::All => Some(None),
178 ComponentSelection::Distance(distance) => Some(Some(*distance)),
179 ComponentSelection::Since(block) => Some(Some(snapshot_block.saturating_sub(*block) + 1)),
180 ComponentSelection::None => None,
181 }
182}
183
184fn sort_planned_archives(all_downloads: &mut [PlannedArchive]) {
186 all_downloads.sort_by(|a, b| {
187 archive_priority_rank(a.ty)
188 .cmp(&archive_priority_rank(b.ty))
189 .then_with(|| a.component.cmp(&b.component))
190 .then_with(|| a.archive.file_name.cmp(&b.archive.file_name))
191 });
192}
193
194pub(crate) fn collect_planned_archives(
196 manifest: &SnapshotManifest,
197 selections: &BTreeMap<SnapshotComponentType, ComponentSelection>,
198) -> Result<PlannedDownloads> {
199 let mut archives = Vec::new();
200 let mut total_download_size = 0;
201 let mut total_output_size = 0;
202
203 for (ty, selection) in selections {
204 let Some(distance) = selection_archive_distance(selection, manifest.block) else {
205 continue;
206 };
207
208 if let Some(ComponentManifest::Chunked(chunked)) = manifest.component(*ty) &&
209 !chunked.chunk_files_are_consistent()
210 {
211 eyre::bail!(
212 "Invalid modular manifest: {} chunk_files length ({}) does not match chunk count ({})",
213 ty.key(),
214 chunked.chunk_files.len(),
215 chunked.num_chunks()
216 );
217 }
218
219 total_download_size += manifest.size_for_distance(*ty, distance);
220 total_output_size += manifest.output_size_for_distance(*ty, distance);
221
222 let snapshot_archives = manifest.snapshot_archives_for_distance(*ty, distance);
223 let component = ty.display_name().to_string();
224 if !snapshot_archives.is_empty() {
225 info!(target: "reth::cli",
226 component = %component,
227 archives = snapshot_archives.len(),
228 selection = %selection,
229 "Queued component for download"
230 );
231 }
232
233 for archive in snapshot_archives {
234 if archive.output_files.is_empty() {
235 eyre::bail!(
236 "Invalid modular manifest: {} is missing plain output checksum metadata",
237 archive.file_name
238 );
239 }
240
241 archives.push(PlannedArchive { ty: *ty, component: component.clone(), archive });
242 }
243 }
244
245 sort_planned_archives(&mut archives);
246 Ok(PlannedDownloads { archives, total_download_size, total_output_size })
247}
248
249#[cfg(test)]
250mod tests {
251 use super::*;
252 use tempfile::tempdir;
253
254 #[test]
255 fn summarize_download_startup_counts_reusable_and_needs_download() {
256 let dir = tempdir().unwrap();
257 let target_dir = dir.path();
258 let ok_file = target_dir.join("ok.bin");
259 std::fs::write(&ok_file, vec![1_u8; 4]).unwrap();
260 let ok_hash = blake3::hash(&[1_u8; 4]).to_hex().to_string();
261
262 let planned = vec![
263 PlannedArchive {
264 ty: SnapshotComponentType::State,
265 component: "State".to_string(),
266 archive: SnapshotArchive {
267 url: "https://example.com/ok.tar.zst".to_string(),
268 file_name: "ok.tar.zst".to_string(),
269 size: 10,
270 blake3: None,
271 output_files: vec![OutputFileChecksum {
272 path: "ok.bin".to_string(),
273 size: 4,
274 blake3: ok_hash,
275 }],
276 },
277 },
278 PlannedArchive {
279 ty: SnapshotComponentType::Headers,
280 component: "Headers".to_string(),
281 archive: SnapshotArchive {
282 url: "https://example.com/missing.tar.zst".to_string(),
283 file_name: "missing.tar.zst".to_string(),
284 size: 10,
285 blake3: None,
286 output_files: vec![OutputFileChecksum {
287 path: "missing.bin".to_string(),
288 size: 1,
289 blake3: "deadbeef".to_string(),
290 }],
291 },
292 },
293 PlannedArchive {
294 ty: SnapshotComponentType::Transactions,
295 component: "Transactions".to_string(),
296 archive: SnapshotArchive {
297 url: "https://example.com/bad-size.tar.zst".to_string(),
298 file_name: "bad-size.tar.zst".to_string(),
299 size: 10,
300 blake3: None,
301 output_files: vec![],
302 },
303 },
304 ];
305
306 let summary = summarize_download_startup(&planned, target_dir).unwrap();
307 assert_eq!(summary.reusable, 1);
308 assert_eq!(summary.needs_download, 2);
309 }
310
311 #[test]
312 fn archive_priority_prefers_state_then_rocksdb() {
313 let mut planned = [
314 PlannedArchive {
315 ty: SnapshotComponentType::Transactions,
316 component: "Transactions".to_string(),
317 archive: SnapshotArchive {
318 url: "u3".to_string(),
319 file_name: "t.tar.zst".to_string(),
320 size: 1,
321 blake3: None,
322 output_files: vec![OutputFileChecksum {
323 path: "a".to_string(),
324 size: 1,
325 blake3: "x".to_string(),
326 }],
327 },
328 },
329 PlannedArchive {
330 ty: SnapshotComponentType::RocksdbIndices,
331 component: "RocksDB Indices".to_string(),
332 archive: SnapshotArchive {
333 url: "u2".to_string(),
334 file_name: "rocksdb_indices.tar.zst".to_string(),
335 size: 1,
336 blake3: None,
337 output_files: vec![OutputFileChecksum {
338 path: "b".to_string(),
339 size: 1,
340 blake3: "y".to_string(),
341 }],
342 },
343 },
344 PlannedArchive {
345 ty: SnapshotComponentType::State,
346 component: "State (mdbx)".to_string(),
347 archive: SnapshotArchive {
348 url: "u1".to_string(),
349 file_name: "state.tar.zst".to_string(),
350 size: 1,
351 blake3: None,
352 output_files: vec![OutputFileChecksum {
353 path: "c".to_string(),
354 size: 1,
355 blake3: "z".to_string(),
356 }],
357 },
358 },
359 ];
360
361 planned.sort_by(|a, b| {
362 archive_priority_rank(a.ty)
363 .cmp(&archive_priority_rank(b.ty))
364 .then_with(|| a.component.cmp(&b.component))
365 .then_with(|| a.archive.file_name.cmp(&b.archive.file_name))
366 });
367
368 assert_eq!(planned[0].ty, SnapshotComponentType::State);
369 assert_eq!(planned[1].ty, SnapshotComponentType::RocksdbIndices);
370 assert_eq!(planned[2].ty, SnapshotComponentType::Transactions);
371 }
372
373 #[test]
374 fn collect_planned_archives_tracks_download_and_output_totals() {
375 let mut components = BTreeMap::new();
376 components.insert(
377 "state".to_string(),
378 ComponentManifest::Single(SingleArchive {
379 file: "state.tar.zst".to_string(),
380 size: 10,
381 decompressed_size: 100,
382 blake3: None,
383 output_files: vec![OutputFileChecksum {
384 path: "db/mdbx.dat".to_string(),
385 size: 100,
386 blake3: "h0".to_string(),
387 }],
388 }),
389 );
390 components.insert(
391 "transactions".to_string(),
392 ComponentManifest::Chunked(ChunkedArchive {
393 blocks_per_file: 500_000,
394 total_blocks: 1_000_000,
395 chunk_sizes: vec![20, 30],
396 chunk_decompressed_sizes: vec![200, 300],
397 chunk_files: vec![],
398 chunk_output_files: vec![
399 vec![OutputFileChecksum {
400 path: "static_files/tx-0".to_string(),
401 size: 200,
402 blake3: "h1".to_string(),
403 }],
404 vec![OutputFileChecksum {
405 path: "static_files/tx-1".to_string(),
406 size: 300,
407 blake3: "h2".to_string(),
408 }],
409 ],
410 }),
411 );
412
413 let manifest = SnapshotManifest {
414 block: 1_000_000,
415 chain_id: 1,
416 storage_version: 2,
417 timestamp: 0,
418 base_url: Some("https://example.com".to_string()),
419 reth_version: None,
420 components,
421 extensions: Default::default(),
422 };
423
424 let selections = BTreeMap::from([
425 (SnapshotComponentType::State, ComponentSelection::All),
426 (SnapshotComponentType::Transactions, ComponentSelection::Distance(500_000)),
427 ]);
428
429 let planned = collect_planned_archives(&manifest, &selections).unwrap();
430
431 assert_eq!(planned.total_download_size, 40);
432 assert_eq!(planned.total_output_size, 400);
433 assert_eq!(planned.archives.len(), 2);
434
435 let plan = DownloadPlan::from_planned(&manifest, &planned);
436 assert_eq!(
437 serde_json::to_value(plan).unwrap(),
438 serde_json::json!({
439 "schemaVersion": 1,
440 "chainId": 1,
441 "block": 1_000_000,
442 "totalDownloadSize": 40,
443 "totalOutputSize": 400,
444 "archives": [
445 {
446 "component": "state",
447 "fileName": "state.tar.zst",
448 "url": "https://example.com/state.tar.zst",
449 "downloadSize": 10,
450 "outputSize": 100
451 },
452 {
453 "component": "transactions",
454 "fileName": "transactions-500000-999999.tar.zst",
455 "url": "https://example.com/transactions-500000-999999.tar.zst",
456 "downloadSize": 30,
457 "outputSize": 300
458 }
459 ]
460 })
461 );
462 }
463
464 #[test]
465 fn collect_planned_archives_rejects_mismatched_chunk_files_length() {
466 let mut components = BTreeMap::new();
467 components.insert(
468 "transactions".to_string(),
469 ComponentManifest::Chunked(ChunkedArchive {
470 blocks_per_file: 500_000,
471 total_blocks: 1_000_000,
472 chunk_sizes: vec![20, 30],
473 chunk_decompressed_sizes: vec![200, 300],
474 chunk_files: vec!["static_files/transactions-0-499999.tar.zst".to_string()],
475 chunk_output_files: vec![
476 vec![OutputFileChecksum {
477 path: "static_files/tx-0".to_string(),
478 size: 200,
479 blake3: "h1".to_string(),
480 }],
481 vec![OutputFileChecksum {
482 path: "static_files/tx-1".to_string(),
483 size: 300,
484 blake3: "h2".to_string(),
485 }],
486 ],
487 }),
488 );
489
490 let manifest = SnapshotManifest {
491 block: 1_000_000,
492 chain_id: 1,
493 storage_version: 2,
494 timestamp: 0,
495 base_url: Some("https://example.com/mainnet".to_string()),
496 reth_version: None,
497 components,
498 extensions: Default::default(),
499 };
500 let selections =
501 BTreeMap::from([(SnapshotComponentType::Transactions, ComponentSelection::All)]);
502
503 let err = collect_planned_archives(&manifest, &selections).unwrap_err();
504 assert!(
505 err.to_string().contains("chunk_files length"),
506 "expected chunk_files length error, got: {err}"
507 );
508 }
509}