aioduct 0.2.4

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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
#![cfg(feature = "tokio")]

#[path = "timeouts/connection_acquisition.rs"]
mod connection_acquisition;
#[path = "timeouts/read_timeout.rs"]
mod read_timeout;
#[path = "timeouts/request_timeout.rs"]
mod request_timeout;
#[path = "timeouts/write_timeout.rs"]
mod write_timeout;
use std::convert::Infallible;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;

use bytes::Bytes;
use http_body_util::Full;
use hyper::Response;

use aioduct::HttpEngineSend;
use aioduct::observer::{
    ConnectionEvent, ConnectionPhase, RequestEvent, RequestObserver, RequestPhase,
};
use aioduct::runtime::TokioRuntime;
use aioduct::runtime::tokio_rt::TcpConnector;

use aioduct_test_server::h1::{h1_server, h1_server_with};

#[derive(Default, Clone)]
struct RecordingObserver {
    events: Arc<Mutex<Vec<RequestPhase>>>,
    connection_events: Arc<Mutex<Vec<ConnectionPhase>>>,
}

impl RequestObserver for RecordingObserver {
    fn on_event(&self, event: &RequestEvent) {
        self.events.lock().unwrap().push(event.phase.clone());
    }

    fn on_connection_event(&self, event: &ConnectionEvent) {
        self.connection_events
            .lock()
            .unwrap()
            .push(event.phase.clone());
    }
}

impl RecordingObserver {
    fn phases(&self) -> Vec<String> {
        self.events
            .lock()
            .unwrap()
            .iter()
            .map(|p| match p {
                RequestPhase::Started => "Started".into(),
                RequestPhase::PoolCheckoutComplete { outcome, .. } => {
                    format!("PoolCheckoutComplete({outcome:?})")
                }
                RequestPhase::DnsResolved { .. } => "DnsResolved".into(),
                RequestPhase::TcpConnected { .. } => "TcpConnected".into(),
                RequestPhase::TlsHandshakeComplete { .. } => "TlsHandshakeComplete".into(),
                RequestPhase::RequestSent { .. } => "RequestSent".into(),
                RequestPhase::ResponseStarted { .. } => "ResponseStarted".into(),
                RequestPhase::ResponseComplete { .. } => "ResponseComplete".into(),
                RequestPhase::Failed { .. } => "Failed".into(),
                RequestPhase::BytesTransferred { .. } => "BytesTransferred".into(),
                RequestPhase::TransferComplete { .. } => "TransferComplete".into(),
                RequestPhase::TransferAborted { .. } => "TransferAborted".into(),
                RequestPhase::Redirected { .. } => "Redirected".into(),
                RequestPhase::Retrying { .. } => "Retrying".into(),
                RequestPhase::TrailersReceived { .. } => "TrailersReceived".into(),
            })
            .collect()
    }
}

#[tokio::test]
async fn test_connect_timeout() {
    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .connect_timeout(Duration::from_millis(100))
        .build()
        .unwrap();

    let start = tokio::time::Instant::now();
    let result = client
        .get("http://192.0.2.1:81/slow")
        .unwrap()
        .timeout(Duration::from_secs(5))
        .send()
        .await;

    assert!(result.is_err(), "connect_timeout should fire");
    assert!(
        start.elapsed() < Duration::from_secs(2),
        "should timeout quickly, not wait for request timeout"
    );
}

#[tokio::test]
async fn client_timeout_triggers_on_slow_response() {
    let (addr, _counter) = h1_server_with(|_req| async {
        tokio::time::sleep(Duration::from_millis(300)).await;
        Ok::<_, Infallible>(Response::new(Full::new(Bytes::from("slow"))))
    })
    .await;

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .timeout(Duration::from_millis(100))
        .build()
        .unwrap();

    let result = client.get(&format!("http://{addr}/")).unwrap().send().await;

    let err = result.unwrap_err();
    assert!(err.is_timeout(), "expected timeout, got: {err:?}");
}

