aioduct 0.2.5

Async-native HTTP client built directly on hyper 1.x — no hyper-util, no legacy
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
};
use std::task::{Context, Poll};
use std::time::Duration;

use bytes::Bytes;
use http_body::Body;
use http_body::Frame;
use pin_project_lite::pin_project;

pin_project! {
    #[project = TimeoutProj]
    pub enum Timeout<F, S> {
        NoTimeout { #[pin] future: F },
        WithTimeout { #[pin] future: F, #[pin] sleep: S },
    }
}

impl<F, S, T, E> Future for Timeout<F, S>
where
    F: Future<Output = Result<T, E>>,
    S: Future<Output = ()>,
    E: From<crate::error::Error>,
{
    type Output = Result<T, E>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        match self.project() {
            TimeoutProj::NoTimeout { future } => future.poll(cx),
            TimeoutProj::WithTimeout { future, sleep } => {
                if let Poll::Ready(result) = future.poll(cx) {
                    return Poll::Ready(result);
                }
                if let Poll::Ready(()) = sleep.poll(cx) {
                    return Poll::Ready(Err(crate::error::Error::Timeout.into()));
                }
                Poll::Pending
            }
        }
    }
}

pin_project! {
    /// Body wrapper that records when request upload has ended.
    pub(crate) struct BodyCompletion<B> {
        #[pin]
        inner: B,
        complete: Arc<AtomicBool>,
    }
}

pub(crate) fn mark_body_completion<B>(body: B) -> (BodyCompletion<B>, Arc<AtomicBool>)
where
    B: Body,
{
    let complete = Arc::new(AtomicBool::new(body.is_end_stream()));
    (
        BodyCompletion {
            inner: body,
            complete: complete.clone(),
        },
        complete,
    )
}

impl<B> Body for BodyCompletion<B>
where
    B: Body<Data = Bytes, Error = crate::error::Error>,
{
    type Data = Bytes;
    type Error = crate::error::Error;

    fn poll_frame(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
        let mut this = self.project();
        match this.inner.as_mut().poll_frame(cx) {
            Poll::Ready(None) => {
                this.complete.store(true, Ordering::Release);
                Poll::Ready(None)
            }
            Poll::Ready(Some(Err(error))) => {
                this.complete.store(true, Ordering::Release);
                Poll::Ready(Some(Err(error)))
            }
            Poll::Ready(Some(Ok(frame))) => {
                if this.inner.is_end_stream() {
                    this.complete.store(true, Ordering::Release);
                }
                Poll::Ready(Some(Ok(frame)))
            }
            Poll::Pending => Poll::Pending,
        }
    }

    fn is_end_stream(&self) -> bool {
        self.inner.is_end_stream()
    }

    fn size_hint(&self) -> http_body::SizeHint {
        self.inner.size_hint()
    }
}

pin_project! {
    /// Timeout that starts after request upload completes.
    pub(crate) struct FirstByteTimeout<F, R>
    where
        R: crate::runtime::RuntimeCompletion,
    {
        #[pin]
        future: F,
        request_body_complete: Arc<AtomicBool>,
        duration: Duration,
        #[pin]
        sleep: Option<R::Sleep>,
        _runtime: PhantomData<R>,
    }
}

impl<F, R> FirstByteTimeout<F, R>
where
    R: crate::runtime::RuntimeCompletion,
{
    pub(crate) fn new(
        future: F,
        request_body_complete: Arc<AtomicBool>,
        duration: Duration,
    ) -> Self {
        Self {
            future,
            request_body_complete,
            duration,
            sleep: None,
            _runtime: PhantomData,
        }
    }
}

impl<F, R, T, E> Future for FirstByteTimeout<F, R>
where
    F: Future<Output = Result<T, E>>,
    R: crate::runtime::RuntimeCompletion,
    E: From<crate::error::Error>,
{
    type Output = Result<T, E>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut this = self.project();
        if let Poll::Ready(result) = this.future.as_mut().poll(cx) {
            return Poll::Ready(result);
        }

        if this.request_body_complete.load(Ordering::Acquire) {
            if this.sleep.as_ref().get_ref().is_none() {
                this.sleep.set(Some(R::sleep(*this.duration)));
            }
            if let Some(sleep) = this.sleep.as_mut().as_pin_mut()
                && let Poll::Ready(()) = sleep.poll(cx)
            {
                this.sleep.set(None);
                return Poll::Ready(Err(crate::error::Error::Timeout.into()));
            }
        }

        Poll::Pending
    }
}

