hyperlane-plugin-rate-limit 23.4.0

A 64-way sharded lock-free atomic GCRA and fixed-window rate limiter plugin for the Hyperlane framework with extensible KeyExtractor and RateLimitStore traits and RFC RateLimit headers.
Documentation
use super::*;

/// Computes the shard index for `key` using zero-allocation 8-byte word hashing.
///
/// # Arguments
///
/// - `&str` - Bucket key.
///
/// # Returns
///
/// - `usize` - Shard index in `0..RATE_LIMIT_SHARD_COUNT`.
#[inline(always)]
pub(crate) fn rate_limit_shard_index(key: &str) -> usize {
    let mut hasher: FxHasher = FxHasher::default();
    hasher.write(key.as_bytes());
    let h: u64 = hasher.finish();
    (((h >> 32) ^ h) as usize) & (RATE_LIMIT_SHARD_COUNT - 1)
}

/// Converts nanoseconds upward to whole seconds (minimum `1` when `nanos > 0`).
///
/// # Arguments
///
/// - `u64` - Duration in nanoseconds.
///
/// # Returns
///
/// - `u64` - Ceiling whole seconds.
#[inline(always)]
pub(crate) fn ceil_nanos_to_secs(nanos: u64) -> u64 {
    if nanos == 0 {
        return 0;
    }
    nanos.div_ceil(NANOS_PER_SEC)
}

/// Formats an unsigned 64-bit integer into `buf` without heap allocation using a 2-digit LUT.
///
/// # Arguments
///
/// - `u64` - Value to format in decimal.
/// - `&mut [u8; U64_STACK_BUF_LEN]` - Stack byte buffer.
///
/// # Returns
///
/// - `&str` - Borrowed decimal string slice inside `buf`.
#[inline]
pub(crate) fn format_u64_stack(mut value: u64, buf: &mut [u8; U64_STACK_BUF_LEN]) -> &str {
    if value < 10 {
        buf[U64_STACK_BUF_LEN - 1] = BYTE_ZERO + value as u8;
        return from_utf8(&buf[U64_STACK_BUF_LEN - 1..]).unwrap_or_default();
    }
    let mut pos: usize = U64_STACK_BUF_LEN;
    while value >= 100 {
        let pair: usize = ((value % 100) as usize) * 2;
        value /= 100;
        pos -= 2;
        buf[pos] = DEC_DIGITS_LUT[pair];
        buf[pos + 1] = DEC_DIGITS_LUT[pair + 1];
    }
    if value >= 10 {
        let pair: usize = (value as usize) * 2;
        pos -= 2;
        buf[pos] = DEC_DIGITS_LUT[pair];
        buf[pos + 1] = DEC_DIGITS_LUT[pair + 1];
    } else {
        pos -= 1;
        buf[pos] = BYTE_ZERO + value as u8;
    }
    from_utf8(&buf[pos..]).unwrap_or_default()
}

/// Borrows the last value of request header `name` case-insensitively without heap allocation.
///
/// # Arguments
///
/// - `&'a Request` - Incoming HTTP request.
/// - `&str` - Header name to inspect.
///
/// # Returns
///
/// - `Option<&'a str>` - Borrowed last header value, if present.
#[inline]
pub(crate) fn get_request_header_back_ref<'a>(request: &'a Request, name: &str) -> Option<&'a str> {
    let bytes: &[u8] = name.as_bytes();
    if !bytes.iter().any(|b: &u8| b.is_ascii_uppercase()) {
        return request
            .get_headers()
            .get(name)
            .and_then(|values: &VecDeque<String>| values.back())
            .map(String::as_str);
    }
    if bytes.len() <= STACK_HEADER_NAME_LEN {
        let mut stack_key: [u8; STACK_HEADER_NAME_LEN] = [0u8; STACK_HEADER_NAME_LEN];
        for (dst, &src) in stack_key.iter_mut().zip(bytes.iter()) {
            *dst = src.to_ascii_lowercase();
        }
        if let Ok(lower) = from_utf8(&stack_key[..bytes.len()]) {
            return request
                .get_headers()
                .get(lower)
                .and_then(|values: &VecDeque<String>| values.back())
                .map(String::as_str);
        }
    }
    request
        .get_headers()
        .get(&name.to_ascii_lowercase())
        .and_then(|values: &VecDeque<String>| values.back())
        .map(String::as_str)
}