#[tokio::test]
async fn per_request_timeout_triggers_on_slow_response() {
    let (addr, _counter) = h1_server_with(|_req| async {
        tokio::time::sleep(Duration::from_millis(300)).await;
        Ok::<_, Infallible>(Response::new(Full::new(Bytes::from("slow"))))
    })
    .await;

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::new();

    let result = client
        .get(&format!("http://{addr}/"))
        .unwrap()
        .timeout(Duration::from_millis(100))
        .send()
        .await;

    let err = result.unwrap_err();
    assert!(err.is_timeout(), "expected timeout, got: {err:?}");
}

#[tokio::test]
async fn connect_timeout_with_unreachable_ip() {
    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .connect_timeout(Duration::from_millis(100))
        .build()
        .unwrap();

    let result = client
        .get("http://192.0.2.1:81/slow")
        .unwrap()
        .timeout(Duration::from_secs(5))
        .send()
        .await;

    let err = result.unwrap_err();
    assert!(
        err.is_timeout() || err.is_connect(),
        "expected timeout or connect error, got: {err:?}"
    );
}

#[tokio::test]
async fn read_timeout_does_not_apply_to_headers() {
    // aioduct's read_timeout only applies to body reads, not header wait time.
    // Use request timeout for header wait timeouts.
    let (addr, _counter) = h1_server_with(|_req| async {
        tokio::time::sleep(Duration::from_millis(200)).await;
        Ok::<_, Infallible>(Response::new(Full::new(Bytes::from("slow headers"))))
    })
    .await;

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .read_timeout(Duration::from_millis(100))
        .timeout(Duration::from_secs(5))
        .build()
        .unwrap();

    let resp = client
        .get(&format!("http://{addr}/"))
        .unwrap()
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), http::StatusCode::OK);
    assert_eq!(resp.text().await.unwrap(), "slow headers");
}

#[tokio::test]
async fn request_timeout_overrides_client_timeout() {
    let (addr, _counter) = h1_server_with(|_req| async {
        tokio::time::sleep(Duration::from_millis(150)).await;
        Ok::<_, Infallible>(Response::new(Full::new(Bytes::from("delayed"))))
    })
    .await;

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .timeout(Duration::from_millis(50))
        .build()
        .unwrap();

    let resp = client
        .get(&format!("http://{addr}/"))
        .unwrap()
        .timeout(Duration::from_secs(5))
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), http::StatusCode::OK);
    assert_eq!(resp.text().await.unwrap(), "delayed");
}

#[tokio::test]
async fn timeout_fast_response_succeeds() {
    let (addr, _counter) = h1_server().await;

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .timeout(Duration::from_secs(5))
        .build()
        .unwrap();

    let resp = client
        .get(&format!("http://{addr}/"))
        .unwrap()
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), http::StatusCode::OK);
    assert_eq!(resp.content_length(), Some(13));
    let text = resp.text().await.unwrap();
    assert_eq!(text, "hello aioduct");
}

#[tokio::test]
async fn connect_timeout_does_not_affect_fast_connects() {
    let (addr, _counter) = h1_server().await;

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .connect_timeout(Duration::from_secs(5))
        .build()
        .unwrap();

    let resp = client
        .get(&format!("http://{addr}/"))
        .unwrap()
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), http::StatusCode::OK);
}

// ── Edge-Case Timeout Tests ─────────────────────────────────────────────

// 1. Per-request connect_timeout without client-level connect_timeout.
#[tokio::test]
async fn connect_timeout_per_request() {
    // Use TEST-NET-1 (RFC 5737) — guaranteed unroutable, TCP connect will time out.
    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::new();

    let result = client
        .get("http://192.0.2.1:81/unreachable")
        .unwrap()
        .connect_timeout(Duration::from_millis(100))
        .send()
        .await;

    assert!(
        result.is_err(),
        "per-request connect_timeout should produce an error for unroutable IP"
    );
    let err = result.unwrap_err();
    // Platform-dependent error classification:
    // - Linux: TCP SYN times out → is_timeout()
    // - macOS / some platforms: ICMP host unreachable arrives quickly → is_connect()
    assert!(
        err.is_timeout() || err.is_connect(),
        "expected timeout or connect error, got: {err:?}"
    );
}