/// Race a future against an optional connect timeout using the runtime's sleep.
///
/// Maps `Error::Timeout` to `Error::ConnectTimeout` so proxy handshake timeouts
/// are classified correctly by `is_connect()`.
pub(crate) async fn connect_timeout<R, F, T>(
    future: F,
    timeout: Option<Duration>,
) -> Result<T, crate::error::Error>
where
    R: crate::runtime::RuntimeCompletion,
    F: Future<Output = Result<T, crate::error::Error>>,
{
    match timeout {
        Some(duration) => {
            match (Timeout::WithTimeout {
                future,
                sleep: R::sleep(duration),
            })
            .await
            {
                Err(crate::error::Error::Timeout) => Err(crate::error::Error::ConnectTimeout),
                other => other,
            }
        }
        None => future.await,
    }
}

pin_project! {
    /// Body wrapper that enforces a timeout between data chunks.
    ///
    /// Generic over the inner body type `B` — works with both `RequestBodySend`
    /// (Send path) and `ResponseBodyLocal` (Local path).
    pub(crate) struct ReadTimeoutBody<B, S: crate::runtime::RuntimeCompletion> {
        #[pin]
        inner: B,
        duration: Duration,
        #[pin]
        sleep: Option<S::Sleep>,
    }
}

impl<B, S: crate::runtime::RuntimeCompletion> ReadTimeoutBody<B, S> {
    pub fn new(inner: B, duration: Duration) -> Self {
        Self {
            inner,
            duration,
            sleep: None,
        }
    }
}

impl<B, S> http_body::Body for ReadTimeoutBody<B, S>
where
    B: http_body::Body<Data = Bytes, Error = crate::error::Error>,
    S: crate::runtime::RuntimeCompletion,
{
    type Data = Bytes;
    type Error = crate::error::Error;

    fn poll_frame(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
        let mut this = self.project();

        match this.inner.poll_frame(cx) {
            Poll::Ready(result) => {
                this.sleep.set(None);
                Poll::Ready(result)
            }
            Poll::Pending => {
                if this.sleep.as_ref().get_ref().is_none() {
                    this.sleep.set(Some(S::sleep(*this.duration)));
                }
                if let Some(sleep) = this.sleep.as_mut().as_pin_mut()
                    && let Poll::Ready(()) = sleep.poll(cx)
                {
                    this.sleep.set(None);
                    return Poll::Ready(Some(Err(crate::error::Error::ReadTimeout)));
                }
                Poll::Pending
            }
        }
    }

    fn is_end_stream(&self) -> bool {
        self.inner.is_end_stream()
    }

    fn size_hint(&self) -> http_body::SizeHint {
        self.inner.size_hint()
    }
}

pin_project! {
    /// Body wrapper that enforces a timeout between data chunks during upload.
    ///
    /// Generic over the inner body type `B` — works with both `RequestBodySend`
    /// (Send path) and `RequestBodyLocal` (Local path).
    ///
    /// When the HTTP engine cannot accept more data (flow-control backpressure),
    /// `poll_frame` returns `Pending` and the sleep timer starts. If the inner
    /// body remains `Pending` beyond the configured duration, an
    /// [`Error::WriteTimeout`](crate::error::Error::WriteTimeout) is emitted.
    pub(crate) struct WriteTimeoutBody<B, S: crate::runtime::RuntimeCompletion> {
        #[pin]
        inner: B,
        duration: Duration,
        #[pin]
        sleep: Option<S::Sleep>,
    }
}

impl<B, S: crate::runtime::RuntimeCompletion> WriteTimeoutBody<B, S> {
    pub fn new(inner: B, duration: Duration) -> Self {
        Self {
            inner,
            duration,
            sleep: None,
        }
    }
}

