Attempt to download file 3 times before crashing

This commit is contained in:
Tyler Hallada 2021-07-18 01:45:08 -04:00
parent 4e500f0b0b
commit 62c0f5295f

View File

@ -6,7 +6,7 @@ use std::{env, time::Duration};
use tempfile::tempfile;
use tokio::fs::File;
use tokio_util::compat::FuturesAsyncReadCompatExt;
use tracing::{info, instrument};
use tracing::{info, instrument, warn};
use super::{rate_limit_wait_duration, GAME_NAME, USER_AGENT};
@ -53,6 +53,7 @@ impl DownloadLinkResponse {
#[instrument(skip(self, client))]
pub async fn download_file(&self, client: &Client) -> Result<File> {
for attempt in 1..=3 {
let mut tokio_file = File::from_std(tempfile()?);
let res = client
.get(self.link()?)
@ -70,8 +71,15 @@ impl DownloadLinkResponse {
.into_async_read()
.compat();
tokio::io::copy(&mut byte_stream, &mut tokio_file).await?;
match tokio::io::copy(&mut byte_stream, &mut tokio_file).await {
Ok(_) => {
return Ok(tokio_file);
}
Err(err) => {
warn!(error = %err, attempt, "Failed to download file, trying again");
}
}
}
Err(anyhow!("Failed to download file in three attempts"))
}
}