// 2. Timeout fires during body upload when server reads slowly.
#[tokio::test]
async fn timeout_during_body_upload() {
    use tokio::io::AsyncReadExt;

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();

    // Server: accept connection, read only headers, then delay reading body.
    // This causes TCP send buffer backpressure on the client side.
    tokio::spawn(async move {
        let (mut stream, _) = listener.accept().await.unwrap();
        let mut buf = [0u8; 8192];
        let mut total = 0;
        loop {
            let n = stream.read(&mut buf[total..]).await.unwrap();
            if n == 0 {
                return;
            }
            total += n;
            if buf[..total].windows(4).any(|w| w == b"\r\n\r\n") {
                break;
            }
        }
        // Server has read headers but intentionally does not read the body.
        // Sleep to keep the connection open while client uploads.
        tokio::time::sleep(Duration::from_secs(30)).await;
    });

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .timeout(Duration::from_millis(500))
        .build()
        .unwrap();

    // Large streaming body: many small chunks to prolong streaming time
    // and reliably trigger TCP send buffer backpressure within the 500ms timeout.
    // CI note: 500×1KB reduces total data vs 200×64KB while extending wall time.
    use http_body_util::BodyExt;
    let chunk = Bytes::from(vec![b'X'; 1024]);
    let num_chunks = 500;
    let chunks: Vec<_> = (0..num_chunks)
        .map(|_| Ok(hyper::body::Frame::data(chunk.clone())))
        .collect();
    let stream = futures_util::stream::iter(chunks);
    let stream_body: aioduct::body::RequestBodySend =
        http_body_util::StreamBody::new(stream).boxed_unsync();

    let result = client
        .post(&format!("http://{addr}/upload"))
        .unwrap()
        .body_stream(stream_body)
        .send()
        .await;

    assert!(result.is_err(), "timeout should fire during body upload");
    let err = result.unwrap_err();
    assert!(
        err.is_timeout(),
        "expected timeout during upload, got: {err:?}"
    );
}

// 3. After a request times out, the timed-out connection is not returned to the pool.
#[tokio::test]
async fn timeout_cancellation_does_not_pool_broken_connection() {
    let slow_req_count = Arc::new(AtomicUsize::new(0));
    let rc = Arc::clone(&slow_req_count);

    let (addr, _counter) = h1_server_with(move |_req| {
        let n = rc.fetch_add(1, Ordering::SeqCst);
        async move {
            if n == 1 {
                // Second request (n=1): sleep past the client timeout.
                tokio::time::sleep(Duration::from_secs(10)).await;
            }
            Ok::<_, Infallible>(Response::new(Full::new(Bytes::from("ok"))))
        }
    })
    .await;

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .pool_idle_timeout(Duration::from_secs(60))
        .pool_max_idle_per_host(5)
        .timeout(Duration::from_millis(200))
        .build()
        .unwrap();

    // Prime the pool with one connection.
    let resp = client
        .get(&format!("http://{addr}/"))
        .unwrap()
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), http::StatusCode::OK);
    let _body = resp.text().await.unwrap();
    // Allow time for connection to be returned to pool.
    tokio::time::sleep(Duration::from_millis(100)).await;

    // Second request uses the pooled connection but times out mid-response.
    let result = client.get(&format!("http://{addr}/")).unwrap().send().await;
    assert!(result.is_err(), "second request should time out");
    assert!(result.unwrap_err().is_timeout());
    // Allow time for pool eviction.
    tokio::time::sleep(Duration::from_millis(100)).await;

    // After timeout, a new request should still succeed (fresh connection).
    let resp = client
        .get(&format!("http://{addr}/"))
        .unwrap()
        .timeout(Duration::from_secs(5))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), http::StatusCode::OK);
    let _body = resp.text().await.unwrap();
}

