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
use super::*;

/// 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.
/// - `Option<&RootCertStore>` - Optional custom 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: Option<&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)]
pub(super) 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 striped 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.
/// - `Option<&RootCertStore>` - Optional custom TLS trust store.
///
/// # Returns
///
/// - `Option<AsyncClientTransport>` - A reusable keep-alive connection, or `None`.
#[inline(always)]
pub(crate) fn take_async_h1_conn(
    is_https: bool,
    host: &str,
    port: u16,
    proxy: Option<&Proxy>,
    roots: Option<&RootCertStore>,
) -> Option<AsyncClientTransport> {
    let lookup: PoolLookup<'_> = PoolLookup {
        is_https,
        host,
        port,
        proxy,
        roots,
        root_fp: root_cert_fingerprint(roots),
        sync_timeout_ms: 0,
    };
    ASYNC_H1_POOL.get_or_init(StripedH1Pool::new).take(lookup)
}

/// Returns a clean asynchronous HTTP/1.1 connection to the striped 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.
/// - `Option<&RootCertStore>` - Optional custom TLS trust store.
/// - `AsyncClientTransport` - Idle keep-alive stream ready for the next request.
#[inline(always)]
pub(crate) fn put_async_h1_conn(
    is_https: bool,
    host: &str,
    port: u16,
    proxy: Option<&Proxy>,
    roots: Option<&RootCertStore>,
    stream: AsyncClientTransport,
) {
    let lookup: PoolLookup<'_> = PoolLookup {
        is_https,
        host,
        port,
        proxy,
        roots,
        root_fp: root_cert_fingerprint(roots),
        sync_timeout_ms: 0,
    };
    ASYNC_H1_POOL
        .get_or_init(StripedH1Pool::new)
        .put(lookup, stream);
}

/// Takes one non-expired synchronous HTTP/1.1 connection from the striped 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.
/// - `Option<&RootCertStore>` - Optional custom TLS trust store.
/// - `u64` - Synchronous socket timeout in milliseconds.
///
/// # Returns
///
/// - `Option<SyncClientTransport>` - A reusable keep-alive connection, or `None`.
#[inline(always)]
pub(crate) fn take_sync_h1_conn(
    is_https: bool,
    host: &str,
    port: u16,
    proxy: Option<&Proxy>,
    roots: Option<&RootCertStore>,
    sync_timeout_ms: u64,
) -> Option<SyncClientTransport> {
    let lookup: PoolLookup<'_> = PoolLookup {
        is_https,
        host,
        port,
        proxy,
        roots,
        root_fp: root_cert_fingerprint(roots),
        sync_timeout_ms,
    };
    SYNC_H1_POOL.get_or_init(StripedH1Pool::new).take(lookup)
}

/// Returns a clean synchronous HTTP/1.1 connection to the striped 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.
/// - `Option<&RootCertStore>` - Optional custom TLS trust store.
/// - `u64` - Synchronous socket timeout in milliseconds.
/// - `SyncClientTransport` - Idle keep-alive stream ready for the next request.
#[inline(always)]
pub(crate) fn put_sync_h1_conn(
    is_https: bool,
    host: &str,
    port: u16,
    proxy: Option<&Proxy>,
    roots: Option<&RootCertStore>,
    sync_timeout_ms: u64,
    stream: SyncClientTransport,
) {
    let lookup: PoolLookup<'_> = PoolLookup {
        is_https,
        host,
        port,
        proxy,
        roots,
        root_fp: root_cert_fingerprint(roots),
        sync_timeout_ms,
    };
    SYNC_H1_POOL
        .get_or_init(StripedH1Pool::new)
        .put(lookup, stream);
}

/// Retrieves a cloned multiplexed HTTP/2 sender matching `lookup` under a shared read lock without allocating.
///
/// # Arguments
///
/// - `PoolLookup<'_>` - Borrowed origin, proxy, and TLS trust store lookup parameters.
///
/// # Returns
///
/// - `Option<SendRequest<Bytes>>` - Cloned HTTP/2 request sender, or `None`.
#[inline(always)]
pub(crate) fn get_h2_sender(lookup: PoolLookup<'_>) -> Option<SendRequest<Bytes>> {
    let lock: &RwLock<H2PoolList> = ASYNC_H2_POOL.get_or_init(|| RwLock::new(Vec::new()));
    let Ok(entries) = lock.read() else {
        return None;
    };
    entries
        .iter()
        .find(|(k, _): &&(PoolKey, SendRequest<Bytes>)| {
            pool_key_matches(
                k,
                lookup.is_https,
                lookup.host,
                lookup.port,
                lookup.proxy,
                lookup.root_fp,
                0,
            )
        })
        .map(|(_, sender): &(PoolKey, SendRequest<Bytes>)| sender.clone())
}

/// Stores or replaces an active multiplexed HTTP/2 sender in the pool.
///
/// # Arguments
///
/// - `PoolLookup<'_>` - Borrowed origin, proxy, and TLS trust store lookup parameters.
/// - `SendRequest<Bytes>` - Active HTTP/2 sender handle.
pub(crate) fn put_h2_sender(lookup: PoolLookup<'_>, sender: SendRequest<Bytes>) {
    let lock: &RwLock<H2PoolList> = ASYNC_H2_POOL.get_or_init(|| RwLock::new(Vec::new()));
    let Ok(mut entries) = lock.write() else {
        return;
    };
    if let Some((_, existing)) =
        entries
            .iter_mut()
            .find(|(k, _): &&mut (PoolKey, SendRequest<Bytes>)| {
                pool_key_matches(
                    k,
                    lookup.is_https,
                    lookup.host,
                    lookup.port,
                    lookup.proxy,
                    lookup.root_fp,
                    0,
                )
            })
    {
        *existing = sender;
        return;
    }
    if entries.len() >= POOL_MAX_IDLE_TOTAL {
        entries.clear();
    }
    let key: PoolKey = make_pool_key(
        lookup.is_https,
        lookup.host,
        lookup.port,
        lookup.proxy,
        lookup.roots,
        0,
    );
    entries.push((key, sender));
}

/// Removes a closed or broken HTTP/2 sender matching `lookup` from the pool.
///
/// # Arguments
///
/// - `PoolLookup<'_>` - Borrowed origin, proxy, and TLS trust store lookup parameters.
pub(crate) fn remove_h2_sender(lookup: PoolLookup<'_>) {
    let lock: &RwLock<H2PoolList> = ASYNC_H2_POOL.get_or_init(|| RwLock::new(Vec::new()));
    if let Ok(mut entries) = lock.write()
        && let Some(pos) = entries
            .iter()
            .position(|(k, _): &(PoolKey, SendRequest<Bytes>)| {
                pool_key_matches(
                    k,
                    lookup.is_https,
                    lookup.host,
                    lookup.port,
                    lookup.proxy,
                    lookup.root_fp,
                    0,
                )
            })
    {
        let _: (PoolKey, SendRequest<Bytes>) = entries.swap_remove(pos);
    }
}

/// 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);
        }
    });
}