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
//! Async-native HTTP client built directly on hyper 1.x.
//!
//! aioduct is runtime-agnostic: enable `tokio`, `smol`, or `compio` via feature flags.
//! For HTTPS, enable the `rustls` feature.

#![deny(missing_docs)]
#![deny(clippy::expect_used, clippy::unwrap_used, clippy::panic)]
#![cfg_attr(test, allow(clippy::expect_used, clippy::unwrap_used, clippy::panic))]
#![cfg_attr(target_arch = "wasm32", allow(dead_code))]

#[cfg(not(any(
    feature = "tokio",
    feature = "smol",
    feature = "compio",
    feature = "wasm",
    feature = "wasi-p2",
    doc
)))]
compile_error!(
    "aioduct: enable at least one runtime feature: tokio, smol, compio, wasm, or wasi-p2"
);

#[cfg(all(feature = "http3", not(feature = "rustls")))]
compile_error!("aioduct: the `http3` feature currently requires the `rustls` TLS backend feature");

// ── Portable modules (available on all targets including wasm32) ─────────────

/// Token-bucket bandwidth limiter for throttling download throughput.
pub mod bandwidth;
/// Request and response body types.
pub mod body;
/// HTTP response caching with conditional validation.
pub mod cache;
mod clock;
/// Cookie storage and automatic cookie handling.
pub mod cookie;
mod decompress;
mod digest_auth;
/// Error types for HTTP operations.
pub mod error;
/// Forwarded header builder and parser (RFC 7239).
pub mod forwarded;
pub(crate) mod h2c_probe;
/// HSTS (HTTP Strict Transport Security) store.
pub mod hsts;
/// HTTP/2 connection configuration.
pub mod http2;
/// Link header parsing (RFC 8288).
pub mod link;
/// Request/response middleware trait and stack.
pub mod middleware;
/// Multipart/form-data request body builder.
pub mod multipart;
/// Netrc credential file parsing and middleware.
pub mod netrc;
/// Real-time request lifecycle observer for load testing and tracing.
pub mod observer;
/// HTTP and SOCKS proxy configuration.
pub mod proxy;
/// Redirect policy configuration.
pub mod redirect;
/// Automatic retry with exponential backoff.
pub mod retry;
/// Server-Sent Events (SSE) stream parser.
pub mod sse;
/// Token-bucket rate limiter for throttling requests.
pub mod throttle;
/// Per-request timing breakdown (DNS, TCP, TLS, TTFB).
///
/// Deprecated: Use [`observer::RequestObserver`] for detailed per-phase timing.
pub mod timing;
/// Consumer-facing client trait and extension traits.
pub mod traits;

/// RFC 9457 Problem Details for HTTP APIs.
#[cfg(feature = "json")]
pub mod problem;

// ── Native-only modules (require OS networking) ──────────────────────────────

/// Blocking (synchronous) HTTP client wrapper.
#[cfg(feature = "blocking")]
pub mod blocking;
/// Parallel range-request file downloader.
#[cfg(not(target_arch = "wasm32"))]
pub mod chunk_download;
/// HTTP client with connection pooling and redirect handling.
#[cfg(not(target_arch = "wasm32"))]
pub mod client;
/// Tower-based connector layer support.
#[cfg(feature = "tower")]
pub mod connector;
/// Request forwarding for proxy/gateway use cases.
#[cfg(not(target_arch = "wasm32"))]
pub mod forward;
#[cfg(not(target_arch = "wasm32"))]
mod happy_eyeballs;
/// Hickory DNS resolver integration.
#[cfg(feature = "hickory-dns")]
pub mod hickory;
/// Internal connection pool for HTTP keep-alive.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) mod pool;
/// Request builder for configuring and sending HTTP requests.
#[cfg(not(target_arch = "wasm32"))]
pub mod request;
/// HTTP response type with status, headers, and body.
#[cfg(not(target_arch = "wasm32"))]
pub mod response;
/// Async runtime abstraction layer.
#[cfg(not(target_arch = "wasm32"))]
pub mod runtime;
#[cfg(not(target_arch = "wasm32"))]
mod socks4;
#[cfg(not(target_arch = "wasm32"))]
mod socks5;
#[cfg(not(target_arch = "wasm32"))]
mod timeout;
/// TLS configuration and connector types.
#[cfg(not(target_arch = "wasm32"))]
pub mod tls;
/// HTTP upgrade (e.g., WebSocket) support.
#[cfg(not(target_arch = "wasm32"))]
pub mod upgrade;