// 4. Timeout covers the entire redirect chain, not reset per hop.
#[tokio::test]
async fn timeout_during_redirect_chain() {
    // Server B: slow — sleeps 500 ms before responding.
    let (slow_addr, _slow_counter) = h1_server_with(|_req| async {
        tokio::time::sleep(Duration::from_millis(500)).await;
        Ok::<_, Infallible>(Response::new(Full::new(Bytes::from("slow response"))))
    })
    .await;

    // Server A: redirects to the slow Server B immediately.
    let (redirect_addr, _redirect_counter) = h1_server_with(move |_req| {
        let target = format!("http://{slow_addr}/slow");
        async move {
            Ok::<_, Infallible>(
                Response::builder()
                    .status(302)
                    .header("location", target)
                    .body(Full::new(Bytes::new()))
                    .unwrap(),
            )
        }
    })
    .await;

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .timeout(Duration::from_millis(200))
        .build()
        .unwrap();

    // The timeout covers the redirect hop + slow response — 200 ms < 500 ms.
    let result = client
        .get(&format!("http://{redirect_addr}/start"))
        .unwrap()
        .send()
        .await;

    assert!(
        result.is_err(),
        "200ms timeout should fire before 500ms redirect chain completes"
    );
    let err = result.unwrap_err();
    assert!(
        err.is_timeout(),
        "expected timeout bounding entire redirect chain, got: {err:?}"
    );

    // With a generous per-request timeout the same redirect chain succeeds.
    let resp = client
        .get(&format!("http://{redirect_addr}/start"))
        .unwrap()
        .timeout(Duration::from_secs(5))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), http::StatusCode::OK);
    let body = resp.text().await.unwrap();
    assert_eq!(body, "slow response");
}

// 5a. connect_timeout fires independently from overall timeout.
#[tokio::test]
async fn connect_timeout_independent_of_overall_timeout() {
    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .connect_timeout(Duration::from_millis(100))
        .timeout(Duration::from_secs(10))
        .build()
        .unwrap();

    let result = client
        .get("http://192.0.2.1:82/unreachable")
        .unwrap()
        .send()
        .await;
    assert!(result.is_err(), "connect_timeout should fire");
    let err = result.unwrap_err();
    assert!(err.is_timeout() || err.is_connect());
}

// 5b. Overall timeout does not interfere with fast successful requests.
#[tokio::test]
async fn overall_timeout_allows_fast_requests() {
    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .timeout(Duration::from_secs(10))
        .build()
        .unwrap();

    let (addr, _counter) = h1_server().await;
    let resp = client
        .get(&format!("http://{addr}/"))
        .unwrap()
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), http::StatusCode::OK);
    let body = resp.text().await.unwrap();
    assert_eq!(body, "hello aioduct");
}

// 5c. read_timeout fires on stalled body reads, independently of overall timeout.
#[tokio::test]
async fn read_timeout_independent_of_overall_timeout() {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .read_timeout(Duration::from_millis(500))
        .timeout(Duration::from_secs(10))
        .build()
        .unwrap();

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let read_addr = listener.local_addr().unwrap();

    tokio::spawn(async move {
        let (mut stream, _) = listener.accept().await.unwrap();
        let mut buf = [0u8; 4096];
        let _ = stream.read(&mut buf).await;
        // Send headers + partial body, then stall.
        stream
            .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nhello")
            .await
            .unwrap();
        stream.flush().await.unwrap();
        // Never send the remaining 5 bytes.
        tokio::time::sleep(Duration::from_secs(30)).await;
    });

    let resp = client
        .get(&format!("http://{read_addr}/"))
        .unwrap()
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), http::StatusCode::OK);

    let body_result = resp.text().await;
    assert!(
        body_result.is_err(),
        "read_timeout should fire on stalled body chunks"
    );
    assert!(
        body_result.unwrap_err().is_timeout(),
        "error should be a timeout error"
    );
}

