hyperlane-plugin-gateway 23.0.0

A reverse proxy and API gateway plugin for the Hyperlane framework with load balancing, path-prefix routing, token-bucket rate limiting, circuit breaking, RFC 9110 hop-by-hop header stripping, and pooled HTTP/1.1 + HTTP/2 upstream forwarding.
Documentation
use super::*;

/// Returns the current Unix timestamp in milliseconds.
///
/// # Returns
///
/// - `u64` - Milliseconds since Unix epoch.
#[inline]
pub(crate) fn gateway_now_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|dur: Duration| dur.as_millis() as u64)
        .unwrap_or(0)
}

/// Borrows the last value of a lowercased HTTP request header without heap allocation.
///
/// # Arguments
///
/// - `&'a Request` - Incoming HTTP request.
/// - `&str` - Lowercased header key name.
///
/// # Returns
///
/// - `Option<&'a str>` - Borrowed last header value, if present.
#[inline(always)]
pub(crate) fn request_header_back<'a>(req: &'a Request, lower_key: &str) -> Option<&'a str> {
    req.get_headers()
        .get(lower_key)
        .and_then(|values: &VecDeque<String>| values.back())
        .map(String::as_str)
}

/// Normalizes a route prefix so segment-boundary matching is canonical.
///
/// # Arguments
///
/// - `&str` - Raw route prefix.
///
/// # Returns
///
/// - `String` - Prefix beginning with `/` and without trailing `/` (except `"/"`).
pub(crate) fn normalize_prefix(prefix: &str) -> String {
    let trimmed: &str = prefix.trim();
    if trimmed.is_empty() || trimmed == "/" {
        return "/".to_owned();
    }
    let with_slash: String = if trimmed.starts_with('/') {
        trimmed.to_owned()
    } else {
        format!("/{trimmed}")
    };
    with_slash.trim_end_matches('/').to_owned()
}

/// Reports whether `path` matches `prefix` on an exact path-segment boundary.
///
/// For example, `"/api"` matches `"/api"` and `"/api/orders"`, but never `"/apiv2"`.
///
/// # Arguments
///
/// - `&str` - Incoming request path.
/// - `&str` - Normalized route prefix.
///
/// # Returns
///
/// - `bool` - `true` when `path` falls under `prefix`.
#[inline(always)]
pub fn path_matches_prefix(path: &str, prefix: &str) -> bool {
    let p_bytes: &[u8] = prefix.as_bytes();
    let plen: usize = p_bytes.len();
    if plen == 1 && p_bytes[0] == ASCII_SLASH {
        return true;
    }
    let path_bytes: &[u8] = path.as_bytes();
    if path_bytes.len() < plen {
        return false;
    }
    if path_bytes.len() > plen && path_bytes[plen] != ASCII_SLASH {
        return false;
    }
    if plen > 0 && path_bytes[plen - 1] != p_bytes[plen - 1] {
        return false;
    }
    &path_bytes[..plen] == p_bytes
}

/// Rewrites an incoming path + optional query string onto `base_url`.
///
/// # Arguments
///
/// - `&str` - Normalized upstream base URL (no trailing slash).
/// - `&str` - Incoming request path.
/// - `&str` - Incoming query string (without leading `?`).
/// - `&str` - Normalized matched prefix.
/// - `bool` - Whether to strip `prefix` from the forwarded path.
///
/// # Returns
///
/// - `String` - Complete upstream URL ready for `http-request`.
#[inline]
pub fn build_upstream_url(
    base_url: &str,
    path: &str,
    query: &str,
    prefix: &str,
    strip_prefix: bool,
) -> String {
    let forward_path: &str = if strip_prefix && prefix != "/" {
        let stripped: &str = path.strip_prefix(prefix).unwrap_or(path);
        if stripped.is_empty() { "/" } else { stripped }
    } else if path.is_empty() {
        "/"
    } else {
        path
    };
    let extra: usize = if query.is_empty() { 0 } else { 1 + query.len() };
    let mut url: String = String::with_capacity(base_url.len() + forward_path.len() + extra);
    url.push_str(base_url);
    url.push_str(forward_path);
    if !query.is_empty() {
        url.push('?');
        url.push_str(query);
    }
    url
}

