11use std:: { collections:: HashMap , env, path:: Path } ;
22
33use alloy:: rpc:: types:: beacon:: BlsPublicKey ;
4- use bytes:: { BufMut , BytesMut } ;
54use eyre:: { bail, Context , Result } ;
65use serde:: de:: DeserializeOwned ;
76
87use super :: JWTS_ENV ;
9- use crate :: { config:: MUXER_HTTP_MAX_LENGTH , types:: ModuleId } ;
8+ use crate :: {
9+ config:: MUXER_HTTP_MAX_LENGTH ,
10+ types:: ModuleId ,
11+ utils:: { read_chunked_body_with_max, ResponseReadError } ,
12+ } ;
1013
1114pub const CB_TEST_HTTP_DISABLE_CONTENT_LENGTH_ENV : & str = "CB_TEST_HTTP_DISABLE_CONTENT_LENGTH" ;
1215
@@ -36,7 +39,7 @@ pub fn load_jwt_secrets() -> Result<HashMap<ModuleId, String>> {
3639
3740/// Reads an HTTP response safely, erroring out if it failed or if the body is
3841/// too large.
39- pub async fn safe_read_http_response ( mut response : reqwest:: Response ) -> Result < String > {
42+ pub async fn safe_read_http_response ( response : reqwest:: Response ) -> Result < String > {
4043 // Get the content length from the response headers
4144 let mut content_length = response. content_length ( ) ;
4245 if env:: var ( CB_TEST_HTTP_DISABLE_CONTENT_LENGTH_ENV ) . is_ok ( ) {
@@ -56,18 +59,16 @@ pub async fn safe_read_http_response(mut response: reqwest::Response) -> Result<
5659 }
5760
5861 // Read the response to a buffer in chunks
59- let mut buffer = BytesMut :: with_capacity ( 1024 ) ;
60- while let Some ( chunk) = response. chunk ( ) . await ? {
61- if buffer. len ( ) > MUXER_HTTP_MAX_LENGTH as usize {
62- bail ! (
63- "Response body exceeds the maximum allowed length ({MUXER_HTTP_MAX_LENGTH} bytes)"
64- ) ;
65- }
66- buffer. put ( chunk) ;
67- }
62+ let result = read_chunked_body_with_max ( response, MUXER_HTTP_MAX_LENGTH as usize ) . await ;
63+ let bytes = match result {
64+ Ok ( bytes) => Ok ( bytes) ,
65+ Err ( ResponseReadError :: PayloadTooLarge { max : _, raw : _ } ) => bail ! (
66+ "Response body exceeds the maximum allowed length ({MUXER_HTTP_MAX_LENGTH} bytes)"
67+ ) ,
68+ Err ( ResponseReadError :: ChunkError { inner } ) => Err ( inner) ,
69+ } ?;
6870
6971 // Convert the buffer to a string
70- let bytes = buffer. freeze ( ) ;
7172 match std:: str:: from_utf8 ( & bytes) {
7273 Ok ( s) => Ok ( s. to_string ( ) ) ,
7374 Err ( e) => bail ! ( "Failed to decode response body as UTF-8: {e}" ) ,
0 commit comments