// ── Elapsed-timing discrimination and pool-eviction tests ─────────────────

/// A raw H1 server that sends headers + a partial body and then stalls forever.
/// Used to exercise response read-timeout behavior deterministically.
async fn stalling_body_server() -> std::net::SocketAddr {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();

    tokio::spawn(async move {
        loop {
            let (mut stream, _) = match listener.accept().await {
                Ok(c) => c,
                Err(_) => return,
            };
            tokio::spawn(async move {
                let mut buf = [0u8; 4096];
                let _ = stream.read(&mut buf).await;
                let _ = stream
                    .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nhello")
                    .await;
                let _ = stream.flush().await;
                // Never send the remaining 5 bytes.
                tokio::time::sleep(Duration::from_secs(30)).await;
            });
        }
    });

    addr
}

/// Per-request `read_timeout()` overrides the client default. The client default
/// is generous (5 s) but the per-request override (100 ms) fires on the stalled
/// body.
#[tokio::test]
async fn per_request_read_timeout_overrides_client_default() {
    let addr = stalling_body_server().await;

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .read_timeout(Duration::from_secs(5))
        .timeout(Duration::from_secs(30))
        .build()
        .unwrap();

    let start = tokio::time::Instant::now();
    let resp = client
        .get(&format!("http://{addr}/"))
        .unwrap()
        .read_timeout(Duration::from_millis(100))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), http::StatusCode::OK);

    let err = resp.bytes().await.unwrap_err();
    assert!(
        matches!(err, aioduct::Error::ReadTimeout),
        "per-request read_timeout should fire, got: {err:?}"
    );
    assert!(
        start.elapsed() < Duration::from_secs(2),
        "per-request 100ms read_timeout should fire well before the 5s client default, elapsed {:?}",
        start.elapsed()
    );
}

/// A request with no per-request read_timeout still inherits the client default.
#[tokio::test]
async fn per_request_read_timeout_inherits_client_default() {
    let addr = stalling_body_server().await;

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .read_timeout(Duration::from_millis(100))
        .timeout(Duration::from_secs(30))
        .build()
        .unwrap();

    let resp = client
        .get(&format!("http://{addr}/"))
        .unwrap()
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), http::StatusCode::OK);

    let err = resp.bytes().await.unwrap_err();
    assert!(
        matches!(err, aioduct::Error::ReadTimeout),
        "client default read_timeout should still apply when no per-request override is set, got: {err:?}"
    );
}

/// read_timeout is a per-chunk gap, not a one-shot first-read deadline. A body
/// that keeps trickling chunks just under the read_timeout interval must NOT
/// time out, even when the total transfer far exceeds a single interval.
#[tokio::test]
async fn read_timeout_resets_between_chunks_not_total_transfer() {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();

    // 10 chunks, 50ms apart = ~500ms total, well over the 150ms read_timeout
    // but each gap (50ms) is under it.
    tokio::spawn(async move {
        let (mut stream, _) = listener.accept().await.unwrap();
        let mut buf = [0u8; 4096];
        let _ = stream.read(&mut buf).await;
        stream
            .write_all(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n")
            .await
            .unwrap();
        stream.flush().await.unwrap();
        for i in 0..10u8 {
            tokio::time::sleep(Duration::from_millis(50)).await;
            let chunk = format!("1\r\n{}\r\n", (b'0' + i) as char);
            stream.write_all(chunk.as_bytes()).await.unwrap();
            stream.flush().await.unwrap();
        }
        stream.write_all(b"0\r\n\r\n").await.unwrap();
        stream.flush().await.unwrap();
    });

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .read_timeout(Duration::from_millis(150))
        .timeout(Duration::from_secs(30))
        .build()
        .unwrap();

    let resp = client
        .get(&format!("http://{addr}/"))
        .unwrap()
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), http::StatusCode::OK);

    let body = resp.text().await.unwrap();
    assert_eq!(
        body, "0123456789",
        "steady sub-interval chunks should complete; read_timeout must reset per chunk"
    );
}

