1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
// Copyright 2019-2024 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT

use std::{
    fmt::Display,
    path::{Path, PathBuf},
    str::FromStr,
};

use crate::{
    networks::NetworkChain,
    utils::{retry, RetryArgs},
};
use anyhow::{bail, Context as _};
use chrono::NaiveDate;
use tracing::event;
use url::Url;

use crate::cli_shared::snapshot::parse::ParsedFilename;

/// Who hosts the snapshot on the web?
/// See [`stable_url`].
#[derive(
    Debug,
    Clone,
    Copy,
    Hash,
    PartialEq,
    Eq,
    Default,
    strum::EnumString, // impl std::str::FromStr
    strum::Display,    // impl Display
    clap::ValueEnum,   // allow values to be enumerated and parsed by clap
)]
#[strum(serialize_all = "kebab-case")]
pub enum TrustedVendor {
    #[default]
    Forest,
}

/// Create a filename in the "full" format. See [`parse`].
// Common between export, and [`fetch`].
// Keep in sync with the CLI documentation for the `snapshot` sub-command.
pub fn filename(
    vendor: impl Display,
    chain: impl Display,
    date: NaiveDate,
    height: i64,
    forest_format: bool,
) -> String {
    let vendor = vendor.to_string();
    let chain = chain.to_string();
    ParsedFilename::Full {
        vendor: &vendor,
        chain: &chain,
        date,
        height,
        forest_format,
    }
    .to_string()
}

/// Returns the path to the downloaded file.
pub async fn fetch(
    directory: &Path,
    chain: &NetworkChain,
    vendor: TrustedVendor,
) -> anyhow::Result<PathBuf> {
    let (url, _len, path) = peek(vendor, chain).await?;
    let (date, height, forest_format) = ParsedFilename::parse_str(&path)
        .context("unexpected path format")?
        .date_and_height_and_forest();
    let filename = filename(vendor, chain, date, height, forest_format);

    download_file_with_retry(&url, directory, &filename).await
}

pub async fn download_file_with_retry(
    url: &Url,
    directory: &Path,
    filename: &str,
) -> anyhow::Result<PathBuf> {
    Ok(retry(
        RetryArgs {
            timeout: None,
            ..Default::default()
        },
        || download_http(url, directory, filename),
    )
    .await?)
}

/// Returns
/// - The final URL after redirection(s)
/// - The size of the snapshot from this vendor on this chain
/// - The filename of the snapshot
pub async fn peek(
    vendor: TrustedVendor,
    chain: &NetworkChain,
) -> anyhow::Result<(Url, u64, String)> {
    let stable_url = stable_url(vendor, chain)?;
    // issue an actual GET, so the content length will be of the body
    // (we never actually fetch the body)
    // if we issue a HEAD, the content-length will be zero for our stable URLs
    // (this is a bug, maybe in reqwest - HEAD _should_ give us the length)
    // (probably because the stable URLs are all double-redirects 301 -> 302 -> 200)
    let response = reqwest::get(stable_url)
        .await?
        .error_for_status()
        .context("server returned an error response")?;
    let final_url = response.url().clone();
    let cd_path = response
        .headers()
        .get(reqwest::header::CONTENT_DISPOSITION)
        .and_then(parse_content_disposition);
    Ok((
        final_url,
        response
            .content_length()
            .context("no content-length header")?,
        cd_path.context("no content-disposition filepath")?,
    ))
}

// Extract file paths from content-disposition values:
//   "attachment; filename=\"911520_2023_09_14T06_13_00Z.car.zst\""
// => "911520_2023_09_14T06_13_00Z.car.zst"
fn parse_content_disposition(value: &reqwest::header::HeaderValue) -> Option<String> {
    use regex::Regex;
    let re = Regex::new("filename=\"([^\"]+)\"").ok()?;
    let cap = re.captures(value.to_str().ok()?)?;
    Some(cap.get(1)?.as_str().to_owned())
}