/// Rewrites an incoming request path and query parameters directly onto `base_url` in one allocation.
///
/// # Arguments
///
/// - `&str` - Normalized upstream base URL (no trailing slash).
/// - `&Request` - Incoming HTTP request.
/// - `&str` - Normalized matched prefix.
/// - `bool` - Whether to strip `prefix` from the forwarded path.
///
/// # Returns
///
/// - `String` - Complete upstream URL ready for `http-request`.
#[inline]
pub(crate) fn build_upstream_url_from_request(
    base_url: &str,
    req: &Request,
    prefix: &str,
    strip_prefix: bool,
) -> String {
    let path: &str = req.get_path();
    let forward_path: &str = if strip_prefix && prefix != "/" {
        let stripped: &str = path.strip_prefix(prefix).unwrap_or(path);
        if stripped.is_empty() { "/" } else { stripped }
    } else if path.is_empty() {
        "/"
    } else {
        path
    };
    let mut query_len: usize = 0;
    for (k, vals) in req.get_querys() {
        for v in vals {
            query_len += 1 + k.len() + if v.is_empty() { 0 } else { 1 + v.len() };
        }
    }
    let mut url: String = String::with_capacity(base_url.len() + forward_path.len() + query_len);
    url.push_str(base_url);
    url.push_str(forward_path);
    let mut first: bool = true;
    for (k, vals) in req.get_querys() {
        for v in vals {
            url.push(if first { '?' } else { '&' });
            first = false;
            url.push_str(k);
            if !v.is_empty() {
                url.push('=');
                url.push_str(v);
            }
        }
    }
    url
}

/// Reports whether `name` is an RFC 9110 hop-by-hop header that proxies must not forward.
///
/// Uses length-dispatched zero-allocation ASCII case-insensitive comparison for standard
/// hop-by-hop headers and only consults `extra_connection_headers` when non-empty.
///
/// # Arguments
///
/// - `&str` - Header name (any casing).
/// - `&HashSet<String>` - Additional lowercased header names nominated by `Connection`.
///
/// # Returns
///
/// - `bool` - `true` when the header must be stripped before forwarding.
#[inline(always)]
pub fn is_hop_by_hop_header(name: &str, extra_connection_headers: &HashSet<String>) -> bool {
    let is_standard: bool = match name.len() {
        2 => name.eq_ignore_ascii_case(TE),
        7 => name.eq_ignore_ascii_case(UPGRADE) || name.eq_ignore_ascii_case(HEADER_TRAILER),
        10 => name.eq_ignore_ascii_case(CONNECTION) || name.eq_ignore_ascii_case(KEEP_ALIVE),
        16 => name.eq_ignore_ascii_case(HEADER_PROXY_CONNECTION),
        17 => name.eq_ignore_ascii_case(TRANSFER_ENCODING),
        18 => name.eq_ignore_ascii_case(PROXY_AUTHENTICATE),
        19 => name.eq_ignore_ascii_case(PROXY_AUTHORIZATION),
        _ => false,
    };
    if is_standard {
        return true;
    }
    if extra_connection_headers.is_empty() {
        return false;
    }
    if extra_connection_headers.contains(name) {
        return true;
    }
    if !name.bytes().any(|b: u8| b.is_ascii_uppercase()) {
        return false;
    }
    extra_connection_headers.contains(&name.to_ascii_lowercase())
}

/// Inserts non-trivial lowercased `Connection` header tokens into `tokens` lazily.
///
/// # Arguments
///
/// - `&str` - Raw `Connection` header value.
/// - `&mut HashSet<String>` - Destination set receiving custom nominated header names.
#[inline]
pub(crate) fn collect_custom_connection_tokens(val: &str, tokens: &mut HashSet<String>) {
    for part in val.split(',') {
        let trimmed: &str = part.trim();
        if trimmed.is_empty()
            || trimmed.eq_ignore_ascii_case(KEEP_ALIVE)
            || trimmed.eq_ignore_ascii_case(HEADER_VALUE_CLOSE)
        {
            continue;
        }
        tokens.insert(trimmed.to_ascii_lowercase());
    }
}

/// Extracts custom lowercased header names listed in incoming request `Connection` headers.
///
/// # Arguments
///
/// - `&Request` - Incoming HTTP request.
///
/// # Returns
///
/// - `HashSet<String>` - Custom nominated header names (empty without allocation on standard `keep-alive`/`close`).
#[inline]
pub(crate) fn extract_request_connection_tokens(req: &Request) -> HashSet<String> {
    let mut tokens: HashSet<String> = HashSet::new();
    if let Some(values) = req.get_headers().get(CONNECTION) {
        for val in values {
            collect_custom_connection_tokens(val, &mut tokens);
        }
    }
    tokens
}

/// Extracts custom lowercased header names listed in upstream response `Connection` headers.
///
/// # Arguments
///
/// - `&HashMapXxHash3_64<String, String>` - Upstream response headers.
///
/// # Returns
///
/// - `HashSet<String>` - Custom nominated header names (empty without allocation on standard `keep-alive`/`close`).
#[inline]
pub(crate) fn extract_response_connection_tokens(
    headers: &HashMapXxHash3_64<String, String>,
) -> HashSet<String> {
    let mut tokens: HashSet<String> = HashSet::new();
    for (k, val) in headers {
        if k.len() == CONNECTION.len() && k.eq_ignore_ascii_case(CONNECTION) {
            collect_custom_connection_tokens(val, &mut tokens);
        }
    }
    tokens
}