http-request 23.0.0

http-request is a lightweight, efficient library for building, sending, and handling HTTP/HTTPS requests in Rust applications. It provides a simple and intuitive API, allowing developers to easily interact with web services, whether they use the "HTTP" or "HTTPS" protocol. The library supports various HTTP methods, custom headers, request bodies, timeout, automatic handling of redirects (including detecting redirect loops), and enhanced response body decoding (both automatic and manual), enabling fast and secure communication. Whether working with secure "HTTPS" connections or standard "HTTP" requests, the library is optimized for performance, minimal resource usage, and easy integration into Rust projects.
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
use super::*;

/// Computes a deterministic 64-bit fingerprint for custom TLS trust stores (`0` for default roots).
///
/// # Arguments
///
/// - `&RootCertStore` - Configured TLS trust anchor store.
///
/// # Returns
///
/// - `u64` - `0` when using the default Mozilla root set, or a non-zero FNV-1a digest of custom anchors.
fn root_cert_fingerprint(roots: &RootCertStore) -> u64 {
    if roots.roots.len() == TLS_SERVER_ROOTS.len() {
        return 0;
    }
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    let extra_start: usize = roots.roots.len().min(TLS_SERVER_ROOTS.len());
    for anchor in &roots.roots[extra_start..] {
        for &byte in anchor.subject.as_ref() {
            hash ^= u64::from(byte);
            hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
        }
        for &byte in anchor.subject_public_key_info.as_ref() {
            hash ^= u64::from(byte);
            hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
        }
    }
    hash ^ (roots.roots.len() as u64)
}

/// Builds a normalized [`PoolKey`] for connection pooling.
///
/// # Arguments
///
/// - `bool` - Whether the request targets HTTPS.
/// - `&str` - Target hostname or IP literal.
/// - `u16` - Effective target TCP port.
/// - `Option<&Proxy>` - Optional proxy configuration.
/// - `&RootCertStore` - Configured root CA certificate store.
/// - `u64` - Synchronous socket timeout in milliseconds (`0` for async pools).
///
/// # Returns
///
/// - `PoolKey` - Canonical lookup key for the connection pool.
pub(crate) fn make_pool_key(
    is_https: bool,
    host: &str,
    port: u16,
    proxy: Option<&Proxy>,
    roots: &RootCertStore,
    sync_timeout_ms: u64,
) -> PoolKey {
    let proxy_key: Option<ProxyKey> = proxy.map(|p: &Proxy| ProxyKey {
        proxy_type_tag: match *p.get_proxy_type() {
            ProxyType::Http => 0,
            ProxyType::Https => 1,
            ProxyType::Socks5 => 2,
        },
        host: p.get_host().to_ascii_lowercase(),
        port: p.get_port(),
        username: p.get_username(),
        password: p.get_password(),
    });
    PoolKey {
        is_https,
        host: host.to_ascii_lowercase(),
        port,
        proxy: proxy_key,
        root_cert_fingerprint: root_cert_fingerprint(roots),
        sync_timeout_ms,
    }
}

/// Checks whether a cached [`PoolKey`] matches borrowed origin and proxy parameters without allocating.
///
/// # Arguments
///
/// - `&PoolKey` - Cached key stored in the pool bucket.
/// - `bool` - Whether the request targets HTTPS.
/// - `&str` - Target hostname or IP literal.
/// - `u16` - Effective target TCP port.
/// - `Option<&Proxy>` - Optional proxy configuration.
/// - `u64` - Precomputed TLS root certificate fingerprint.
/// - `u64` - Synchronous socket timeout in milliseconds (`0` for async pools).
///
/// # Returns
///
/// - `bool` - `true` when all origin, proxy, TLS trust, and timeout fields match.
#[inline(always)]
fn pool_key_matches(
    key: &PoolKey,
    is_https: bool,
    host: &str,
    port: u16,
    proxy: Option<&Proxy>,
    root_fp: u64,
    sync_timeout_ms: u64,
) -> bool {
    if key.is_https != is_https
        || key.port != port
        || key.root_cert_fingerprint != root_fp
        || key.sync_timeout_ms != sync_timeout_ms
        || !key.host.eq_ignore_ascii_case(host)
    {
        return false;
    }
    match (&key.proxy, proxy) {
        (None, None) => true,
        (Some(pk), Some(p)) => {
            let tag: u8 = match *p.get_proxy_type() {
                ProxyType::Http => 0,
                ProxyType::Https => 1,
                ProxyType::Socks5 => 2,
            };
            pk.proxy_type_tag == tag
                && pk.port == p.get_port()
                && pk.host.eq_ignore_ascii_case(p.get_host())
                && pk.username == p.get_username()
                && pk.password == p.get_password()
        }
        _ => false,
    }
}