/// Download the file at `url` with a private HTTP client, returning the path to the downloaded file
async fn download_http(url: &Url, directory: &Path, filename: &str) -> anyhow::Result<PathBuf> {
    let dst_path = directory.join(filename);
    let destination = dst_path.display();
    event!(target: "forest::snapshot", tracing::Level::INFO, %url, %destination, "downloading snapshot");
    let mut reader = crate::utils::net::reader(url.as_str()).await?;
    let tmp_dst_path = {
        // like `crdownload` for the chrome browser
        const DOWNLOAD_EXTENSION: &str = "frdownload";
        let mut path = dst_path.clone();
        if let Some(ext) = path.extension() {
            path.set_extension(format!(
                "{}.{DOWNLOAD_EXTENSION}",
                ext.to_str().unwrap_or_default()
            ));
        } else {
            path.set_extension(DOWNLOAD_EXTENSION);
        }
        path
    };
    let mut tempfile = tokio::fs::File::create(&tmp_dst_path)
        .await
        .context("couldn't create destination file")?;
    tokio::io::copy(&mut reader, &mut tempfile)
        .await
        .context("couldn't download file")?;
    std::fs::rename(&tmp_dst_path, &dst_path).context("couldn't rename file")?;

    Ok(dst_path)
}

/// Also defines an `ALL_URLS` constant for test purposes
macro_rules! define_urls {
    ($($vis:vis const $name:ident: &str = $value:literal;)* $(,)?) => {
        $($vis const $name: &str = $value;)*

        #[cfg(test)]
        const ALL_URLS: &[&str] = [
            $($name,)*
        ].as_slice();
    };
}

define_urls!(
    const FOREST_MAINNET_COMPRESSED: &str = "https://forest-archive.chainsafe.dev/latest/mainnet/";
    const FOREST_CALIBNET_COMPRESSED: &str =
        "https://forest-archive.chainsafe.dev/latest/calibnet/";
);

pub fn stable_url(vendor: TrustedVendor, chain: &NetworkChain) -> anyhow::Result<Url> {
    let s = match (vendor, chain) {
        (TrustedVendor::Forest, NetworkChain::Mainnet) => FOREST_MAINNET_COMPRESSED,
        (TrustedVendor::Forest, NetworkChain::Calibnet) => FOREST_CALIBNET_COMPRESSED,
        (TrustedVendor::Forest, NetworkChain::Butterflynet | NetworkChain::Devnet(_)) => {
            bail!("unsupported chain {chain}")
        }
    };
    Ok(Url::from_str(s).unwrap())
}

#[test]
fn parse_stable_urls() {
    for url in ALL_URLS {
        let _did_not_panic = Url::from_str(url).unwrap();
    }
}

mod parse {
    //! Vendors publish filenames with two formats:
    //! `filecoin_snapshot_calibnet_2023-06-13_height_643680.car.zst` "full" and
    //! `632400_2023_06_09T08_13_00Z.car.zst` "short".
    //!
    //! This module contains utilities for parsing and printing these formats.

    use std::{fmt::Display, str::FromStr};

    use anyhow::{anyhow, bail};
    use chrono::{NaiveDate, NaiveDateTime, NaiveTime};
    use nom::{
        branch::alt,
        bytes::complete::{tag, take_until},
        character::complete::digit1,
        combinator::{map_res, recognize},
        error::ErrorKind,
        error_position,
        multi::many1,
        sequence::tuple,
        Err,
    };

    use crate::db::car::forest::FOREST_CAR_FILE_EXTENSION;

