use reqwest::{Response, StatusCode};
pub const USER_AGENT: &str = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36";
pub const MAX_BODY_BYTES: usize = 5 * 1024 * 1024;
fn push_capped(buf: &mut Vec<u8>, chunk: &[u8], max: usize) -> bool {
let remaining = max.saturating_sub(buf.len());
if chunk.len() >= remaining {
buf.extend_from_slice(&chunk[..remaining]);
true
} else {
buf.extend_from_slice(chunk);
false
}
}
pub async fn read_body_capped(resp: Response) -> Result<String, (anyhow::Error, bool)> {
let bytes = read_body_capped_bytes(resp).await?;
Ok(String::from_utf8_lossy(&bytes).into_owned())
}
pub async fn read_body_capped_bytes(mut resp: Response) -> Result<Vec<u8>, (anyhow::Error, bool)> {
let mut buf: Vec<u8> = Vec::new();
if let Some(len) = resp.content_length() {
buf.reserve(len.min(MAX_BODY_BYTES as u64) as usize);
}
loop {
match resp.chunk().await {
Ok(Some(chunk)) => {
if push_capped(&mut buf, &chunk, MAX_BODY_BYTES) {
break;
}
}
Ok(None) => break,
Err(e) => {
let transient = e.is_timeout();
return Err((e.into(), transient));
}
}
}
Ok(buf)
}
pub fn transient_send_error(e: &reqwest::Error) -> bool {
e.is_timeout() || e.is_connect() || e.is_request()
}
pub fn transient_status(status: StatusCode) -> bool {
status.is_server_error() || status.as_u16() == 429
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn push_capped_truncates_oversized_chunk() {
let mut buf = Vec::new();
let stopped = push_capped(&mut buf, &[b'x'; 10], 4);
assert!(stopped);
assert_eq!(buf.len(), 4);
}
#[test]
fn push_capped_accumulates_until_cap() {
let mut buf = Vec::new();
assert!(!push_capped(&mut buf, b"abc", 8));
assert!(!push_capped(&mut buf, b"de", 8));
assert_eq!(buf, b"abcde");
let stopped = push_capped(&mut buf, b"fghij", 8);
assert!(stopped);
assert_eq!(buf.len(), 8);
assert_eq!(buf, b"abcdefgh");
}
#[test]
fn push_capped_small_body_unaffected() {
let mut buf = Vec::new();
let stopped = push_capped(&mut buf, b"hello", 1024);
assert!(!stopped);
assert_eq!(buf, b"hello");
}
#[test]
fn transient_status_covers_5xx_and_429() {
assert!(transient_status(StatusCode::INTERNAL_SERVER_ERROR));
assert!(transient_status(StatusCode::TOO_MANY_REQUESTS));
assert!(!transient_status(StatusCode::NOT_FOUND));
assert!(!transient_status(StatusCode::FORBIDDEN));
}
}