/// Takes one non-expired asynchronous HTTP/1.1 connection from the pool without allocating a lookup key.
///
/// # Arguments
///
/// - `bool` - Whether the target uses HTTPS.
/// - `&str` - Target host or IP literal.
/// - `u16` - Target TCP port.
/// - `Option<&Proxy>` - Optional proxy configuration.
/// - `&RootCertStore` - Configured TLS trust store.
///
/// # Returns
///
/// - `Option<Box<dyn AsyncReadWrite>>` - A reusable keep-alive connection, or `None`.
pub(crate) fn take_async_h1_conn(
    is_https: bool,
    host: &str,
    port: u16,
    proxy: Option<&Proxy>,
    roots: &RootCertStore,
) -> Option<Box<dyn AsyncReadWrite>> {
    let map_lock: &Mutex<AsyncH1PoolMap> = ASYNC_H1_POOL.get_or_init(|| Mutex::new(HashMap::new()));
    let Ok(mut map) = map_lock.lock() else {
        return None;
    };
    let root_fp: u64 = root_cert_fingerprint(roots);
    let bucket: &mut Vec<(PoolKey, VecDeque<PooledAsyncConn>)> = map.get_mut(&port)?;
    let pos: usize = bucket
        .iter()
        .position(|(k, _): &(PoolKey, VecDeque<PooledAsyncConn>)| {
            pool_key_matches(k, is_https, host, port, proxy, root_fp, 0)
        })?;
    let ttl: Duration = Duration::from_secs(POOL_IDLE_TTL_SECS);
    let now: Instant = Instant::now();
    let mut found: Option<Box<dyn AsyncReadWrite>> = None;
    while let Some(conn) = bucket[pos].1.pop_back() {
        if now.saturating_duration_since(conn.idle_since) < ttl {
            found = Some(conn.stream);
            break;
        }
    }
    if bucket[pos].1.is_empty() {
        let _: (PoolKey, VecDeque<PooledAsyncConn>) = bucket.swap_remove(pos);
        if bucket.is_empty() {
            let _: Option<Vec<(PoolKey, VecDeque<PooledAsyncConn>)>> = map.remove(&port);
        }
    }
    found
}

/// Returns a clean asynchronous HTTP/1.1 connection to the idle pool within capacity caps.
///
/// # Arguments
///
/// - `bool` - Whether the target uses HTTPS.
/// - `&str` - Target host or IP literal.
/// - `u16` - Target TCP port.
/// - `Option<&Proxy>` - Optional proxy configuration.
/// - `&RootCertStore` - Configured TLS trust store.
/// - `Box<dyn AsyncReadWrite>` - Idle keep-alive stream ready for the next request.
pub(crate) fn put_async_h1_conn(
    is_https: bool,
    host: &str,
    port: u16,
    proxy: Option<&Proxy>,
    roots: &RootCertStore,
    stream: Box<dyn AsyncReadWrite>,
) {
    let map_lock: &Mutex<AsyncH1PoolMap> = ASYNC_H1_POOL.get_or_init(|| Mutex::new(HashMap::new()));
    let Ok(mut map) = map_lock.lock() else {
        return;
    };
    let ttl: Duration = Duration::from_secs(POOL_IDLE_TTL_SECS);
    let now: Instant = Instant::now();
    let mut total: usize = map
        .values()
        .map(|bucket: &Vec<(PoolKey, VecDeque<PooledAsyncConn>)>| {
            bucket
                .iter()
                .map(|(_, q): &(PoolKey, VecDeque<PooledAsyncConn>)| q.len())
                .sum::<usize>()
        })
        .sum();
    if total >= POOL_MAX_IDLE_TOTAL {
        total = 0;
        map.retain(
            |_: &u16, bucket: &mut Vec<(PoolKey, VecDeque<PooledAsyncConn>)>| {
                bucket.retain_mut(|(_, q): &mut (PoolKey, VecDeque<PooledAsyncConn>)| {
                    q.retain(|item: &PooledAsyncConn| {
                        now.saturating_duration_since(item.idle_since) < ttl
                    });
                    total += q.len();
                    !q.is_empty()
                });
                !bucket.is_empty()
            },
        );
        if total >= POOL_MAX_IDLE_TOTAL {
            return;
        }
    }
    let root_fp: u64 = root_cert_fingerprint(roots);
    let bucket: &mut Vec<(PoolKey, VecDeque<PooledAsyncConn>)> = map.entry(port).or_default();
    let queue: &mut VecDeque<PooledAsyncConn> = if let Some(pos) =
        bucket
            .iter()
            .position(|(k, _): &(PoolKey, VecDeque<PooledAsyncConn>)| {
                pool_key_matches(k, is_https, host, port, proxy, root_fp, 0)
            }) {
        &mut bucket[pos].1
    } else {
        let key: PoolKey = make_pool_key(is_https, host, port, proxy, roots, 0);
        bucket.push((key, VecDeque::with_capacity(4)));
        let last: usize = bucket.len() - 1;
        &mut bucket[last].1
    };
    if queue.len() >= POOL_MAX_IDLE_PER_HOST {
        queue.retain(|item: &PooledAsyncConn| now.saturating_duration_since(item.idle_since) < ttl);
    }
    if queue.len() < POOL_MAX_IDLE_PER_HOST {
        queue.push_back(PooledAsyncConn {
            stream,
            idle_since: now,
        });
    }
}

