tez 0.0.3

A lightweight, ergonomic, and fast high-level HTTP client for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
use std::{fmt, net::SocketAddr, pin::Pin, time::Duration};

use bytes::Bytes;
use http::{Extensions, HeaderMap, StatusCode, Uri, Version, header};
use http_body::Body as _;
use serde::de::DeserializeOwned;

use crate::{Body, Error, Limits, Result, stream::ResponseStream};

/// A final HTTP response with a one-shot streaming Tez body.
///
/// An HTTP status is never an error by itself. Inspect [`Response::status`] to
/// decide what success means for the operation. Borrow the one-shot body to
/// stream frames, consume it with a collecting helper, or call
/// [`Response::discard`].
pub struct Response {
    inner: http::Response<Body>,
    url: Uri,
    content_length: Option<u64>,
    remote_addr: Option<SocketAddr>,
    limits: Limits,
    info: ResponseInfo,
}

/// Stable metadata about the work that produced a response.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ResponseInfo {
    attempts: usize,
    redirects: usize,
    elapsed: Duration,
}

impl ResponseInfo {
    /// Returns the initial request plus any policy-scheduled retry attempts.
    #[must_use]
    pub const fn attempts(self) -> usize {
        self.attempts
    }

    /// Returns the total redirects followed across all attempts.
    #[must_use]
    pub const fn redirects(self) -> usize {
        self.redirects
    }

    /// Returns time from dispatch until final response headers arrived.
    #[must_use]
    pub const fn elapsed(self) -> Duration {
        self.elapsed
    }
}

impl Response {
    pub(crate) fn new(
        parts: http::response::Parts,
        body: Body,
        url: Uri,
        remote_addr: Option<SocketAddr>,
        limits: Limits,
    ) -> Self {
        let content_length = body.size_hint().exact();
        Self {
            inner: http::Response::from_parts(parts, body),
            url,
            content_length,
            remote_addr,
            limits,
            info: ResponseInfo {
                attempts: 1,
                redirects: 0,
                elapsed: Duration::ZERO,
            },
        }
    }

    pub(crate) fn into_parts(
        self,
    ) -> (
        http::Response<Body>,
        Uri,
        Option<u64>,
        Option<SocketAddr>,
        Limits,
        ResponseInfo,
    ) {
        (
            self.inner,
            self.url,
            self.content_length,
            self.remote_addr,
            self.limits,
            self.info,
        )
    }

    pub(crate) fn record_dispatch(&mut self, attempts: usize, redirects: usize, elapsed: Duration) {
        self.info = ResponseInfo {
            attempts,
            redirects,
            elapsed,
        };
    }

    /// Returns the final status code after redirects.
    #[must_use]
    pub fn status(&self) -> StatusCode {
        self.inner.status()
    }

    /// Returns the HTTP version used by the final response.
    #[must_use]
    pub fn version(&self) -> Version {
        self.inner.version()
    }

    /// Returns response headers, preserving repeated values.
    #[must_use]
    pub fn headers(&self) -> &HeaderMap {
        self.inner.headers()
    }

    /// Returns response headers mutably.
    #[must_use]
    pub fn headers_mut(&mut self) -> &mut HeaderMap {
        self.inner.headers_mut()
    }

    /// Returns response extensions.
    #[must_use]
    pub fn extensions(&self) -> &Extensions {
        self.inner.extensions()
    }

    /// Returns response extensions mutably.
    #[must_use]
    pub fn extensions_mut(&mut self) -> &mut Extensions {
        self.inner.extensions_mut()
    }

    /// Returns the final absolute URL after redirects.
    #[must_use]
    pub fn url(&self) -> &Uri {
        &self.url
    }

    /// Returns the exposed response body length when it is known.
    ///
    /// This is body metadata after the client's decompression policy, not a
    /// parsed `Content-Length` header. Automatically decompressed or streaming
    /// responses commonly have no known length.
    #[must_use]
    pub const fn content_length(&self) -> Option<u64> {
        self.content_length
    }

    /// Returns the final transport peer address when it is known.
    ///
    /// When a proxy is in use, this may be the proxy address rather than the
    /// origin server address.
    #[must_use]
    pub const fn remote_addr(&self) -> Option<SocketAddr> {
        self.remote_addr
    }

    /// Returns attempt, redirect, and response-header timing metadata.
    #[must_use]
    pub const fn info(&self) -> ResponseInfo {
        self.info
    }

    /// Converts a client or server response status into an error.
    ///
    /// Informational, successful, and redirect responses are returned
    /// unchanged.
    ///
    /// # Errors
    ///
    /// Returns a status error for `4xx` and `5xx` responses.
    pub fn error_for_status(self) -> Result<Self> {
        self.error_for_status_ref()?;
        Ok(self)
    }

