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
use super::{
    util::{retry_future, Retryable},
    Item,
};
use bytes::{Buf, Bytes};
use reqwest::{header::LOCATION, redirect, Client, StatusCode};
use std::time::Duration;
use thiserror::Error;
use tryhard::RetryPolicy;

const MAX_RETRIES: u32 = 7;
const RETRY_INITIAL_DELAY_DURATION: Duration = Duration::from_millis(250);
const BAD_GATEWAY_DELAY_DURATION: Duration = Duration::from_secs(30);
const TCP_KEEPALIVE_DURATION: Duration = Duration::from_secs(20);
const DEFAULT_REQUEST_TIMEOUT_DURATION: Duration = Duration::from_secs(10);

#[derive(Error, Debug)]
pub enum Error {
    #[error("I/O error")]
    Io(#[from] std::io::Error),
    #[error("HTTP client error: {0:?}")]
    Client(#[from] reqwest::Error),
    #[error("Unexpected redirect: {0:?}")]
    UnexpectedRedirect(Option<String>),
    #[error("Unexpected redirect URL: {0:?}")]
    UnexpectedRedirectUrl(String),
    #[error("Unexpected status code: {0:?}")]
    UnexpectedStatus(StatusCode),
}

impl Retryable for Error {
    fn max_retries() -> u32 {
        MAX_RETRIES
    }

    fn log_level() -> Option<log::Level> {
        Some(log::Level::Warn)
    }

    fn default_initial_delay() -> Duration {
        RETRY_INITIAL_DELAY_DURATION
    }

    fn custom_retry_policy(&self) -> Option<RetryPolicy> {
        match self {
            Error::Io(_) => None,
            Error::Client(_) => None,
            // 502 (often Too Many Requests)
            Error::UnexpectedStatus(StatusCode::BAD_GATEWAY) => {
                Some(RetryPolicy::Delay(BAD_GATEWAY_DELAY_DURATION))
            }
            _ => Some(RetryPolicy::Break),
        }
    }
}

pub struct RedirectResolution {
    pub url: String,
    pub timestamp: String,
    pub content: Bytes,
    pub valid_initial_content: bool,
    pub valid_digest: bool,
}

#[derive(Clone)]
pub struct Downloader {
    client: Client,
}

impl Downloader {
    pub fn new(request_timeout: Duration) -> reqwest::Result<Self> {
        let tcp_keepalive = Some(TCP_KEEPALIVE_DURATION);

        Ok(Self {
            client: Client::builder()
                .timeout(request_timeout)
                .tcp_keepalive(tcp_keepalive)
                .redirect(redirect::Policy::none())
                .build()?,
        })
    }

    fn wayback_url(url: &str, timestamp: &str, original: bool) -> String {
        format!(
            "http://web.archive.org/web/{}{}/{}",
            timestamp,
            if original { "id_" } else { "if_" },
            url
        )
    }

    pub async fn resolve_redirect(
        &self,
        url: &str,
        timestamp: &str,
        expected_digest: &str,
    ) -> Result<RedirectResolution, Error> {
        let initial_url = Self::wayback_url(url, timestamp, true);
        let initial_response = self.client.head(&initial_url).send().await?;

        match initial_response.status() {
            StatusCode::FOUND => {
                match initial_response
                    .headers()
                    .get(LOCATION)
                    .and_then(|value| value.to_str().ok())
                    .map(str::to_string)
                {
                    Some(location) => {
                        let info = location
                            .parse::<super::item::UrlInfo>()
                            .map_err(|_| Error::UnexpectedRedirectUrl(location))?;

                        let guess = super::util::redirect::guess_redirect_content(&info.url);
                        let mut guess_bytes = guess.as_bytes();
                        let guess_digest = super::digest::compute_digest(&mut guess_bytes)?;

                        let mut valid_initial_content = true;
                        let mut valid_digest = true;

                        let content = if guess_digest == expected_digest {
                            Bytes::from(guess)
                        } else {
                            log::warn!("Invalid guess, re-requesting");
                            let direct_bytes =
                                self.client.get(&initial_url).send().await?.bytes().await?;
                            let direct_digest =
                                super::digest::compute_digest(&mut direct_bytes.clone().reader())?;
                            valid_initial_content = false;
                            valid_digest = direct_digest == expected_digest;

                            direct_bytes
                        };

                        let actual_url = self
                            .direct_resolve_redirect(&info.url, &info.timestamp)
                            .await?;

                        let actual_info = actual_url
                            .parse::<super::item::UrlInfo>()
                            .map_err(|_| Error::UnexpectedRedirectUrl(actual_url))?;

                        Ok(RedirectResolution {
                            url: actual_info.url,
                            timestamp: actual_info.timestamp,
                            content,
                            valid_initial_content,
                            valid_digest,
                        })
                    }
                    None => Err(Error::UnexpectedRedirect(None)),
                }
            }
            other => Err(Error::UnexpectedStatus(other)),
        }
    }

    async fn direct_resolve_redirect(&self, url: &str, timestamp: &str) -> Result<String, Error> {
        let response = self
            .client
            .head(Self::wayback_url(url, timestamp, true))
            .send()
            .await?;

        match response.status() {
            StatusCode::FOUND => {
                match response
                    .headers()
                    .get(LOCATION)
                    .and_then(|value| value.to_str().ok())
                    .map(str::to_string)
                {
                    Some(location) => Ok(location),
                    None => Err(Error::UnexpectedRedirect(None)),
                }
            }
            other => Err(Error::UnexpectedStatus(other)),
        }
    }

    async fn download(&self, url: &str, timestamp: &str, original: bool) -> Result<Bytes, Error> {
        retry_future(|| self.download_once(url, timestamp, original)).await
    }

    async fn download_once(
        &self,
        url: &str,
        timestamp: &str,
        original: bool,
    ) -> Result<Bytes, Error> {
        let response = self
            .client
            .get(Self::wayback_url(url, timestamp, original))
            .send()
            .await?;

        match response.status() {
            StatusCode::OK => Ok(response.bytes().await?),
            other => Err(Error::UnexpectedStatus(other)),
        }
    }

    pub async fn download_item(&self, item: &Item) -> Result<Bytes, Error> {
        self.download(&item.url, &item.timestamp(), true).await
    }
}

impl Default for Downloader {
    fn default() -> Self {
        Self::new(DEFAULT_REQUEST_TIMEOUT_DURATION).unwrap()
    }
}