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
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
#![cfg(any(feature = "tokio", feature = "compio"))]

#[path = "middleware/request_response.rs"]
mod request_response;
use std::convert::Infallible;
use std::sync::Arc;
#[cfg(feature = "tokio")]
use std::sync::atomic::AtomicU32;
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(feature = "tokio")]
use std::time::Duration;

use bytes::Bytes;
use http_body_util::BodyExt;
use http_body_util::Full;
#[cfg(feature = "tokio")]
use hyper::Response;

#[cfg(feature = "compio")]
use aioduct::HttpEngineLocal;
#[cfg(feature = "tokio")]
use aioduct::HttpEngineSend;
#[cfg(feature = "tokio")]
use aioduct::runtime::TokioRuntime;
#[cfg(feature = "compio")]
use aioduct::runtime::compio_rt::{CompioRuntime, TcpConnector as CompioTcpConnector};
#[cfg(feature = "tokio")]
use aioduct::runtime::tokio_rt::TcpConnector;

#[cfg(feature = "tokio")]
use aioduct_test_server::h1::{h1_server, h1_server_with};

#[cfg(feature = "tokio")]
use aioduct_test_server::h2::h2_server;

#[cfg(feature = "tokio")]
#[tokio::test]
async fn test_middleware_on_error_callback() {
    use std::sync::atomic::AtomicBool;

    struct ErrorRecorder {
        error_seen: Arc<AtomicBool>,
    }

    impl aioduct::Middleware for ErrorRecorder {
        fn on_error(&self, _err: &aioduct::Error, _uri: &http::Uri, _method: &http::Method) {
            self.error_seen.store(true, Ordering::SeqCst);
        }
    }

    let error_seen = Arc::new(AtomicBool::new(false));
    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .middleware(ErrorRecorder {
            error_seen: error_seen.clone(),
        })
        .build()
        .unwrap();

    // Connect to a port that will refuse connection
    let result = client.get("http://127.0.0.1:1/").unwrap().send().await;
    assert!(result.is_err());
    assert!(
        error_seen.load(Ordering::SeqCst),
        "middleware on_error should have been called"
    );
}
#[cfg(feature = "tokio")]
#[tokio::test]
async fn test_middleware_on_redirect_callback() {
    use std::sync::atomic::AtomicBool;

    struct RedirectRecorder {
        redirect_seen: Arc<AtomicBool>,
    }

    impl aioduct::Middleware for RedirectRecorder {
        fn on_redirect(&self, _status: http::StatusCode, _from: &http::Uri, _to: &http::Uri) {
            self.redirect_seen.store(true, Ordering::SeqCst);
        }
    }

    let (final_addr, _counter) = h1_server().await;
    let (redirect_addr, _counter) = h1_server_with(move |_req| {
        let target = format!("http://{final_addr}/");
        async move {
            Ok::<_, Infallible>(
                Response::builder()
                    .status(302)
                    .header("location", target)
                    .body(Full::new(Bytes::new()))
                    .unwrap(),
            )
        }
    })
    .await;

    let redirect_seen = Arc::new(AtomicBool::new(false));
    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .middleware(RedirectRecorder {
            redirect_seen: redirect_seen.clone(),
        })
        .build()
        .unwrap();

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

    assert_eq!(resp.status(), http::StatusCode::OK);
    assert!(
        redirect_seen.load(Ordering::SeqCst),
        "middleware on_redirect should have been called"
    );
}
#[cfg(feature = "tokio")]
#[tokio::test]
async fn test_middleware_on_retry_callback() {
    use std::sync::atomic::AtomicBool;

    struct RetryRecorder {
        retry_seen: Arc<AtomicBool>,
    }

    impl aioduct::Middleware for RetryRecorder {
        fn on_retry(
            &self,
            _err: &aioduct::Error,
            _uri: &http::Uri,
            _method: &http::Method,
            _attempt: u32,
        ) {
            self.retry_seen.store(true, Ordering::SeqCst);
        }
    }

    let attempt = Arc::new(AtomicU32::new(0));
    let attempt_clone = attempt.clone();
    let (addr, _counter) = h1_server_with(move |_req| {
        let attempt = attempt_clone.clone();
        async move {
            let n = attempt.fetch_add(1, Ordering::SeqCst);
            if n < 1 {
                Ok::<_, Infallible>(
                    Response::builder()
                        .status(500)
                        .body(Full::new(Bytes::from("error")))
                        .unwrap(),
                )
            } else {
                Ok(Response::new(Full::new(Bytes::from("ok"))))
            }
        }
    })
    .await;

    let retry_seen = Arc::new(AtomicBool::new(false));
    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .middleware(RetryRecorder {
            retry_seen: retry_seen.clone(),
        })
        .retry(
            aioduct::RetryConfig::default()
                .max_retries(2)
                .initial_backoff(Duration::from_millis(10)),
        )
        .build()
        .unwrap();

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

    assert_eq!(resp.status(), http::StatusCode::OK);
    assert!(
        retry_seen.load(Ordering::SeqCst),
        "middleware on_retry should have been called"
    );
}