    /// Checks whether the response has a client or server error status.
    ///
    /// # Errors
    ///
    /// Returns a status error for `4xx` and `5xx` responses.
    pub fn error_for_status_ref(&self) -> Result<&Self> {
        if self.status().is_client_error() || self.status().is_server_error() {
            return Err(Error::status_error(self.status()));
        }
        Ok(self)
    }

    /// Returns the one-shot streaming response body.
    #[must_use]
    pub fn body(&self) -> &Body {
        self.inner.body()
    }

    /// Returns the one-shot streaming response body mutably.
    #[must_use]
    pub fn body_mut(&mut self) -> &mut Body {
        self.inner.body_mut()
    }

    /// Consumes the response and returns its one-shot streaming body.
    #[must_use]
    pub fn into_body(self) -> Body {
        self.inner.into_body()
    }

    /// Consumes the response as an incremental body stream.
    ///
    /// Select JSON, NDJSON, or SSE framing explicitly on the returned stream,
    /// or consume it as a raw [`http_body::Body`].
    #[must_use]
    pub fn stream(self) -> ResponseStream {
        let item_limit = self.limits.stream_item_bytes();
        ResponseStream::new(self.into_body(), item_limit)
    }

    /// Reads the next response-body data chunk.
    ///
    /// Empty data frames and trailers are skipped. `None` means the complete
    /// body has been consumed and the connection is eligible for reuse.
    pub async fn chunk(&mut self) -> Result<Option<Bytes>> {
        loop {
            let frame =
                std::future::poll_fn(|context| Pin::new(self.inner.body_mut()).poll_frame(context))
                    .await;
            match frame {
                Some(Ok(frame)) => {
                    if let Ok(data) = frame.into_data()
                        && !data.is_empty()
                    {
                        return Ok(Some(data));
                    }
                }
                Some(Err(error)) => return Err(error),
                None => return Ok(None),
            }
        }
    }

    /// Completes an HTTP protocol switch negotiated by this response.
    ///
    /// Validate the status and protocol-specific response headers before
    /// awaiting the returned future. The response body is discarded and its
    /// HTTP/1 connection is permanently removed from the pool.
    #[must_use]
    pub fn upgrade(mut self) -> crate::Upgrade {
        self.extensions_mut()
            .remove::<crate::Upgrade>()
            .unwrap_or_else(crate::Upgrade::unavailable)
    }

    /// Collects response body data up to the client's configured limit.
    ///
    /// The limit applies after automatic decompression when enabled. This
    /// consumes the response. Use streaming access for larger bodies.
    ///
    /// # Errors
    ///
    /// Returns an error if reading fails or the decoded body exceeds the limit.
    pub async fn bytes(self) -> Result<Bytes> {
        let limit = self.limits.response_body_bytes();
        collect(self.into_body(), limit).await
    }

    /// Collects response body data up to an explicit limit.
    ///
    /// This overrides the client collection limit for this response without
    /// changing streaming behavior.
    pub async fn bytes_with_limit(self, limit: usize) -> Result<Bytes> {
        if limit == 0 {
            return Err(Error::request(
                "response body limit must be greater than zero",
            ));
        }
        collect(self.into_body(), limit).await
    }

    /// Collects the response body as text.
    ///
    /// The limit applies after automatic decompression when enabled. The
    /// character encoding comes from `Content-Type` and defaults to UTF-8.
    /// Malformed input is rejected rather than replaced.
    ///
    /// # Errors
    ///
    /// Returns an error if collection or character decoding fails.
    pub async fn text(self) -> Result<String> {
        let content_type = content_type(self.headers()).map(ToOwned::to_owned);
        decode_text(&self.bytes().await?, content_type.as_deref())
    }

    /// Collects the response body as text up to an explicit byte limit.
    ///
    /// # Errors
    ///
    /// Returns an error if collection or character decoding fails.
    pub async fn text_with_limit(self, limit: usize) -> Result<String> {
        let content_type = content_type(self.headers()).map(ToOwned::to_owned);
        decode_text(
            &self.bytes_with_limit(limit).await?,
            content_type.as_deref(),
        )
    }

    /// Collects the response body as JSON.
    ///
    /// The limit applies after automatic decompression when enabled. This
    /// consumes the response. JSON is decoded regardless of the response
    /// `Content-Type` value.
    ///
    /// # Errors
    ///
    /// Returns an error if collection fails or the body is not valid JSON for
    /// `T`.
    pub async fn json<T>(self) -> Result<T>
    where
        T: DeserializeOwned,
    {
        crate::content::decode_json(&self.bytes().await?, "response JSON could not be decoded")
    }

