Skip to main content

eggfetch_core/
response.rs

1//! Incoming response type.
2//!
3//! A `Response` holds the HTTP status, version, headers, final URL, and a
4//! body handle. The body can be consumed in two ways:
5//!
6//! - **Buffered**: `bytes()` or `text()` collects the entire body.
7//! - **Streaming**: `bytes_stream()` yields decoded body chunks incrementally;
8//!   `raw_bytes_stream()` selects encoded chunks for compressed responses.
9//!
10//! # Body ownership
11//!
12//! The body can be consumed exactly once. After calling `bytes()`,
13//! `text()`, `bytes_stream()`, or `raw_bytes_stream()`, further reads return
14//! an error.
15
16use std::pin::Pin;
17use std::task::{Context, Poll};
18
19use bytes::{Bytes, BytesMut};
20use futures_core::Stream;
21use http::{HeaderMap, StatusCode, Version};
22use url::Url;
23
24use crate::body::{BoxBytesStream, ResponseBody, SharedTrailers};
25use crate::error::Result;
26use crate::network_stream::NetworkStream;
27
28/// A metadata-only snapshot of a redirect response.
29///
30/// History entries intentionally omit the response body. This makes it
31/// structurally impossible for redirect history to retain active body
32/// streams or pool permits.
33#[derive(Clone)]
34pub struct HistoryEntry {
35    status: StatusCode,
36    version: Version,
37    headers: HeaderMap,
38    url: Url,
39    reason_phrase: String,
40}
41
42impl std::fmt::Debug for HistoryEntry {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        f.debug_struct("HistoryEntry")
45            .field("status", &self.status)
46            .field("version", &self.version)
47            .field("headers", &redacted_headers(&self.headers))
48            .field("url", &redacted_url(&self.url))
49            .field("reason_phrase", &self.reason_phrase)
50            .finish()
51    }
52}
53
54impl HistoryEntry {
55    /// Create a history entry from a response that has already been
56    /// drained (body consumed).
57    pub(crate) fn from_response(response: &Response) -> Self {
58        let reason = response
59            .wire_reason_phrase
60            .clone()
61            .or_else(|| response.status.canonical_reason().map(str::to_owned))
62            .unwrap_or_default();
63        Self {
64            status: response.status,
65            version: response.version,
66            headers: response.headers.clone(),
67            url: response.url.clone(),
68            reason_phrase: reason,
69        }
70    }
71
72    /// Returns the HTTP status code.
73    #[must_use]
74    pub fn status(&self) -> StatusCode {
75        self.status
76    }
77
78    /// Returns the HTTP version.
79    #[must_use]
80    pub fn version(&self) -> Version {
81        self.version
82    }
83
84    /// Returns the response headers.
85    #[must_use]
86    pub fn headers(&self) -> &HeaderMap {
87        &self.headers
88    }
89
90    /// Returns the URL.
91    #[must_use]
92    pub fn url(&self) -> &Url {
93        &self.url
94    }
95
96    /// Returns the reason phrase.
97    #[must_use]
98    pub fn reason_phrase(&self) -> &str {
99        &self.reason_phrase
100    }
101}
102
103/// An HTTP response.
104///
105/// # Trailers
106///
107/// HTTP trailers (HTTP/1.1 chunked trailers, HTTP/2 trailing HEADERS, and
108/// HTTP/3 trailing headers where the h3 crate exposes them) are captured
109/// without buffering the body. The body stream yields data frames exactly
110/// as before; when the trailing-headers frame arrives it is stored and the
111/// stream ends normally. Use [`Self::trailers`] after fully consuming the
112/// body (`bytes()`, `bytes_stream()` to EOF) to retrieve them.
113///
114/// Lifecycle: `trailers()` returns `None` until the body has advanced far
115/// enough for trailers to arrive, when the response carried no trailers,
116/// or when a body error occurred before trailers (errors remain body
117/// errors, never fabricated trailer state). Partial consumption or early
118/// drop never reports trailers and releases the pool permit without
119/// waiting for them. Read timeouts apply while waiting for trailers at
120/// the body boundary; the explicit native `total` deadline bounds
121/// transport setup and is not restarted per trailer wait.
122pub struct Response {
123    status: StatusCode,
124    version: Version,
125    headers: HeaderMap,
126    url: Url,
127    /// Original wire value retained for compatibility adapters that expose
128    /// response metadata after automatic decompression.
129    wire_content_encoding: Option<String>,
130    /// Original wire value retained for compatibility adapters that expose
131    /// response metadata after automatic decompression.
132    wire_content_length: Option<String>,
133    /// Original wire reason phrase from the HTTP status line.
134    ///
135    /// HTTP/1.x responses include a reason phrase after the status code.
136    /// This field preserves the original wire bytes so compatibility
137    /// adapters can expose the exact phrase rather than deriving one from
138    /// the status code alone. HTTP/2 has no wire reason phrase; this
139    /// field will be `None` for H2 responses.
140    wire_reason_phrase: Option<String>,
141    pub(crate) body: ResponseBody,
142    history: Vec<HistoryEntry>,
143    /// Shared trailer store populated as the body stream advances.
144    ///
145    /// Cloned into the body stream at construction so `trailers()` stays
146    /// available after `bytes()` collection. `None` until trailers arrive.
147    trailers: SharedTrailers,
148    /// Optional network stream handle for connection metadata and
149    /// upgraded-connection IO. Set for responses where the underlying
150    /// transport metadata is available:
151    ///
152    /// - **101 Switching Protocols**: set to `NetworkStream::Upgraded`
153    ///   with full IO access.
154    /// - **Successful CONNECT (200)**: set to `NetworkStream::Upgraded`
155    ///   when the tunnel is established (handled in the proxy path).
156    /// - **Ordinary HTTP/1.1 and HTTP/2 responses**: always `None`.
157    ///   Hyper's connection pool retains ownership of the socket and
158    ///   does not expose per-response socket metadata. Raw IO would
159    ///   corrupt pool state. This is a documented bounded difference
160    ///   from httpcore, which owns its connections directly.
161    network_stream: Option<NetworkStream>,
162}
163
164impl std::fmt::Debug for Response {
165    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166        f.debug_struct("Response")
167            .field("status", &self.status)
168            .field("version", &self.version)
169            .field("headers", &redacted_headers(&self.headers))
170            .field("url", &redacted_url(&self.url))
171            .field("wire_content_encoding", &self.wire_content_encoding)
172            .field("wire_content_length", &self.wire_content_length)
173            .field("wire_reason_phrase", &self.wire_reason_phrase)
174            .field("body", &self.body)
175            .field("history", &self.history)
176            .field(
177                "trailers",
178                &self.trailers.get().map(|h| redacted_headers(&h)),
179            )
180            .field(
181                "network_stream",
182                &self.network_stream.as_ref().map(|_| "..."),
183            )
184            .finish()
185    }
186}
187
188fn redacted_headers(headers: &HeaderMap) -> HeaderMap {
189    crate::redact::redact_headers(headers)
190}
191
192fn redacted_url(url: &Url) -> String {
193    crate::redact::redact_url(url)
194}
195
196impl Response {
197    /// Create a new response (crate-internal).
198    pub(crate) fn new(
199        status: StatusCode,
200        version: Version,
201        headers: HeaderMap,
202        url: Url,
203        body: ResponseBody,
204    ) -> Self {
205        let wire_content_encoding = headers
206            .get("content-encoding")
207            .and_then(|value| value.to_str().ok())
208            .map(ToOwned::to_owned);
209        let wire_content_length = headers
210            .get("content-length")
211            .and_then(|value| value.to_str().ok())
212            .map(ToOwned::to_owned);
213        Self {
214            status,
215            version,
216            headers,
217            url,
218            wire_content_encoding,
219            wire_content_length,
220            wire_reason_phrase: None,
221            body,
222            history: Vec::new(),
223            trailers: SharedTrailers::new(),
224            network_stream: None,
225        }
226    }
227
228    /// Replace the body of this response. Crate-internal: used to attach
229    /// a leased body after pool acquisition.
230    pub(crate) fn set_body(&mut self, body: ResponseBody) {
231        self.body = body;
232    }
233
234    /// Attach the shared trailer store linked to the body stream.
235    ///
236    /// Transports create one [`SharedTrailers`], hand a clone to the
237    /// streaming adapter, and install the same instance here so
238    /// [`Self::trailers`] observes trailers populated during streaming.
239    pub(crate) fn set_trailers(&mut self, trailers: SharedTrailers) {
240        self.trailers = trailers;
241    }
242
243    /// Returns received HTTP trailers, if any.
244    ///
245    /// Returns `None` until the body has been fully consumed and trailers
246    /// have arrived, when the response carried no trailers, or when a body
247    /// error occurred before trailers. Duplicate/multi-value trailing
248    /// headers are preserved in the returned [`HeaderMap`].
249    ///
250    /// This never buffers the body: drive the body to EOF via `bytes()` or
251    /// `bytes_stream()` first, then call this method.
252    #[must_use]
253    pub fn trailers(&self) -> Option<HeaderMap> {
254        self.trailers.get()
255    }
256
257    /// Consume the response and return its body.
258    #[allow(dead_code)]
259    pub(crate) fn into_body(self) -> ResponseBody {
260        self.body
261    }
262
263    /// Returns the HTTP status code.
264    #[must_use]
265    pub fn status(&self) -> StatusCode {
266        self.status
267    }
268
269    /// Returns the HTTP version.
270    #[must_use]
271    pub fn version(&self) -> Version {
272        self.version
273    }
274
275    /// Returns the response headers.
276    #[must_use]
277    pub fn headers(&self) -> &HeaderMap {
278        &self.headers
279    }
280
281    /// Returns a mutable reference to the response headers.
282    pub fn headers_mut(&mut self) -> &mut HeaderMap {
283        &mut self.headers
284    }
285
286    /// Returns the original wire `Content-Encoding` value, if present.
287    ///
288    /// Automatic decompression may remove this value from [`Self::headers`];
289    /// compatibility adapters can use this read-only snapshot to preserve
290    /// wire metadata without changing the core decoded-header policy.
291    #[must_use]
292    pub fn wire_content_encoding(&self) -> Option<&str> {
293        self.wire_content_encoding.as_deref()
294    }
295
296    /// Returns the original wire `Content-Length` value, if present.
297    ///
298    /// The value describes encoded wire bytes and is never derived from the
299    /// decompressed response body.
300    #[must_use]
301    pub fn wire_content_length(&self) -> Option<&str> {
302        self.wire_content_length.as_deref()
303    }
304
305    /// Returns the original wire reason phrase, if present.
306    ///
307    /// HTTP/1.x responses include a reason phrase after the status code.
308    /// This preserves the original wire bytes rather than deriving from
309    /// the status code alone. HTTP/2 has no wire reason phrase.
310    #[must_use]
311    pub fn wire_reason_phrase(&self) -> Option<&str> {
312        self.wire_reason_phrase.as_deref()
313    }
314
315    /// Set the wire reason phrase for this response.
316    ///
317    /// Used by transports that parse the HTTP/1.x status line directly
318    /// and can extract the original reason phrase.
319    #[allow(dead_code)]
320    pub(crate) fn set_wire_reason_phrase(&mut self, reason: Option<String>) {
321        self.wire_reason_phrase = reason;
322    }
323
324    /// Returns the final URL of the response (after any redirects).
325    #[must_use]
326    pub fn url(&self) -> &Url {
327        &self.url
328    }
329
330    /// Returns the redirect history (prior responses in order).
331    #[must_use]
332    pub fn history(&self) -> &[HistoryEntry] {
333        &self.history
334    }
335
336    /// Returns a mutable reference to the redirect history.
337    pub fn history_mut(&mut self) -> &mut Vec<HistoryEntry> {
338        &mut self.history
339    }
340
341    /// Set the redirect history.
342    pub(crate) fn set_history(&mut self, history: Vec<HistoryEntry>) {
343        self.history = history;
344    }
345
346    /// Returns `true` if the status code indicates success (2xx).
347    #[must_use]
348    pub fn is_success(&self) -> bool {
349        self.status.is_success()
350    }
351
352    /// Returns a reference to the response body.
353    #[must_use]
354    pub fn body(&self) -> &ResponseBody {
355        &self.body
356    }
357
358    /// Returns a mutable reference to the response body.
359    pub fn body_mut(&mut self) -> &mut ResponseBody {
360        &mut self.body
361    }
362
363    /// Consume the response and return the body bytes.
364    ///
365    /// For buffered bodies, this is O(1). For streaming bodies, this
366    /// collects all chunks.
367    ///
368    /// # Errors
369    ///
370    /// Returns an error if the body has already been consumed or if a
371    /// stream chunk fails.
372    pub async fn bytes(&mut self) -> Result<Bytes> {
373        self.body.bytes().await
374    }
375
376    /// Consume the response and return the body as a UTF-8 string.
377    ///
378    /// # Errors
379    ///
380    /// Returns an error if the body is not valid UTF-8 or has already
381    /// been consumed.
382    pub async fn text(&mut self) -> Result<String> {
383        self.body.text().await
384    }
385
386    /// Consume the response body and return a stream of byte chunks.
387    ///
388    /// For buffered bodies, yields the entire body as a single chunk.
389    /// For streaming bodies, yields chunks incrementally.
390    ///
391    /// # Errors
392    ///
393    /// Returns an error if the body has already been consumed.
394    pub fn bytes_stream(&mut self) -> Result<BoxBytesStream> {
395        self.body.bytes_stream()
396    }
397
398    /// Consume the response body and return encoded byte chunks.
399    ///
400    /// Compressed streaming responses select the original encoded transport
401    /// body. Raw and decoded body selection are mutually exclusive and
402    /// single-consumption operations.
403    ///
404    /// # Errors
405    ///
406    /// Returns an error if the response body has already been consumed.
407    pub fn raw_bytes_stream(&mut self) -> Result<BoxBytesStream> {
408        self.body.raw_bytes_stream()
409    }
410
411    /// Consume the response body and return a stream of text lines.
412    ///
413    /// Each line is decoded as UTF-8 without the trailing newline.
414    /// Incomplete lines at chunk boundaries are buffered until the
415    /// next chunk completes them.
416    ///
417    /// # Errors
418    ///
419    /// Returns an error if the body has already been consumed or if a
420    /// chunk contains invalid UTF-8.
421    pub fn text_lines(&mut self) -> Result<impl Stream<Item = Result<String>>> {
422        let byte_stream = self.bytes_stream()?;
423        Ok(LineStream::new(byte_stream))
424    }
425
426    /// Returns a reference to the network stream handle, if available.
427    ///
428    /// For upgraded connections (101/CONNECT), this provides full
429    /// IO access. For ordinary pooled connections, this provides
430    /// read-only metadata.
431    #[must_use]
432    pub fn network_stream(&self) -> Option<&NetworkStream> {
433        self.network_stream.as_ref()
434    }
435
436    /// Returns a mutable reference to the network stream handle.
437    pub fn network_stream_mut(&mut self) -> Option<&mut NetworkStream> {
438        self.network_stream.as_mut()
439    }
440
441    /// Take the network stream out of the response, leaving `None` in
442    /// its place. This is the canonical way to obtain ownership of an
443    /// upgraded stream while still keeping the rest of the response.
444    #[must_use]
445    pub fn take_network_stream(&mut self) -> Option<NetworkStream> {
446        self.network_stream.take()
447    }
448
449    /// Set the network stream handle for this response.
450    pub(crate) fn set_network_stream(&mut self, stream: NetworkStream) {
451        self.network_stream = Some(stream);
452    }
453
454    /// Consume the response and return the network stream, if any.
455    ///
456    /// This is the primary way to obtain ownership of an upgraded
457    /// stream (101 Switching Protocols or successful CONNECT).
458    #[must_use]
459    pub fn into_network_stream(self) -> Option<NetworkStream> {
460        self.network_stream
461    }
462}
463
464/// Stream adapter that splits a byte stream into text lines.
465struct LineStream {
466    stream: BoxBytesStream,
467    buffer: BytesMut,
468}
469
470const MAX_LINE_LENGTH: usize = 1024 * 1024;
471
472impl LineStream {
473    fn new(stream: BoxBytesStream) -> Self {
474        Self {
475            stream,
476            buffer: BytesMut::new(),
477        }
478    }
479}
480
481impl Stream for LineStream {
482    type Item = Result<String>;
483
484    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
485        loop {
486            // Fast path: emit a line already sitting in the buffer. The
487            // length cap applies here too — a single chunk may carry an
488            // over-long line piggybacked behind a valid one.
489            if let Some(pos) = self.buffer.iter().position(|&b| b == b'\n') {
490                if pos > MAX_LINE_LENGTH {
491                    return Poll::Ready(Some(Err(crate::error::Error::Body(format!(
492                        "response line exceeded maximum length of {MAX_LINE_LENGTH} bytes"
493                    )))));
494                }
495                let line_bytes = self.buffer.split_to(pos + 1);
496                let mut line = &line_bytes[..line_bytes.len() - 1]; // strip \n
497                if line.ends_with(b"\r") {
498                    line = &line[..line.len() - 1];
499                }
500                let line = std::str::from_utf8(line)
501                    .map(str::to_owned)
502                    .map_err(|e| crate::error::Error::Body(e.to_string()))?;
503                return Poll::Ready(Some(Ok(line)));
504            }
505
506            // No newline yet; a partially assembled line must stay bounded.
507            if self.buffer.len() > MAX_LINE_LENGTH {
508                return Poll::Ready(Some(Err(crate::error::Error::Body(format!(
509                    "response line exceeded maximum length of {MAX_LINE_LENGTH} bytes"
510                )))));
511            }
512
513            // Pull more data. Ready chunks are drained in this loop rather
514            // than rescheduling through the executor per chunk.
515            match Pin::new(&mut self.stream).poll_next(cx) {
516                Poll::Ready(Some(Ok(chunk))) => {
517                    if chunk.is_empty() {
518                        // Empty chunks carry no data. Ignore them and let the
519                        // upstream stream determine whether another wake is
520                        // needed.
521                        continue;
522                    }
523                    // Bound the buffer before extending: a single chunk of
524                    // size `MAX+1` without a newline would otherwise push the
525                    // buffer to `MAX + chunk` before the next loop's limit
526                    // check. If the combined buffer would exceed `MAX` and
527                    // there is no newline within the first `MAX` bytes, reject
528                    // immediately without allocating the oversize tail.
529                    if self.buffer.len().saturating_add(chunk.len()) > MAX_LINE_LENGTH {
530                        let remaining = MAX_LINE_LENGTH.saturating_sub(self.buffer.len());
531                        // `buffer` is known to contain no newline (otherwise
532                        // we would have emitted at the top of the loop), so
533                        // only need to inspect the prefix of `chunk` that fits
534                        // within the limit.
535                        let prefix = &chunk[..remaining.min(chunk.len())];
536                        if !prefix.contains(&b'\n') {
537                            // Also check if chunk itself contains an overlong
538                            // line that straddles the boundary: if the first
539                            // newline in the full chunk is beyond `MAX`, the
540                            // first line is already overlong.
541                            if let Some(pos) = chunk.iter().position(|&b| b == b'\n') {
542                                if self.buffer.len() + pos > MAX_LINE_LENGTH {
543                                    return Poll::Ready(Some(Err(
544                                        crate::error::Error::Body(format!(
545                                            "response line exceeded maximum length of {MAX_LINE_LENGTH} bytes"
546                                        )),
547                                    )));
548                                }
549                            } else {
550                                return Poll::Ready(Some(Err(
551                                    crate::error::Error::Body(format!(
552                                        "response line exceeded maximum length of {MAX_LINE_LENGTH} bytes"
553                                    )),
554                                )));
555                            }
556                        }
557                    }
558                    self.buffer.extend_from_slice(&chunk);
559                }
560                Poll::Ready(Some(Err(e))) => return Poll::Ready(Some(Err(e))),
561                Poll::Ready(None) => {
562                    // Stream ended; flush remaining buffer as a final line.
563                    if self.buffer.is_empty() {
564                        return Poll::Ready(None);
565                    }
566                    let remaining = std::mem::take(&mut self.buffer);
567                    if remaining.len() > MAX_LINE_LENGTH {
568                        return Poll::Ready(Some(Err(crate::error::Error::Body(format!(
569                            "response line exceeded maximum length of {MAX_LINE_LENGTH} bytes"
570                        )))));
571                    }
572                    let mut line = &remaining[..remaining.len()];
573                    if line.ends_with(b"\r") {
574                        line = &line[..line.len() - 1];
575                    }
576                    let line = std::str::from_utf8(line)
577                        .map(str::to_owned)
578                        .map_err(|e| crate::error::Error::Body(e.to_string()))?;
579                    return Poll::Ready(Some(Ok(line)));
580                }
581                Poll::Pending => return Poll::Pending,
582            }
583        }
584    }
585}
586
587#[cfg(test)]
588mod tests {
589    use super::*;
590    use http::HeaderValue;
591
592    #[test]
593    fn response_debug_redacts_sensitive_headers_and_url_parts() {
594        let mut headers = HeaderMap::new();
595        headers.insert("authorization", HeaderValue::from_static("Bearer secret"));
596        headers.insert("set-cookie", HeaderValue::from_static("session=secret"));
597        let response = Response::new(
598            StatusCode::FOUND,
599            Version::HTTP_11,
600            headers,
601            Url::parse("https://user:pass@example.com/path?token=secret#fragment").unwrap(),
602            ResponseBody::buffered(Bytes::new()),
603        );
604        let rendered = format!("{response:?}");
605        assert!(!rendered.contains("secret"));
606        assert!(!rendered.contains("user:pass"));
607        assert!(rendered.contains("https://example.com/path"));
608    }
609
610    #[test]
611    fn response_retains_wire_content_metadata_without_changing_headers() {
612        let mut headers = HeaderMap::new();
613        headers.insert("content-encoding", HeaderValue::from_static("gzip"));
614        headers.insert("content-length", HeaderValue::from_static("42"));
615        let response = Response::new(
616            StatusCode::OK,
617            Version::HTTP_11,
618            headers,
619            Url::parse("http://example.com").unwrap(),
620            ResponseBody::buffered(Bytes::new()),
621        );
622
623        assert_eq!(response.wire_content_encoding(), Some("gzip"));
624        assert_eq!(response.wire_content_length(), Some("42"));
625        assert_eq!(
626            response.headers().get("content-encoding"),
627            Some(&HeaderValue::from_static("gzip"))
628        );
629        assert_eq!(
630            response.headers().get("content-length"),
631            Some(&HeaderValue::from_static("42"))
632        );
633    }
634    use futures_util::StreamExt;
635
636    #[tokio::test]
637    async fn response_bytes_and_text() {
638        let mut resp = Response::new(
639            StatusCode::OK,
640            Version::HTTP_11,
641            HeaderMap::new(),
642            Url::parse("http://example.com").unwrap(),
643            ResponseBody::buffered(Bytes::from("hello")),
644        );
645        assert!(resp.is_success());
646        let text = resp.text().await.unwrap();
647        assert_eq!(text, "hello");
648    }
649
650    #[tokio::test]
651    async fn response_streaming_bytes_collect() {
652        let chunks = vec![Ok(Bytes::from("hello ")), Ok(Bytes::from("world"))];
653        let stream = Box::pin(futures_util::stream::iter(chunks));
654        let mut resp = Response::new(
655            StatusCode::OK,
656            Version::HTTP_11,
657            HeaderMap::new(),
658            Url::parse("http://example.com").unwrap(),
659            ResponseBody::streaming(stream),
660        );
661        let bytes = resp.bytes().await.unwrap();
662        assert_eq!(bytes, "hello world");
663    }
664
665    #[tokio::test]
666    async fn response_text_lines_rejects_unbounded_line() {
667        let stream = Box::pin(futures_util::stream::iter(vec![Ok(Bytes::from(vec![
668            b'a'; MAX_LINE_LENGTH + 1
669        ]))]));
670        let mut response = Response::new(
671            StatusCode::OK,
672            Version::HTTP_11,
673            HeaderMap::new(),
674            Url::parse("http://example.com").unwrap(),
675            ResponseBody::streaming(stream),
676        );
677        let mut lines = response.text_lines().unwrap();
678        let error = lines.next().await.unwrap().unwrap_err();
679        assert!(matches!(error, crate::error::Error::Body(_)));
680    }
681
682    #[tokio::test]
683    async fn response_text_lines_rejects_overlong_line_after_valid_line() {
684        // A single chunk carrying a valid line followed by an over-long
685        // line must not smuggle the second line past MAX_LINE_LENGTH via
686        // the buffered fast path.
687        let mut payload = b"ok\n".to_vec();
688        payload.extend_from_slice(&vec![b'a'; MAX_LINE_LENGTH + 1]);
689        payload.push(b'\n');
690        let stream = Box::pin(futures_util::stream::iter(vec![Ok(Bytes::from(payload))]));
691        let mut resp = Response::new(
692            StatusCode::OK,
693            Version::HTTP_11,
694            HeaderMap::new(),
695            Url::parse("http://example.com").unwrap(),
696            ResponseBody::streaming(stream),
697        );
698        let mut lines = resp.text_lines().unwrap();
699        assert_eq!(lines.next().await.unwrap().unwrap(), "ok");
700        let error = lines.next().await.unwrap().unwrap_err();
701        assert!(matches!(error, crate::error::Error::Body(_)));
702    }
703
704    #[tokio::test]
705    async fn response_text_lines_rejects_unbounded_terminal_line() {
706        // The terminal flush path (`Poll::Ready(None)`) must enforce
707        // `MAX_LINE_LENGTH` even when the over-long buffer never sees a
708        // trailing newline.
709        let stream = Box::pin(futures_util::stream::iter(vec![Ok(Bytes::from(vec![
710            b'a'; MAX_LINE_LENGTH + 1
711        ]))]));
712        let mut resp = Response::new(
713            StatusCode::OK,
714            Version::HTTP_11,
715            HeaderMap::new(),
716            Url::parse("http://example.com").unwrap(),
717            ResponseBody::streaming(stream),
718        );
719        let mut lines = resp.text_lines().unwrap();
720        let error = lines.next().await.unwrap().unwrap_err();
721        assert!(matches!(error, crate::error::Error::Body(_)));
722    }
723
724    #[tokio::test]
725    async fn response_bytes_stream_yields_chunks() {
726        let chunks = vec![Ok(Bytes::from("a")), Ok(Bytes::from("b"))];
727        let stream = Box::pin(futures_util::stream::iter(chunks));
728        let mut resp = Response::new(
729            StatusCode::OK,
730            Version::HTTP_11,
731            HeaderMap::new(),
732            Url::parse("http://example.com").unwrap(),
733            ResponseBody::streaming(stream),
734        );
735        let mut stream = resp.bytes_stream().unwrap();
736        assert_eq!(stream.next().await.unwrap().unwrap(), "a");
737        assert_eq!(stream.next().await.unwrap().unwrap(), "b");
738        assert!(stream.next().await.is_none());
739    }
740
741    #[tokio::test]
742    async fn response_text_lines_basic() {
743        let chunks = vec![Ok(Bytes::from("line1\nline2\nline3\n"))];
744        let stream = Box::pin(futures_util::stream::iter(chunks));
745        let mut resp = Response::new(
746            StatusCode::OK,
747            Version::HTTP_11,
748            HeaderMap::new(),
749            Url::parse("http://example.com").unwrap(),
750            ResponseBody::streaming(stream),
751        );
752        let mut lines = resp.text_lines().unwrap();
753        assert_eq!(lines.next().await.unwrap().unwrap(), "line1");
754        assert_eq!(lines.next().await.unwrap().unwrap(), "line2");
755        assert_eq!(lines.next().await.unwrap().unwrap(), "line3");
756        assert!(lines.next().await.is_none());
757    }
758
759    #[tokio::test]
760    async fn response_text_lines_crlf() {
761        let chunks = vec![Ok(Bytes::from("line1\r\nline2\r\n"))];
762        let stream = Box::pin(futures_util::stream::iter(chunks));
763        let mut resp = Response::new(
764            StatusCode::OK,
765            Version::HTTP_11,
766            HeaderMap::new(),
767            Url::parse("http://example.com").unwrap(),
768            ResponseBody::streaming(stream),
769        );
770        let mut lines = resp.text_lines().unwrap();
771        assert_eq!(lines.next().await.unwrap().unwrap(), "line1");
772        assert_eq!(lines.next().await.unwrap().unwrap(), "line2");
773        assert!(lines.next().await.is_none());
774    }
775
776    #[tokio::test]
777    async fn response_text_lines_across_chunks() {
778        let chunks = vec![
779            Ok(Bytes::from("hel")),
780            Ok(Bytes::from("lo\nwor")),
781            Ok(Bytes::from("ld\n")),
782        ];
783        let stream = Box::pin(futures_util::stream::iter(chunks));
784        let mut resp = Response::new(
785            StatusCode::OK,
786            Version::HTTP_11,
787            HeaderMap::new(),
788            Url::parse("http://example.com").unwrap(),
789            ResponseBody::streaming(stream),
790        );
791        let mut lines = resp.text_lines().unwrap();
792        assert_eq!(lines.next().await.unwrap().unwrap(), "hello");
793        assert_eq!(lines.next().await.unwrap().unwrap(), "world");
794        assert!(lines.next().await.is_none());
795    }
796
797    #[tokio::test]
798    async fn response_text_lines_no_trailing_newline() {
799        let chunks = vec![Ok(Bytes::from("hello"))];
800        let stream = Box::pin(futures_util::stream::iter(chunks));
801        let mut resp = Response::new(
802            StatusCode::OK,
803            Version::HTTP_11,
804            HeaderMap::new(),
805            Url::parse("http://example.com").unwrap(),
806            ResponseBody::streaming(stream),
807        );
808        let mut lines = resp.text_lines().unwrap();
809        assert_eq!(lines.next().await.unwrap().unwrap(), "hello");
810        assert!(lines.next().await.is_none());
811    }
812
813    #[test]
814    fn trailers_absent_initially() {
815        let resp = Response::new(
816            StatusCode::OK,
817            Version::HTTP_11,
818            HeaderMap::new(),
819            Url::parse("http://example.com").unwrap(),
820            ResponseBody::buffered(Bytes::new()),
821        );
822        assert!(resp.trailers().is_none());
823    }
824
825    #[test]
826    fn trailers_preserve_duplicate_multi_value() {
827        use crate::body::SharedTrailers;
828        let shared = SharedTrailers::new();
829        let mut map = HeaderMap::new();
830        map.append("x-trailer", HeaderValue::from_static("a"));
831        map.append("x-trailer", HeaderValue::from_static("b"));
832        map.insert("x-single", HeaderValue::from_static("v"));
833        shared.store(map);
834        let mut resp = Response::new(
835            StatusCode::OK,
836            Version::HTTP_11,
837            HeaderMap::new(),
838            Url::parse("http://example.com").unwrap(),
839            ResponseBody::buffered(Bytes::new()),
840        );
841        resp.set_trailers(shared);
842        let trailers = resp.trailers().expect("trailers present");
843        let values: Vec<_> = trailers
844            .get_all("x-trailer")
845            .iter()
846            .map(|v| v.to_str().unwrap().to_owned())
847            .collect();
848        assert_eq!(values, vec!["a", "b"]);
849        assert_eq!(trailers.get("x-single").unwrap(), "v");
850    }
851
852    #[tokio::test]
853    async fn trailers_available_after_bytes_collection() {
854        use crate::body::SharedTrailers;
855        // Simulate a transport that populates trailers when the body is
856        // driven to EOF (same contract as `wrap_incoming`).
857        let shared = SharedTrailers::new();
858        let shared_for_stream = shared.clone();
859        let stream = Box::pin(futures_util::stream::unfold(0, move |step| {
860            let shared_for_stream = shared_for_stream.clone();
861            async move {
862                if step == 0 {
863                    Some((Ok(Bytes::from("hello")), 1))
864                } else if step == 1 {
865                    let mut map = HeaderMap::new();
866                    map.insert("x-done", HeaderValue::from_static("yes"));
867                    shared_for_stream.store(map);
868                    None
869                } else {
870                    None
871                }
872            }
873        }));
874        let mut resp = Response::new(
875            StatusCode::OK,
876            Version::HTTP_11,
877            HeaderMap::new(),
878            Url::parse("http://example.com").unwrap(),
879            ResponseBody::streaming(stream),
880        );
881        resp.set_trailers(shared);
882        assert!(
883            resp.trailers().is_none(),
884            "partial consumption reports None"
885        );
886        let bytes = resp.bytes().await.unwrap();
887        assert_eq!(bytes, "hello");
888        assert_eq!(
889            resp.trailers().unwrap().get("x-done").unwrap(),
890            "yes",
891            "trailers available after body completion"
892        );
893    }
894
895    #[tokio::test]
896    async fn partial_consumption_does_not_falsely_report_trailers() {
897        let stream = Box::pin(futures_util::stream::iter(vec![Ok(Bytes::from("a"))]));
898        let mut resp = Response::new(
899            StatusCode::OK,
900            Version::HTTP_11,
901            HeaderMap::new(),
902            Url::parse("http://example.com").unwrap(),
903            ResponseBody::streaming(stream),
904        );
905        // No trailers wired; even after partial read there must be none.
906        let mut s = resp.bytes_stream().unwrap();
907        assert_eq!(s.next().await.unwrap().unwrap(), "a");
908        assert!(resp.trailers().is_none());
909    }
910
911    #[tokio::test]
912    async fn body_error_before_trailers_leaves_no_trailers() {
913        use crate::body::SharedTrailers;
914        let shared = SharedTrailers::new();
915        let stream = Box::pin(futures_util::stream::iter(vec![
916            Ok(Bytes::from("a")),
917            Err(crate::error::Error::Body("boom".into())),
918        ]));
919        let mut resp = Response::new(
920            StatusCode::OK,
921            Version::HTTP_11,
922            HeaderMap::new(),
923            Url::parse("http://example.com").unwrap(),
924            ResponseBody::streaming(stream),
925        );
926        resp.set_trailers(shared);
927        let err = resp.bytes().await.unwrap_err();
928        assert!(matches!(err, crate::error::Error::Body(_)));
929        assert!(
930            resp.trailers().is_none(),
931            "body errors must not fabricate trailer state"
932        );
933    }
934}