impl<B, S> http_body::Body for WriteTimeoutBody<B, S>
where
    B: http_body::Body<Data = Bytes, Error = crate::error::Error>,
    S: crate::runtime::RuntimeCompletion,
{
    type Data = Bytes;
    type Error = crate::error::Error;

    fn poll_frame(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
        let mut this = self.project();

        match this.inner.poll_frame(cx) {
            Poll::Ready(result) => {
                this.sleep.set(None);
                Poll::Ready(result)
            }
            Poll::Pending => {
                if this.sleep.as_ref().get_ref().is_none() {
                    this.sleep.set(Some(S::sleep(*this.duration)));
                }
                if let Some(sleep) = this.sleep.as_mut().as_pin_mut()
                    && let Poll::Ready(()) = sleep.poll(cx)
                {
                    this.sleep.set(None);
                    return Poll::Ready(Some(Err(crate::error::Error::WriteTimeout)));
                }
                Poll::Pending
            }
        }
    }

    fn is_end_stream(&self) -> bool {
        self.inner.is_end_stream()
    }

    fn size_hint(&self) -> http_body::SizeHint {
        self.inner.size_hint()
    }
}

#[cfg(all(test, feature = "tokio"))]
mod tests {
    use super::*;
    use std::task::{Context, Poll};

    #[tokio::test]
    async fn no_timeout_passes_through() {
        let t: Timeout<_, std::future::Ready<()>> = Timeout::NoTimeout {
            future: async { Ok::<i32, crate::error::Error>(42) },
        };
        let result = t.await;
        assert_eq!(result.unwrap(), 42);
    }

    #[tokio::test]
    async fn with_timeout_completes_before_deadline() {
        let t = Timeout::WithTimeout {
            future: async { Ok::<i32, crate::error::Error>(42) },
            sleep: tokio::time::sleep(Duration::from_secs(10)),
        };
        let result = t.await;
        assert_eq!(result.unwrap(), 42);
    }

    #[tokio::test]
    async fn with_timeout_fires_on_slow_future() {
        let t = Timeout::WithTimeout {
            future: async {
                tokio::time::sleep(Duration::from_secs(10)).await;
                Ok::<i32, crate::error::Error>(42)
            },
            sleep: tokio::time::sleep(Duration::from_millis(10)),
        };
        let result = t.await;
        assert!(matches!(result, Err(crate::error::Error::Timeout)));
    }

    #[tokio::test]
    async fn connect_timeout_maps_timeout_classification() {
        use crate::runtime::tokio_rt::TokioRuntime;

        let result = connect_timeout::<TokioRuntime, _, i32>(
            async {
                tokio::time::sleep(Duration::from_secs(10)).await;
                Ok(42)
            },
            Some(Duration::from_millis(1)),
        )
        .await;

        assert!(matches!(result, Err(crate::error::Error::ConnectTimeout)));
    }

    #[tokio::test]
    async fn read_timeout_body_end_stream() {
        use crate::runtime::tokio_rt::TokioRuntime;
        use http_body::Body;
        use http_body_util::BodyExt;

        let inner: crate::body::RequestBodySend = http_body_util::Empty::new()
            .map_err(|never| match never {})
            .boxed_unsync();
        let body = ReadTimeoutBody::<_, TokioRuntime>::new(inner, Duration::from_secs(1));
        assert!(body.is_end_stream());
    }

    #[tokio::test]
    async fn read_timeout_body_size_hint() {
        use crate::runtime::tokio_rt::TokioRuntime;
        use http_body::Body;
        use http_body_util::BodyExt;

        let inner: crate::body::RequestBodySend = http_body_util::Full::new(Bytes::from("hello"))
            .map_err(|never| match never {})
            .boxed_unsync();
        let body = ReadTimeoutBody::<_, TokioRuntime>::new(inner, Duration::from_secs(1));
        assert_eq!(body.size_hint().exact(), Some(5));
    }