/// A stalled `.text()` body read with a per-request read_timeout returns an
/// error promptly instead of hanging indefinitely.
#[tokio::test]
async fn read_timeout_bounds_stalled_text_read() {
    let addr = stalling_body_server().await;

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::new();

    let resp = client
        .get(&format!("http://{addr}/"))
        .unwrap()
        .read_timeout(Duration::from_millis(100))
        .send()
        .await
        .unwrap();

    let start = tokio::time::Instant::now();
    let err = resp.text().await.unwrap_err();
    assert!(
        matches!(err, aioduct::Error::ReadTimeout),
        "stalled text() read should be bounded by read_timeout, got: {err:?}"
    );
    assert!(
        start.elapsed() < Duration::from_secs(2),
        "text() must not hang; read_timeout should fire promptly, elapsed {:?}",
        start.elapsed()
    );
}

/// Both per-request timeout and read-timeout surface as `is_timeout()`.
/// Only elapsed timing distinguishes which one fired: the per-request
/// timeout fires at 200 ms, while read_timeout would wait 5 s.
///
/// The server delays sending *everything* (headers included) beyond 100 ms,
/// so the per-request deadline triggers during `send()`.
#[tokio::test]
async fn per_request_timeout_vs_read_timeout_distinguished_by_elapsed() {
    let (addr, _counter) = h1_server_with(|_req| async {
        tokio::time::sleep(Duration::from_millis(200)).await;
        Ok::<_, Infallible>(Response::new(Full::new(Bytes::from("delayed"))))
    })
    .await;

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .read_timeout(Duration::from_secs(5))
        .build()
        .unwrap();

    let start = tokio::time::Instant::now();
    let result = client
        .get(&format!("http://{addr}/"))
        .unwrap()
        .timeout(Duration::from_millis(200))
        .send()
        .await;

    assert!(result.is_err(), "per-request timeout should fire");
    assert!(result.unwrap_err().is_timeout());
    assert!(
        start.elapsed() < Duration::from_millis(1000),
        "elapsed {:?} — per-request timeout (~200ms) should fire, not read_timeout (5s)",
        start.elapsed()
    );
}