    #[derive(PartialEq, Debug, Clone, Hash)]
    pub(super) enum ParsedFilename<'a> {
        Short {
            date: NaiveDate,
            time: NaiveTime,
            height: i64,
        },
        Full {
            vendor: &'a str,
            chain: &'a str,
            date: NaiveDate,
            height: i64,
            forest_format: bool,
        },
    }

    impl Display for ParsedFilename<'_> {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match self {
                ParsedFilename::Short { date, time, height } => f.write_fmt(format_args!(
                    "{height}_{}.car.zst",
                    NaiveDateTime::new(*date, *time).format("%Y_%m_%dT%H_%M_%SZ")
                )),
                ParsedFilename::Full {
                    vendor,
                    chain,
                    date,
                    height,
                    forest_format,
                } => f.write_fmt(format_args!(
                    "{vendor}_snapshot_{chain}_{}_height_{height}{}.car.zst",
                    date.format("%Y-%m-%d"),
                    if *forest_format { ".forest" } else { "" }
                )),
            }
        }
    }

    impl<'a> ParsedFilename<'a> {
        pub fn date_and_height_and_forest(&self) -> (NaiveDate, i64, bool) {
            match self {
                ParsedFilename::Short { date, height, .. } => (*date, *height, false),
                ParsedFilename::Full {
                    date,
                    height,
                    forest_format,
                    ..
                } => (*date, *height, *forest_format),
            }
        }

        pub fn parse_str(input: &'a str) -> anyhow::Result<Self> {
            enter_nom(alt((short, full)), input)
        }
    }

    /// Parse a number using its [`FromStr`] implementation.
    fn number<T>(input: &str) -> nom::IResult<&str, T>
    where
        T: FromStr,
    {
        map_res(recognize(many1(digit1)), T::from_str)(input)
    }

    /// Create a parser for `YYYY-MM-DD` etc
    fn ymd(separator: &str) -> impl Fn(&str) -> nom::IResult<&str, NaiveDate> + '_ {
        move |input| {
            let (rest, (year, _, month, _, day)) =
                tuple((number, tag(separator), number, tag(separator), number))(input)?;
            match NaiveDate::from_ymd_opt(year, month, day) {
                Some(date) => Ok((rest, date)),
                None => Err(Err::Error(error_position!(input, ErrorKind::Verify))),
            }
        }
    }

    /// Create a parser for `HH_MM_SS` etc
    fn hms(separator: &str) -> impl Fn(&str) -> nom::IResult<&str, NaiveTime> + '_ {
        move |input| {
            let (rest, (hour, _, minute, _, second)) =
                tuple((number, tag(separator), number, tag(separator), number))(input)?;
            match NaiveTime::from_hms_opt(hour, minute, second) {
                Some(date) => Ok((rest, date)),
                None => Err(Err::Error(error_position!(input, ErrorKind::Verify))),
            }
        }
    }

    fn full(input: &str) -> nom::IResult<&str, ParsedFilename> {
        let (rest, (vendor, _snapshot_, chain, _, date, _height_, height, car_zst)) =
            tuple((
                take_until("_snapshot_"),
                tag("_snapshot_"),
                take_until("_"),
                tag("_"),
                ymd("-"),
                tag("_height_"),
                number,
                alt((tag(".car.zst"), tag(FOREST_CAR_FILE_EXTENSION))),
            ))(input)?;
        Ok((
            rest,
            ParsedFilename::Full {
                vendor,
                chain,
                date,
                height,
                forest_format: car_zst == FOREST_CAR_FILE_EXTENSION,
            },
        ))
    }

    fn short(input: &str) -> nom::IResult<&str, ParsedFilename> {
        let (rest, (height, _, date, _, time, _)) = tuple((
            number,
            tag("_"),
            ymd("_"),
            tag("T"),
            hms("_"),
            tag("Z.car.zst"),
        ))(input)?;
        Ok((rest, ParsedFilename::Short { date, time, height }))
    }

    fn enter_nom<'a, T>(
        mut parser: impl nom::Parser<&'a str, T, nom::error::Error<&'a str>>,
        input: &'a str,
    ) -> anyhow::Result<T> {
        let (rest, t) = parser
            .parse(input)
            .map_err(|e| anyhow!("Parser error: {e}"))?;
        if !rest.is_empty() {
            bail!("Unexpected trailing input: {rest}")
        }
        Ok(t)
    }

    #[test]
    fn test_serialization() {
        impl ParsedFilename<'static> {
            /// # Panics
            /// - If `ymd`/`hms` aren't valid
            fn short(
                height: i64,
                year: i32,
                month: u32,
                day: u32,
                hour: u32,
                min: u32,
                sec: u32,
            ) -> Self {
                Self::Short {
                    date: NaiveDate::from_ymd_opt(year, month, day).unwrap(),
                    time: NaiveTime::from_hms_opt(hour, min, sec).unwrap(),
                    height,
                }
            }
        }

        impl<'a> ParsedFilename<'a> {
            /// # Panics
            /// - If `ymd` isn't valid
            fn full(
                vendor: &'a str,
                chain: &'a str,
                year: i32,
                month: u32,
                day: u32,
                height: i64,
                forest_format: bool,
            ) -> Self {
                Self::Full {
                    vendor,
                    chain,
                    date: NaiveDate::from_ymd_opt(year, month, day).unwrap(),
                    height,
                    forest_format,
                }
            }
        }

        for (text, value) in [
            (
                "forest_snapshot_mainnet_2023-05-30_height_2905376.car.zst",
                ParsedFilename::full("forest", "mainnet", 2023, 5, 30, 2905376, false),
            ),
            (
                "forest_snapshot_calibnet_2023-05-30_height_604419.car.zst",
                ParsedFilename::full("forest", "calibnet", 2023, 5, 30, 604419, false),
            ),
            (
                "forest_snapshot_mainnet_2023-05-30_height_2905376.forest.car.zst",
                ParsedFilename::full("forest", "mainnet", 2023, 5, 30, 2905376, true),
            ),
            (
                "forest_snapshot_calibnet_2023-05-30_height_604419.forest.car.zst",
                ParsedFilename::full("forest", "calibnet", 2023, 5, 30, 604419, true),
            ),
            (
                "2905920_2023_05_30T22_00_00Z.car.zst",
                ParsedFilename::short(2905920, 2023, 5, 30, 22, 0, 0),
            ),
            (
                "605520_2023_05_31T00_13_00Z.car.zst",
                ParsedFilename::short(605520, 2023, 5, 31, 0, 13, 0),
            ),
            (
                "filecoin_snapshot_calibnet_2023-06-13_height_643680.car.zst",
                ParsedFilename::full("filecoin", "calibnet", 2023, 6, 13, 643680, false),
            ),
            (
                "venus_snapshot_pineconenet_2045-01-01_height_2.car.zst",
                ParsedFilename::full("venus", "pineconenet", 2045, 1, 1, 2, false),
            ),
            (
                "filecoin_snapshot_calibnet_2023-06-13_height_643680.forest.car.zst",
                ParsedFilename::full("filecoin", "calibnet", 2023, 6, 13, 643680, true),
            ),
            (
                "venus_snapshot_pineconenet_2045-01-01_height_2.forest.car.zst",
                ParsedFilename::full("venus", "pineconenet", 2045, 1, 1, 2, true),
            ),
        ] {
            assert_eq!(
                value,
                ParsedFilename::parse_str(text).unwrap(),
                "mismatch in deserialize"
            );
            assert_eq!(value.to_string(), text, "mismatch in serialize");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::parse_content_disposition;
    use reqwest::header::HeaderValue;

    #[test]
    fn content_disposition_forest() {
        assert_eq!(
            parse_content_disposition(&HeaderValue::from_static(
                "attachment; filename*=UTF-8''forest_snapshot_calibnet_2023-09-14_height_911888.forest.car.zst; \
                 filename=\"forest_snapshot_calibnet_2023-09-14_height_911888.forest.car.zst\""
            )).unwrap(),
            "forest_snapshot_calibnet_2023-09-14_height_911888.forest.car.zst"
        );
    }
}