http-request 23.3.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
use super::*;

/// Implements [`AsyncRead`] for [`AsyncClientTransport`] with static dispatch on TCP/TLS.
impl AsyncRead for AsyncClientTransport {
    /// Polls to read bytes from the underlying concrete transport.
    ///
    /// # Arguments
    ///
    /// - `Pin<&mut Self>` - Pinned transport handle.
    /// - `&mut Context<'_>` - Async task context.
    /// - `&mut ReadBuf<'_>` - Destination read buffer.
    ///
    /// # Returns
    ///
    /// - `Poll<io::Result<()>>` - Poll status of the read operation.
    #[inline(always)]
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        match self.get_mut() {
            Self::Tcp(stream) => Pin::new(stream).poll_read(cx, buf),
            Self::Tls(stream) => Pin::new(&mut **stream).poll_read(cx, buf),
            Self::Proxy(stream) => Pin::new(&mut **stream).poll_read(cx, buf),
        }
    }
}

/// Implements [`AsyncWrite`] for [`AsyncClientTransport`] with static dispatch on TCP/TLS.
impl AsyncWrite for AsyncClientTransport {
    /// Polls to write bytes into the underlying concrete transport.
    ///
    /// # Arguments
    ///
    /// - `Pin<&mut Self>` - Pinned transport handle.
    /// - `&mut Context<'_>` - Async task context.
    /// - `&[u8]` - Source byte slice to transmit.
    ///
    /// # Returns
    ///
    /// - `Poll<io::Result<usize>>` - Number of bytes written or pending state.
    #[inline(always)]
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        match self.get_mut() {
            Self::Tcp(stream) => Pin::new(stream).poll_write(cx, buf),
            Self::Tls(stream) => Pin::new(&mut **stream).poll_write(cx, buf),
            Self::Proxy(stream) => Pin::new(&mut **stream).poll_write(cx, buf),
        }
    }

    /// Polls to flush buffered outbound bytes on the underlying transport.
    ///
    /// # Arguments
    ///
    /// - `Pin<&mut Self>` - Pinned transport handle.
    /// - `&mut Context<'_>` - Async task context.
    ///
    /// # Returns
    ///
    /// - `Poll<io::Result<()>>` - Ready once flushed.
    #[inline(always)]
    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        match self.get_mut() {
            Self::Tcp(stream) => Pin::new(stream).poll_flush(cx),
            Self::Tls(stream) => Pin::new(&mut **stream).poll_flush(cx),
            Self::Proxy(stream) => Pin::new(&mut **stream).poll_flush(cx),
        }
    }

    /// Polls to gracefully shut down the write half of the underlying transport.
    ///
    /// # Arguments
    ///
    /// - `Pin<&mut Self>` - Pinned transport handle.
    /// - `&mut Context<'_>` - Async task context.
    ///
    /// # Returns
    ///
    /// - `Poll<io::Result<()>>` - Ready once shut down.
    #[inline(always)]
    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        match self.get_mut() {
            Self::Tcp(stream) => Pin::new(stream).poll_shutdown(cx),
            Self::Tls(stream) => Pin::new(&mut **stream).poll_shutdown(cx),
            Self::Proxy(stream) => Pin::new(&mut **stream).poll_shutdown(cx),
        }
    }
}

/// Implements [`Read`] for [`SyncClientTransport`] with static dispatch on TCP/TLS.
impl Read for SyncClientTransport {
    /// Reads bytes synchronously from the underlying concrete transport.
    ///
    /// # Arguments
    ///
    /// - `&mut [u8]` - Destination buffer.
    ///
    /// # Returns
    ///
    /// - `io::Result<usize>` - Number of bytes read.
    #[inline(always)]
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self {
            Self::Tcp(stream) => stream.read(buf),
            Self::Tls(stream) => stream.read(buf),
            Self::Proxy(stream) => stream.read(buf),
        }
    }
}

/// Implements [`Write`] for [`SyncClientTransport`] with static dispatch on TCP/TLS.
impl Write for SyncClientTransport {
    /// Writes bytes synchronously to the underlying concrete transport.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Source bytes to transmit.
    ///
    /// # Returns
    ///
    /// - `io::Result<usize>` - Number of bytes written.
    #[inline(always)]
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match self {
            Self::Tcp(stream) => stream.write(buf),
            Self::Tls(stream) => stream.write(buf),
            Self::Proxy(stream) => stream.write(buf),
        }
    }

    /// Flushes any buffered writes on the underlying concrete transport.
    ///
    /// # Returns
    ///
    /// - `io::Result<()>` - Flush completion result.
    #[inline(always)]
    fn flush(&mut self) -> io::Result<()> {
        match self {
            Self::Tcp(stream) => stream.flush(),
            Self::Tls(stream) => stream.flush(),
            Self::Proxy(stream) => stream.flush(),
        }
    }
}

