aioduct 0.2.0-alpha.1

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
use std::sync::Arc;

use http::{Method, StatusCode, Uri};

#[cfg(not(target_arch = "wasm32"))]
use http_body_util::BodyExt;

#[cfg(not(target_arch = "wasm32"))]
use crate::body::RequestBodyLocal;
use crate::body::RequestBodySend;
use crate::error::Error;

/// Middleware that can inspect or modify requests and responses.
///
/// Implement this trait to add cross-cutting behavior like logging, metrics,
/// or auth token refresh. Middleware is applied in order: request hooks run
/// first-to-last, response hooks run last-to-first.
///
/// Note: all hooks are synchronous. Async operations (e.g., token refresh) are not supported.
pub trait Middleware: Send + Sync + 'static {
    /// Called before the request is sent. May modify the request in place.
    fn on_request(&self, request: &mut http::Request<RequestBodySend>, uri: &Uri) {
        let _ = (request, uri);
    }

    /// Called after the response is received. May modify the response in place.
    fn on_response(&self, response: &mut http::Response<RequestBodySend>, uri: &Uri) {
        let _ = (response, uri);
    }

    /// Called when a request fails with an error.
    fn on_error(&self, error: &Error, uri: &Uri, method: &Method) {
        let _ = (error, uri, method);
    }

    /// Called when a redirect is followed.
    fn on_redirect(&self, status: StatusCode, from: &Uri, to: &Uri) {
        let _ = (status, from, to);
    }

    /// Called before a retry attempt.
    fn on_retry(&self, error: &Error, uri: &Uri, method: &Method, attempt: u32) {
        let _ = (error, uri, method, attempt);
    }
}

impl<F> Middleware for F
where
    F: Fn(&mut http::Request<RequestBodySend>, &Uri) + Send + Sync + 'static,
{
    fn on_request(&self, request: &mut http::Request<RequestBodySend>, uri: &Uri) {
        (self)(request, uri);
    }
}

struct SentinelBody {
    replaced: std::sync::Arc<std::sync::atomic::AtomicBool>,
}

impl http_body::Body for SentinelBody {
    type Data = bytes::Bytes;
    type Error = Error;

    fn poll_frame(
        self: std::pin::Pin<&mut Self>,
        _cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {
        std::task::Poll::Ready(None)
    }
}

impl Drop for SentinelBody {
    fn drop(&mut self) {
        self.replaced
            .store(true, std::sync::atomic::Ordering::Relaxed);
    }
}

pub(crate) struct MiddlewareStack {
    layers: Vec<Arc<dyn Middleware>>,
}

impl Clone for MiddlewareStack {
    fn clone(&self) -> Self {
        Self {
            layers: self.layers.clone(),
        }
    }
}

impl MiddlewareStack {
    pub fn new() -> Self {
        Self { layers: Vec::new() }
    }

    pub fn push(&mut self, middleware: Arc<dyn Middleware>) {
        self.layers.push(middleware);
    }

    pub fn is_empty(&self) -> bool {
        self.layers.is_empty()
    }

    pub fn apply_request(&self, request: &mut http::Request<RequestBodySend>, uri: &Uri) {
        for layer in &self.layers {
            layer.on_request(request, uri);
        }
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub fn apply_request_local(&self, request: &mut http::Request<RequestBodyLocal>, uri: &Uri) {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicBool, Ordering};

        let body_replaced = Arc::new(AtomicBool::new(false));
        let sentinel = SentinelBody {
            replaced: Arc::clone(&body_replaced),
        };
        let dummy_body: RequestBodySend = sentinel.boxed_unsync();
        let mut proxy = http::Request::new(dummy_body);
        *proxy.method_mut() = request.method().clone();
        *proxy.uri_mut() = request.uri().clone();
        *proxy.version_mut() = request.version();
        *proxy.headers_mut() = request.headers().clone();
        *proxy.extensions_mut() = request.extensions().clone();
        for layer in &self.layers {
            layer.on_request(&mut proxy, uri);
        }
        *request.method_mut() = proxy.method().clone();
        *request.uri_mut() = proxy.uri().clone();
        *request.version_mut() = proxy.version();
        *request.headers_mut() = proxy.headers().clone();
        *request.extensions_mut() = proxy.extensions().clone();
        if body_replaced.load(Ordering::Relaxed) {
            let (_, body) = proxy.into_parts();
            *request.body_mut() = Box::pin(body);
        }
    }

    pub fn apply_response(&self, response: &mut http::Response<RequestBodySend>, uri: &Uri) {
        for layer in self.layers.iter().rev() {
            layer.on_response(response, uri);
        }
    }