/// Takes one non-expired synchronous HTTP/1.1 connection from the pool without allocating a lookup key.
///
/// # Arguments
///
/// - `bool` - Whether the target uses HTTPS.
/// - `&str` - Target host or IP literal.
/// - `u16` - Target TCP port.
/// - `Option<&Proxy>` - Optional proxy configuration.
/// - `&RootCertStore` - Configured TLS trust store.
/// - `u64` - Synchronous socket timeout in milliseconds.
///
/// # Returns
///
/// - `Option<Box<dyn ReadWrite>>` - A reusable keep-alive connection, or `None`.
pub(crate) fn take_sync_h1_conn(
    is_https: bool,
    host: &str,
    port: u16,
    proxy: Option<&Proxy>,
    roots: &RootCertStore,
    sync_timeout_ms: u64,
) -> Option<Box<dyn ReadWrite>> {
    let map_lock: &Mutex<SyncH1PoolMap> = SYNC_H1_POOL.get_or_init(|| Mutex::new(HashMap::new()));
    let Ok(mut map) = map_lock.lock() else {
        return None;
    };
    let root_fp: u64 = root_cert_fingerprint(roots);
    let bucket: &mut Vec<(PoolKey, VecDeque<PooledSyncConn>)> = map.get_mut(&port)?;
    let pos: usize = bucket
        .iter()
        .position(|(k, _): &(PoolKey, VecDeque<PooledSyncConn>)| {
            pool_key_matches(k, is_https, host, port, proxy, root_fp, sync_timeout_ms)
        })?;
    let ttl: Duration = Duration::from_secs(POOL_IDLE_TTL_SECS);
    let now: Instant = Instant::now();
    let mut found: Option<Box<dyn ReadWrite>> = None;
    while let Some(conn) = bucket[pos].1.pop_back() {
        if now.saturating_duration_since(conn.idle_since) < ttl {
            found = Some(conn.stream);
            break;
        }
    }
    if bucket[pos].1.is_empty() {
        let _: (PoolKey, VecDeque<PooledSyncConn>) = bucket.swap_remove(pos);
        if bucket.is_empty() {
            let _: Option<Vec<(PoolKey, VecDeque<PooledSyncConn>)>> = map.remove(&port);
        }
    }
    found
}

/// Returns a clean synchronous HTTP/1.1 connection to the idle pool within capacity caps.
///
/// # Arguments
///
/// - `bool` - Whether the target uses HTTPS.
/// - `&str` - Target host or IP literal.
/// - `u16` - Target TCP port.
/// - `Option<&Proxy>` - Optional proxy configuration.
/// - `&RootCertStore` - Configured TLS trust store.
/// - `u64` - Synchronous socket timeout in milliseconds.
/// - `Box<dyn ReadWrite>` - Idle keep-alive stream ready for the next request.
pub(crate) fn put_sync_h1_conn(
    is_https: bool,
    host: &str,
    port: u16,
    proxy: Option<&Proxy>,
    roots: &RootCertStore,
    sync_timeout_ms: u64,
    stream: Box<dyn ReadWrite>,
) {
    let map_lock: &Mutex<SyncH1PoolMap> = SYNC_H1_POOL.get_or_init(|| Mutex::new(HashMap::new()));
    let Ok(mut map) = map_lock.lock() else {
        return;
    };
    let ttl: Duration = Duration::from_secs(POOL_IDLE_TTL_SECS);
    let now: Instant = Instant::now();
    let mut total: usize = map
        .values()
        .map(|bucket: &Vec<(PoolKey, VecDeque<PooledSyncConn>)>| {
            bucket
                .iter()
                .map(|(_, q): &(PoolKey, VecDeque<PooledSyncConn>)| q.len())
                .sum::<usize>()
        })
        .sum();
    if total >= POOL_MAX_IDLE_TOTAL {
        total = 0;
        map.retain(
            |_: &u16, bucket: &mut Vec<(PoolKey, VecDeque<PooledSyncConn>)>| {
                bucket.retain_mut(|(_, q): &mut (PoolKey, VecDeque<PooledSyncConn>)| {
                    q.retain(|item: &PooledSyncConn| {
                        now.saturating_duration_since(item.idle_since) < ttl
                    });
                    total += q.len();
                    !q.is_empty()
                });
                !bucket.is_empty()
            },
        );
        if total >= POOL_MAX_IDLE_TOTAL {
            return;
        }
    }
    let root_fp: u64 = root_cert_fingerprint(roots);
    let bucket: &mut Vec<(PoolKey, VecDeque<PooledSyncConn>)> = map.entry(port).or_default();
    let queue: &mut VecDeque<PooledSyncConn> = if let Some(pos) =
        bucket
            .iter()
            .position(|(k, _): &(PoolKey, VecDeque<PooledSyncConn>)| {
                pool_key_matches(k, is_https, host, port, proxy, root_fp, sync_timeout_ms)
            }) {
        &mut bucket[pos].1
    } else {
        let key: PoolKey = make_pool_key(is_https, host, port, proxy, roots, sync_timeout_ms);
        bucket.push((key, VecDeque::with_capacity(4)));
        let last: usize = bucket.len() - 1;
        &mut bucket[last].1
    };
    if queue.len() >= POOL_MAX_IDLE_PER_HOST {
        queue.retain(|item: &PooledSyncConn| now.saturating_duration_since(item.idle_since) < ttl);
    }
    if queue.len() < POOL_MAX_IDLE_PER_HOST {
        queue.push_back(PooledSyncConn {
            stream,
            idle_since: now,
        });
    }
}