// ── Interaction Tests ──────────────────────────────────────────────────

/// Middleware sees every redirect in a 3-hop chain, recording from/to URIs.
#[cfg(feature = "tokio")]
#[tokio::test]
async fn middleware_on_redirect_sees_all_hops() {
    use std::sync::Mutex;

    // 3-hop chain: start -> hop1 -> hop2 -> final
    let (final_addr, _counter) = h1_server().await;

    let (hop2_addr, _counter) = h1_server_with({
        move |_req| {
            let target = format!("http://{final_addr}/");
            async move {
                Ok::<_, Infallible>(
                    Response::builder()
                        .status(302)
                        .header("location", target)
                        .body(Full::new(Bytes::new()))
                        .unwrap(),
                )
            }
        }
    })
    .await;

    let (hop1_addr, _counter) = h1_server_with({
        move |_req| {
            let target = format!("http://{hop2_addr}/");
            async move {
                Ok::<_, Infallible>(
                    Response::builder()
                        .status(302)
                        .header("location", target)
                        .body(Full::new(Bytes::new()))
                        .unwrap(),
                )
            }
        }
    })
    .await;

    let (start_addr, _counter) = h1_server_with({
        move |_req| {
            let target = format!("http://{hop1_addr}/");
            async move {
                Ok::<_, Infallible>(
                    Response::builder()
                        .status(302)
                        .header("location", target)
                        .body(Full::new(Bytes::new()))
                        .unwrap(),
                )
            }
        }
    })
    .await;

    struct HopRecorder {
        count: Arc<AtomicU32>,
        from_uris: Arc<Mutex<Vec<String>>>,
        to_uris: Arc<Mutex<Vec<String>>>,
    }

    impl aioduct::Middleware for HopRecorder {
        fn on_redirect(&self, _status: http::StatusCode, from: &http::Uri, to: &http::Uri) {
            self.count.fetch_add(1, Ordering::SeqCst);
            self.from_uris.lock().unwrap().push(from.to_string());
            self.to_uris.lock().unwrap().push(to.to_string());
        }
    }

    let count = Arc::new(AtomicU32::new(0));
    let from_uris = Arc::new(Mutex::new(Vec::new()));
    let to_uris = Arc::new(Mutex::new(Vec::new()));

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .middleware(HopRecorder {
            count: count.clone(),
            from_uris: from_uris.clone(),
            to_uris: to_uris.clone(),
        })
        .build()
        .unwrap();

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

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

    let n = count.load(Ordering::SeqCst);
    assert_eq!(n, 3, "expected 3 redirect hops, got {n}");

    let from = from_uris.lock().unwrap();
    let to = to_uris.lock().unwrap();
    assert_eq!(from.len(), 3);
    assert_eq!(to.len(), 3);

    // First redirect: start -> hop1
    assert!(
        from[0].contains(&start_addr.to_string()),
        "first from should be start"
    );
    assert!(
        to[0].contains(&hop1_addr.to_string()),
        "first to should be hop1"
    );
    // Second redirect: hop1 -> hop2
    assert!(
        from[1].contains(&hop1_addr.to_string()),
        "second from should be hop1"
    );
    assert!(
        to[1].contains(&hop2_addr.to_string()),
        "second to should be hop2"
    );
    // Third redirect: hop2 -> final
    assert!(
        from[2].contains(&hop2_addr.to_string()),
        "third from should be hop2"
    );
    assert!(
        to[2].contains(&final_addr.to_string()),
        "third to should be final"
    );
}