/// Inherent implementation of [`SyncClientTransport`].
impl SyncClientTransport {
    /// Updates the read timeout on direct TCP/TLS transports when enforcing an overall deadline.
    ///
    /// # Arguments
    ///
    /// - `Option<Duration>` - New read timeout duration to apply.
    #[inline(always)]
    pub(crate) fn set_read_timeout(&self, timeout: Option<Duration>) {
        match self {
            Self::Tcp(stream) => {
                let _: Result<(), io::Error> = stream.set_read_timeout(timeout);
            }
            Self::Tls(stream) => {
                let _: Result<(), io::Error> = stream.get_ref().set_read_timeout(timeout);
            }
            Self::Proxy(_) => {}
        }
    }
}

/// Inherent implementation of [`H1PoolStripe`].
impl<T> H1PoolStripe<T> {
    /// Creates an empty pool stripe.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty stripe with zero idle connections.
    #[inline(always)]
    pub(crate) fn new() -> Self {
        Self {
            entries: Vec::new(),
            total: 0,
        }
    }

    /// Evicts expired connections and removes empty origin buckets in place.
    ///
    /// # Arguments
    ///
    /// - `Instant` - Current timestamp.
    /// - `Duration` - Idle expiration TTL.
    pub(crate) fn evict_expired(&mut self, now: Instant, ttl: Duration) {
        let Self { entries, total } = self;
        let mut remaining: usize = 0;
        entries.retain_mut(|(_, queue): &mut (PoolKey, VecDeque<PooledConn<T>>)| {
            queue.retain(|item: &PooledConn<T>| {
                now.saturating_duration_since(item.idle_since) < ttl
            });
            remaining += queue.len();
            !queue.is_empty()
        });
        *total = remaining;
    }
}

/// Inherent implementation of [`StripedH1Pool`].
impl<T> StripedH1Pool<T> {
    /// Creates a new multi-stripe HTTP/1.1 connection pool.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized pool with `H1_POOL_STRIPES` empty lock stripes.
    pub(crate) fn new() -> Self {
        Self {
            stripes: array::from_fn(|_: usize| Mutex::new(H1PoolStripe::new())),
            non_empty_mask: AtomicU64::new(0),
        }
    }

    /// Attempts to pop one non-expired matching connection from stripe `stripe_idx`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Stripe index (`0..H1_POOL_STRIPES`).
    /// - `PoolLookup<'_>` - Borrowed origin, proxy, TLS, and timeout matching parameters.
    ///
    /// # Returns
    ///
    /// - `Option<T>` - A fresh pooled connection if found in this stripe.
    #[inline(always)]
    fn take_from_stripe(&self, stripe_idx: usize, lookup: PoolLookup<'_>) -> Option<T> {
        let Self {
            stripes,
            non_empty_mask,
        } = self;
        let Ok(mut stripe) = stripes[stripe_idx].lock() else {
            return None;
        };
        if stripe.total == 0 {
            non_empty_mask.fetch_and(!(1u64 << stripe_idx), Ordering::Release);
            return None;
        }
        let pos: usize = stripe
            .entries
            .iter()
            .position(|(k, _): &H1StripeEntry<T>| {
                pool_key_matches(
                    k,
                    lookup.is_https,
                    lookup.host,
                    lookup.port,
                    lookup.proxy,
                    lookup.root_fp,
                    lookup.sync_timeout_ms,
                )
            })?;
        let ttl: Duration = Duration::from_secs(POOL_IDLE_TTL_SECS);
        let now: Instant = Instant::now();
        let mut found: Option<T> = None;
        while let Some(conn) = stripe.entries[pos].1.pop_back() {
            stripe.total = stripe.total.saturating_sub(1);
            if now.saturating_duration_since(conn.idle_since) < ttl {
                found = Some(conn.stream);
                break;
            }
        }
        if stripe.entries[pos].1.is_empty() {
            let _: H1StripeEntry<T> = stripe.entries.swap_remove(pos);
        }
        if stripe.total == 0 {
            non_empty_mask.fetch_and(!(1u64 << stripe_idx), Ordering::Release);
        }
        found
    }

    /// Takes one non-expired matching connection, probing the caller's preferred stripe first.
    ///
    /// # Arguments
    ///
    /// - `PoolLookup<'_>` - Borrowed origin, proxy, TLS, and timeout matching parameters.
    ///
    /// # Returns
    ///
    /// - `Option<T>` - A reusable keep-alive connection, or `None`.
    #[inline(always)]
    pub(crate) fn take(&self, lookup: PoolLookup<'_>) -> Option<T> {
        let Self { non_empty_mask, .. } = self;
        let mask: u64 = non_empty_mask.load(Ordering::Acquire);
        if mask == 0 {
            return None;
        }
        let pref: usize = WORKER_H1_STRIPE.with(|idx: &usize| *idx);
        let pref_bit: u64 = 1u64 << pref;
        if (mask & pref_bit) != 0
            && let Some(conn) = self.take_from_stripe(pref, lookup)
        {
            return Some(conn);
        }
        let mut remaining: u64 = mask & !pref_bit;
        while remaining != 0 {
            let idx: usize = remaining.trailing_zeros() as usize;
            remaining &= remaining - 1;
            if let Some(conn) = self.take_from_stripe(idx, lookup) {
                return Some(conn);
            }
        }
        None
    }