// ── Platform-specific client modules ─────────────────────────────────────────

/// WebAssembly (browser) runtime support.
#[cfg(feature = "wasm")]
pub mod wasm;

/// WASI Preview 2 HTTP client using wasi:http/outgoing-handler.
#[cfg(feature = "wasi-p2")]
pub mod wasi_p2;

#[cfg(feature = "tracing")]
mod tracing_middleware;
#[cfg(feature = "tracing")]
pub use tracing_middleware::TracingMiddleware;

#[cfg(feature = "otel")]
mod otel_middleware;
#[cfg(feature = "otel")]
pub use otel_middleware::OtelMiddleware;

#[cfg(all(feature = "http3", feature = "rustls"))]
mod alt_svc;
#[cfg(all(feature = "http3", feature = "rustls"))]
#[path = "h3/mod.rs"]
/// HTTP/3 transport layer using QUIC.
pub mod h3_transport;

// ── Re-exports: portable ─────────────────────────────────────────────────────

pub use bandwidth::BandwidthLimiter;
pub use body::{BodyStreamSend, RequestBody};
pub use cache::{CacheConfig, CacheEntry, CacheStore, HttpCache, InMemoryCacheStore};
pub use cookie::{Cookie, CookieJar, SameSite};
pub use error::{Error, SendError};
pub use forwarded::ForwardedElement;
pub use hsts::HstsStore;
pub use http2::Http2Config;
pub use link::Link;
pub use middleware::Middleware;
pub use multipart::{Multipart, Part};
pub use netrc::{Netrc, NetrcMiddleware};
pub use observer::{
    ConnectionEvent, ConnectionPhase, NegotiatedProtocol, PoolOutcome, RequestEvent,
    RequestObserver, RequestPhase, TransferDirection,
};
pub use proxy::{NoProxy, ProxyConfig, ProxySettings};
pub use redirect::{RedirectAction, RedirectPolicy};
pub use retry::{RetryBudget, RetryConfig};
#[cfg(not(target_arch = "wasm32"))]
pub use sse::SseStreamLocal;
pub use sse::{SseDecoder, SseEvent, SseMessage, SseStream, SseStreamSend};
pub use throttle::RateLimiter;
#[allow(deprecated)]
pub use timing::RequestTimings;
pub use traits::{HttpClient, RequestBuilderExt, ResponseExt};

#[cfg(feature = "json")]
pub use problem::ProblemDetails;

// ── Re-exports: native-only ──────────────────────────────────────────────────

#[cfg(not(target_arch = "wasm32"))]
pub use chunk_download::ChunkDownload;
#[cfg(not(target_arch = "wasm32"))]
pub use chunk_download::ChunkDownloadLocal;
#[cfg(not(target_arch = "wasm32"))]
pub use client::HttpEngineBuilder;
#[cfg(not(target_arch = "wasm32"))]
pub use client::HttpEngineCore;
#[cfg(not(target_arch = "wasm32"))]
pub use client::HttpEngineLocal;
#[cfg(not(target_arch = "wasm32"))]
pub use client::HttpEngineSend;

#[cfg(not(target_arch = "wasm32"))]
pub use forward::ForwardBuilder;
#[cfg(not(target_arch = "wasm32"))]
pub use forward::forward_local::ForwardBuilderLocal;
#[cfg(feature = "hickory-dns")]
pub use hickory::HickoryResolver;
#[cfg(not(target_arch = "wasm32"))]
pub use request::RequestBuilderLocal;
#[cfg(not(target_arch = "wasm32"))]
pub use request::RequestBuilderSend;