    pub fn apply_error(&self, error: &Error, uri: &Uri, method: &Method) {
        for layer in &self.layers {
            layer.on_error(error, uri, method);
        }
    }

    pub fn apply_redirect(&self, status: StatusCode, from: &Uri, to: &Uri) {
        for layer in &self.layers {
            layer.on_redirect(status, from, to);
        }
    }

    pub fn apply_retry(&self, error: &Error, uri: &Uri, method: &Method, attempt: u32) {
        for layer in &self.layers {
            layer.on_retry(error, uri, method, attempt);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use http_body_util::BodyExt;
    use std::sync::Mutex;

    fn empty_body() -> RequestBodySend {
        http_body_util::Full::new(bytes::Bytes::new())
            .map_err(|never| match never {})
            .boxed_unsync()
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn local_body() -> RequestBodyLocal {
        Box::pin(http_body_util::Full::new(bytes::Bytes::new()).map_err(|never| match never {}))
    }

    fn test_uri() -> Uri {
        "http://example.com/test".parse().unwrap()
    }

    struct RecordingMiddleware {
        id: i32,
        log: Arc<Mutex<Vec<(i32, &'static str)>>>,
    }

    impl Middleware for RecordingMiddleware {
        fn on_request(&self, _req: &mut http::Request<RequestBodySend>, _uri: &Uri) {
            self.log.lock().unwrap().push((self.id, "request"));
        }
        fn on_response(&self, _resp: &mut http::Response<RequestBodySend>, _uri: &Uri) {
            self.log.lock().unwrap().push((self.id, "response"));
        }
        fn on_error(&self, _err: &Error, _uri: &Uri, _method: &Method) {
            self.log.lock().unwrap().push((self.id, "error"));
        }
        fn on_redirect(&self, _status: StatusCode, _from: &Uri, _to: &Uri) {
            self.log.lock().unwrap().push((self.id, "redirect"));
        }
        fn on_retry(&self, _err: &Error, _uri: &Uri, _method: &Method, _attempt: u32) {
            self.log.lock().unwrap().push((self.id, "retry"));
        }
    }

    fn make_stack(log: &Arc<Mutex<Vec<(i32, &'static str)>>>) -> MiddlewareStack {
        let mut stack = MiddlewareStack::new();
        stack.push(Arc::new(RecordingMiddleware {
            id: 1,
            log: Arc::clone(log),
        }));
        stack.push(Arc::new(RecordingMiddleware {
            id: 2,
            log: Arc::clone(log),
        }));
        stack
    }

    #[test]
    fn new_stack_is_empty() {
        let stack = MiddlewareStack::new();
        assert!(stack.is_empty());
    }

    #[test]
    fn push_makes_non_empty() {
        let mut stack = MiddlewareStack::new();
        let log = Arc::new(Mutex::new(Vec::new()));
        stack.push(Arc::new(RecordingMiddleware {
            id: 1,
            log: Arc::clone(&log),
        }));
        assert!(!stack.is_empty());
    }

    #[test]
    fn apply_request_runs_first_to_last() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let stack = make_stack(&log);
        let uri = test_uri();
        let mut req = http::Request::get("http://example.com")
            .body(empty_body())
            .unwrap();
        stack.apply_request(&mut req, &uri);
        let entries = log.lock().unwrap();
        assert_eq!(entries[0], (1, "request"));
        assert_eq!(entries[1], (2, "request"));
    }

    #[test]
    fn apply_response_runs_last_to_first() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let stack = make_stack(&log);
        let uri = test_uri();
        let mut resp = http::Response::builder()
            .status(200)
            .body(empty_body())
            .unwrap();
        stack.apply_response(&mut resp, &uri);
        let entries = log.lock().unwrap();
        assert_eq!(entries[0], (2, "response"));
        assert_eq!(entries[1], (1, "response"));
    }

    #[test]
    fn apply_error_invokes_all() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let stack = make_stack(&log);
        let uri = test_uri();
        stack.apply_error(&Error::Timeout, &uri, &Method::GET);
        let entries = log.lock().unwrap();
        assert_eq!(entries.len(), 2);
        assert!(entries.iter().all(|(_, kind)| *kind == "error"));
    }

    #[test]
    fn apply_redirect_invokes_all() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let stack = make_stack(&log);
        let from: Uri = "http://a.com".parse().unwrap();
        let to: Uri = "http://b.com".parse().unwrap();
        stack.apply_redirect(StatusCode::MOVED_PERMANENTLY, &from, &to);
        let entries = log.lock().unwrap();
        assert_eq!(entries.len(), 2);
        assert!(entries.iter().all(|(_, kind)| *kind == "redirect"));
    }

    #[test]
    fn apply_retry_invokes_all() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let stack = make_stack(&log);
        let uri = test_uri();
        stack.apply_retry(&Error::Timeout, &uri, &Method::POST, 1);
        let entries = log.lock().unwrap();
        assert_eq!(entries.len(), 2);
        assert!(entries.iter().all(|(_, kind)| *kind == "retry"));
    }

