use std::io::{self, Read};
use std::time::{Duration, Instant};
pub(crate) const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
pub(crate) fn agent(global: Duration) -> ureq::Agent {
ureq::Agent::config_builder()
.timeout_connect(Some(CONNECT_TIMEOUT.min(global)))
.timeout_global(Some(global))
.max_redirects(0)
.http_status_as_error(false)
.proxy(None)
.max_idle_connections_per_host(2)
.user_agent(concat!("fleetwire/", env!("CARGO_PKG_VERSION")))
.build()
.into()
}
#[derive(Debug)]
pub(crate) enum ReadError {
CapExceeded,
Deadline,
Io(io::Error),
}
pub(crate) fn read_capped(
reader: &mut impl Read,
max: usize,
deadline: Instant,
) -> Result<Vec<u8>, ReadError> {
let mut body = Vec::new();
let mut buf = [0u8; 16 * 1024];
loop {
if Instant::now() >= deadline {
return Err(ReadError::Deadline);
}
let n = match reader.read(&mut buf) {
Ok(0) => return Ok(body),
Ok(n) => n,
Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
Err(e) if Instant::now() >= deadline || is_timeout(&e) => {
return Err(ReadError::Deadline);
}
Err(e) => return Err(ReadError::Io(e)),
};
let chunk = buf.get(..n).unwrap_or_default();
if body.len().saturating_add(chunk.len()) > max {
return Err(ReadError::CapExceeded);
}
body.extend_from_slice(chunk);
}
}
fn is_timeout(e: &io::Error) -> bool {
e.kind() == io::ErrorKind::TimedOut
|| e.get_ref()
.and_then(|inner| inner.downcast_ref::<ureq::Error>())
.is_some_and(|u| matches!(u, ureq::Error::Timeout(_)))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Stage {
NotSent,
Unknown,
}
pub(crate) fn classify(e: &ureq::Error) -> Stage {
use ureq::Error as E;
use ureq::Timeout as T;
match e {
E::Io(io) if io.kind() == io::ErrorKind::ConnectionRefused => Stage::NotSent,
E::Timeout(T::Connect | T::Resolve) => Stage::NotSent,
E::HostNotFound
| E::BadUri(_)
| E::Http(_)
| E::RequireHttpsOnly(_)
| E::InvalidProxyUrl
| E::TlsRequired => Stage::NotSent,
_ => Stage::Unknown,
}
}
pub(crate) fn redact_ureq_error(e: &ureq::Error) -> String {
let s = crate::redaction::redact_transport_error(e);
match s.find('?') {
Some(i) => format!("{}?<redacted>", s.get(..i).unwrap_or_default()),
None => s,
}
}
#[cfg(test)]
mod tests;