/// Middleware on_error fires when connect_timeout expires targeting a
/// non-routable IP.
#[cfg(feature = "tokio")]
#[tokio::test]
async fn middleware_on_error_for_connect_timeout() {
    struct TimeoutRecorder {
        error_seen: Arc<AtomicBool>,
        error_is_timeout: Arc<AtomicBool>,
    }

    impl aioduct::Middleware for TimeoutRecorder {
        fn on_error(&self, err: &aioduct::Error, _uri: &http::Uri, _method: &http::Method) {
            self.error_seen.store(true, Ordering::SeqCst);
            if err.is_timeout() {
                self.error_is_timeout.store(true, Ordering::SeqCst);
            }
        }
    }

    let error_seen = Arc::new(AtomicBool::new(false));
    let error_is_timeout = Arc::new(AtomicBool::new(false));

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .middleware(TimeoutRecorder {
            error_seen: error_seen.clone(),
            error_is_timeout: error_is_timeout.clone(),
        })
        .connect_timeout(Duration::from_millis(50))
        .build()
        .unwrap();

    // 192.0.2.1 is TEST-NET-1 (RFC 5737), non-routable
    let result = client.get("http://192.0.2.1:81/").unwrap().send().await;

    assert!(result.is_err(), "connect timeout should produce an error");
    assert!(
        error_seen.load(Ordering::SeqCst),
        "middleware on_error should have been called"
    );
    assert!(
        error_is_timeout.load(Ordering::SeqCst),
        "error should be classified as a timeout error"
    );
}

/// Middleware on_response fires for both the priming request and the
/// subsequent fresh cache hit.
#[cfg(feature = "tokio")]
#[tokio::test]
async fn middleware_with_cache_fresh_hit() {
    let (addr, _counter) = h1_server_with(|_req| async {
        Ok::<_, Infallible>(
            Response::builder()
                .header("cache-control", "max-age=3600")
                .body(Full::new(Bytes::from("cached body")))
                .unwrap(),
        )
    })
    .await;

    struct CacheAwareMiddleware {
        response_count: Arc<AtomicU32>,
    }

    impl aioduct::Middleware for CacheAwareMiddleware {
        fn on_response(
            &self,
            _response: &mut http::Response<aioduct::body::RequestBodySend>,
            _uri: &http::Uri,
        ) {
            self.response_count.fetch_add(1, Ordering::SeqCst);
        }
    }

    let response_count = Arc::new(AtomicU32::new(0));
    let cache = aioduct::HttpCache::new();
    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .cache(cache)
        .middleware(CacheAwareMiddleware {
            response_count: response_count.clone(),
        })
        .build()
        .unwrap();

    let url = format!("http://{addr}/resource");

    // First request primes the cache
    let resp = client.get(&url).unwrap().send().await.unwrap();
    assert_eq!(resp.text().await.unwrap(), "cached body");
    assert_eq!(
        response_count.load(Ordering::SeqCst),
        1,
        "on_response should fire for initial request"
    );

    // Second request is a fresh cache hit
    let resp = client.get(&url).unwrap().send().await.unwrap();
    assert_eq!(resp.text().await.unwrap(), "cached body");
    assert_eq!(
        response_count.load(Ordering::SeqCst),
        2,
        "on_response should fire for fresh cache hit too"
    );
}

/// Middleware modifies the request URI path; the server receives the
/// modified path.
#[cfg(feature = "tokio")]
#[tokio::test]
async fn middleware_modifies_uri_in_on_request() {
    let (addr, _counter) = h1_server_with(|req| async move {
        let path = req.uri().path().to_string();
        Ok::<_, Infallible>(Response::new(Full::new(Bytes::from(path))))
    })
    .await;

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .middleware(
            |req: &mut http::Request<aioduct::body::RequestBodySend>, uri: &http::Uri| {
                // Change the path in the request URI to /modified
                let modified_uri = format!(
                    "http://{}:{}/modified",
                    uri.authority().map(|a| a.host()).unwrap_or("127.0.0.1"),
                    uri.authority().and_then(|a| a.port_u16()).unwrap_or(80)
                );
                *req.uri_mut() = modified_uri.parse().unwrap();
            },
        )
        .build()
        .unwrap();

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

    assert_eq!(resp.status(), http::StatusCode::OK);
    assert_eq!(
        resp.text().await.unwrap(),
        "/modified",
        "middleware should have changed the URI path to /modified"
    );
}