/// Retrieves a cloned multiplexed HTTP/2 sender for `key` when an active connection exists.
///
/// # Arguments
///
/// - `&PoolKey` - Origin and proxy pool key.
///
/// # Returns
///
/// - `Option<SendRequest<Bytes>>` - Cloned HTTP/2 request sender, or `None`.
pub(crate) fn get_h2_sender(key: &PoolKey) -> Option<SendRequest<Bytes>> {
    let map_lock: &Mutex<HashMap<PoolKey, SendRequest<Bytes>>> =
        ASYNC_H2_POOL.get_or_init(|| Mutex::new(HashMap::new()));
    let Ok(map) = map_lock.lock() else {
        return None;
    };
    map.get(key).cloned()
}

/// Stores an active multiplexed HTTP/2 sender in the pool.
///
/// # Arguments
///
/// - `PoolKey` - Origin and proxy pool key.
/// - `SendRequest<Bytes>` - Active HTTP/2 sender handle.
pub(crate) fn put_h2_sender(key: PoolKey, sender: SendRequest<Bytes>) {
    let map_lock: &Mutex<HashMap<PoolKey, SendRequest<Bytes>>> =
        ASYNC_H2_POOL.get_or_init(|| Mutex::new(HashMap::new()));
    let Ok(mut map) = map_lock.lock() else {
        return;
    };
    if map.len() >= POOL_MAX_IDLE_TOTAL {
        map.clear();
    }
    map.insert(key, sender);
}

/// Removes a closed or broken HTTP/2 sender from the pool.
///
/// # Arguments
///
/// - `&PoolKey` - Origin and proxy pool key to evict.
pub(crate) fn remove_h2_sender(key: &PoolKey) {
    let map_lock: &Mutex<HashMap<PoolKey, SendRequest<Bytes>>> =
        ASYNC_H2_POOL.get_or_init(|| Mutex::new(HashMap::new()));
    if let Ok(mut map) = map_lock.lock() {
        map.remove(key);
    }
}

/// Takes a recycled empty byte buffer with at least `min_cap` capacity from the worker-local pool.
///
/// # Arguments
///
/// - `usize` - Minimum required capacity in bytes.
///
/// # Returns
///
/// - `Vec<u8>` - Empty buffer retaining pooled capacity when available.
#[inline(always)]
pub(crate) fn take_client_buffer(min_cap: usize) -> Vec<u8> {
    CLIENT_BUFFER_POOL.with(|pool: &RefCell<Vec<Vec<u8>>>| {
        let mut buf: Vec<u8> = pool
            .borrow_mut()
            .pop()
            .unwrap_or_else(|| Vec::with_capacity(min_cap));
        buf.clear();
        if buf.capacity() < min_cap {
            buf.reserve(min_cap - buf.capacity());
        }
        buf
    })
}

/// Returns a reusable byte buffer to the worker-local pool when within size caps.
///
/// # Arguments
///
/// - `Vec<u8>` - Buffer to recycle.
#[inline(always)]
pub(crate) fn return_client_buffer(mut buf: Vec<u8>) {
    if buf.capacity() == 0 || buf.capacity() > CLIENT_MAX_POOLED_BUFFER_CAP {
        return;
    }
    buf.clear();
    CLIENT_BUFFER_POOL.with(|pool: &RefCell<Vec<Vec<u8>>>| {
        let mut guard: RefMut<'_, Vec<Vec<u8>>> = pool.borrow_mut();
        if guard.len() < CLIENT_MAX_POOLED_BUFFERS {
            guard.push(buf);
        }
    });
}