    #[test]
    fn closure_as_middleware() {
        let mut stack = MiddlewareStack::new();
        stack.push(Arc::new(
            |req: &mut http::Request<RequestBodySend>, _uri: &Uri| {
                req.headers_mut()
                    .insert("x-test", http::header::HeaderValue::from_static("added"));
            },
        ));
        let uri = test_uri();
        let mut req = http::Request::get("http://example.com")
            .body(empty_body())
            .unwrap();
        stack.apply_request(&mut req, &uri);
        assert_eq!(req.headers().get("x-test").unwrap(), "added");
    }

    #[test]
    fn clone_preserves_layers() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let stack = make_stack(&log);
        let cloned = stack.clone();
        assert!(!cloned.is_empty());
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn apply_request_local_copies_headers_from_middleware() {
        let mut stack = MiddlewareStack::new();
        stack.push(Arc::new(
            |req: &mut http::Request<RequestBodySend>, _uri: &Uri| {
                req.headers_mut().insert(
                    "x-injected",
                    http::header::HeaderValue::from_static("hello"),
                );
            },
        ));
        let uri = test_uri();
        let mut req = http::Request::get("http://example.com/path")
            .body(local_body())
            .unwrap();
        stack.apply_request_local(&mut req, &uri);
        assert_eq!(req.headers().get("x-injected").unwrap(), "hello");
    }

    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn apply_request_local_copies_method_change() {
        let mut stack = MiddlewareStack::new();
        stack.push(Arc::new(
            |req: &mut http::Request<RequestBodySend>, _uri: &Uri| {
                *req.method_mut() = Method::POST;
            },
        ));
        let uri = test_uri();
        let mut req = http::Request::get("http://example.com")
            .body(local_body())
            .unwrap();
        assert_eq!(req.method(), Method::GET);
        stack.apply_request_local(&mut req, &uri);
        assert_eq!(req.method(), Method::POST);
    }

    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn apply_request_local_copies_uri_change() {
        let mut stack = MiddlewareStack::new();
        stack.push(Arc::new(
            |req: &mut http::Request<RequestBodySend>, _uri: &Uri| {
                *req.uri_mut() = "http://redirected.example.com/new".parse().unwrap();
            },
        ));
        let uri = test_uri();
        let mut req = http::Request::get("http://example.com/old")
            .body(local_body())
            .unwrap();
        stack.apply_request_local(&mut req, &uri);
        assert_eq!(req.uri(), "http://redirected.example.com/new");
    }

    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn apply_request_local_copies_version_change() {
        let mut stack = MiddlewareStack::new();
        stack.push(Arc::new(
            |req: &mut http::Request<RequestBodySend>, _uri: &Uri| {
                *req.version_mut() = http::Version::HTTP_2;
            },
        ));
        let uri = test_uri();
        let mut req = http::Request::get("http://example.com")
            .body(local_body())
            .unwrap();
        stack.apply_request_local(&mut req, &uri);
        assert_eq!(req.version(), http::Version::HTTP_2);
    }

    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn apply_request_local_with_multiple_middleware() {
        let mut stack = MiddlewareStack::new();
        stack.push(Arc::new(
            |req: &mut http::Request<RequestBodySend>, _uri: &Uri| {
                req.headers_mut()
                    .insert("x-first", http::header::HeaderValue::from_static("1"));
            },
        ));
        stack.push(Arc::new(
            |req: &mut http::Request<RequestBodySend>, _uri: &Uri| {
                req.headers_mut()
                    .insert("x-second", http::header::HeaderValue::from_static("2"));
            },
        ));
        let uri = test_uri();
        let mut req = http::Request::get("http://example.com")
            .body(local_body())
            .unwrap();
        stack.apply_request_local(&mut req, &uri);
        assert_eq!(req.headers().get("x-first").unwrap(), "1");
        assert_eq!(req.headers().get("x-second").unwrap(), "2");
    }

    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn apply_request_local_preserves_existing_headers() {
        let mut stack = MiddlewareStack::new();
        stack.push(Arc::new(
            |req: &mut http::Request<RequestBodySend>, _uri: &Uri| {
                req.headers_mut()
                    .insert("x-new", http::header::HeaderValue::from_static("added"));
            },
        ));
        let uri = test_uri();
        let mut req = http::Request::get("http://example.com")
            .header("x-existing", "preserved")
            .body(local_body())
            .unwrap();
        stack.apply_request_local(&mut req, &uri);
        assert_eq!(req.headers().get("x-existing").unwrap(), "preserved");
        assert_eq!(req.headers().get("x-new").unwrap(), "added");
    }

