use bytes::Bytes;
use futures_util::StreamExt;
use crate::config::HARD_MAX_BODY_BYTES;
use crate::error::{AppError, AppResult, ErrorDetail};
pub(super) async fn read_body_capped(resp: reqwest::Response, max_bytes: u64) -> AppResult<Bytes> {
let max_bytes = max_bytes.min(HARD_MAX_BODY_BYTES);
let content_length = resp.content_length();
if let Some(n) = content_length
&& n > max_bytes
{
return Err(AppError::of(ErrorDetail::BodyOverBudget { max_bytes }));
}
let capacity = content_length
.map(|n| (n as usize).min(max_bytes as usize))
.unwrap_or(0);
let mut stream = resp.bytes_stream();
let mut buf: Vec<u8> = Vec::new();
if capacity > 0 {
buf.try_reserve_exact(capacity).map_err(|e| {
AppError::of_with_source(ErrorDetail::BodyReserveFailed { bytes: capacity }, e)
})?;
}
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(|e| AppError::of_with_source(ErrorDetail::BodyRead, e))?;
if (buf.len() as u64).saturating_add(chunk.len() as u64) > max_bytes {
return Err(AppError::of(ErrorDetail::BodyOverBudget { max_bytes }));
}
let need = chunk.len();
if buf.capacity().saturating_sub(buf.len()) < need {
buf.try_reserve(need).map_err(|e| {
AppError::of_with_source(ErrorDetail::BodyReserveFailed { bytes: need }, e)
})?;
}
buf.extend_from_slice(&chunk);
}
Ok(Bytes::from(buf))
}
pub fn decode_utf8(body: &Bytes) -> AppResult<String> {
let mut bytes = body.as_ref();
if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
bytes = &bytes[3..];
}
std::str::from_utf8(bytes)
.map(|s| s.to_string())
.map_err(|e| AppError::of_with_source(ErrorDetail::BodyNotUtf8, e))
}