/// Appends one decimal octet (`0..=255`) into `buf` at `pos` using the 2-digit lookup table.
///
/// # Arguments
///
/// - `u8` - Octet value.
/// - `&mut [u8]` - Destination byte slice.
/// - `usize` - Starting write offset.
///
/// # Returns
///
/// - `usize` - Updated write offset.
#[inline(always)]
pub(crate) fn write_octet(octet: u8, buf: &mut [u8], pos: usize) -> usize {
    if octet >= 100 {
        let hundreds: u8 = octet / 100;
        let rem: usize = ((octet - hundreds * 100) as usize) * 2;
        buf[pos] = BYTE_ZERO + hundreds;
        buf[pos + 1] = DEC_DIGITS_LUT[rem];
        buf[pos + 2] = DEC_DIGITS_LUT[rem + 1];
        return pos + 3;
    }
    if octet >= 10 {
        let pair: usize = (octet as usize) * 2;
        buf[pos] = DEC_DIGITS_LUT[pair];
        buf[pos + 1] = DEC_DIGITS_LUT[pair + 1];
        return pos + 2;
    }
    buf[pos] = BYTE_ZERO + octet;
    pos + 1
}

/// Formats `ip` into `buf` without heap allocation.
///
/// # Arguments
///
/// - `IpAddr` - Peer IP address.
/// - `&mut [u8; IP_STACK_BUF_LEN]` - Stack byte buffer.
///
/// # Returns
///
/// - `&str` - Borrowed formatted IP string slice inside `buf`.
#[inline]
pub(crate) fn format_ip_stack(ip: IpAddr, buf: &mut [u8; IP_STACK_BUF_LEN]) -> &str {
    match ip {
        IpAddr::V4(v4) => {
            let octets: [u8; 4] = v4.octets();
            let mut pos: usize = write_octet(octets[0], buf, 0);
            buf[pos] = BYTE_DOT;
            pos = write_octet(octets[1], buf, pos + 1);
            buf[pos] = BYTE_DOT;
            pos = write_octet(octets[2], buf, pos + 1);
            buf[pos] = BYTE_DOT;
            pos = write_octet(octets[3], buf, pos + 1);
            from_utf8(&buf[..pos]).unwrap_or(FALLBACK_CLIENT_KEY)
        }
        IpAddr::V6(v6) => {
            let mut writer: StackFmtWriter<'_> = StackFmtWriter { buf, len: 0 };
            let _: fmt::Result = write!(&mut writer, "{v6}");
            let written: usize = writer.len;
            from_utf8(&buf[..written]).unwrap_or(FALLBACK_CLIENT_KEY)
        }
    }
}

/// Resolves the client IP key directly as a borrowed slice without heap allocation.
///
/// # Arguments
///
/// - `&Stream` - Transport stream.
/// - `&'a Context` - Request context.
/// - `bool` - Whether forwarding headers (`X-Forwarded-For` / `X-Real-Ip`) are trusted.
/// - `&'a mut [u8; IP_STACK_BUF_LEN]` - Stack scratch buffer used when formatting peer socket IPs.
///
/// # Returns
///
/// - `&'a str` - Borrowed client IP partition key.
#[inline]
pub(crate) fn resolve_client_ip_ref<'a>(
    stream: &Stream,
    ctx: &'a Context,
    trust_proxy: bool,
    buf: &'a mut [u8; IP_STACK_BUF_LEN],
) -> &'a str {
    if trust_proxy {
        let request: &'a Request = ctx.get_request();
        if let Some(xff) = request
            .get_headers()
            .get(X_FORWARDED_FOR)
            .and_then(|values: &VecDeque<String>| values.back())
            && let Some(first) = xff.split(XFF_COMMA_DELIMITER).next()
        {
            let trimmed: &'a str = first.trim();
            if !trimmed.is_empty() {
                return trimmed;
            }
        }
        if let Some(real_ip) = request
            .get_headers()
            .get(X_REAL_IP)
            .and_then(|values: &VecDeque<String>| values.back())
        {
            let trimmed: &'a str = real_ip.trim();
            if !trimmed.is_empty() {
                return trimmed;
            }
        }
    }
    if let Ok(addr) = stream.get_peer_addr() {
        let peer: SocketAddr = addr;
        return format_ip_stack(peer.ip(), buf);
    }
    FALLBACK_CLIENT_KEY
}

/// Extracts the first client IP token from `X-Forwarded-For`, `X-Real-Ip`, or peer socket address.
///
/// # Arguments
///
/// - `&Stream` - Transport stream.
/// - `&Context` - Request context.
/// - `bool` - Whether forwarding headers (`X-Forwarded-For` / `X-Real-Ip`) are trusted.
///
/// # Returns
///
/// - `String` - Resolved client key.
#[inline]
pub(crate) fn resolve_client_ip(stream: &Stream, ctx: &Context, trust_proxy: bool) -> String {
    let mut ip_buf: [u8; IP_STACK_BUF_LEN] = [0u8; IP_STACK_BUF_LEN];
    resolve_client_ip_ref(stream, ctx, trust_proxy, &mut ip_buf).to_owned()
}