/// When read_timeout fires on a pooled connection (headers received, body
/// stalls), the broken connection must be evicted from the pool.  A
/// subsequent request must open a fresh TCP connection.
#[tokio::test]
async fn read_timeout_evicts_pooled_connection() {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();

    // Raw TCP server that honours keep-alive so the pool can reuse connections.
    // Request 1 → full body (prime pool).  Request 2 → partial body + stall.
    // Request 3 → new TCP connection with full body (fresh connection).
    let conn_count = Arc::new(AtomicUsize::new(0));
    let cc = Arc::clone(&conn_count);
    tokio::spawn(async move {
        loop {
            let (mut stream, _) = match listener.accept().await {
                Ok(c) => c,
                Err(_) => return,
            };
            // Handle keep-alive: read multiple HTTP requests on one TCP conn.
            loop {
                let mut buf = vec![0u8; 4096];
                let n_read = match stream.read(&mut buf).await {
                    Ok(0) | Err(_) => break,
                    Ok(n) => n,
                };
                if n_read == 0 {
                    break;
                }

                let n = cc.fetch_add(1, Ordering::SeqCst);

                match n {
                    // Request 0 — full body (prime pool), keep-alive
                    0 => {
                        stream
                            .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello")
                            .await
                            .unwrap();
                        stream.flush().await.unwrap();
                        // Continue inner loop — wait for next request on same conn.
                    }
                    // Request 1 — headers + partial body, then stall
                    1 => {
                        stream
                            .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nhel")
                            .await
                            .unwrap();
                        stream.flush().await.unwrap();
                        // Stall: never send the remaining bytes.
                        tokio::time::sleep(Duration::from_millis(500)).await;
                        break; // Close connection after stall.
                    }
                    // Request 2+ — full body on fresh connection
                    _ => {
                        stream
                            .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nworld")
                            .await
                            .unwrap();
                        stream.flush().await.unwrap();
                        break;
                    }
                }
            }
        }
    });

    let obs = RecordingObserver::default();

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .pool_idle_timeout(Duration::from_secs(60))
        .pool_max_idle_per_host(5)
        .read_timeout(Duration::from_millis(100))
        .timeout(Duration::from_secs(10))
        .request_observer(obs.clone())
        .build()
        .unwrap();

    // Prime the pool.
    let resp = client
        .get(&format!("http://{addr}/"))
        .unwrap()
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), http::StatusCode::OK);
    let _body = resp.bytes().await.unwrap();
    // Give the connection time to be returned to the pool.
    tokio::time::sleep(Duration::from_millis(50)).await;

    // Clear events — we only want request 2's phases.
    obs.events.lock().unwrap().clear();

    // Second request: should use pooled connection, read_timeout fires on stalled body.
    let resp2 = client
        .get(&format!("http://{addr}/"))
        .unwrap()
        .send()
        .await
        .unwrap();
    assert_eq!(resp2.status(), http::StatusCode::OK);

    // Verify request 2 reused the pooled connection (no new TCP connect).
    let phases2 = obs.phases();
    assert!(
        !phases2.contains(&"TcpConnected".to_string()),
        "request 2 should reuse pooled connection, got phases: {phases2:?}"
    );
    assert!(
        phases2.contains(&"PoolCheckoutComplete(Hit)".to_string()),
        "request 2 should hit the pool, got phases: {phases2:?}"
    );

    let body_result = resp2.text().await;
    match &body_result {
        Ok(text) => {
            panic!(
                "body read should have timed out, but got body text: {text:?} (len={})",
                text.len()
            );
        }
        Err(e) => {
            assert!(e.is_timeout(), "expected read_timeout error, got: {e:?}");
        }
    }
    // Allow time for the broken connection to be evicted from the pool.
    tokio::time::sleep(Duration::from_millis(100)).await;

    // Clear events so we only see the third request's lifecycle.
    obs.events.lock().unwrap().clear();

    // Third request must succeed on a fresh connection.
    let resp3 = client
        .get(&format!("http://{addr}/"))
        .unwrap()
        .send()
        .await
        .unwrap();
    assert_eq!(resp3.status(), http::StatusCode::OK);
    let _body = resp3.bytes().await.unwrap();

    // The third request MUST have opened a new TCP connection — the stalled
    // pooled connection was evicted.
    let phases = obs.phases();
    assert!(
        phases.contains(&"TcpConnected".to_string()),
        "third request should use a fresh TCP connection (stalled connection evicted), got phases: {phases:?}"
    );
}

/// When a request times out while uploading a streaming body (server never
/// reads the request), no response headers exist — the error is purely a
/// timeout, not a body or status error.
#[tokio::test]
async fn upload_timeout_no_response_received() {
    use tokio::io::AsyncReadExt;

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();

    // Server accepts the connection but never reads the request body.
    tokio::spawn(async move {
        let (mut stream, _) = listener.accept().await.unwrap();
        let mut buf = [0u8; 8192];
        let mut total = 0;
        loop {
            let n = stream.read(&mut buf[total..]).await.unwrap();
            if n == 0 {
                return;
            }
            total += n;
            if buf[..total].windows(4).any(|w| w == b"\r\n\r\n") {
                break;
            }
        }
        // Headers received; now stall — never read the streaming body.
        tokio::time::sleep(Duration::from_secs(30)).await;
    });

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .build()
        .unwrap();

    // Large (non-buffered) streaming body to fill TCP send buffers.
    use http_body_util::BodyExt;
    let chunk = Bytes::from(vec![b'X'; 65536]);
    let num_chunks = 200;
    let chunks: Vec<_> = (0..num_chunks)
        .map(|_| Ok(hyper::body::Frame::data(chunk.clone())))
        .collect();
    let stream = futures_util::stream::iter(chunks);
    let stream_body: aioduct::body::RequestBodySend =
        http_body_util::StreamBody::new(stream).boxed_unsync();

    let result = client
        .post(&format!("http://{addr}/upload"))
        .unwrap()
        .body_stream(stream_body)
        .timeout(Duration::from_millis(200))
        .send()
        .await;

    assert!(result.is_err(), "timeout should fire during upload phase");
    let err = result.unwrap_err();
    assert!(
        err.is_timeout(),
        "expected timeout during upload, got: {err:?}"
    );
    // No response was received, so there are no headers, status, or cookies
    // to inspect — the error is purely a timeout.
}