/// When a retry budget is exhausted due to a transport error on the retry
/// attempt, on_retry fires first and on_error fires on the final failure.
#[cfg(feature = "tokio")]
#[tokio::test]
async fn middleware_on_retry_exhausted_fires_on_error() {
    use tokio::io::AsyncWriteExt;
    use tokio::net::TcpListener;

    let attempt = Arc::new(AtomicU32::new(0));
    let attempt_clone = attempt.clone();

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

    // Raw TCP server: returns 500 on first connection, drops connection on retry
    tokio::spawn(async move {
        loop {
            let (mut stream, _) = match listener.accept().await {
                Ok(v) => v,
                Err(_) => break,
            };
            let n = attempt_clone.fetch_add(1, Ordering::SeqCst);
            if n == 0 {
                // First request: proper 500 response
                let _ = stream
                    .write_all(b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
                    .await;
            }
            // Retry attempt: drop the stream immediately to cause a
            // transport error (connection reset / incomplete response).
            drop(stream);
        }
    });

    struct RetryExhaustedRecorder {
        retry_count: Arc<AtomicU32>,
        error_seen: Arc<AtomicBool>,
    }

    impl aioduct::Middleware for RetryExhaustedRecorder {
        fn on_retry(
            &self,
            _err: &aioduct::Error,
            _uri: &http::Uri,
            _method: &http::Method,
            _attempt: u32,
        ) {
            self.retry_count.fetch_add(1, Ordering::SeqCst);
        }
        fn on_error(&self, _err: &aioduct::Error, _uri: &http::Uri, _method: &http::Method) {
            self.error_seen.store(true, Ordering::SeqCst);
        }
    }

    let retry_count = Arc::new(AtomicU32::new(0));
    let error_seen = Arc::new(AtomicBool::new(false));

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .middleware(RetryExhaustedRecorder {
            retry_count: retry_count.clone(),
            error_seen: error_seen.clone(),
        })
        .retry(
            aioduct::RetryConfig::default()
                .max_retries(1)
                .initial_backoff(Duration::from_millis(10)),
        )
        .build()
        .unwrap();

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

    assert!(result.is_err(), "retry exhausted should result in an error");
    assert_eq!(
        retry_count.load(Ordering::SeqCst),
        1,
        "on_retry should fire once when the first attempt fails with 500"
    );
    assert!(
        error_seen.load(Ordering::SeqCst),
        "on_error should fire when the retry budget is exhausted by a transport error"
    );
}

// ── Interaction Tests: Transport, SSE, Local, Streaming ────────────────────────

/// Middleware `on_request` and `on_response` hooks both fire when using
/// HTTP/2 prior knowledge.
#[cfg(feature = "tokio")]
#[tokio::test]
async fn middleware_with_h2_transport() {
    let (addr, _counter) = h2_server().await;

    struct TransportCountingMiddleware {
        on_request_count: Arc<AtomicU32>,
        on_response_count: Arc<AtomicU32>,
    }

    impl aioduct::Middleware for TransportCountingMiddleware {
        fn on_request(
            &self,
            _req: &mut http::Request<aioduct::body::RequestBodySend>,
            _uri: &http::Uri,
        ) {
            self.on_request_count.fetch_add(1, Ordering::SeqCst);
        }
        fn on_response(
            &self,
            _resp: &mut http::Response<aioduct::body::RequestBodySend>,
            _uri: &http::Uri,
        ) {
            self.on_response_count.fetch_add(1, Ordering::SeqCst);
        }
    }

    let on_request_count = Arc::new(AtomicU32::new(0));
    let on_response_count = Arc::new(AtomicU32::new(0));

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .middleware(TransportCountingMiddleware {
            on_request_count: on_request_count.clone(),
            on_response_count: on_response_count.clone(),
        })
        .build()
        .unwrap();

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

    assert_eq!(resp.status(), http::StatusCode::OK);
    assert_eq!(
        resp.version(),
        http::Version::HTTP_2,
        "response should use HTTP/2"
    );
    let body = resp.text().await.unwrap();
    assert_eq!(body, "hello aioduct");

    assert_eq!(
        on_request_count.load(Ordering::SeqCst),
        1,
        "on_request should fire once on H2 transport"
    );
    assert_eq!(
        on_response_count.load(Ordering::SeqCst),
        1,
        "on_response should fire once on H2 transport"
    );
}

/// Middleware `on_response` fires before the SSE stream is consumed.
/// Response headers from middleware survive `into_sse_stream()`.
#[cfg(feature = "tokio")]
#[tokio::test]
async fn middleware_with_sse_streaming() {
    let (addr, _counter) = h1_server_with(|_req| async move {
        Ok::<_, Infallible>(
            Response::builder()
                .header("content-type", "text/event-stream")
                .header("cache-control", "no-cache")
                .body(Full::new(Bytes::from("data: hello sse\n\n")))
                .unwrap(),
        )
    })
    .await;

    struct SseMiddleware {
        on_response_count: Arc<AtomicU32>,
        on_request_count: Arc<AtomicU32>,
    }

    impl aioduct::Middleware for SseMiddleware {
        fn on_request(
            &self,
            _req: &mut http::Request<aioduct::body::RequestBodySend>,
            _uri: &http::Uri,
        ) {
            self.on_request_count.fetch_add(1, Ordering::SeqCst);
        }
        fn on_response(
            &self,
            response: &mut http::Response<aioduct::body::RequestBodySend>,
            _uri: &http::Uri,
        ) {
            self.on_response_count.fetch_add(1, Ordering::SeqCst);
            response.headers_mut().insert(
                http::header::HeaderName::from_static("x-sse-from-middleware"),
                http::header::HeaderValue::from_static("tagged"),
            );
        }
    }

    let on_request_count = Arc::new(AtomicU32::new(0));
    let on_response_count = Arc::new(AtomicU32::new(0));

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .middleware(SseMiddleware {
            on_request_count: on_request_count.clone(),
            on_response_count: on_response_count.clone(),
        })
        .build()
        .unwrap();

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

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

    // on_response fires during dispatch, before the caller gets the Response
    assert_eq!(
        on_request_count.load(Ordering::SeqCst),
        1,
        "on_request should fire before SSE stream consumption"
    );
    assert_eq!(
        on_response_count.load(Ordering::SeqCst),
        1,
        "on_response should fire before SSE stream consumption"
    );

    // Headers survive the middleware chain — verify before consuming the body
    assert_eq!(
        resp.headers()
            .get("x-sse-from-middleware")
            .unwrap()
            .to_str()
            .unwrap(),
        "tagged",
        "middleware-added header should be visible on the response"
    );

    // Consume via into_sse_stream() — this takes ownership of the response
    let mut sse = resp.into_sse_stream();
    let event = sse.next().await.unwrap().unwrap();
    match event {
        aioduct::sse::SseEvent::Message(m) => {
            assert_eq!(m.data, "hello sse");
        }
        other => panic!("expected SSE message, got {other:?}"),
    }
    assert!(sse.next().await.is_none(), "SSE stream should be exhausted");
}

/// Middleware `apply_request_local` modifies headers that the server sees.
/// When middleware does NOT replace the body, the original body is preserved
/// (not accidentally consumed by the sentinel in the middleware bridge).
#[cfg(feature = "compio")]
#[test]
fn middleware_apply_request_local_full_path() {
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
            let addr = listener.local_addr().unwrap();
            tx.send(addr).unwrap();

            loop {
                let (stream, _) = match listener.accept().await {
                    Ok(v) => v,
                    Err(_) => break,
                };
                tokio::spawn(async move {
                    let io = aioduct_test_server::TokioIo::new(stream);
                    let svc = hyper::service::service_fn(
                        |req: hyper::Request<hyper::body::Incoming>| async move {
                            let header_val = req
                                .headers()
                                .get("x-local-middleware")
                                .map(|v| v.to_str().unwrap().to_string())
                                .unwrap_or_else(|| "missing".to_string());
                            let body_bytes = req.into_body().collect().await.unwrap().to_bytes();
                            let body_str = String::from_utf8_lossy(&body_bytes);
                            Ok::<_, Infallible>(hyper::Response::new(Full::new(Bytes::from(
                                format!("{header_val}|{body_str}"),
                            ))))
                        },
                    );
                    let _ = hyper::server::conn::http1::Builder::new()
                        .serve_connection(io, svc)
                        .await;
                });
            }
        });
    });
    let addr: std::net::SocketAddr = rx.recv().unwrap();

    compio_runtime::Runtime::new().unwrap().block_on(async {
        // ── Part 1: middleware modifies headers, server sees them ───

        struct HeaderInjector {
            fired: Arc<AtomicBool>,
        }

        impl aioduct::Middleware for HeaderInjector {
            fn on_request(
                &self,
                req: &mut http::Request<aioduct::body::RequestBodySend>,
                _uri: &http::Uri,
            ) {
                self.fired.store(true, Ordering::SeqCst);
                req.headers_mut().insert(
                    http::header::HeaderName::from_static("x-local-middleware"),
                    http::header::HeaderValue::from_static("yes-from-local"),
                );
            }
        }

        let fired = Arc::new(AtomicBool::new(false));
        let client = HttpEngineLocal::<CompioRuntime, CompioTcpConnector>::builder()
            .middleware(HeaderInjector {
                fired: fired.clone(),
            })
            .build_local()
            .unwrap();

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

        assert!(
            fired.load(Ordering::SeqCst),
            "middleware on_request should fire"
        );
        assert_eq!(resp.status(), http::StatusCode::OK);
        let body = resp.text().await.unwrap();
        assert!(
            body.starts_with("yes-from-local|"),
            "server should receive middleware header, got: {body}"
        );

        // ── Part 2: middleware modifies metadata only, body preserved ───

        struct MetadataOnlyMiddleware {
            fired: Arc<AtomicBool>,
        }

        impl aioduct::Middleware for MetadataOnlyMiddleware {
            fn on_request(
                &self,
                req: &mut http::Request<aioduct::body::RequestBodySend>,
                _uri: &http::Uri,
            ) {
                self.fired.store(true, Ordering::SeqCst);
                req.headers_mut().insert(
                    http::header::HeaderName::from_static("x-local-middleware"),
                    http::header::HeaderValue::from_static("metadata-only"),
                );
            }
        }

        let fired2 = Arc::new(AtomicBool::new(false));
        let client2 = HttpEngineLocal::<CompioRuntime, CompioTcpConnector>::builder()
            .middleware(MetadataOnlyMiddleware {
                fired: fired2.clone(),
            })
            .build_local()
            .unwrap();

        let resp2 = client2
            .get_local(&format!("http://{addr}/echo-body"))
            .unwrap()
            .body("original-body-content")
            .send()
            .await
            .unwrap();

        assert!(
            fired2.load(Ordering::SeqCst),
            "metadata-only middleware should fire"
        );
        assert_eq!(resp2.status(), http::StatusCode::OK);
        let body2 = resp2.text().await.unwrap();
        assert!(
            body2.starts_with("metadata-only|"),
            "server should receive middleware header, got: {body2}"
        );
        assert!(
            body2.contains("original-body-content"),
            "body should be preserved when middleware only modifies metadata, got: {body2}"
        );
    });
}