#[cfg(not(target_arch = "wasm32"))]
#[deprecated(since = "0.2.0", note = "Renamed to `RequestBuilderSend`")]
/// Deprecated alias for [`RequestBuilderSend`].
pub type RequestBuilder<'a, R, C> = RequestBuilderSend<'a, R, C>;
#[cfg(not(target_arch = "wasm32"))]
pub use response::Response;
#[cfg(not(target_arch = "wasm32"))]
#[allow(deprecated)]
pub use runtime::Runtime;
#[cfg(not(target_arch = "wasm32"))]
pub use runtime::{
    ConnectorLocal, ConnectorSend, Resolve, RuntimeCompletion, RuntimeLocal, RuntimePoll,
    SocketConfig,
};
#[cfg(feature = "wasi-p2")]
pub use traits::OwnedWasiRequestBuilder;
#[cfg(feature = "wasm")]
pub use traits::OwnedWasmRequestBuilder;
#[cfg(not(target_arch = "wasm32"))]
pub use traits::{OwnedRequestBuilderLocal, OwnedRequestBuilderSend};

#[cfg(not(target_arch = "wasm32"))]
#[deprecated(since = "0.2.0", note = "Renamed to `OwnedRequestBuilderSend`")]
/// Deprecated alias for [`OwnedRequestBuilderSend`].
pub type OwnedRequestBuilder<R, C> = OwnedRequestBuilderSend<R, C>;
#[cfg(not(target_arch = "wasm32"))]
pub use upgrade::Upgraded;
#[cfg(not(target_arch = "wasm32"))]
pub use upgrade::UpgradedLocal;

/// Convenience alias for [`HttpEngineSend`] using the Tokio runtime.
#[cfg(feature = "tokio")]
pub type TokioClient =
    HttpEngineSend<runtime::tokio_rt::TokioRuntime, runtime::tokio_rt::TcpConnector>;

/// Alias for [`TokioClient`].
#[cfg(feature = "tokio")]
pub type TokioEngine = TokioClient;

/// Convenience alias for [`HttpEngineSend`] using the smol runtime.
#[cfg(feature = "smol")]
pub type SmolClient = HttpEngineSend<runtime::smol_rt::SmolRuntime, runtime::smol_rt::TcpConnector>;

/// Alias for [`SmolClient`].
#[cfg(feature = "smol")]
pub type SmolEngine = SmolClient;

/// Convenience alias for [`HttpEngineLocal`] using the compio runtime.
#[cfg(feature = "compio")]
pub type CompioClient =
    HttpEngineLocal<runtime::compio_rt::CompioRuntime, runtime::compio_rt::TcpConnector>;

/// Alias for [`CompioClient`].
#[cfg(feature = "compio")]
pub type CompioEngine = CompioClient;

/// Convenience alias for the WebAssembly (browser Fetch API) client.
#[cfg(feature = "wasm")]
pub type WasmClient = wasm::WasmClient;

/// Convenience alias for the WASI Preview 2 HTTP client.
#[cfg(feature = "wasi-p2")]
pub type WasiClient = wasi_p2::WasiClient;

/// Blocking client backed by the tokio runtime.
#[cfg(all(feature = "blocking", feature = "tokio"))]
pub type BlockingTokioClient =
    blocking::BlockingClient<TokioClient, runtime::tokio_rt::TokioRuntime>;

/// Blocking client backed by the smol runtime.
#[cfg(all(feature = "blocking", feature = "smol"))]
pub type BlockingSmolClient = blocking::BlockingClient<SmolClient, runtime::smol_rt::SmolRuntime>;

/// Blocking client backed by the compio runtime.
#[cfg(all(feature = "blocking", feature = "compio"))]
pub type BlockingCompioClient =
    blocking::BlockingClient<CompioClient, runtime::compio_rt::CompioRuntime>;

#[cfg(not(target_arch = "wasm32"))]
pub use tls::TlsInfo;
#[cfg(not(target_arch = "wasm32"))]
pub use tls::TlsVersion;
#[cfg(feature = "rustls")]
pub use tls::{Certificate, Identity};

pub use http::{HeaderMap, Method, StatusCode, Uri, Version};
#[cfg(not(target_arch = "wasm32"))]
pub use hyper::ext::Protocol;

