reqx 0.1.35

Rust HTTP transport client for API SDK libraries with retry, timeout, idempotency, proxy, and pluggable TLS backends
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
use std::future::{Future, poll_fn};
use std::io;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};

use bytes::Bytes;
use http::{HeaderMap, StatusCode};
use hyper::body::{Body as HyperBody, Incoming};
use serde::de::DeserializeOwned;
use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt, ReadBuf};
use tokio::time::Sleep;

use crate::body::decode_content_encoded_body_limited;
use crate::content_encoding::should_decode_content_encoded_body;
use crate::error::{Error, TimeoutPhase};
use crate::extensions::Clock;
use crate::limiters::{GlobalRequestPermit, HostRequestPermit};

use super::{
    Response, StreamCompletion, StreamLifecycle, deadline_elapsed, deadline_limits_wait,
    deadline_within_slack,
};

#[derive(Debug)]
pub(crate) struct StreamPermits {
    global: Option<GlobalRequestPermit>,
    host: Option<HostRequestPermit>,
}

impl StreamPermits {
    pub(crate) fn new(
        global: Option<GlobalRequestPermit>,
        host: Option<HostRequestPermit>,
    ) -> Self {
        Self { global, host }
    }
}

pub(crate) struct ResponseStreamContext {
    pub(crate) method: http::Method,
    pub(crate) uri_raw: String,
    pub(crate) uri_redacted: String,
    pub(crate) timeout_ms: u128,
    pub(crate) total_timeout_ms: Option<u128>,
    pub(crate) deadline_at: Option<Instant>,
    pub(crate) deadline_slack: Duration,
    pub(crate) clock: Arc<dyn Clock>,
    pub(crate) lifecycle: Option<StreamLifecycle>,
    pub(crate) permits: StreamPermits,
}

struct StreamBody {
    inner: Incoming,
    method: http::Method,
    uri_redacted: String,
    timeout_ms: u128,
    total_timeout_ms: Option<u128>,
    deadline_at: Option<Instant>,
    deadline_slack: Duration,
    clock: Arc<dyn Clock>,
    frame_timeout: Option<Pin<Box<Sleep>>>,
    frame_timeout_deadline_limited: bool,
    read_buffer: Bytes,
    lifecycle: Option<StreamLifecycle>,
    _global_permit: Option<GlobalRequestPermit>,
    _host_permit: Option<HostRequestPermit>,
}

impl StreamBody {
    fn new(inner: Incoming, context: ResponseStreamContext) -> Self {
        let ResponseStreamContext {
            method,
            uri_raw: _,
            uri_redacted,
            timeout_ms,
            total_timeout_ms,
            deadline_at,
            deadline_slack,
            clock,
            lifecycle,
            permits,
        } = context;
        Self {
            inner,
            method,
            uri_redacted,
            timeout_ms: timeout_ms.max(1),
            total_timeout_ms,
            deadline_at,
            deadline_slack,
            clock,
            frame_timeout: None,
            frame_timeout_deadline_limited: false,
            read_buffer: Bytes::new(),
            lifecycle,
            _global_permit: permits.global,
            _host_permit: permits.host,
        }
    }

    fn attach_completion(&mut self, completion: StreamCompletion) {
        super::attach_completion(&mut self.lifecycle, completion);
    }

    fn method(&self) -> &http::Method {
        &self.method
    }

    fn uri_redacted(&self) -> &str {
        &self.uri_redacted
    }

    fn response_body_timeout_error(&self) -> Error {
        Error::Timeout {
            phase: TimeoutPhase::ResponseBody,
            timeout_ms: self.timeout_ms.max(1),
            method: self.method.clone(),
            uri: self.uri_redacted.clone(),
        }
    }

    fn deadline_exceeded_error(&self) -> Error {
        Error::DeadlineExceeded {
            timeout_ms: self
                .total_timeout_ms
                .unwrap_or_else(|| self.timeout_ms.max(1)),
            method: self.method.clone(),
            uri: self.uri_redacted.clone(),
        }
    }

    fn response_body_too_large_error(&self, limit_bytes: usize, actual_bytes: usize) -> Error {
        Error::ResponseBodyTooLarge {
            limit_bytes,
            actual_bytes,
            method: self.method.clone(),
            uri: self.uri_redacted.clone(),
        }
    }

    fn write_error(&self, source: io::Error) -> Error {
        super::write_body_error(&self.method, &self.uri_redacted, source)
    }

    fn effective_frame_timeout(&self) -> crate::Result<(Duration, bool)> {
        let phase_timeout = Duration::from_millis(self.timeout_ms.max(1) as u64);
        let Some(deadline_at) = self.deadline_at else {
            return Ok((phase_timeout, false));
        };
        let now = self.clock.now_monotonic();
        if deadline_elapsed(deadline_at, now) {
            return Err(self.deadline_exceeded_error());
        }
        let remaining = deadline_at.saturating_duration_since(now);
        Ok((
            phase_timeout.min(remaining),
            deadline_limits_wait(phase_timeout, deadline_at, now),
        ))
    }