/// Middleware `on_request` fires and header modifications reach the server
/// when using a streaming request body. The streaming body is preserved.
#[cfg(feature = "tokio")]
#[tokio::test]
async fn middleware_with_streaming_request_body() {
    let (addr, _counter) = h1_server_with(|req| async move {
        use http_body_util::BodyExt;
        let middleware_header = req
            .headers()
            .get("x-streaming-header")
            .map(|v| v.to_str().unwrap().to_string())
            .unwrap_or_else(|| "absent".to_string());
        let body_bytes = req.into_body().collect().await.unwrap().to_bytes();
        let body_str = String::from_utf8_lossy(&body_bytes);
        Ok::<_, Infallible>(Response::new(Full::new(Bytes::from(format!(
            "header={middleware_header}|body={body_str}"
        )))))
    })
    .await;

    struct StreamingRequestMiddleware {
        on_request_count: Arc<AtomicU32>,
    }

    impl aioduct::Middleware for StreamingRequestMiddleware {
        fn on_request(
            &self,
            req: &mut http::Request<aioduct::body::RequestBodySend>,
            _uri: &http::Uri,
        ) {
            self.on_request_count.fetch_add(1, Ordering::SeqCst);
            req.headers_mut().insert(
                http::header::HeaderName::from_static("x-streaming-header"),
                http::header::HeaderValue::from_static("streaming-injected"),
            );
        }
    }

    let on_request_count = Arc::new(AtomicU32::new(0));

    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .middleware(StreamingRequestMiddleware {
            on_request_count: on_request_count.clone(),
        })
        .build()
        .unwrap();

    let stream_body: aioduct::body::RequestBodySend =
        http_body_util::Full::new(Bytes::from("streaming-payload"))
            .map_err(|never| match never {})
            .boxed_unsync();

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

    assert_eq!(resp.status(), http::StatusCode::OK);
    let body = resp.text().await.unwrap();

    assert_eq!(
        on_request_count.load(Ordering::SeqCst),
        1,
        "on_request should fire for streaming request"
    );
    assert!(
        body.contains("header=streaming-injected"),
        "server should receive streaming header, got: {body}"
    );
    assert!(
        body.contains("body=streaming-payload"),
        "streaming body should be preserved through middleware, got: {body}"
    );
}

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

