Skip to main content

ntex/client/
response.rs

1use std::cell::{Cell, Ref, RefMut};
2use std::task::{Context, Poll, ready};
3use std::{fmt, future::Future, marker::PhantomData, pin::Pin};
4
5use serde::de::DeserializeOwned;
6
7#[cfg(feature = "cookie")]
8use coo_kie::{Cookie, ParseError as CookieParseError};
9
10use crate::Cfg;
11use crate::error::Error;
12use crate::http::header::{AsName, CONTENT_LENGTH, HeaderValue};
13use crate::http::{HeaderMap, HttpMessage, Payload, ResponseHead, StatusCode, Version};
14use crate::http::{error::PayloadError, helpers::take_trimmed};
15use crate::time::{Deadline, Millis};
16use crate::util::{Bytes, BytesMut, Extensions, Stream};
17
18use super::error::{ClientPayloadError, JsonPayloadError};
19use super::{ClientConfig, ServiceResponse};
20
21/// An HTTP client response.
22pub struct ClientResponse {
23    pub(crate) head: ResponseHead,
24    pub(crate) payload: Cell<Option<Payload>>,
25    /// Set once the stream has reported `PayloadError::AlreadyTaken`.
26    taken_reported: Cell<bool>,
27    pub(crate) config: Cfg<ClientConfig>,
28}
29
30impl HttpMessage for ClientResponse {
31    fn message_headers(&self) -> &HeaderMap {
32        &self.head.headers
33    }
34
35    fn message_extensions(&self) -> Ref<'_, Extensions> {
36        self.head.extensions()
37    }
38
39    fn message_extensions_mut(&self) -> RefMut<'_, Extensions> {
40        self.head.extensions_mut()
41    }
42
43    #[cfg(feature = "cookie")]
44    /// Parses cookies from the response `Set-Cookie` headers.
45    ///
46    /// Headers that are not valid UTF-8 or cannot be parsed are skipped.
47    ///
48    /// # Errors
49    ///
50    /// This implementation does not return an error.
51    fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> {
52        use crate::http::header::SET_COOKIE;
53
54        struct Cookies(Vec<Cookie<'static>>);
55
56        if self.message_extensions().get::<Cookies>().is_none() {
57            let mut cookies = Vec::new();
58            for hdr in self.message_headers().get_all(&SET_COOKIE) {
59                if let Ok(s) = std::str::from_utf8(hdr.as_bytes())
60                    && let Ok(cookie) = Cookie::parse_encoded(s)
61                {
62                    cookies.push(cookie.into_owned());
63                }
64            }
65            self.message_extensions_mut().insert(Cookies(cookies));
66        }
67        Ok(Ref::map(self.message_extensions(), |ext| {
68            &ext.get::<Cookies>().unwrap().0
69        }))
70    }
71}
72
73impl ClientResponse {
74    /// Creates a client response.
75    #[doc(hidden)]
76    pub fn new(head: ResponseHead, payload: Payload, config: Cfg<ClientConfig>) -> Self {
77        ClientResponse {
78            head,
79            config,
80            payload: Cell::new(Some(payload)),
81            taken_reported: Cell::new(false),
82        }
83    }
84
85    #[cfg(feature = "ws")]
86    pub(crate) fn with_empty_payload(head: ResponseHead, config: Cfg<ClientConfig>) -> Self {
87        ClientResponse::new(head, Payload::None, config)
88    }
89
90    #[inline]
91    pub(crate) fn head(&self) -> &ResponseHead {
92        &self.head
93    }
94
95    #[inline]
96    pub(crate) fn head_mut(&mut self) -> &mut ResponseHead {
97        &mut self.head
98    }
99
100    /// Returns the response HTTP version.
101    #[inline]
102    pub fn version(&self) -> Version {
103        self.head().version
104    }
105
106    /// Returns the response status.
107    #[inline]
108    pub fn status(&self) -> StatusCode {
109        self.head().status
110    }
111
112    #[inline]
113    /// Returns the first header value associated with `name`.
114    pub fn header<N: AsName>(&self, name: N) -> Option<&HeaderValue> {
115        self.head().headers.get(name)
116    }
117
118    #[inline]
119    /// Returns the response headers.
120    pub fn headers(&self) -> &HeaderMap {
121        &self.head().headers
122    }
123
124    #[inline]
125    /// Returns mutable access to the response headers.
126    pub fn headers_mut(&mut self) -> &mut HeaderMap {
127        &mut self.head_mut().headers
128    }
129
130    /// Replaces the response payload.
131    ///
132    /// Any unread previous payload is dropped. The response can be read again
133    /// even if its previous payload was already taken.
134    pub fn set_payload(&self, payload: Payload) {
135        self.payload.set(Some(payload));
136        self.taken_reported.set(false);
137    }
138
139    #[must_use]
140    /// Takes the response payload.
141    ///
142    /// Subsequent calls return an empty payload. After the payload is taken,
143    /// [`body()`](Self::body), [`json()`](Self::json) and the response stream
144    /// report [`PayloadError::AlreadyTaken`] instead of an empty body.
145    pub fn take_payload(&self) -> Payload {
146        if let Some(pl) = self.payload.take() {
147            pl
148        } else {
149            Payload::None
150        }
151    }
152
153    /// Returns the response extensions.
154    #[inline]
155    pub fn extensions(&self) -> Ref<'_, Extensions> {
156        self.head().extensions()
157    }
158
159    /// Returns mutable access to the response extensions.
160    #[inline]
161    pub fn extensions_mut(&self) -> RefMut<'_, Extensions> {
162        self.head().extensions_mut()
163    }
164}
165
166impl ClientResponse {
167    /// Returns a future that buffers the response body.
168    ///
169    /// The response payload is taken when this method is called, not when the
170    /// future is first polled. Dropping the future without awaiting it
171    /// discards the body. Once the payload has been taken, by this method,
172    /// [`json()`](Self::json), [`take_payload()`](Self::take_payload) or the
173    /// response stream, a later `body()` fails with
174    /// [`PayloadError::AlreadyTaken`]. A response without a body still yields
175    /// empty bytes. That includes bodiless responses (`HEAD` requests, `204`,
176    /// `304`): their `Content-Length` is not checked against the limit.
177    ///
178    /// To keep the raw body when JSON parsing fails, buffer it once and parse
179    /// the retained bytes:
180    ///
181    /// ```rust,no_run
182    /// # async fn read(res: ntex::client::ClientResponse) -> Result<(), Box<dyn std::error::Error>> {
183    /// let body = res.body().await?;
184    /// match serde_json::from_slice::<serde_json::Value>(&body) {
185    ///     Ok(value) => println!("json: {value}"),
186    ///     Err(_) => println!("raw: {} bytes", body.len()),
187    /// }
188    /// # Ok(())
189    /// # }
190    /// ```
191    pub fn body(&self) -> MessageBody {
192        MessageBody::new(self)
193    }
194
195    /// Returns a future that buffers and deserializes a JSON response body.
196    ///
197    /// The future returns an error when:
198    ///
199    /// * the content type is not JSON;
200    /// * the body exceeds the configured response payload limit; or
201    /// * reading or deserializing the body fails.
202    ///
203    /// A JSON content type is checked before the payload is taken, so a
204    /// content-type error leaves the body available. Otherwise the payload is
205    /// taken when this method is called, as with [`body()`](Self::body): a
206    /// dropped future or a deserialization failure leaves no body, and later
207    /// reads fail with [`PayloadError::AlreadyTaken`]. Use `body()` and
208    /// `serde_json::from_slice()` to keep the raw bytes.
209    pub fn json<T: DeserializeOwned>(&self) -> JsonBody<T> {
210        JsonBody::new(self)
211    }
212}
213
214impl Stream for ClientResponse {
215    type Item = Result<Bytes, Error<ClientPayloadError>>;
216
217    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
218        if let Some(mut pl) = self.payload.take() {
219            let result = Pin::new(&mut pl).poll_next(cx);
220            self.payload.set(Some(pl));
221            Poll::Ready(
222                ready!(result).map(|item| item.map_err(|e| Error::from(ClientPayloadError(e)))),
223            )
224        } else if self.taken_reported.replace(true) {
225            Poll::Ready(None)
226        } else {
227            Poll::Ready(Some(Err(Error::from(ClientPayloadError(
228                PayloadError::AlreadyTaken,
229            )))))
230        }
231    }
232}
233
234impl From<ServiceResponse> for ClientResponse {
235    fn from(res: ServiceResponse) -> Self {
236        Self {
237            head: res.head,
238            payload: Cell::new(Some(res.payload)),
239            taken_reported: Cell::new(false),
240            config: res.config,
241        }
242    }
243}
244
245impl fmt::Debug for ClientResponse {
246    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
247        writeln!(f, "\nClientResponse {:?} {}", self.version(), self.status())?;
248        writeln!(f, "  headers:")?;
249        for (key, val) in self.headers() {
250            writeln!(f, "    {key:?}: {val:?}")?;
251        }
252        Ok(())
253    }
254}
255
256#[derive(Debug)]
257/// Future that buffers a complete HTTP response body.
258pub struct MessageBody {
259    length: Option<usize>,
260    err: Option<Error<ClientPayloadError>>,
261    fut: Option<ReadBody>,
262    config: Cfg<ClientConfig>,
263}
264
265impl MessageBody {
266    /// Creates a body future for `res`.
267    ///
268    /// This takes the response payload. If the payload was already taken, the
269    /// future fails with [`PayloadError::AlreadyTaken`].
270    pub fn new(res: &ClientResponse) -> MessageBody {
271        let config = res.config.clone();
272
273        let len = match content_length(res) {
274            Ok(len) => len,
275            Err(e) => return Self::err(Error::from(e).with_service(config.service()), config),
276        };
277
278        let Some(payload) = res.payload.take() else {
279            return Self::err(
280                Error::from(ClientPayloadError(PayloadError::AlreadyTaken))
281                    .with_service(config.service()),
282                config,
283            );
284        };
285
286        MessageBody {
287            config,
288            length: len,
289            err: None,
290            fut: Some(ReadBody::new(
291                payload,
292                res.config.response_payload_limit(),
293                res.config.response_payload_timeout(),
294                res.config.clone(),
295            )),
296        }
297    }
298
299    #[must_use]
300    /// Sets the maximum buffered payload size.
301    ///
302    /// The default is 256 KiB. A value of zero disables the limit.
303    pub fn limit(mut self, limit: usize) -> Self {
304        if let Some(ref mut fut) = self.fut {
305            fut.limit = limit;
306        }
307        self
308    }
309
310    #[must_use]
311    /// Sets the timeout for reading the complete payload.
312    ///
313    /// The default is 10 seconds. A zero duration disables the timeout.
314    pub fn timeout<T: Into<Millis>>(mut self, to: T) -> Self {
315        if let Some(ref mut fut) = self.fut {
316            fut.timeout.reset(to.into());
317        }
318        self
319    }
320
321    fn err(e: Error<ClientPayloadError>, config: Cfg<ClientConfig>) -> Self {
322        MessageBody {
323            config,
324            fut: None,
325            err: Some(e),
326            length: None,
327        }
328    }
329}
330
331impl Future for MessageBody {
332    type Output = Result<Bytes, Error<ClientPayloadError>>;
333
334    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
335        let this = self.get_mut();
336
337        if let Some(err) = this.err.take() {
338            return Poll::Ready(Err(err));
339        }
340
341        if let Some(len) = this.length.take() {
342            let limit = this.fut.as_ref().unwrap().limit;
343            if limit > 0 && len > limit {
344                return Poll::Ready(Err(Error::from(ClientPayloadError(PayloadError::Overflow))
345                    .with_service(this.config.service())));
346            }
347        }
348
349        Pin::new(&mut *this.fut.as_mut().unwrap())
350            .poll(cx)
351            .map_err(|e| e.map(ClientPayloadError::from))
352    }
353}
354
355#[derive(Debug)]
356/// Future that buffers and deserializes a JSON response body.
357///
358/// The future returns an error when:
359///
360/// * the content type is not JSON;
361/// * the body exceeds the configured response payload limit; or
362/// * reading or deserializing the body fails.
363pub struct JsonBody<U> {
364    length: Option<usize>,
365    err: Option<Error<JsonPayloadError>>,
366    fut: Option<ReadBody>,
367    config: Cfg<ClientConfig>,
368    _t: PhantomData<U>,
369}
370
371impl<U> JsonBody<U>
372where
373    U: DeserializeOwned,
374{
375    #[must_use]
376    /// Creates a JSON body future for `res`.
377    ///
378    /// This takes the response payload unless the content type is not JSON. If
379    /// the payload was already taken, the future fails with
380    /// [`PayloadError::AlreadyTaken`].
381    pub fn new(res: &ClientResponse) -> Self {
382        let config = res.config.clone();
383
384        // check content-type
385        let json = if let Ok(Some(mime)) = res.mime_type() {
386            mime.subtype() == mime::JSON || mime.suffix() == Some(mime::JSON)
387        } else {
388            false
389        };
390        if !json {
391            let err =
392                Some(Error::from(JsonPayloadError::ContentType).with_service(config.service()));
393            return JsonBody {
394                err,
395                config,
396                length: None,
397                fut: None,
398                _t: PhantomData,
399            };
400        }
401
402        let len = match content_length(res) {
403            Ok(len) => len,
404            Err(e) => {
405                return JsonBody {
406                    err: Some(
407                        Error::from(JsonPayloadError::Payload(e)).with_service(config.service()),
408                    ),
409                    config,
410                    length: None,
411                    fut: None,
412                    _t: PhantomData,
413                };
414            }
415        };
416
417        let Some(payload) = res.payload.take() else {
418            return JsonBody {
419                err: Some(
420                    Error::from(JsonPayloadError::Payload(ClientPayloadError(
421                        PayloadError::AlreadyTaken,
422                    )))
423                    .with_service(config.service()),
424                ),
425                config,
426                length: None,
427                fut: None,
428                _t: PhantomData,
429            };
430        };
431
432        JsonBody {
433            config,
434            length: len,
435            err: None,
436            fut: Some(ReadBody::new(
437                payload,
438                res.config.response_payload_limit(),
439                res.config.response_payload_timeout(),
440                res.config.clone(),
441            )),
442            _t: PhantomData,
443        }
444    }
445
446    #[must_use]
447    /// Sets the maximum buffered payload size.
448    ///
449    /// The default is 256 KiB. A value of zero disables the limit.
450    pub fn limit(mut self, limit: usize) -> Self {
451        if let Some(ref mut fut) = self.fut {
452            fut.limit = limit;
453        }
454        self
455    }
456
457    #[must_use]
458    /// Sets the timeout for reading the complete payload.
459    ///
460    /// The default is 10 seconds. A zero duration disables the timeout.
461    pub fn timeout<T: Into<Millis>>(mut self, to: T) -> Self {
462        if let Some(ref mut fut) = self.fut {
463            fut.timeout.reset(to.into());
464        }
465        self
466    }
467}
468
469impl<U> Unpin for JsonBody<U> where U: DeserializeOwned {}
470
471impl<U> Future for JsonBody<U>
472where
473    U: DeserializeOwned,
474{
475    type Output = Result<U, Error<JsonPayloadError>>;
476
477    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
478        if let Some(err) = self.err.take() {
479            return Poll::Ready(Err(err));
480        }
481
482        if let Some(len) = self.length.take() {
483            let limit = self.fut.as_ref().unwrap().limit;
484            if limit > 0 && len > limit {
485                return Poll::Ready(Err(Error::from(JsonPayloadError::Payload(
486                    ClientPayloadError(PayloadError::Overflow),
487                ))
488                .with_service(self.config.service())));
489            }
490        }
491
492        let this = self.get_mut();
493        let body = match Pin::new(&mut *this.fut.as_mut().unwrap()).poll(cx) {
494            Poll::Ready(result) => result.map_err(|e| e.map(JsonPayloadError::from))?,
495            Poll::Pending => return Poll::Pending,
496        };
497        Poll::Ready(crate::http::json::from_slice::<U>(&body).map_err(|e| {
498            Error::from(JsonPayloadError::from(e)).with_service(this.config.service())
499        }))
500    }
501}
502
503/// Parses the response `Content-Length` header.
504///
505/// Returns `None` for bodiless responses (`HEAD` requests, `1xx`, `204`,
506/// `304`), which the protocol layer marks with [`Payload::None`]. Their
507/// `Content-Length` describes a representation that is not sent, so it must
508/// not be checked against the payload limit.
509fn content_length(res: &ClientResponse) -> Result<Option<usize>, ClientPayloadError> {
510    let payload = res.payload.take();
511    let bodiless = matches!(payload, Some(Payload::None));
512    res.payload.set(payload);
513    if bodiless {
514        return Ok(None);
515    }
516
517    res.headers()
518        .get(&CONTENT_LENGTH)
519        .map(|l| {
520            l.to_str()
521                .ok()
522                .and_then(|s| s.parse::<usize>().ok())
523                .ok_or(ClientPayloadError(PayloadError::UnknownLength))
524        })
525        .transpose()
526}
527
528#[derive(Debug)]
529struct ReadBody {
530    stream: Payload,
531    buf: BytesMut,
532    limit: usize,
533    timeout: Deadline,
534    config: Cfg<ClientConfig>,
535}
536
537impl ReadBody {
538    fn new(stream: Payload, limit: usize, timeout: Millis, config: Cfg<ClientConfig>) -> Self {
539        Self {
540            stream,
541            limit,
542            config,
543            buf: BytesMut::with_capacity(std::cmp::min(limit, 32768)),
544            timeout: Deadline::new(timeout),
545        }
546    }
547}
548
549impl Future for ReadBody {
550    type Output = Result<Bytes, Error<ClientPayloadError>>;
551
552    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
553        let this = self.get_mut();
554
555        loop {
556            return match Pin::new(&mut this.stream).poll_next(cx) {
557                Poll::Ready(Some(Ok(chunk))) => {
558                    if this.limit > 0 && (this.buf.len() + chunk.len()) > this.limit {
559                        Poll::Ready(Err(Error::from(ClientPayloadError(PayloadError::Overflow))
560                            .with_service(this.config.service())))
561                    } else {
562                        this.buf.extend_from_slice(&chunk);
563                        continue;
564                    }
565                }
566                Poll::Ready(None) => Poll::Ready(Ok(take_trimmed(&mut this.buf))),
567                Poll::Ready(Some(Err(err))) => Poll::Ready(Err(Error::from(ClientPayloadError(
568                    err,
569                ))
570                .with_service(this.config.service()))),
571                Poll::Pending => {
572                    if this.timeout.poll_elapsed(cx).is_ready() {
573                        Poll::Ready(Err(Error::from(ClientPayloadError(
574                            PayloadError::Incomplete(Some(std::io::Error::new(
575                                std::io::ErrorKind::TimedOut,
576                                "Operation timed out",
577                            ))),
578                        ))
579                        .with_service(this.config.service())))
580                    } else {
581                        Poll::Pending
582                    }
583                }
584            };
585        }
586    }
587}
588
589#[cfg(test)]
590mod tests {
591    use serde::{Deserialize, Serialize};
592
593    use super::*;
594    use crate::client::{error::ClientPayloadError, test::TestResponse};
595    use crate::http::header;
596
597    /// STATEMENT: Body collection validates length and size limits and returns a compact payload.
598    ///
599    /// HOW:
600    /// - Collect malformed-length, oversized, limited, and valid bodies and inspect errors or bytes.
601    /// - Trim a collected large body and verify its data pointer stays unchanged.
602    #[crate::rt_test]
603    async fn test_body() {
604        let req = TestResponse::with_header(header::CONTENT_LENGTH, "xxxx").build();
605        match &*req.body().await.err().unwrap().into_error() {
606            PayloadError::UnknownLength => (),
607            _ => unreachable!("error"),
608        }
609
610        let req = TestResponse::with_header(header::CONTENT_LENGTH, "1000000").build();
611        match &*req.body().await.err().unwrap().into_error() {
612            PayloadError::Overflow => (),
613            _ => unreachable!("error"),
614        }
615
616        let req = TestResponse::builder()
617            .set_payload(Bytes::from_static(b"test"))
618            .build();
619        assert_eq!(req.body().await.ok().unwrap(), Bytes::from_static(b"test"));
620
621        let req = TestResponse::builder()
622            .set_payload(Bytes::from_static(b"11111111111111"))
623            .build();
624        match &*req.body().limit(5).await.err().unwrap().into_error() {
625            PayloadError::Overflow => (),
626            _ => unreachable!("error"),
627        }
628
629        // the body does not keep the unused part of the buffer
630        let req = TestResponse::builder()
631            .set_payload(Bytes::from(vec![b'x'; 1000]))
632            .build();
633        let mut body = req.body().await.ok().unwrap();
634        let ptr = body.as_ptr();
635        body.trimdown();
636        assert_eq!(body, [b'x'; 1000][..]);
637        assert_eq!(body.as_ptr(), ptr, "the body has no unused space");
638    }
639
640    #[derive(Serialize, Deserialize, PartialEq, Debug)]
641    struct MyObject {
642        name: String,
643    }
644
645    fn json_eq(err: &JsonPayloadError, other: &JsonPayloadError) -> bool {
646        match err {
647            JsonPayloadError::Payload(ClientPayloadError(PayloadError::Overflow)) => {
648                matches!(
649                    other,
650                    JsonPayloadError::Payload(ClientPayloadError(PayloadError::Overflow))
651                )
652            }
653            JsonPayloadError::Payload(ClientPayloadError(PayloadError::UnknownLength)) => {
654                matches!(
655                    other,
656                    JsonPayloadError::Payload(ClientPayloadError(PayloadError::UnknownLength))
657                )
658            }
659            JsonPayloadError::ContentType => matches!(other, JsonPayloadError::ContentType),
660            _ => false,
661        }
662    }
663
664    /// STATEMENT: Bodiless responses skip the declared `Content-Length` checks.
665    ///
666    /// HOW:
667    /// - Build responses with an oversized or malformed `Content-Length` and
668    ///   replace their payload with `Payload::None`.
669    /// - Assert `body()` returns empty bytes and `json()` fails while parsing
670    ///   instead of with `Overflow` or `UnknownLength`.
671    #[crate::rt_test]
672    async fn test_bodiless_response_ignores_content_length() {
673        for len in ["1000000", "xxxx"] {
674            let res = TestResponse::with_header(header::CONTENT_LENGTH, len).build();
675            res.set_payload(Payload::None);
676            assert_eq!(res.body().await.unwrap(), Bytes::new());
677
678            let res = TestResponse::with_header(header::CONTENT_LENGTH, len)
679                .header(header::CONTENT_TYPE, "application/json")
680                .build();
681            res.set_payload(Payload::None);
682            let err = res.json::<MyObject>().await.unwrap_err();
683            assert!(matches!(&*err, JsonPayloadError::Deserialize(_)), "{err:?}");
684        }
685    }
686
687    /// STATEMENT: JSON collection validates content type and payload length before deserialization.
688    ///
689    /// HOW:
690    /// - Exercise absent/wrong media types, oversized and invalid lengths, and a valid object.
691    /// - Compare error categories and the successfully deserialized value.
692    #[crate::rt_test]
693    async fn test_json_body() {
694        let req = TestResponse::builder().build();
695        let json = JsonBody::<MyObject>::new(&req).await;
696        assert!(json_eq(
697            &json.err().unwrap(),
698            &JsonPayloadError::ContentType
699        ));
700
701        let req = TestResponse::builder()
702            .header(
703                header::CONTENT_TYPE,
704                header::HeaderValue::from_static("application/text"),
705            )
706            .build();
707        let json = JsonBody::<MyObject>::new(&req).await;
708        assert!(json_eq(
709            &json.err().unwrap(),
710            &JsonPayloadError::ContentType
711        ));
712
713        let req = TestResponse::builder()
714            .header(
715                header::CONTENT_TYPE,
716                header::HeaderValue::from_static("application/json"),
717            )
718            .header(
719                header::CONTENT_LENGTH,
720                header::HeaderValue::from_static("10000"),
721            )
722            .build();
723
724        let json = JsonBody::<MyObject>::new(&req).limit(100).await;
725        assert!(json_eq(
726            &json.err().unwrap(),
727            &JsonPayloadError::Payload(ClientPayloadError(PayloadError::Overflow))
728        ));
729
730        let req = TestResponse::with_header(header::CONTENT_TYPE, "application/json")
731            .header(header::CONTENT_LENGTH, "xxxx")
732            .set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
733            .build();
734        let json = JsonBody::<MyObject>::new(&req).await;
735        assert!(json_eq(
736            &json.err().unwrap(),
737            &JsonPayloadError::Payload(ClientPayloadError(PayloadError::UnknownLength))
738        ));
739
740        let req = TestResponse::builder()
741            .header(
742                header::CONTENT_TYPE,
743                header::HeaderValue::from_static("application/json"),
744            )
745            .header(
746                header::CONTENT_LENGTH,
747                header::HeaderValue::from_static("16"),
748            )
749            .set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
750            .build();
751
752        let json = JsonBody::<MyObject>::new(&req).await;
753        assert_eq!(
754            json.ok().unwrap(),
755            MyObject {
756                name: "test".to_owned()
757            }
758        );
759    }
760
761    fn pending_payload() -> Payload {
762        Payload::Stream(Box::pin(futures_util::stream::pending()))
763    }
764
765    fn error_payload() -> Payload {
766        Payload::Stream(Box::pin(futures_util::stream::iter([
767            Ok(Bytes::from_static(b"{")),
768            Err(PayloadError::Incomplete(None)),
769        ])))
770    }
771
772    fn is_timeout(err: &PayloadError) -> bool {
773        matches!(err, PayloadError::Incomplete(Some(e)) if e.kind() == std::io::ErrorKind::TimedOut)
774    }
775
776    /// STATEMENT: Body futures propagate timeout and stream errors and take exclusive ownership of the payload.
777    ///
778    /// HOW:
779    /// - Collect pending and failing streams, then create two body futures for one response.
780    /// - Check the errors, verify the second future fails with `PayloadError::AlreadyTaken`, and
781    ///   verify the first future still receives the original bytes.
782    #[crate::rt_test]
783    async fn test_body_timeout_and_error() {
784        let res = TestResponse::builder().build();
785        res.set_payload(pending_payload());
786        let err = res.body().timeout(Millis(1)).await.unwrap_err();
787        assert!(is_timeout(&err.into_error().0));
788
789        let res = TestResponse::builder().build();
790        res.set_payload(error_payload());
791        let err = res.body().await.unwrap_err();
792        assert!(matches!(err.into_error().0, PayloadError::Incomplete(None)));
793
794        // the payload is taken by the first body future
795        let res = TestResponse::builder()
796            .set_payload(b"data".as_ref())
797            .build();
798        let body = res.body();
799        let err = res.body().await.unwrap_err();
800        assert!(matches!(err.into_error().0, PayloadError::AlreadyTaken));
801        assert_eq!(body.await.unwrap(), Bytes::from_static(b"data"));
802    }
803
804    /// STATEMENT: JSON collection distinguishes stream and deserialize failures and accepts JSON syntax suffixes.
805    ///
806    /// HOW:
807    /// - Use pending, failing, and type-invalid payloads and verify their error variants.
808    /// - Decode an `application/problem+json` response and check its object field.
809    #[crate::rt_test]
810    async fn test_json_timeout_and_errors() {
811        let res = TestResponse::with_header(header::CONTENT_TYPE, "application/json").build();
812        res.set_payload(pending_payload());
813        let err = res.json::<MyObject>().timeout(Millis(1)).await.unwrap_err();
814        let JsonPayloadError::Payload(ClientPayloadError(err)) = &*err else {
815            panic!("{err:?}")
816        };
817        assert!(is_timeout(err));
818
819        let res = TestResponse::with_header(header::CONTENT_TYPE, "application/json").build();
820        res.set_payload(error_payload());
821        let err = res.json::<MyObject>().await.unwrap_err();
822        assert!(matches!(
823            &*err,
824            JsonPayloadError::Payload(ClientPayloadError(PayloadError::Incomplete(None)))
825        ));
826
827        let res = TestResponse::with_header(header::CONTENT_TYPE, "application/json")
828            .set_payload(b"{\"name\": 1}".as_ref())
829            .build();
830        let err = res.json::<MyObject>().await.unwrap_err();
831        assert!(matches!(&*err, JsonPayloadError::Deserialize(Some(_))));
832
833        // a structured syntax suffix is json
834        let res = TestResponse::with_header(header::CONTENT_TYPE, "application/problem+json")
835            .set_payload(b"{\"name\": \"test\"}".as_ref())
836            .build();
837        assert_eq!(res.json::<MyObject>().await.unwrap().name, "test");
838    }
839
840    /// STATEMENT: Response streaming yields payload chunks and errors, and reports a taken payload once
841    /// before ending.
842    ///
843    /// HOW:
844    /// - Poll successful and failing response streams and inspect their items.
845    /// - Take a payload twice and verify the second take is empty, then verify the stream yields one
846    ///   `PayloadError::AlreadyTaken` error followed by `None`.
847    #[crate::rt_test]
848    async fn test_response_stream() {
849        use futures_util::StreamExt;
850
851        let mut res = TestResponse::builder()
852            .set_payload(b"data".as_ref())
853            .build();
854        assert_eq!(res.next().await.unwrap().unwrap(), "data");
855        assert!(res.next().await.is_none());
856
857        let mut res = TestResponse::builder().build();
858        res.set_payload(error_payload());
859        assert_eq!(res.next().await.unwrap().unwrap(), "{");
860        let err = res.next().await.unwrap().unwrap_err();
861        assert!(matches!(err.into_error().0, PayloadError::Incomplete(None)));
862
863        // the payload is taken
864        let mut res = TestResponse::builder()
865            .set_payload(b"data".as_ref())
866            .build();
867        assert!(matches!(
868            res.take_payload(),
869            Payload::Stream(_) | Payload::H1(_)
870        ));
871        assert!(matches!(res.take_payload(), Payload::None));
872        let err = res.next().await.unwrap().unwrap_err();
873        assert!(matches!(err.into_error().0, PayloadError::AlreadyTaken));
874        assert!(res.next().await.is_none());
875        assert!(res.next().await.is_none());
876    }
877
878    fn is_taken(err: Error<ClientPayloadError>) -> bool {
879        matches!(err.into_error().0, PayloadError::AlreadyTaken)
880    }
881
882    fn is_json_taken(err: &JsonPayloadError) -> bool {
883        matches!(
884            err,
885            JsonPayloadError::Payload(ClientPayloadError(PayloadError::AlreadyTaken))
886        )
887    }
888
889    /// STATEMENT: Reading a client response body after its payload was taken fails with
890    /// `PayloadError::AlreadyTaken` instead of returning an empty body, while real empty bodies,
891    /// JSON content-type rejection, buffer-once parsing and `set_payload()` keep working.
892    ///
893    /// HOW:
894    /// - Drop an unpolled `body()` future and assert later `body()`, `json()` and stream reads
895    ///   report `AlreadyTaken`, with the stream ending afterwards.
896    /// - Read a body twice and a response without a body twice; assert the first reads return the
897    ///   data or empty bytes and the second reads fail.
898    /// - Fail `json()` on malformed JSON and assert `body()` then reports `AlreadyTaken`.
899    /// - Reject a `text/plain` response in `json()` and assert `body()` still returns all bytes.
900    /// - Buffer a malformed JSON body once with `body()`, assert `serde_json::from_slice()` fails
901    ///   while the retained bytes are intact.
902    /// - Install a new payload with `set_payload()` after the stream reported the error and assert
903    ///   both `body()` and the stream can read again.
904    #[crate::rt_test]
905    async fn test_taken_payload_is_reported() {
906        use futures_util::StreamExt;
907
908        let mut res = TestResponse::with_header(header::CONTENT_TYPE, "application/json")
909            .set_payload(b"{\"name\": \"test\"}".as_ref())
910            .build();
911        drop(res.body());
912        assert!(is_taken(res.body().await.unwrap_err()));
913        assert!(is_json_taken(&res.json::<MyObject>().await.unwrap_err()));
914        assert!(is_taken(res.next().await.unwrap().unwrap_err()));
915        assert!(res.next().await.is_none());
916
917        let res = TestResponse::builder()
918            .set_payload(b"data".as_ref())
919            .build();
920        assert_eq!(res.body().await.unwrap(), "data");
921        assert!(is_taken(res.body().await.unwrap_err()));
922
923        let res = TestResponse::builder().build();
924        assert_eq!(res.body().await.unwrap(), Bytes::new());
925        assert!(is_taken(res.body().await.unwrap_err()));
926
927        let res = TestResponse::with_header(header::CONTENT_TYPE, "application/json")
928            .set_payload(b"{\"name\":".as_ref())
929            .build();
930        let err = res.json::<MyObject>().await.unwrap_err();
931        assert!(matches!(&*err, JsonPayloadError::Deserialize(Some(_))));
932        assert!(is_taken(res.body().await.unwrap_err()));
933
934        let res = TestResponse::with_header(header::CONTENT_TYPE, "text/plain")
935            .set_payload(b"{\"name\": \"test\"}".as_ref())
936            .build();
937        let err = res.json::<MyObject>().await.unwrap_err();
938        assert!(matches!(&*err, JsonPayloadError::ContentType));
939        assert_eq!(res.body().await.unwrap(), "{\"name\": \"test\"}");
940
941        let res = TestResponse::with_header(header::CONTENT_TYPE, "application/json")
942            .set_payload(b"{\"name\":".as_ref())
943            .build();
944        let body = res.body().await.unwrap();
945        assert!(serde_json::from_slice::<MyObject>(&body).is_err());
946        assert_eq!(body, "{\"name\":");
947
948        let mut res = TestResponse::builder().build();
949        drop(res.take_payload());
950        assert!(is_taken(res.next().await.unwrap().unwrap_err()));
951        res.set_payload(Payload::from(crate::channel::bstream::empty(Some(
952            Bytes::from_static(b"again"),
953        ))));
954        assert_eq!(res.next().await.unwrap().unwrap(), "again");
955        res.set_payload(Payload::from(crate::channel::bstream::empty(Some(
956            Bytes::from_static(b"again"),
957        ))));
958        assert_eq!(res.body().await.unwrap(), "again");
959        assert!(is_taken(res.next().await.unwrap().unwrap_err()));
960    }
961
962    /// STATEMENT: A malformed `Set-Cookie` header is skipped without hiding valid cookies.
963    ///
964    /// HOW:
965    /// - Build a client response with `Set-Cookie` headers `garbage`, a non-UTF-8 value, and
966    ///   `sid=ok; Path=/p`.
967    /// - Confirm `cookies` returns only `sid` and `cookie("sid")` keeps value `ok` and path `/p`.
968    #[cfg(feature = "cookie")]
969    #[test]
970    fn test_cookies_malformed_header() {
971        let res = TestResponse::with_header(header::SET_COOKIE, "garbage")
972            .header(
973                header::SET_COOKIE,
974                HeaderValue::from_bytes(b"c=\xff").unwrap(),
975            )
976            .header(header::SET_COOKIE, "sid=ok; Path=/p")
977            .build();
978        assert_eq!(res.cookies().unwrap().len(), 1);
979        let cookie = res.cookie("sid").unwrap();
980        assert_eq!((cookie.value(), cookie.path()), ("ok", Some("/p")));
981    }
982
983    /// STATEMENT: Response metadata mutations are visible through accessors and debug output.
984    ///
985    /// HOW:
986    /// - Set version, headers, and an extension, then inspect getters and the formatted response.
987    #[test]
988    fn test_response_accessors() {
989        let mut res = TestResponse::with_header(header::CONTENT_TYPE, "text/plain")
990            .version(Version::HTTP_2)
991            .build();
992        res.headers_mut()
993            .insert(header::SERVER, HeaderValue::from_static("test"));
994        assert_eq!(res.header(header::SERVER).unwrap(), "test");
995        assert_eq!(res.version(), Version::HTTP_2);
996
997        res.extensions_mut().insert(10u32);
998        assert_eq!(res.extensions().get::<u32>(), Some(&10));
999
1000        let s = format!("{res:?}");
1001        assert!(s.contains("ClientResponse HTTP/2.0 200 OK"), "{s}");
1002        assert!(s.contains("\"server\": \"test\""), "{s}");
1003    }
1004}