use std::fmt;
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::time::Duration;
use crate::remote::request::{Method, Request};
#[derive(Clone, Copy, Debug)]
pub struct Policy {
pub attempts: u32,
pub backoff: Duration,
pub timeout: Duration,
pub max_redirects: u32,
pub max_bytes: u64,
}
impl Default for Policy {
fn default() -> Self {
Self {
attempts: 3,
backoff: Duration::from_millis(500),
timeout: Duration::from_secs(600),
max_redirects: 5,
max_bytes: 64 * 1024 * 1024 * 1024,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Fetched {
pub url: String,
pub status: u16,
pub bytes: u64,
}
#[derive(Debug)]
pub enum FetchError {
Unreachable {
url: String,
why: String,
},
Status {
url: String,
status: u16,
},
TooLarge {
url: String,
limit: u64,
},
Io {
path: PathBuf,
source: io::Error,
},
Unsendable {
url: String,
method: Method,
},
}
impl fmt::Display for FetchError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unreachable { url, why } => {
write!(f, "could not fetch {url}: {why}")
}
Self::Status { url, status } => {
write!(f, "{url} answered {status}")
}
Self::TooLarge { url, limit } => write!(
f,
"{url} is larger than the {limit} bytes this fetch allows"
),
Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
Self::Unsendable { url, method } => write!(
f,
"{url} would have to be asked with {method}, which this \
engine cannot send yet: a request body is part of what \
identifies a record, so the method is understood before it \
can be issued"
),
}
}
}
impl std::error::Error for FetchError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io { source, .. } => Some(source),
_ => None,
}
}
}
impl FetchError {
#[must_use]
pub const fn worth_retrying(&self) -> bool {
match self {
Self::Unreachable { .. } => true,
Self::Status { status, .. } => *status == 429 || *status >= 500,
Self::TooLarge { .. } | Self::Io { .. } | Self::Unsendable { .. } => false,
}
}
}
pub trait Transport: Send + Sync {
fn fetch(&self, request: &Request, into: &Path) -> Result<Fetched, FetchError>;
}
#[derive(Debug)]
pub struct Network {
agent: ureq::Agent,
policy: Policy,
}
impl Network {
#[must_use]
pub fn new(policy: Policy) -> Self {
let config = ureq::Agent::config_builder()
.max_redirects(policy.max_redirects)
.max_redirects_will_error(true)
.http_status_as_error(false)
.timeout_global(Some(policy.timeout))
.build();
Self {
agent: config.into(),
policy,
}
}
fn attempt(&self, request: &Request, into: &Path) -> Result<Fetched, FetchError> {
use ureq::ResponseExt as _;
use ureq::http::Uri;
let url = request.url.as_str();
let mut call = self.agent.get(url);
if let Some(auth) = &request.auth {
let (name, value) = auth.header();
call = call.header(name, value);
}
let response = call.call().map_err(|error| FetchError::Unreachable {
url: url.to_owned(),
why: error.to_string(),
})?;
let status = response.status().as_u16();
let answered: &Uri = response.get_uri();
let answered = answered.to_string();
if !(200..300).contains(&status) {
return Err(FetchError::Status {
url: url.to_owned(),
status,
});
}
let limit = self.policy.max_bytes;
let cap = limit.saturating_add(1);
let mut reader = response.into_body().into_with_config().limit(cap).reader();
let written = stream(&mut reader, into, cap).map_err(|source| FetchError::Io {
path: into.to_path_buf(),
source,
})?;
if written > limit {
return Err(FetchError::TooLarge {
url: url.to_owned(),
limit,
});
}
Ok(Fetched {
url: answered,
status,
bytes: written,
})
}
}
impl Transport for Network {
fn fetch(&self, request: &Request, into: &Path) -> Result<Fetched, FetchError> {
let url = request.url.as_str();
if request.method != Method::Get {
return Err(FetchError::Unsendable {
url: url.to_owned(),
method: request.method,
});
}
let mut waited = self.policy.backoff;
for attempt in 1..=self.policy.attempts.max(1) {
match self.attempt(request, into) {
Ok(fetched) => return Ok(fetched),
Err(error) => {
let _ = fs::remove_file(into);
if attempt == self.policy.attempts || !error.worth_retrying() {
return Err(error);
}
std::thread::sleep(waited);
waited = waited.saturating_mul(2);
}
}
}
Err(FetchError::Unreachable {
url: url.to_owned(),
why: "no attempt was made".to_owned(),
})
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Offline;
impl Transport for Offline {
fn fetch(&self, request: &Request, _into: &Path) -> Result<Fetched, FetchError> {
Err(FetchError::Unreachable {
url: request.url.clone(),
why: "this run may not fetch anything, and the store does not \
hold it. Run it once with the network available, or point \
it at a store that has been"
.to_owned(),
})
}
}
fn stream(from: &mut impl Read, into: &Path, cap: u64) -> io::Result<u64> {
if let Some(parent) = into.parent() {
fs::create_dir_all(parent)?;
}
let mut file = File::create(into)?;
let mut buffer = vec![0u8; 64 * 1024];
let mut written = 0u64;
while written < cap {
let room = usize::try_from(cap - written).unwrap_or(usize::MAX);
let want = room.min(buffer.len());
let read = from.read(&mut buffer[..want])?;
if read == 0 {
break;
}
file.write_all(&buffer[..read])?;
written += read as u64;
}
file.flush()?;
Ok(written)
}