    #[test]
    fn clone_stack_runs_middleware_independently() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let stack = make_stack(&log);
        let cloned = stack.clone();

        let uri = test_uri();
        let mut req = http::Request::get("http://example.com")
            .body(empty_body())
            .unwrap();
        cloned.apply_request(&mut req, &uri);

        let entries = log.lock().unwrap();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0], (1, "request"));
        assert_eq!(entries[1], (2, "request"));
    }

    #[test]
    fn closure_middleware_on_request_modifies_headers() {
        let mut stack = MiddlewareStack::new();
        stack.push(Arc::new(
            |req: &mut http::Request<RequestBodySend>, _uri: &Uri| {
                req.headers_mut().insert(
                    "authorization",
                    http::header::HeaderValue::from_static("Bearer token123"),
                );
            },
        ));
        let uri = test_uri();
        let mut req = http::Request::get("http://example.com")
            .body(empty_body())
            .unwrap();
        stack.apply_request(&mut req, &uri);
        assert_eq!(
            req.headers().get("authorization").unwrap(),
            "Bearer token123"
        );
    }

    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn apply_request_local_copies_extensions() {
        let mut stack = MiddlewareStack::new();
        stack.push(Arc::new(
            |req: &mut http::Request<RequestBodySend>, _uri: &Uri| {
                req.extensions_mut().insert(42u32);
            },
        ));
        let uri = test_uri();
        let mut req = http::Request::get("http://example.com")
            .body(local_body())
            .unwrap();
        req.extensions_mut().insert("original".to_string());
        stack.apply_request_local(&mut req, &uri);
        assert_eq!(
            req.extensions().get::<String>().map(|s| s.as_str()),
            Some("original"),
            "original extensions should be preserved"
        );
        assert_eq!(
            req.extensions().get::<u32>().copied(),
            Some(42),
            "middleware-added extensions should be propagated back"
        );
    }

    #[tokio::test]
    #[cfg(not(target_arch = "wasm32"))]
    async fn apply_request_local_propagates_body_modification() {
        let mut stack = MiddlewareStack::new();
        stack.push(Arc::new(
            |req: &mut http::Request<RequestBodySend>, _uri: &Uri| {
                *req.body_mut() = http_body_util::Full::new(bytes::Bytes::from("injected"))
                    .map_err(|never| match never {})
                    .boxed_unsync();
            },
        ));
        let uri = test_uri();
        let mut req = http::Request::get("http://example.com")
            .body(local_body())
            .unwrap();
        stack.apply_request_local(&mut req, &uri);
        let body = std::mem::replace(req.body_mut(), local_body());
        let collected = http_body_util::BodyExt::collect(body).await.unwrap();
        assert_eq!(
            collected.to_bytes(),
            bytes::Bytes::from("injected"),
            "body modification by middleware should be propagated back"
        );
    }

    #[tokio::test]
    #[cfg(not(target_arch = "wasm32"))]
    async fn apply_request_local_preserves_body_when_not_modified() {
        let mut stack = MiddlewareStack::new();
        stack.push(Arc::new(
            |req: &mut http::Request<RequestBodySend>, _uri: &Uri| {
                req.headers_mut()
                    .insert("x-added", http::header::HeaderValue::from_static("yes"));
            },
        ));
        let uri = test_uri();
        let original: RequestBodyLocal = Box::pin(
            http_body_util::Full::new(bytes::Bytes::from("original content"))
                .map_err(|never| match never {}),
        );
        let mut req = http::Request::get("http://example.com")
            .body(original)
            .unwrap();
        stack.apply_request_local(&mut req, &uri);
        assert_eq!(req.headers().get("x-added").unwrap(), "yes");
        let body = std::mem::replace(req.body_mut(), local_body());
        let collected = http_body_util::BodyExt::collect(body).await.unwrap();
        assert_eq!(
            collected.to_bytes(),
            bytes::Bytes::from("original content"),
            "original body should be preserved when middleware does not replace it"
        );
    }
}