    fn ensure_frame_timeout(&mut self) -> crate::Result<()> {
        if self.frame_timeout.is_none() {
            let (timeout, deadline_limited) = self.effective_frame_timeout()?;
            self.frame_timeout = Some(Box::pin(tokio::time::sleep(timeout)));
            self.frame_timeout_deadline_limited = deadline_limited;
        }
        Ok(())
    }

    fn poll_next_chunk(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Bytes, Error>>> {
        loop {
            match Pin::new(&mut self.inner).poll_frame(cx) {
                Poll::Ready(Some(Ok(frame))) => {
                    self.frame_timeout = None;
                    self.frame_timeout_deadline_limited = false;
                    match frame.into_data() {
                        Ok(data) if data.is_empty() => continue,
                        Ok(data) => return Poll::Ready(Some(Ok(data))),
                        Err(_) => continue,
                    }
                }
                Poll::Ready(Some(Err(source))) => {
                    self.frame_timeout = None;
                    self.frame_timeout_deadline_limited = false;
                    return Poll::Ready(Some(Err(Error::ReadBody {
                        source: Box::new(source),
                    })));
                }
                Poll::Ready(None) => {
                    self.frame_timeout = None;
                    self.frame_timeout_deadline_limited = false;
                    return Poll::Ready(None);
                }
                Poll::Pending => {
                    if let Err(error) = self.ensure_frame_timeout() {
                        return Poll::Ready(Some(Err(error)));
                    }
                    if let Some(timer) = self.frame_timeout.as_mut()
                        && timer.as_mut().poll(cx).is_ready()
                    {
                        self.frame_timeout = None;
                        let now = self.clock.now_monotonic();
                        let error = if self.deadline_at.is_some_and(|deadline_at| {
                            deadline_elapsed(deadline_at, now)
                                || (self.frame_timeout_deadline_limited
                                    && deadline_within_slack(deadline_at, now, self.deadline_slack))
                        }) {
                            self.deadline_exceeded_error()
                        } else {
                            self.response_body_timeout_error()
                        };
                        self.frame_timeout_deadline_limited = false;
                        return Poll::Ready(Some(Err(error)));
                    }
                    return Poll::Pending;
                }
            }
        }
    }

    async fn next_chunk(&mut self) -> crate::Result<Option<Bytes>> {
        match poll_fn(|cx| Pin::new(&mut *self).poll_next_chunk(cx)).await {
            Some(Ok(chunk)) => Ok(Some(chunk)),
            Some(Err(error)) => Err(error),
            None => Ok(None),
        }
    }

    fn take_pending_chunk(&mut self) -> Option<Bytes> {
        if self.read_buffer.is_empty() {
            None
        } else {
            Some(std::mem::take(&mut self.read_buffer))
        }
    }

    async fn read_raw_bytes_limited(&mut self, max_bytes: usize) -> crate::Result<Bytes> {
        let max_bytes = max_bytes.max(1);
        let mut collected = Vec::new();
        let mut total_len = 0_usize;

        if let Some(chunk) = self.take_pending_chunk() {
            total_len = total_len.saturating_add(chunk.len());
            if total_len > max_bytes {
                return Err(self.response_body_too_large_error(max_bytes, total_len));
            }
            collected.extend_from_slice(&chunk);
        }

        while let Some(chunk) = self.next_chunk().await? {
            total_len = total_len.saturating_add(chunk.len());
            if total_len > max_bytes {
                return Err(self.response_body_too_large_error(max_bytes, total_len));
            }
            collected.extend_from_slice(&chunk);
        }
        Ok(Bytes::from(collected))
    }

    async fn write_chunk<W>(&mut self, writer: &mut W, chunk: &[u8]) -> crate::Result<()>
    where
        W: AsyncWrite + Unpin + Send + ?Sized,
    {
        if let Err(source) = writer.write_all(chunk).await {
            let error = self.write_error(source);
            self.complete_error(&error);
            return Err(error);
        }
        Ok(())
    }

    async fn flush_writer<W>(&mut self, writer: &mut W) -> crate::Result<()>
    where
        W: AsyncWrite + Unpin + Send + ?Sized,
    {
        if let Err(source) = writer.flush().await {
            let error = self.write_error(source);
            self.complete_error(&error);
            return Err(error);
        }
        Ok(())
    }

    async fn copy_to_writer<W>(&mut self, writer: &mut W) -> crate::Result<u64>
    where
        W: AsyncWrite + Unpin + Send + ?Sized,
    {
        let mut copied = 0_u64;

        if let Some(chunk) = self.take_pending_chunk() {
            self.write_chunk(writer, &chunk).await?;
            copied = copied.saturating_add(chunk.len() as u64);
        }

        while let Some(chunk) = match self.next_chunk().await {
            Ok(chunk) => chunk,
            Err(error) => {
                self.complete_error(&error);
                return Err(error);
            }
        } {
            self.write_chunk(writer, &chunk).await?;
            copied = copied.saturating_add(chunk.len() as u64);
        }
        self.flush_writer(writer).await?;
        self.complete_success();
        Ok(copied)
    }

    async fn copy_to_writer_limited<W>(
        &mut self,
        writer: &mut W,
        max_bytes: usize,
    ) -> crate::Result<u64>
    where
        W: AsyncWrite + Unpin + Send + ?Sized,
    {
        let max_bytes = max_bytes.max(1);
        let mut copied = 0_u64;

        if let Some(chunk) = self.take_pending_chunk() {
            copied = copied.saturating_add(chunk.len() as u64);
            if copied > max_bytes as u64 {
                let error = self.response_body_too_large_error(max_bytes, copied as usize);
                self.complete_error(&error);
                return Err(error);
            }
            self.write_chunk(writer, &chunk).await?;
        }

        while let Some(chunk) = match self.next_chunk().await {
            Ok(chunk) => chunk,
            Err(error) => {
                self.complete_error(&error);
                return Err(error);
            }
        } {
            copied = copied.saturating_add(chunk.len() as u64);
            if copied > max_bytes as u64 {
                let error = self.response_body_too_large_error(max_bytes, copied as usize);
                self.complete_error(&error);
                return Err(error);
            }
            self.write_chunk(writer, &chunk).await?;
        }
        self.flush_writer(writer).await?;
        self.complete_success();
        Ok(copied)
    }

    fn complete_success(&mut self) {
        super::complete_success(&mut self.lifecycle);
    }

    fn complete_error(&mut self, error: &Error) {
        super::complete_error(&mut self.lifecycle, error);
    }
}

impl std::fmt::Debug for StreamBody {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("StreamBody")
            .field("method", &self.method)
            .field("uri_redacted", &self.uri_redacted)
            .field("timeout_ms", &self.timeout_ms)
            .field("total_timeout_ms", &self.total_timeout_ms)
            .field("deadline_at", &self.deadline_at)
            .field("deadline_slack", &self.deadline_slack)
            .field("has_frame_timeout", &self.frame_timeout.is_some())
            .field(
                "frame_timeout_deadline_limited",
                &self.frame_timeout_deadline_limited,
            )
            .field("read_buffer_len", &self.read_buffer.len())
            .field("has_lifecycle", &self.lifecycle.is_some())
            .finish()
    }
}