/// Middleware `on_response` sees the original `Content-Encoding: gzip` header
/// before decompression in `finalize_response`. After consuming the body, the
/// decompressed text must match the original plaintext.
#[cfg(all(feature = "tokio", feature = "gzip"))]
#[tokio::test]
async fn middleware_on_response_sees_original_headers_before_decompression() {
    use flate2::Compression;
    use flate2::write::GzEncoder;
    use std::io::Write;

    let content = "hello middleware before decompress";
    let mut encoder = GzEncoder::new(Vec::new(), Compression::fast());
    encoder.write_all(content.as_bytes()).unwrap();
    let compressed = encoder.finish().unwrap();
    let compressed_len = compressed.len();

    let (addr, _counter) = h1_server_with(move |_req| {
        let compressed = compressed.clone();
        async move {
            Ok::<_, Infallible>(
                Response::builder()
                    .header("content-encoding", "gzip")
                    .header("content-length", compressed_len.to_string())
                    .body(Full::new(Bytes::from(compressed)))
                    .unwrap(),
            )
        }
    })
    .await;

    struct DecompressObserver {
        saw_content_encoding: Arc<AtomicBool>,
    }

    impl aioduct::Middleware for DecompressObserver {
        fn on_response(
            &self,
            response: &mut http::Response<aioduct::body::RequestBodySend>,
            _uri: &http::Uri,
        ) {
            self.saw_content_encoding.store(
                response.headers().get("content-encoding").is_some(),
                Ordering::SeqCst,
            );
        }
    }

    let saw_content_encoding = Arc::new(AtomicBool::new(false));
    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .middleware(DecompressObserver {
            saw_content_encoding: saw_content_encoding.clone(),
        })
        .build()
        .unwrap();

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

    // on_response fires during finalize_response, BEFORE decompress step
    assert!(
        saw_content_encoding.load(Ordering::SeqCst),
        "on_response must see Content-Encoding: gzip before decompression"
    );

    // Headers have been stripped by decompress() after middleware ran
    assert!(
        resp.headers().get("content-encoding").is_none(),
        "Content-Encoding should be stripped after decompression"
    );

    // Body is decompressed correctly
    let text = resp.text().await.unwrap();
    assert_eq!(text, content);
}

