Skip to main content

ic_http_gateway_protocol/response/
response_handler.rs

1use crate::protocol::validate;
2use crate::{HttpGatewayResponseBody, ResponseBodyStream, ResponseBodyStreamItem};
3use bytes::Bytes;
4use candid::Principal;
5use futures::{future, stream, Stream, StreamExt, TryStreamExt};
6use http_body::Frame;
7use http_body_util::{BodyExt, Full};
8use ic_agent::{Agent, AgentError};
9use ic_http_certification::{HttpRequest, HttpResponse, StatusCode};
10use ic_response_verification::MAX_VERIFICATION_VERSION;
11use ic_utils::interfaces::http_request::HeaderField;
12use ic_utils::{
13    call::SyncCall,
14    interfaces::http_request::{
15        HttpRequestCanister, HttpRequestStreamingCallbackAny, HttpResponse as AgentResponse,
16        StreamingCallbackHttpResponse, StreamingStrategy, Token,
17    },
18};
19
20// Limit the total number of calls to an HTTP Request loop to 1000 for now.
21static MAX_HTTP_REQUEST_STREAM_CALLBACK_CALL_COUNT: usize = 1000;
22
23// Limit the total number of calls to an HTTP request look that can be verified
24static MAX_VERIFIED_HTTP_REQUEST_STREAM_CALLBACK_CALL_COUNT: usize = 4;
25
26// Limit the number of Stream Callbacks buffered
27static STREAM_CALLBACK_BUFFER: usize = 2;
28
29pub type AgentResponseAny = AgentResponse<Token, HttpRequestStreamingCallbackAny>;
30
31pub async fn get_body_and_streaming_body(
32    agent: &Agent,
33    response: &AgentResponseAny,
34) -> Result<HttpGatewayResponseBody, AgentError> {
35    // if we already have the full body, we can return it early
36    let Some(StreamingStrategy::Callback(callback_strategy)) = response.streaming_strategy.clone()
37    else {
38        return Ok(HttpGatewayResponseBody::Right(Full::from(
39            response.body.clone(),
40        )));
41    };
42
43    let (streamed_body, token) = create_stream(
44        agent.clone(),
45        callback_strategy.callback.clone(),
46        Some(callback_strategy.token),
47    )
48    .take(MAX_VERIFIED_HTTP_REQUEST_STREAM_CALLBACK_CALL_COUNT)
49    .map(|x| async move { x })
50    .buffered(STREAM_CALLBACK_BUFFER)
51    .try_fold(
52        (vec![], None::<Token>),
53        |mut accum, (mut body, token)| async move {
54            accum.0.append(&mut body);
55            accum.1 = token;
56
57            Ok(accum)
58        },
59    )
60    .await?;
61
62    let streamed_body = [response.body.clone(), streamed_body].concat();
63
64    // if we still have a token at this point,
65    // we were unable to collect the response within the allowed certified callback limit,
66    // fallback to uncertified streaming using what we've streamed so far as the initial body
67    if token.is_some() {
68        let body_stream = create_body_stream(
69            agent.clone(),
70            callback_strategy.callback,
71            token,
72            streamed_body,
73        );
74
75        return Ok(HttpGatewayResponseBody::Left(body_stream));
76    };
77
78    // if we no longer have a token at this point,
79    // we were able to collect the response within the allow certified callback limit,
80    // return this collected response as a standard response body so it will be verified
81    Ok(HttpGatewayResponseBody::Right(Full::from(streamed_body)))
82}
83
84fn create_body_stream(
85    agent: Agent,
86    callback: HttpRequestStreamingCallbackAny,
87    token: Option<Token>,
88    initial_body: Vec<u8>,
89) -> ResponseBodyStream {
90    let chunks_stream = create_stream(agent, callback, token).map_ok(|(body, _)| body);
91
92    let body_stream = stream::once(async move { Ok(initial_body) })
93        .chain(chunks_stream)
94        .take(MAX_HTTP_REQUEST_STREAM_CALLBACK_CALL_COUNT)
95        .map(|x| async move { x })
96        .buffered(STREAM_CALLBACK_BUFFER);
97
98    ResponseBodyStream::new(Box::pin(chunks_to_frames(body_stream)))
99}
100
101/// Converts a stream of body chunks into a stream of DATA frames, skipping empty chunks.
102///
103/// The end of the body is signalled by the end of the stream, not by a DATA frame, so an empty
104/// DATA frame carries no information. Over HTTP/2 it would be sent as an empty DATA frame without
105/// the END_STREAM flag, so no empty DATA frames are emitted at all.
106///
107/// This must be applied after `.take(MAX_HTTP_REQUEST_STREAM_CALLBACK_CALL_COUNT)`, so that
108/// skipped chunks still count towards the limit on the number of calls made to the canister.
109fn chunks_to_frames<S>(chunks: S) -> impl Stream<Item = ResponseBodyStreamItem>
110where
111    S: Stream<Item = Result<Vec<u8>, AgentError>>,
112{
113    chunks
114        .try_filter(|body| future::ready(!body.is_empty()))
115        .map_ok(|body| Frame::data(Bytes::from(body)))
116}
117
118fn create_stream(
119    agent: Agent,
120    callback: HttpRequestStreamingCallbackAny,
121    token: Option<Token>,
122) -> impl Stream<Item = Result<(Vec<u8>, Option<Token>), AgentError>> {
123    futures::stream::try_unfold(
124        (agent, callback, token),
125        |(agent, callback, token)| async move {
126            let Some(token) = token else {
127                return Ok(None);
128            };
129
130            let canister = HttpRequestCanister::create(&agent, callback.0.principal);
131            match canister
132                .http_request_stream_callback(&callback.0.method, token)
133                .call()
134                .await
135            {
136                Ok((StreamingCallbackHttpResponse { body, token },)) => {
137                    Ok(Some(((body, token.clone()), (agent, callback, token))))
138                }
139                Err(e) => Err(e),
140            }
141        },
142    )
143}
144
145#[derive(Clone, Debug)]
146struct StreamState<'a> {
147    pub http_request: HttpRequest<'a>,
148    pub canister_id: Principal,
149    pub total_length: usize,
150    pub fetched_length: usize,
151    pub skip_verification: bool,
152}
153
154pub async fn get_206_stream_response_body_and_total_length(
155    agent: &Agent,
156    http_request: HttpRequest<'static>,
157    canister_id: Principal,
158    response_headers: &Vec<HeaderField<'static>>,
159    response_206_body: HttpGatewayResponseBody,
160    skip_verification: bool,
161) -> Result<(HttpGatewayResponseBody, usize), AgentError> {
162    let HttpGatewayResponseBody::Right(body) = response_206_body else {
163        return Err(AgentError::InvalidHttpResponse(
164            "Expected full 206 response".to_string(),
165        ));
166    };
167    // The expect below should never panic because `Either::Right` will always have a full body
168    let streamed_body = body
169        .collect()
170        .await
171        .expect("missing streamed chunk body")
172        .to_bytes()
173        .to_vec();
174    let stream_state = get_initial_stream_state(
175        http_request,
176        canister_id,
177        response_headers,
178        streamed_body.len(),
179        skip_verification,
180    )?;
181    let content_length = stream_state.total_length;
182
183    let body_stream = create_206_body_stream(agent.clone(), stream_state, streamed_body);
184    Ok((HttpGatewayResponseBody::Left(body_stream), content_length))
185}
186
187#[derive(Debug)]
188struct ContentRangeValues {
189    pub range_begin: usize,
190    pub range_end: usize,
191    pub total_length: usize,
192}
193
194fn parse_content_range_header_str(
195    content_range_str: &str,
196) -> Result<ContentRangeValues, AgentError> {
197    // expected format: `bytes 21010-47021/47022`
198    let str_value = content_range_str.trim();
199    if !str_value.starts_with("bytes ") {
200        return Err(AgentError::InvalidHttpResponse(format!(
201            "Invalid Content-Range header '{}'",
202            content_range_str
203        )));
204    }
205    let str_value = str_value.trim_start_matches("bytes ");
206
207    let str_value_parts = str_value.split('-').collect::<Vec<_>>();
208    if str_value_parts.len() != 2 {
209        return Err(AgentError::InvalidHttpResponse(format!(
210            "Invalid bytes spec in Content-Range header '{}'",
211            content_range_str
212        )));
213    }
214    let range_begin = str_value_parts[0].parse::<usize>().map_err(|e| {
215        AgentError::InvalidHttpResponse(format!(
216            "Invalid range_begin in '{}': {}",
217            content_range_str, e
218        ))
219    })?;
220
221    let other_value_parts = str_value_parts[1].split('/').collect::<Vec<_>>();
222    if other_value_parts.len() != 2 {
223        return Err(AgentError::InvalidHttpResponse(format!(
224            "Invalid bytes spec in Content-Range header '{}'",
225            content_range_str
226        )));
227    }
228    let range_end = other_value_parts[0].parse::<usize>().map_err(|e| {
229        AgentError::InvalidHttpResponse(format!(
230            "Invalid range_end in '{}': {}",
231            content_range_str, e
232        ))
233    })?;
234    let total_length = other_value_parts[1].parse::<usize>().map_err(|e| {
235        AgentError::InvalidHttpResponse(format!(
236            "Invalid total_length in '{}': {}",
237            content_range_str, e
238        ))
239    })?;
240
241    let rv = ContentRangeValues {
242        range_begin,
243        range_end,
244        total_length,
245    };
246    if rv.range_begin > rv.range_end
247        || rv.range_begin >= rv.total_length
248        || rv.range_end >= rv.total_length
249    {
250        Err(AgentError::InvalidHttpResponse(format!(
251            "inconsistent Content-Range header {}: {:?}",
252            content_range_str, rv
253        )))
254    } else {
255        Ok(rv)
256    }
257}
258
259fn get_content_range_header_str(
260    response_headers: &Vec<HeaderField<'static>>,
261) -> Result<String, AgentError> {
262    for HeaderField(name, value) in response_headers {
263        if name.eq_ignore_ascii_case(http::header::CONTENT_RANGE.as_ref()) {
264            return Ok(value.to_string());
265        }
266    }
267    Err(AgentError::InvalidHttpResponse(
268        "missing Content-Range header in 206 response".to_string(),
269    ))
270}
271
272fn get_content_range_values(
273    response_headers: &Vec<HeaderField<'static>>,
274    fetched_length: usize,
275    body_length: usize,
276) -> Result<ContentRangeValues, AgentError> {
277    let str_value = get_content_range_header_str(response_headers)?;
278    let range_values = parse_content_range_header_str(&str_value)?;
279
280    if range_values.range_begin > fetched_length {
281        return Err(AgentError::InvalidHttpResponse(format!(
282            "chunk out-of-order: range_begin={} is larger than expected begin={} ",
283            range_values.range_begin, fetched_length
284        )));
285    }
286    if range_values.range_end < fetched_length {
287        return Err(AgentError::InvalidHttpResponse(format!(
288            "chunk out-of-order: range_end={} is smaller than length fetched so far={} ",
289            range_values.range_end, fetched_length
290        )));
291    }
292    // The Content-Range header is controlled by the canister, so it must match the body,
293    // otherwise the offsets computed from it cannot be used to slice the body.
294    // `parse_content_range_header_str` guarantees that `range_begin <= range_end`.
295    let range_length = range_values.range_end - range_values.range_begin + 1;
296    if body_length != range_length {
297        return Err(AgentError::InvalidHttpResponse(format!(
298            "Content-Range header {} does not match body length={}",
299            str_value, body_length
300        )));
301    }
302    Ok(range_values)
303}
304
305fn get_initial_stream_state<'a>(
306    http_request: HttpRequest<'a>,
307    canister_id: Principal,
308    response_headers: &Vec<HeaderField<'static>>,
309    initial_body_length: usize,
310    skip_verification: bool,
311) -> Result<StreamState<'a>, AgentError> {
312    let range_values = get_content_range_values(response_headers, 0, initial_body_length)?;
313
314    Ok(StreamState {
315        http_request,
316        canister_id,
317        total_length: range_values.total_length,
318        fetched_length: range_values
319            .range_end
320            .saturating_sub(range_values.range_begin)
321            + 1,
322        skip_verification,
323    })
324}
325
326fn create_206_body_stream(
327    agent: Agent,
328    stream_state: StreamState<'static>,
329    initial_body: Vec<u8>,
330) -> ResponseBodyStream {
331    let chunks_stream = create_206_stream(agent, Some(stream_state)).map_ok(|(body, _)| body);
332
333    let body_stream = stream::once(async move { Ok(initial_body) })
334        .chain(chunks_stream)
335        .take(MAX_HTTP_REQUEST_STREAM_CALLBACK_CALL_COUNT)
336        .map(|x| async move { x })
337        .buffered(STREAM_CALLBACK_BUFFER);
338
339    ResponseBodyStream::new(Box::pin(chunks_to_frames(body_stream)))
340}
341
342fn create_206_stream(
343    agent: Agent,
344    maybe_stream_state: Option<StreamState>,
345) -> impl Stream<Item = Result<(Vec<u8>, Option<StreamState>), AgentError>> {
346    futures::stream::try_unfold(
347        (agent, maybe_stream_state),
348        |(agent, maybe_stream_state)| async move {
349            let Some(stream_state) = maybe_stream_state else {
350                return Ok(None);
351            };
352            let canister = HttpRequestCanister::create(&agent, stream_state.canister_id);
353            let next_chunk_begin = stream_state.fetched_length;
354
355            let range_header = ("Range".to_string(), format!("bytes={}-", next_chunk_begin));
356            let mut updated_headers = stream_state.http_request.headers().to_vec();
357            updated_headers.push(range_header.clone());
358            let headers = updated_headers
359                .iter()
360                .map(|(name, value)| HeaderField(name.into(), value.into()))
361                .collect::<Vec<HeaderField>>()
362                .into_iter();
363            let query_result = canister
364                .http_request(
365                    &stream_state.http_request.method(),
366                    &stream_state.http_request.url(),
367                    headers,
368                    &stream_state.http_request.body(),
369                    Some(&u16::from(MAX_VERIFICATION_VERSION)),
370                )
371                .call()
372                .await;
373            let agent_response = match query_result {
374                Ok((response,)) => response,
375                Err(e) => return Err(e),
376            };
377            let range_values = get_content_range_values(
378                &agent_response.headers,
379                stream_state.fetched_length,
380                agent_response.body.len(),
381            )?;
382            if range_values.total_length != stream_state.total_length {
383                return Err(AgentError::InvalidHttpResponse(format!(
384                    "chunk total_length={} differs from the initial total_length={}",
385                    range_values.total_length, stream_state.total_length
386                )));
387            }
388            let new_bytes_begin = stream_state
389                .fetched_length
390                .saturating_sub(range_values.range_begin);
391            let chunk_length = range_values
392                .range_end
393                .saturating_sub(stream_state.fetched_length)
394                + 1;
395            let current_fetched_length = stream_state.fetched_length + chunk_length;
396            // Verify the chunk from the range response.
397            if agent_response.streaming_strategy.is_some() {
398                return Err(AgentError::InvalidHttpResponse(
399                    "unexpected StreamingStrategy".to_string(),
400                ));
401            }
402
403            let Ok(status_code) = StatusCode::from_u16(agent_response.status_code) else {
404                return Err(AgentError::InvalidHttpResponse(format!(
405                    "Invalid canister response status code: {}",
406                    agent_response.status_code
407                )));
408            };
409            let response = HttpResponse::builder()
410                .with_status_code(status_code)
411                .with_headers(
412                    agent_response
413                        .headers
414                        .iter()
415                        .map(|HeaderField(k, v)| (k.to_string(), v.to_string()))
416                        .collect(),
417                )
418                .with_body(agent_response.body.clone())
419                .build();
420            let mut http_request = stream_state.http_request.clone();
421            http_request.headers_mut().push(range_header);
422            let validation_result = validate(
423                &agent,
424                &stream_state.canister_id,
425                http_request,
426                response,
427                stream_state.skip_verification,
428            );
429
430            if let Err(e) = validation_result {
431                return Err(AgentError::InvalidHttpResponse(format!(
432                    "CertificateVerificationFailed for a chunk starting at {}, error: {}",
433                    stream_state.fetched_length, e
434                )));
435            }
436            let Some(new_bytes) = agent_response.body.get(new_bytes_begin..) else {
437                return Err(AgentError::InvalidHttpResponse(format!(
438                    "chunk starting at {} is shorter than expected",
439                    stream_state.fetched_length
440                )));
441            };
442            let maybe_new_state = if current_fetched_length < stream_state.total_length {
443                Some(StreamState {
444                    fetched_length: current_fetched_length,
445                    ..stream_state
446                })
447            } else {
448                None
449            };
450            Ok(Some((
451                (new_bytes.to_vec(), maybe_new_state.clone()),
452                (agent, maybe_new_state),
453            )))
454        },
455    )
456}
457
458#[cfg(test)]
459mod tests {
460    use super::*;
461    use assert_matches::assert_matches;
462    use std::borrow::Cow;
463
464    #[test]
465    fn should_parse_content_range_header_str() {
466        let header_values = [
467            ContentRangeValues {
468                range_begin: 0,
469                range_end: 0,
470                total_length: 1,
471            },
472            ContentRangeValues {
473                range_begin: 100,
474                range_end: 2000,
475                total_length: 3000,
476            },
477            ContentRangeValues {
478                range_begin: 10_000,
479                range_end: 300_000,
480                total_length: 500_000,
481            },
482        ];
483        for v in header_values {
484            let input = format!("bytes {}-{}/{}", v.range_begin, v.range_end, v.total_length);
485            let result = parse_content_range_header_str(&input);
486            let output = result.unwrap_or_else(|_| panic!("failed parsing '{}'", input));
487            assert_eq!(v.range_begin, output.range_begin);
488            assert_eq!(v.range_end, output.range_end);
489            assert_eq!(v.total_length, output.total_length);
490        }
491    }
492
493    #[test]
494    fn should_fail_parse_content_range_header_str_on_malformed_input() {
495        let malformed_inputs = [
496            "byte 1-2/3",
497            "bites 2-4/8",
498            "bytes 100-200/asdf",
499            "bytes 12345",
500            "something else",
501            "bytes dead-beef/123456",
502        ];
503        for input in malformed_inputs {
504            let result = parse_content_range_header_str(input);
505            assert_matches!(result, Err(e) if format!("{}", e).contains("Invalid "));
506        }
507    }
508
509    #[test]
510    fn should_fail_parse_content_range_header_str_on_inconsistent_input() {
511        let inconsistent_inputs = ["bytes 100-200/190", "bytes 200-150/400", "bytes 100-110/40"];
512        for input in inconsistent_inputs {
513            let result = parse_content_range_header_str(input);
514            assert_matches!(result, Err(e) if format!("{}", e).contains("inconsistent Content-Range header"));
515        }
516    }
517
518    #[test]
519    fn should_get_initial_stream_state() {
520        let http_request = HttpRequest::get("http://example.com/some_file")
521            .with_headers(vec![("Xyz".to_string(), "some value".to_string())])
522            .with_body(vec![42])
523            .build();
524        let canister_id = Principal::from_slice(&[1, 2, 3, 4]);
525        let response_headers = vec![HeaderField(
526            Cow::from("Content-Range"),
527            Cow::from("bytes 0-2/10"), // fetched 3 bytes, total length is 10
528        )];
529        let skip_verification = false;
530        let state = get_initial_stream_state(
531            http_request.clone(),
532            canister_id,
533            &response_headers,
534            3,
535            skip_verification,
536        )
537        .expect("failed constructing StreamState");
538        assert_eq!(state.http_request, http_request);
539        assert_eq!(state.canister_id, canister_id);
540        assert_eq!(state.fetched_length, 3);
541        assert_eq!(state.total_length, 10);
542        assert_eq!(state.skip_verification, skip_verification);
543    }
544
545    #[test]
546    fn should_fail_get_initial_stream_state_without_content_range_header() {
547        let http_request = HttpRequest::get("http://example.com/some_file")
548            .with_headers(vec![("Xyz".to_string(), "some value".to_string())])
549            .with_body(vec![42])
550            .build();
551        let canister_id = Principal::from_slice(&[1, 2, 3, 4]);
552        let response_headers = vec![HeaderField(
553            Cow::from("other header"),
554            Cow::from("other value"),
555        )];
556        let result =
557            get_initial_stream_state(http_request, canister_id, &response_headers, 3, false);
558        assert_matches!(result, Err(e) if format!("{}", e).contains("missing Content-Range header"));
559    }
560
561    #[test]
562    fn should_fail_get_initial_stream_state_with_malformed_content_range_header() {
563        let http_request = HttpRequest::get("http://example.com/some_file")
564            .with_headers(vec![("Xyz".to_string(), "some value".to_string())])
565            .with_body(vec![42])
566            .build();
567        let canister_id = Principal::from_slice(&[1, 2, 3, 4]);
568        let response_headers = vec![HeaderField(
569            Cow::from("Content-Range"),
570            Cow::from("bytes 42/10"),
571        )];
572        let result =
573            get_initial_stream_state(http_request, canister_id, &response_headers, 3, false);
574        assert_matches!(result, Err(e) if format!("{}", e).contains("Invalid bytes spec in Content-Range header"));
575    }
576
577    #[test]
578    fn should_fail_get_initial_stream_state_with_inconsistent_content_range_header() {
579        let http_request = HttpRequest::get("http://example.com/some_file")
580            .with_headers(vec![("Xyz".to_string(), "some value".to_string())])
581            .with_body(vec![42])
582            .build();
583        let canister_id = Principal::from_slice(&[1, 2, 3, 4]);
584        let response_headers = vec![HeaderField(
585            Cow::from("Content-Range"),
586            Cow::from("bytes 40-100/90"),
587        )];
588        let result =
589            get_initial_stream_state(http_request, canister_id, &response_headers, 61, false);
590        assert_matches!(result, Err(e) if format!("{}", e).contains("inconsistent Content-Range header"));
591    }
592
593    #[test]
594    fn should_fail_get_initial_stream_state_with_body_length_mismatch() {
595        let http_request = HttpRequest::get("http://example.com/some_file").build();
596        let canister_id = Principal::from_slice(&[1, 2, 3, 4]);
597        let response_headers = vec![HeaderField(
598            Cow::from("Content-Range"),
599            Cow::from("bytes 0-99/1000"), // claims 100 bytes
600        )];
601        for body_length in [0, 10, 99, 101] {
602            let result = get_initial_stream_state(
603                http_request.clone(),
604                canister_id,
605                &response_headers,
606                body_length,
607                false,
608            );
609            assert_matches!(result, Err(e) if format!("{}", e).contains("does not match body length"));
610        }
611    }
612
613    fn content_range_headers(value: &str) -> Vec<HeaderField<'static>> {
614        vec![HeaderField(
615            Cow::from("Content-Range"),
616            Cow::from(value.to_string()),
617        )]
618    }
619
620    #[test]
621    fn should_get_content_range_values_when_body_length_matches() {
622        // (Content-Range, fetched_length, body_length)
623        let inputs = [
624            ("bytes 0-9/1000", 0, 10),
625            ("bytes 100-149/1000", 100, 50),
626            ("bytes 90-149/1000", 100, 60), // overlaps with the already fetched bytes
627            ("bytes 999-999/1000", 999, 1),
628        ];
629        for (header, fetched_length, body_length) in inputs {
630            let result = get_content_range_values(
631                &content_range_headers(header),
632                fetched_length,
633                body_length,
634            );
635            assert!(
636                result.is_ok(),
637                "unexpected error for '{header}': {result:?}"
638            );
639        }
640    }
641
642    #[test]
643    fn should_fail_get_content_range_values_with_body_length_mismatch() {
644        // (Content-Range, fetched_length, body_length)
645        let inputs = [
646            // The header claims a range starting before the already fetched bytes,
647            // but the body is too short to contain them.
648            ("bytes 0-149/1000", 100, 10),
649            ("bytes 0-20/1000", 10, 5),
650            ("bytes 90-149/1000", 100, 5),
651            ("bytes 100-149/1000", 100, 0),
652            ("bytes 100-149/1000", 100, 49),
653            ("bytes 100-149/1000", 100, 51),
654        ];
655        for (header, fetched_length, body_length) in inputs {
656            let result = get_content_range_values(
657                &content_range_headers(header),
658                fetched_length,
659                body_length,
660            );
661            assert_matches!(result, Err(e) if format!("{}", e).contains("does not match body length"));
662        }
663    }
664
665    fn collect_frames(chunks: Vec<Result<Vec<u8>, AgentError>>) -> Vec<ResponseBodyStreamItem> {
666        futures::executor::block_on(chunks_to_frames(stream::iter(chunks)).collect::<Vec<_>>())
667    }
668
669    fn collect_frames_data(chunks: Vec<Result<Vec<u8>, AgentError>>) -> Vec<Bytes> {
670        collect_frames(chunks)
671            .into_iter()
672            .map(|frame| {
673                frame
674                    .expect("unexpected error in body stream")
675                    .into_data()
676                    .expect("expected a DATA frame")
677            })
678            .collect()
679    }
680
681    #[test]
682    fn should_skip_empty_chunks() {
683        let data = collect_frames_data(vec![
684            Ok(vec![]),
685            Ok(vec![1, 2, 3]),
686            Ok(vec![]),
687            Ok(vec![]),
688            Ok(vec![4, 5]),
689            Ok(vec![]),
690        ]);
691        assert_eq!(
692            data,
693            vec![Bytes::from_static(&[1, 2, 3]), Bytes::from_static(&[4, 5])]
694        );
695    }
696
697    #[test]
698    fn should_yield_no_frames_for_empty_body() {
699        let data = collect_frames_data(vec![Ok(vec![]), Ok(vec![])]);
700        assert!(data.is_empty());
701    }
702
703    #[test]
704    fn should_propagate_errors_when_skipping_empty_chunks() {
705        let frames = collect_frames(vec![
706            Ok(vec![1]),
707            Ok(vec![]),
708            Err(AgentError::InvalidHttpResponse("boom".to_string())),
709        ]);
710        assert_eq!(frames.len(), 2);
711        assert_matches!(&frames[0], Ok(frame) if frame.data_ref() == Some(&Bytes::from_static(&[1])));
712        assert_matches!(&frames[1], Err(AgentError::InvalidHttpResponse(msg)) if msg == "boom");
713    }
714}