#[cfg(feature = "__bench")]
#[doc(hidden)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
pub mod __bench {
    use std::net::{IpAddr, SocketAddr};
    use std::time::Duration;

    use crate::body::RequestBodySend;
    use crate::pool::{ConnectionPool, PoolKey, PooledConnection};
    use crate::runtime::TokioRuntime;
    use http::uri::{Authority, Scheme};

    pub struct BenchPool(ConnectionPool<RequestBodySend>);
    pub struct BenchConn(Option<PooledConnection<RequestBodySend>>);
    pub struct BenchKey(PoolKey);

    pub fn new_pool(max_idle: usize, timeout: Duration) -> BenchPool {
        BenchPool(ConnectionPool::new_no_reaper(max_idle, timeout))
    }

    pub async fn make_h2_conn() -> BenchConn {
        use crate::runtime::tokio_rt::TokioIo;
        let (client_io, server_io) = tokio::io::duplex(65536);

        tokio::spawn(async move {
            use hyper::server::conn::http2::Builder;
            use hyper::service::service_fn;
            let io = TokioIo::new(server_io);
            let _ = Builder::new(crate::runtime::executor::poll_executor::<TokioRuntime>())
                .serve_connection(
                    io,
                    service_fn(|_req| async {
                        Ok::<_, std::convert::Infallible>(hyper::Response::new(
                            http_body_util::Empty::<bytes::Bytes>::new(),
                        ))
                    }),
                )
                .await;
        });

        let io = TokioIo::new(client_io);
        let (sender, conn) = hyper::client::conn::http2::handshake(
            crate::runtime::executor::poll_executor::<TokioRuntime>(),
            io,
        )
        .await
        .expect("h2 handshake");

        tokio::spawn(async move {
            let _ = conn.await;
        });

        BenchConn(Some(PooledConnection::new_h2(sender)))
    }

    pub fn pool_key(host: &str) -> BenchKey {
        BenchKey(PoolKey::new(
            Scheme::HTTPS,
            host.parse::<Authority>().unwrap(),
        ))
    }

    pub fn set_sans(conn: &mut BenchConn, sans: Vec<String>) {
        if let Some(c) = conn.0.as_mut() {
            c.sans = std::sync::Arc::from(sans);
        }
    }

    pub fn set_remote_addr(conn: &mut BenchConn, addr: SocketAddr) {
        if let Some(c) = conn.0.as_mut() {
            c.remote_addr = Some(addr);
        }
    }

    pub fn checkin(pool: &BenchPool, key: BenchKey, conn: BenchConn) {
        if let Some(c) = conn.0 {
            pool.0.checkin(key.0, c);
        }
    }

    pub fn checkout_coalesced(
        pool: &BenchPool,
        target_host: &str,
        resolved_ip: Option<IpAddr>,
    ) -> bool {
        pool.0
            .checkout_coalesced(target_host, resolved_ip)
            .is_some()
    }

    pub fn checkout(pool: &BenchPool, key: &BenchKey) -> Option<BenchConn> {
        pool.0.checkout(&key.0).map(|c| BenchConn(Some(c)))
    }

    pub fn wrap_read_timeout_body(
        body: crate::body::RequestBodySend,
        duration: Duration,
    ) -> crate::body::RequestBodySend {
        use http_body_util::BodyExt;
        crate::timeout::ReadTimeoutBody::<_, TokioRuntime>::new(body, duration)
            .map_err(|e| e)
            .boxed_unsync()
    }

    pub fn wrap_bandwidth_body(
        body: crate::body::RequestBodySend,
        limiter: crate::bandwidth::BandwidthLimiter,
    ) -> crate::body::RequestBodySend {
        use http_body_util::BodyExt;
        crate::bandwidth::BandwidthBody::<_, TokioRuntime>::new(body, limiter).boxed_unsync()
    }

    pub fn make_full_body(total_size: usize) -> crate::body::RequestBodySend {
        use http_body_util::BodyExt;
        http_body_util::Full::new(bytes::Bytes::from(vec![b'X'; total_size]))
            .map_err(|never| match never {})
            .boxed_unsync()
    }
}