1use bytes::Bytes;
4use futures_util::StreamExt;
5
6use crate::config::HARD_MAX_BODY_BYTES;
7use crate::error::{AppError, AppResult, ErrorDetail};
8
9pub(super) async fn read_body_capped(resp: reqwest::Response, max_bytes: u64) -> AppResult<Bytes> {
17 let max_bytes = max_bytes.min(HARD_MAX_BODY_BYTES);
19 let content_length = resp.content_length();
22 if let Some(n) = content_length
23 && n > max_bytes
24 {
25 return Err(AppError::of(ErrorDetail::BodyOverBudget { max_bytes }));
27 }
28 let capacity = content_length
31 .map(|n| (n as usize).min(max_bytes as usize))
32 .unwrap_or(0);
33 let mut stream = resp.bytes_stream();
34 let mut buf: Vec<u8> = Vec::new();
35 if capacity > 0 {
36 buf.try_reserve_exact(capacity).map_err(|e| {
37 AppError::of_with_source(ErrorDetail::BodyReserveFailed { bytes: capacity }, e)
38 })?;
39 }
40 while let Some(chunk) = stream.next().await {
41 let chunk = chunk.map_err(|e| AppError::of_with_source(ErrorDetail::BodyRead, e))?;
42 if (buf.len() as u64).saturating_add(chunk.len() as u64) > max_bytes {
43 return Err(AppError::of(ErrorDetail::BodyOverBudget { max_bytes }));
45 }
46 let need = chunk.len();
48 if buf.capacity().saturating_sub(buf.len()) < need {
49 buf.try_reserve(need).map_err(|e| {
50 AppError::of_with_source(ErrorDetail::BodyReserveFailed { bytes: need }, e)
51 })?;
52 }
53 buf.extend_from_slice(&chunk);
54 }
55 Ok(Bytes::from(buf))
56}
57
58pub fn decode_utf8(body: &Bytes) -> AppResult<String> {
64 let mut bytes = body.as_ref();
65 if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
66 bytes = &bytes[3..];
67 }
68 std::str::from_utf8(bytes)
69 .map(|s| s.to_string())
70 .map_err(|e| AppError::of_with_source(ErrorDetail::BodyNotUtf8, e))
71}