    /// Collects and decodes JSON up to an explicit byte limit.
    pub async fn json_with_limit<T>(self, limit: usize) -> Result<T>
    where
        T: DeserializeOwned,
    {
        crate::content::decode_json(
            &self.bytes_with_limit(limit).await?,
            "response JSON could not be decoded",
        )
    }

    /// Collects and decodes a URL-encoded form response.
    pub async fn form<T>(self) -> Result<T>
    where
        T: DeserializeOwned,
    {
        crate::content::decode_form(&self.bytes().await?, "response form could not be decoded")
    }

    /// Collects and decodes a URL-encoded form up to an explicit byte limit.
    pub async fn form_with_limit<T>(self, limit: usize) -> Result<T>
    where
        T: DeserializeOwned,
    {
        crate::content::decode_form(
            &self.bytes_with_limit(limit).await?,
            "response form could not be decoded",
        )
    }

    /// Copies the decoded response body into an asynchronous writer.
    ///
    /// This path retains at most one response chunk and observes connection
    /// backpressure. It returns the number of bytes written.
    pub async fn copy_to<W>(mut self, writer: &mut W) -> Result<u64>
    where
        W: futures_io::AsyncWrite + Unpin + ?Sized,
    {
        use futures_util::AsyncWriteExt as _;

        let mut written = 0_u64;
        while let Some(chunk) = self.chunk().await? {
            writer.write_all(&chunk).await.map_err(|_| Error::body())?;
            written = written
                .checked_add(chunk.len() as u64)
                .ok_or_else(Error::body)?;
        }
        Ok(written)
    }

    /// Drains the body without retaining it, allowing connection reuse.
    ///
    /// This consumes the response and observes the client's total deadline.
    ///
    /// # Errors
    ///
    /// Returns an error if the body cannot be read to completion.
    pub async fn discard(self) -> Result<()> {
        let mut body = self.into_body();
        while let Some(frame) =
            std::future::poll_fn(|context| Pin::new(&mut body).poll_frame(context)).await
        {
            frame?;
        }
        Ok(())
    }
}

pub(crate) fn decode_text(bytes: &[u8], content_type: Option<&str>) -> Result<String> {
    let charset = content_type
        .and_then(|value| value.parse::<mime::Mime>().ok())
        .and_then(|media_type| {
            media_type
                .get_param(mime::CHARSET)
                .map(|charset| charset.as_str().to_owned())
        });
    let encoding = charset
        .as_deref()
        .and_then(|charset| encoding_rs::Encoding::for_label(charset.as_bytes()))
        .unwrap_or(encoding_rs::UTF_8);
    let (text, _, malformed) = encoding.decode(bytes);
    if malformed {
        return Err(Error::decode(
            "response text is invalid for its declared character encoding",
        ));
    }
    Ok(text.into_owned())
}

fn content_type(headers: &HeaderMap) -> Option<&str> {
    headers.get(header::CONTENT_TYPE)?.to_str().ok()
}

impl fmt::Debug for Response {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Response")
            .field("status", &self.status())
            .field("version", &self.version())
            .field("header_count", &self.headers().len())
            .field("content_length", &self.content_length())
            .field("remote_addr", &self.remote_addr())
            .field("info", &self.info)
            .finish_non_exhaustive()
    }
}