    /// Returns a clean idle connection to the pool using uncontended stripe probing.
    ///
    /// # Arguments
    ///
    /// - `PoolLookup<'_>` - Borrowed origin, proxy, TLS, and timeout matching parameters.
    /// - `T` - Idle keep-alive transport ready for reuse.
    #[inline(always)]
    pub(crate) fn put(&self, lookup: PoolLookup<'_>, stream: T) {
        let Self {
            stripes,
            non_empty_mask,
        } = self;
        let pref: usize = WORKER_H1_STRIPE.with(|idx: &usize| *idx);
        let mut chosen_idx: usize = pref;
        let mut locked: Option<MutexGuard<'_, H1PoolStripe<T>>> = None;
        for probe in 0..H1_POOL_PROBE_ATTEMPTS {
            let idx: usize = (pref + probe) & (H1_POOL_STRIPES - 1);
            if let Ok(guard) = stripes[idx].try_lock() {
                chosen_idx = idx;
                locked = Some(guard);
                break;
            }
        }
        let mut stripe: MutexGuard<'_, H1PoolStripe<T>> = match locked {
            Some(guard) => guard,
            None => match stripes[pref].lock() {
                Ok(guard) => guard,
                Err(_) => return,
            },
        };
        let ttl: Duration = Duration::from_secs(POOL_IDLE_TTL_SECS);
        let now: Instant = Instant::now();
        if stripe.total >= POOL_MAX_IDLE_PER_STRIPE {
            stripe.evict_expired(now, ttl);
            if stripe.total >= POOL_MAX_IDLE_PER_STRIPE {
                return;
            }
        }
        let H1PoolStripe { entries, total } = &mut *stripe;
        let queue_idx: usize = if let Some(pos) =
            entries.iter().position(|(k, _): &H1StripeEntry<T>| {
                pool_key_matches(
                    k,
                    lookup.is_https,
                    lookup.host,
                    lookup.port,
                    lookup.proxy,
                    lookup.root_fp,
                    lookup.sync_timeout_ms,
                )
            }) {
            pos
        } else {
            let key: PoolKey = make_pool_key(
                lookup.is_https,
                lookup.host,
                lookup.port,
                lookup.proxy,
                lookup.roots,
                lookup.sync_timeout_ms,
            );
            entries.push((key, VecDeque::with_capacity(4)));
            entries.len() - 1
        };
        let queue: &mut VecDeque<PooledConn<T>> = &mut entries[queue_idx].1;
        if queue.len() >= POOL_MAX_IDLE_PER_STRIPE_HOST {
            let before: usize = queue.len();
            queue.retain(|item: &PooledConn<T>| {
                now.saturating_duration_since(item.idle_since) < ttl
            });
            let evicted: usize = before - queue.len();
            *total = total.saturating_sub(evicted);
            if queue.len() >= POOL_MAX_IDLE_PER_STRIPE_HOST {
                return;
            }
        }
        queue.push_back(PooledConn {
            stream,
            idle_since: now,
        });
        *total += 1;
        non_empty_mask.fetch_or(1u64 << chosen_idx, Ordering::Release);
    }

    /// Reports whether any stripe currently retains a bucket for `port`.
    ///
    /// # Arguments
    ///
    /// - `u16` - Target TCP port to inspect.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when at least one stripe holds a bucket for `port`.
    #[cfg(test)]
    pub(crate) fn contains_port(&self, port: u16) -> bool {
        let Self { stripes, .. } = self;
        for stripe_lock in stripes {
            if let Ok(stripe) = stripe_lock.lock()
                && stripe
                    .entries
                    .iter()
                    .any(|(k, _): &(PoolKey, VecDeque<PooledConn<T>>)| k.port == port)
            {
                return true;
            }
        }
        false
    }

    /// Inserts a pre-aged entry directly into stripe `0` for expiration tests.
    ///
    /// # Arguments
    ///
    /// - `PoolKey` - Pool key to insert under.
    /// - `PooledConn<T>` - Connection entry with custom `idle_since`.
    #[cfg(test)]
    pub(crate) fn insert_for_test(&self, key: PoolKey, conn: PooledConn<T>) {
        let Self {
            stripes,
            non_empty_mask,
        } = self;
        if let Ok(mut stripe) = stripes[0].lock() {
            let mut queue: VecDeque<PooledConn<T>> = VecDeque::new();
            queue.push_back(conn);
            stripe.entries.push((key, queue));
            stripe.total += 1;
            non_empty_mask.fetch_or(1u64, Ordering::Release);
        }
    }
}