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;
pub const ERROR_BODY_CAP: usize = 64 * 1024;
#[cfg_attr(not(any(feature = "native", feature = "wasi")), allow(dead_code))]
pub(crate) 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 fn transient_status(status: u16) -> bool {
(500..600).contains(&status) || status == 429
}
pub fn status_text(status: u16) -> String {
#[cfg(feature = "native")]
let reason = reqwest::StatusCode::from_u16(status)
.ok()
.and_then(|code| code.canonical_reason());
#[cfg(not(feature = "native"))]
let reason = wasi_reason(status);
match reason {
Some(reason) => format!("{status} {reason}"),
None => status.to_string(),
}
}
#[cfg(not(feature = "native"))]
fn wasi_reason(status: u16) -> Option<&'static str> {
Some(match status {
200 => "OK",
204 => "No Content",
301 => "Moved Permanently",
302 => "Found",
303 => "See Other",
304 => "Not Modified",
307 => "Temporary Redirect",
308 => "Permanent Redirect",
400 => "Bad Request",
401 => "Unauthorized",
403 => "Forbidden",
404 => "Not Found",
405 => "Method Not Allowed",
408 => "Request Timeout",
409 => "Conflict",
410 => "Gone",
413 => "Payload Too Large",
415 => "Unsupported Media Type",
422 => "Unprocessable Entity",
429 => "Too Many Requests",
500 => "Internal Server Error",
501 => "Not Implemented",
502 => "Bad Gateway",
503 => "Service Unavailable",
504 => "Gateway Timeout",
_ => return None,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn status_text_names_the_reason_phrase() {
assert_eq!(status_text(404), "404 Not Found");
assert_eq!(status_text(401), "401 Unauthorized");
assert_eq!(status_text(799), "799");
}
#[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(500));
assert!(transient_status(503));
assert!(transient_status(429));
assert!(!transient_status(404));
assert!(!transient_status(403));
assert!(!transient_status(202));
}
}