/// HSTS pre-loaded with `localhost: includeSubDomains`. Server A redirects
/// to `http://localhost:<port_B>/target`. HSTS upgrades the redirect target
/// to https. Middleware `on_redirect` must see the UPGRADED https URI.
#[cfg(feature = "tokio")]
#[tokio::test]
async fn middleware_on_redirect_with_hsts_upgrade() {
    use std::sync::Mutex;

    // Server B: the final target (plain h1, not used after redirect)
    let (port_b_addr, _counter) = h1_server().await;

    // Server A: redirects to http://localhost:<port_B>/target
    let port_b_port = port_b_addr.port();
    let (port_a_addr, _counter) = h1_server_with({
        move |_req| {
            let target = format!("http://localhost:{port_b_port}/target");
            async move {
                Ok::<_, Infallible>(
                    Response::builder()
                        .status(302)
                        .header("location", target)
                        .body(Full::new(Bytes::new()))
                        .unwrap(),
                )
            }
        }
    })
    .await;

    // Pre-load HSTS store: localhost with includeSubDomains
    let mut hsts_headers = http::HeaderMap::new();
    hsts_headers.insert(
        "strict-transport-security",
        "max-age=31536000; includeSubDomains".parse().unwrap(),
    );
    let hsts_store = aioduct::hsts::HstsStore::new();
    hsts_store.store_from_response("localhost", &hsts_headers);

    struct HstsRedirectRecorder {
        redirect_target: Arc<Mutex<Option<String>>>,
    }

    impl aioduct::Middleware for HstsRedirectRecorder {
        fn on_redirect(&self, _status: http::StatusCode, _from: &http::Uri, to: &http::Uri) {
            *self.redirect_target.lock().unwrap() = Some(to.to_string());
        }
    }

    let redirect_target = Arc::new(Mutex::new(None));
    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .middleware(HstsRedirectRecorder {
            redirect_target: redirect_target.clone(),
        })
        .hsts(hsts_store)
        .connect_timeout(Duration::from_millis(200))
        .build()
        .unwrap();

    // Initial request uses 127.0.0.1 (NOT in HSTS) so it is not upgraded.
    // Only the redirect target (localhost) is HSTS-upgraded.
    let port_a_port = port_a_addr.port();
    let result = client
        .get(&format!("http://127.0.0.1:{port_a_port}/"))
        .unwrap()
        .send()
        .await;

    // We don't care whether the redirected request succeeds — the
    // HSTS-upgraded target uses https but the server only speaks plain
    // HTTP. The middleware recorded the redirect URI before the engine
    // attempted to follow it.
    let _ = result;

    let recorded = redirect_target.lock().unwrap();
    let uri = recorded
        .as_ref()
        .expect("on_redirect should have recorded a target URI");
    assert!(
        uri.starts_with("https://localhost:"),
        "on_redirect must see the HSTS-upgraded https URI, got: {uri}"
    );
    assert!(
        uri.ends_with("/target"),
        "redirect target path must be preserved, got: {uri}"
    );
}

