use reqwest::header::{CONTENT_TYPE, LOCATION};
use reqwest::{redirect::Policy, Client};
use std::net::SocketAddr;
use std::time::{Duration, Instant};
use crate::guard;
use crate::tls::TlsConfig;
use webfetch_core::charset;
use webfetch_core::http::{
read_body_capped_bytes, transient_send_error, transient_status, USER_AGENT,
};
const MAX_ATTEMPTS: u32 = 3;
const MAX_REDIRECTS: usize = 5;
const TOTAL_BUDGET_MULTIPLIER: u32 = 3;
#[derive(Debug, Clone)]
pub struct FetchedPage {
pub body: String,
pub final_url: String,
pub content_type: Option<String>,
pub undecodable_charset: Option<String>,
}
enum Hop {
Page(FetchedPage),
Redirect(String),
}
fn build_client(
url: &reqwest::Url,
timeout: Duration,
pinned: &[SocketAddr],
tls: &TlsConfig,
) -> anyhow::Result<Client> {
let mut builder = Client::builder()
.timeout(timeout)
.redirect(Policy::none())
.user_agent(USER_AGENT)
.gzip(true)
.brotli(true);
builder = tls.apply(builder)?;
if let Some(host) = url.host_str() {
if !pinned.is_empty() {
builder = builder.resolve_to_addrs(host, pinned);
}
}
Ok(builder.build()?)
}
async fn attempt(client: &Client, url: &str) -> Result<Hop, (anyhow::Error, bool)> {
let resp = match client
.get(url)
.header("Accept", "text/html,application/xhtml+xml,*/*;q=0.8")
.header("Accept-Language", "en-US,en;q=0.9")
.send()
.await
{
Ok(r) => r,
Err(e) => {
let transient = transient_send_error(&e);
return Err((e.into(), transient));
}
};
let status = resp.status();
if status.is_redirection() {
return match resp.headers().get(LOCATION).and_then(|v| v.to_str().ok()) {
Some(loc) => Ok(Hop::Redirect(loc.to_string())),
None => Err((
anyhow::anyhow!("redirect ({status}) without a Location header"),
false,
)),
};
}
let resp = match resp.error_for_status() {
Ok(r) => r,
Err(e) => {
let transient = transient_status(status);
return Err((e.into(), transient));
}
};
let final_url = resp.url().to_string();
let content_type = resp
.headers()
.get(CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string());
let raw = read_body_capped_bytes(resp).await?;
let declared = content_type
.as_deref()
.and_then(charset::from_content_type)
.or_else(|| charset::sniff_meta(&raw));
let (body, undecodable_charset) = charset::decode(&raw, declared.as_deref());
Ok(Hop::Page(FetchedPage {
body,
final_url,
content_type,
undecodable_charset,
}))
}
async fn fetch_with_retries(client: &Client, url: &str, deadline: Instant) -> anyhow::Result<Hop> {
let mut delay = Duration::from_millis(200);
for attempt_no in 1..=MAX_ATTEMPTS {
match attempt(client, url).await {
Ok(hop) => return Ok(hop),
Err((err, transient)) => {
if attempt_no == MAX_ATTEMPTS || !transient {
return Err(err);
}
if Instant::now() + delay >= deadline {
return Err(err);
}
tokio::time::sleep(delay).await;
delay *= 2;
}
}
}
unreachable!("loop returns on the final attempt")
}
pub async fn fetch_page(
url: &str,
timeout_secs: u64,
tls: &TlsConfig,
) -> anyhow::Result<FetchedPage> {
let per_request = Duration::from_secs(timeout_secs);
let deadline = Instant::now() + per_request * TOTAL_BUDGET_MULTIPLIER;
let mut current = reqwest::Url::parse(url)?;
let mut hops = 0usize;
loop {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
anyhow::bail!(
"fetch exceeded its total budget ({}s across redirects and retries)",
timeout_secs * TOTAL_BUDGET_MULTIPLIER as u64
);
}
let pinned = guard::validate_url(¤t).await?;
let client = build_client(¤t, per_request.min(remaining), &pinned, tls)?;
match fetch_with_retries(&client, current.as_str(), deadline).await? {
Hop::Page(page) => return Ok(page),
Hop::Redirect(location) => {
hops += 1;
if hops > MAX_REDIRECTS {
anyhow::bail!("too many redirects (>{MAX_REDIRECTS})");
}
current = current
.join(&location)
.map_err(|e| anyhow::anyhow!("invalid redirect target `{location}`: {e}"))?;
}
}
}
}