#[derive(Debug)]
/// Streaming async response body with request metadata.
///
/// Use this when you want to process large response bodies incrementally
/// without buffering them into memory first.
///
/// See also `examples/streaming.rs`.
///
/// # Example
///
/// ```no_run
/// # #[cfg(feature = "_async")]
/// # async fn demo() -> reqx::Result<()> {
/// use reqx::prelude::Client;
///
/// let client = Client::builder("https://api.example.com").build()?;
/// let stream = client.get("/v1/logs").send_response_stream().await?;
/// let _body = stream.into_text_limited(64 * 1024).await?;
/// # Ok(())
/// # }
/// ```
#[cfg_attr(
    docsrs,
    doc(cfg(any(
        feature = "async-tls-rustls-ring",
        feature = "async-tls-rustls-aws-lc-rs",
        feature = "async-tls-native"
    )))
)]
pub struct ResponseStream {
    status: StatusCode,
    headers: HeaderMap,
    uri_raw: String,
    body: StreamBody,
}

impl ResponseStream {
    pub(crate) fn new(
        status: StatusCode,
        headers: HeaderMap,
        body: Incoming,
        context: ResponseStreamContext,
    ) -> Self {
        let uri_raw = context.uri_raw.clone();
        Self {
            status,
            headers,
            uri_raw,
            body: StreamBody::new(body, context),
        }
    }

    pub(crate) fn attach_completion(&mut self, completion: StreamCompletion) {
        self.body.attach_completion(completion);
    }

    /// Returns the HTTP status code.
    pub fn status(&self) -> StatusCode {
        self.status
    }

    /// Returns the response headers.
    pub fn headers(&self) -> &HeaderMap {
        &self.headers
    }

    /// Returns the originating request method.
    pub fn method(&self) -> &http::Method {
        self.body.method()
    }

    /// Returns the original request URI, including query string.
    pub fn uri_raw(&self) -> &str {
        &self.uri_raw
    }