    #[tokio::test]
    async fn read_timeout_body_passes_data() {
        use crate::runtime::tokio_rt::TokioRuntime;
        use http_body::Body;
        use http_body_util::BodyExt;

        let inner: crate::body::RequestBodySend = http_body_util::Full::new(Bytes::from("data"))
            .map_err(|never| match never {})
            .boxed_unsync();
        let body = ReadTimeoutBody::<_, TokioRuntime>::new(inner, Duration::from_secs(1));
        let mut boxed = Box::pin(body);
        let waker = std::task::Waker::noop();
        let mut cx = Context::from_waker(waker);
        let frame = boxed.as_mut().poll_frame(&mut cx);
        match frame {
            Poll::Ready(Some(Ok(f))) => {
                let data = f.into_data().unwrap();
                assert_eq!(data, Bytes::from("data"));
            }
            other => panic!("expected data frame, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn read_timeout_body_fires_on_pending() {
        use crate::runtime::tokio_rt::TokioRuntime;
        use http_body::Body;

        struct PendingBody;

        impl http_body::Body for PendingBody {
            type Data = Bytes;
            type Error = crate::error::Error;

            fn poll_frame(
                self: Pin<&mut Self>,
                _cx: &mut Context<'_>,
            ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
                Poll::Pending
            }

            fn is_end_stream(&self) -> bool {
                false
            }
        }

        use http_body_util::BodyExt;
        let inner: crate::body::RequestBodySend = PendingBody.boxed_unsync();
        let body = ReadTimeoutBody::<_, TokioRuntime>::new(inner, Duration::from_millis(1));
        let mut boxed = Box::pin(body);

        tokio::time::sleep(Duration::from_millis(10)).await;

        let waker = std::task::Waker::noop();
        let mut cx = Context::from_waker(waker);
        let _ = boxed.as_mut().poll_frame(&mut cx);

        tokio::time::sleep(Duration::from_millis(10)).await;
        let result = boxed.as_mut().poll_frame(&mut cx);
        assert!(
            matches!(
                result,
                Poll::Ready(Some(Err(crate::error::Error::ReadTimeout)))
            ),
            "expected ReadTimeout, got {:?}",
            result
        );
    }

    #[tokio::test]
    async fn read_timeout_with_response_body_send() {
        use crate::runtime::tokio_rt::TokioRuntime;
        use http_body::Body;
        use http_body_util::BodyExt;

        let inner: crate::body::RequestBodySend = http_body_util::Full::new(Bytes::from("data"))
            .map_err(|never| match never {})
            .boxed_unsync();
        let resp_body = crate::response::ResponseBodySend::from_boxed(inner);
        let body = ReadTimeoutBody::<_, TokioRuntime>::new(resp_body, Duration::from_secs(1));
        let mut boxed = Box::pin(body);
        let waker = std::task::Waker::noop();
        let mut cx = Context::from_waker(waker);
        let frame = boxed.as_mut().poll_frame(&mut cx);
        match frame {
            Poll::Ready(Some(Ok(f))) => {
                let data = f.into_data().unwrap();
                assert_eq!(data, Bytes::from("data"));
            }
            other => panic!("expected data frame, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn read_timeout_with_response_body_local_passes_data() {
        use crate::runtime::tokio_rt::TokioRuntime;
        use http_body::Body;
        use http_body_util::BodyExt;

        let local_body: crate::body::ResponseBodyLocal = Box::pin(
            http_body_util::Full::new(Bytes::from("local data")).map_err(|never| match never {}),
        );
        let body = ReadTimeoutBody::<_, TokioRuntime>::new(local_body, Duration::from_secs(1));
        let mut boxed = Box::pin(body);
        let waker = std::task::Waker::noop();
        let mut cx = Context::from_waker(waker);
        let frame = boxed.as_mut().poll_frame(&mut cx);
        match frame {
            Poll::Ready(Some(Ok(f))) => {
                let data = f.into_data().unwrap();
                assert_eq!(data, Bytes::from("local data"));
            }
            other => panic!("expected data frame, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn read_timeout_with_response_body_local_fires_on_pending() {
        use crate::runtime::tokio_rt::TokioRuntime;
        use http_body::Body;

        struct PendingLocalBody;
        impl http_body::Body for PendingLocalBody {
            type Data = Bytes;
            type Error = crate::error::Error;
            fn poll_frame(
                self: Pin<&mut Self>,
                _cx: &mut Context<'_>,
            ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
                Poll::Pending
            }
            fn is_end_stream(&self) -> bool {
                false
            }
        }

        let local_body: crate::body::ResponseBodyLocal = Box::pin(PendingLocalBody);
        let body = ReadTimeoutBody::<_, TokioRuntime>::new(local_body, Duration::from_millis(1));
        let mut boxed = Box::pin(body);

        tokio::time::sleep(Duration::from_millis(10)).await;

        let waker = std::task::Waker::noop();
        let mut cx = Context::from_waker(waker);
        let _ = boxed.as_mut().poll_frame(&mut cx);

        tokio::time::sleep(Duration::from_millis(10)).await;
        let result = boxed.as_mut().poll_frame(&mut cx);
        assert!(
            matches!(
                result,
                Poll::Ready(Some(Err(crate::error::Error::ReadTimeout)))
            ),
            "expected ReadTimeout on local body, got {:?}",
            result
        );
    }

    #[tokio::test]
    async fn write_timeout_body_passes_data() {
        use crate::runtime::tokio_rt::TokioRuntime;
        use http_body::Body;
        use http_body_util::BodyExt;

        let inner: crate::body::RequestBodySend = http_body_util::Full::new(Bytes::from("data"))
            .map_err(|never| match never {})
            .boxed_unsync();
        let body = WriteTimeoutBody::<_, TokioRuntime>::new(inner, Duration::from_secs(1));
        let mut boxed = Box::pin(body);
        let waker = std::task::Waker::noop();
        let mut cx = Context::from_waker(waker);
        let frame = boxed.as_mut().poll_frame(&mut cx);
        match frame {
            Poll::Ready(Some(Ok(f))) => {
                let data = f.into_data().unwrap();
                assert_eq!(data, Bytes::from("data"));
            }
            other => panic!("expected data frame, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn write_timeout_body_fires_on_pending() {
        use crate::runtime::tokio_rt::TokioRuntime;
        use http_body::Body;

        struct PendingBody;

        impl http_body::Body for PendingBody {
            type Data = Bytes;
            type Error = crate::error::Error;

            fn poll_frame(
                self: Pin<&mut Self>,
                _cx: &mut Context<'_>,
            ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
                Poll::Pending
            }

            fn is_end_stream(&self) -> bool {
                false
            }
        }

        use http_body_util::BodyExt;
        let inner: crate::body::RequestBodySend = PendingBody.boxed_unsync();
        let body = WriteTimeoutBody::<_, TokioRuntime>::new(inner, Duration::from_millis(1));
        let mut boxed = Box::pin(body);

        tokio::time::sleep(Duration::from_millis(10)).await;

        let waker = std::task::Waker::noop();
        let mut cx = Context::from_waker(waker);
        let _ = boxed.as_mut().poll_frame(&mut cx);

        tokio::time::sleep(Duration::from_millis(10)).await;
        let result = boxed.as_mut().poll_frame(&mut cx);
        assert!(
            matches!(
                result,
                Poll::Ready(Some(Err(crate::error::Error::WriteTimeout)))
            ),
            "expected WriteTimeout, got {:?}",
            result
        );
    }
}

/// Races a future against a deadline. Returns `Some(value)` if the future
/// completes first, or `None` if the deadline fires (timeout).
pub(crate) async fn race_deadline<F, S, T>(future: F, deadline: S) -> Option<T>
where
    F: Future<Output = T>,
    S: Future<Output = ()>,
{
    pin_project! {
        struct SelectLeft<F, S> {
            #[pin]
            left: F,
            #[pin]
            deadline: S,
        }
    }

    impl<F: Future<Output = T>, S: Future<Output = ()>, T> Future for SelectLeft<F, S> {
        type Output = Option<T>;

        fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
            let proj = self.project();
            if let Poll::Ready(val) = proj.left.poll(cx) {
                return Poll::Ready(Some(val));
            }
            if let Poll::Ready(()) = proj.deadline.poll(cx) {
                return Poll::Ready(None);
            }
            Poll::Pending
        }
    }

    SelectLeft {
        left: future,
        deadline,
    }
    .await
}