/// Middleware `on_request` fires even when `force_addr` bypasses DNS.
/// The Host header in the outgoing request matches the URL authority,
/// not the forced address.
#[cfg(feature = "tokio")]
#[tokio::test]
async fn middleware_on_request_with_force_addr() {
    let (addr, _counter) = h1_server_with(|req| async move {
        let host_header = req
            .headers()
            .get("host")
            .map(|v| v.to_str().unwrap().to_string())
            .unwrap_or_default();
        let middleware_header = req
            .headers()
            .get("x-force-addr-middleware")
            .map(|v| v.to_str().unwrap().to_string())
            .unwrap_or_default();
        Ok::<_, Infallible>(Response::new(Full::new(Bytes::from(format!(
            "host={host_header}|mw={middleware_header}"
        )))))
    })
    .await;

    struct ForceAddrMiddleware {
        on_request_fired: Arc<AtomicBool>,
    }

    impl aioduct::Middleware for ForceAddrMiddleware {
        fn on_request(
            &self,
            req: &mut http::Request<aioduct::body::RequestBodySend>,
            _uri: &http::Uri,
        ) {
            self.on_request_fired.store(true, Ordering::SeqCst);
            req.headers_mut().insert(
                http::header::HeaderName::from_static("x-force-addr-middleware"),
                http::header::HeaderValue::from_static("injected"),
            );
        }
    }

    let on_request_fired = Arc::new(AtomicBool::new(false));
    let client = HttpEngineSend::<TokioRuntime, TcpConnector>::builder()
        .middleware(ForceAddrMiddleware {
            on_request_fired: on_request_fired.clone(),
        })
        .build()
        .unwrap();

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

    assert_eq!(resp.status(), http::StatusCode::OK);
    assert!(
        on_request_fired.load(Ordering::SeqCst),
        "on_request must fire even when force_addr is used"
    );

    let body = resp.text().await.unwrap();
    assert!(
        body.contains("mw=injected"),
        "middleware should inject x-force-addr-middleware header, got: {body}"
    );
    assert!(
        body.contains(&format!("host=localhost:{}", addr.port())),
        "Host header must match URL authority (localhost:{}), not force_addr, got: {body}",
        addr.port()
    );
}