    /// Returns a redacted URI suitable for logs and errors.
    ///
    /// The redacted form omits the query string to reduce accidental
    /// leakage of sensitive parameters.
    pub fn uri_redacted(&self) -> &str {
        self.body.uri_redacted()
    }

    /// Buffers the stream into memory, enforcing `max_bytes`.
    ///
    /// See also `examples/streaming.rs`.
    pub async fn into_bytes_limited(self, max_bytes: usize) -> crate::Result<Bytes> {
        let max_bytes = max_bytes.max(1);
        let mut this = self;
        match this.body.read_raw_bytes_limited(max_bytes).await {
            Ok(body) => {
                this.body.complete_success();
                Ok(body)
            }
            Err(error) => {
                this.body.complete_error(&error);
                Err(error)
            }
        }
    }

    /// Copies the streamed body into `writer`.
    ///
    /// See also `examples/streaming.rs`.
    pub async fn copy_to_writer<W>(mut self, writer: &mut W) -> crate::Result<u64>
    where
        W: AsyncWrite + Unpin + Send + ?Sized,
    {
        self.body.copy_to_writer(writer).await
    }

    /// Copies the streamed body into `writer`, enforcing `max_bytes`.
    pub async fn copy_to_writer_limited<W>(
        mut self,
        writer: &mut W,
        max_bytes: usize,
    ) -> crate::Result<u64>
    where
        W: AsyncWrite + Unpin + Send + ?Sized,
    {
        self.body.copy_to_writer_limited(writer, max_bytes).await
    }

    /// Buffers and decodes the stream into a [`Response`], enforcing `max_bytes`.
    ///
    /// See also `examples/streaming.rs`.
    pub async fn into_response_limited(mut self, max_bytes: usize) -> crate::Result<Response> {
        let max_bytes = max_bytes.max(1);
        let method = self.body.method().clone();
        let uri_redacted = self.body.uri_redacted().to_owned();
        let body = match self.body.read_raw_bytes_limited(max_bytes).await {
            Ok(body) => body,
            Err(error) => {
                self.body.complete_error(&error);
                return Err(error);
            }
        };
        let should_decode = should_decode_content_encoded_body(&method, self.status, body.len());
        let body = if should_decode {
            match decode_content_encoded_body_limited(body, &self.headers, max_bytes) {
                Ok(body) => body,
                Err(error) => {
                    let error =
                        super::map_decode_body_error(error, &method, &uri_redacted, max_bytes);
                    self.body.complete_error(&error);
                    return Err(error);
                }
            }
        } else {
            body
        };
        if should_decode && self.headers.contains_key(super::CONTENT_ENCODING) {
            self.headers.remove(super::CONTENT_ENCODING);
            self.headers.remove(super::CONTENT_LENGTH);
        }
        self.body.complete_success();
        Ok(Response::new(self.status, self.headers, body))
    }

    /// Buffers the stream as UTF-8 text, enforcing `max_bytes`.
    pub async fn into_text_limited(self, max_bytes: usize) -> crate::Result<String> {
        let response = self.into_response_limited(max_bytes).await?;
        response.text().map(ToOwned::to_owned)
    }

    /// Buffers the stream as lossy UTF-8 text, enforcing `max_bytes`.
    pub async fn into_text_lossy_limited(self, max_bytes: usize) -> crate::Result<String> {
        let response = self.into_response_limited(max_bytes).await?;
        Ok(response.text_lossy())
    }

    /// Buffers and deserializes the stream from JSON, enforcing `max_bytes`.
    pub async fn into_json_limited<T>(self, max_bytes: usize) -> crate::Result<T>
    where
        T: DeserializeOwned,
    {
        let response = self.into_response_limited(max_bytes).await?;
        response.json()
    }
}

impl AsyncRead for StreamBody {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buffer: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        if buffer.remaining() == 0 {
            return Poll::Ready(Ok(()));
        }

        loop {
            if !self.read_buffer.is_empty() {
                let to_copy = self.read_buffer.len().min(buffer.remaining());
                let chunk = self.read_buffer.split_to(to_copy);
                buffer.put_slice(&chunk);
                return Poll::Ready(Ok(()));
            }

            match self.as_mut().poll_next_chunk(cx) {
                Poll::Ready(Some(Ok(chunk))) => {
                    self.read_buffer = chunk;
                }
                Poll::Ready(Some(Err(error))) => {
                    self.complete_error(&error);
                    return Poll::Ready(Err(super::into_stream_read_io_error(error)));
                }
                Poll::Ready(None) => {
                    self.complete_success();
                    return Poll::Ready(Ok(()));
                }
                Poll::Pending => return Poll::Pending,
            }
        }
    }
}

impl AsyncRead for ResponseStream {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buffer: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        Pin::new(&mut self.body).poll_read(cx, buffer)
    }
}