async fn collect(mut body: Body, limit: usize) -> Result<Bytes> {
    if body.size_hint().lower() > limit as u64 {
        return Err(Error::body_too_large());
    }

    let capacity = body
        .size_hint()
        .exact()
        .and_then(|length| usize::try_from(length).ok())
        .filter(|length| *length <= limit);
    let mut first = None;
    let mut bytes = None;
    while let Some(frame) =
        std::future::poll_fn(|context| Pin::new(&mut body).poll_frame(context)).await
    {
        let frame = frame?;
        if let Ok(data) = frame.into_data() {
            let length = bytes
                .as_ref()
                .map_or_else(|| first.as_ref().map_or(0, Bytes::len), Vec::len)
                .checked_add(data.len())
                .ok_or_else(Error::body_too_large)?;
            if length > limit {
                return Err(Error::body_too_large());
            }
            if let Some(bytes) = &mut bytes {
                bytes.extend_from_slice(&data);
            } else if let Some(previous) = first.take() {
                let mut collected = Vec::with_capacity(capacity.unwrap_or(length).max(length));
                collected.extend_from_slice(&previous);
                collected.extend_from_slice(&data);
                bytes = Some(collected);
            } else {
                first = Some(data);
            }
        }
    }
    Ok(match bytes {
        Some(bytes) => Bytes::from(bytes),
        None => first.unwrap_or_default(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use http_body::{Body as HttpBody, Frame, SizeHint};
    use std::{
        convert::Infallible,
        pin::Pin,
        task::{Context, Poll},
    };

    const COLLECTION_LIMIT: usize = 16 * 1024 * 1024;

    fn response(body: impl Into<Body>) -> Response {
        let inner = http::Response::new(body.into());
        let (parts, body) = inner.into_parts();
        Response::new(
            parts,
            body,
            "https://example.com/resource".parse().unwrap(),
            None,
            Limits::default().response_body(COLLECTION_LIMIT),
        )
    }

    #[tokio::test]
    async fn decoders_consume_the_body_and_classify_invalid_data() {
        assert_eq!(response("tez").text().await.unwrap(), "tez");
        assert_eq!(
            response(br#"{"name":"Ada"}"#.as_slice())
                .json::<serde_json::Value>()
                .await
                .unwrap(),
            serde_json::json!({ "name": "Ada" })
        );

        let error = response(vec![0xff]).text().await.unwrap_err();
        assert!(error.is_decode());
    }

    #[test]
    fn text_decoding_honors_declared_charsets_and_rejects_malformed_data() {
        assert_eq!(
            decode_text(
                &[0x63, 0x61, 0x66, 0xe9],
                Some("text/plain; charset=windows-1252")
            )
            .unwrap(),
            "café"
        );
        assert!(decode_text(&[0xff], Some("text/plain; charset=utf-8")).is_err());
    }

    #[tokio::test]
    async fn collecting_one_data_frame_reuses_its_bytes() {
        let original = Bytes::from_static(b"single allocation");
        let collected = response(original.clone()).bytes().await.unwrap();

        assert_eq!(collected, original);
        assert_eq!(collected.as_ptr(), original.as_ptr());
    }

    #[tokio::test]
    async fn collection_limit_accepts_the_boundary_and_rejects_the_next_byte() {
        let exact = vec![b'x'; COLLECTION_LIMIT];
        assert_eq!(
            collect(Body::from(exact), COLLECTION_LIMIT)
                .await
                .unwrap()
                .len(),
            COLLECTION_LIMIT
        );

        let too_large = vec![b'y'; COLLECTION_LIMIT + 1];
        let error = collect(Body::from(too_large), COLLECTION_LIMIT)
            .await
            .unwrap_err();
        assert!(error.is_body_too_large());
        assert!(error.is_body());
    }

    #[tokio::test]
    async fn collection_does_not_treat_an_upper_hint_as_actual_length() {
        struct LooseUpperBound(Option<Bytes>);

        impl HttpBody for LooseUpperBound {
            type Data = Bytes;
            type Error = Infallible;

            fn poll_frame(
                self: Pin<&mut Self>,
                _context: &mut Context<'_>,
            ) -> Poll<Option<std::result::Result<Frame<Self::Data>, Self::Error>>> {
                Poll::Ready(self.get_mut().0.take().map(Frame::data).map(Ok))
            }

            fn size_hint(&self) -> SizeHint {
                let mut hint = SizeHint::new();
                hint.set_upper(COLLECTION_LIMIT as u64 + 1);
                hint
            }
        }

        let bytes = collect(
            Body::wrap(LooseUpperBound(Some(Bytes::from_static(b"small")))),
            COLLECTION_LIMIT,
        )
        .await
        .unwrap();

        assert_eq!(bytes, "small");
    }

    #[test]
    fn debug_never_includes_header_values_or_body_data() {
        let mut headers = HeaderMap::new();
        headers.insert("authorization", "Bearer secret".parse().unwrap());
        headers.insert(header::CONTENT_LENGTH, "1024".parse().unwrap());
        let mut inner = http::Response::new(Body::from("body secret"));
        *inner.headers_mut() = headers;
        let (parts, body) = inner.into_parts();
        let response = Response::new(
            parts,
            body,
            "https://example.com/resource?token=secret".parse().unwrap(),
            Some("127.0.0.1:8080".parse().unwrap()),
            Limits::default().response_body(COLLECTION_LIMIT),
        );

        let debug = format!("{response:?}");
        assert!(debug.contains("content_length: Some(11)"));
        assert!(debug.contains("remote_addr: Some(127.0.0.1:8080)"));
        assert!(!debug.contains("secret"));
        assert!(!debug.contains("authorization"));
    }
}