/// Each retry attempt gets its own timeout window; the timeout does not span
/// across retry attempts.  If the timeout spanned all attempts, a 200 ms
/// server with 3 attempts would exceed 300 ms, but with per-attempt windows
/// each attempt fits.
#[tokio::test]
async fn timeout_between_retry_attempts_is_per_attempt() {
    let attempt = Arc::new(AtomicUsize::new(0));
    let attempt_clone = Arc::clone(&attempt);

    let (addr, _counter) = h1_server_with(move |_req| {
        let a = Arc::clone(&attempt_clone);
        async move {
            a.fetch_add(1, Ordering::SeqCst);
            tokio::time::sleep(Duration::from_millis(200)).await;
            Ok::<_, Infallible>(
                Response::builder()
                    .status(500)
                    .body(Full::new(Bytes::from("server error")))
                    .unwrap(),
            )
        }
    })
    .await;

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::new();

    let start = tokio::time::Instant::now();
    let resp = client
        .get(&format!("http://{addr}/"))
        .unwrap()
        .timeout(Duration::from_millis(300))
        .retry(
            aioduct::RetryConfig::default()
                .max_retries(2)
                .initial_backoff(Duration::from_millis(10)),
        )
        .send()
        .await
        .unwrap();

    // After exhausting retries (max_retries=2 → 3 total attempts), the
    // final 500 response is returned.
    assert_eq!(resp.status(), http::StatusCode::INTERNAL_SERVER_ERROR);

    let elapsed = start.elapsed();
    assert!(
        elapsed < Duration::from_secs(1),
        "total elapsed {:?} should be under 1s — proving each attempt gets its own timeout window",
        elapsed
    );

    // At least one retry happened (2+ total requests).
    let total_requests = attempt.load(Ordering::SeqCst);
    assert!(
        total_requests >= 2,
        "expected at least one retry, got {total_requests} requests"
    );
    let _body = resp.text().await; // consume body to satisfy the server's connection
}

/// Per-request no_timeout() bypasses the client's default timeout.
#[tokio::test]
async fn no_timeout_bypasses_client_default() {
    let (addr, _counter) = h1_server_with(|_req| async {
        tokio::time::sleep(Duration::from_millis(500)).await;
        Ok::<_, Infallible>(Response::new(Full::new(Bytes::from("slow"))))
    })
    .await;

    // Client default timeout 50ms — would fire before the 500ms server delay.
    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .timeout(Duration::from_millis(50))
        .build()
        .unwrap();

    // Without no_timeout(), this would fail.
    let no_timeout_result = client.get(&format!("http://{addr}/")).unwrap().send().await;
    assert!(no_timeout_result.is_err());
    assert!(no_timeout_result.unwrap_err().is_timeout());

    // With no_timeout(), the request succeeds despite the client default.
    let resp = client
        .get(&format!("http://{addr}/"))
        .unwrap()
        .no_timeout()
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), http::StatusCode::OK);
    assert_eq!(resp.text().await.unwrap(), "slow");
}