hyperlane-plugin-cache 23.0.0

A 64-way sharded bounded in-memory and HTTP response cache plugin for the Hyperlane framework with TTL, byte-budget eviction, single-flight stampede coalescing, pluggable CacheStore traits, and RFC Cache-Control/Vary/Age/X-Cache handling.
Documentation
use super::*;

/// Returns the current Unix epoch timestamp in milliseconds.
///
/// # Returns
///
/// - `u64` - Milliseconds since Unix epoch.
#[inline]
pub(crate) fn cache_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)
}

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

/// Formats a `u64` into a caller-provided 20-byte stack buffer with zero heap allocations.
///
/// # Arguments
///
/// - `u64` - Integer value to format.
/// - `&mut [u8; AGE_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; AGE_STACK_BUF_LEN]) -> &str {
    let mut pos: usize = AGE_STACK_BUF_LEN;
    if value == 0 {
        pos -= 1;
        buf[pos] = ASCII_ZERO;
    } else {
        while value > 0 {
            pos -= 1;
            buf[pos] = ASCII_ZERO + (value % 10) as u8;
            value /= 10;
        }
    }
    from_utf8(&buf[pos..]).unwrap_or_default()
}

/// Computes the shard index for `key` using fast inline 8-byte word mixing.
///
/// # Arguments
///
/// - `&str` - Cache key.
///
/// # Returns
///
/// - `usize` - Shard index in `0..CACHE_SHARD_COUNT`.
#[inline(always)]
pub(crate) fn cache_shard_index(key: &str) -> usize {
    let bytes: &[u8] = key.as_bytes();
    let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
    let mut hash: u64 = CACHE_FNV1A_OFFSET_BASIS ^ (bytes.len() as u64);
    for chunk in chunks {
        hash = (hash ^ u64::from_ne_bytes(*chunk)).wrapping_mul(CACHE_SHARD_MUL1);
    }
    if !rem.is_empty() {
        let mut tail: u64 = 0;
        for &b in rem {
            tail = (tail << 8) | u64::from(b);
        }
        hash = (hash ^ tail).wrapping_mul(CACHE_SHARD_MUL2);
    }
    ((hash ^ (hash >> 32)) as usize) & (CACHE_SHARD_COUNT - 1)
}

/// Lazily builds pre-formatted HTTP/1.1 wire fragments for a [`CachedValue`] matching `Response::build()`.
///
/// # Arguments
///
/// - `&CachedValue` - Cached HTTP response value.
///
/// # Returns
///
/// - `Option<Box<CachedHttp11Wire>>` - Prebuilt wire fragments, or `None` for special framing/encoded responses.
pub(crate) fn build_cached_http11_wire(value: &CachedValue) -> Option<Box<CachedHttp11Wire>> {
    let status: usize = value.get_status_code();
    if (100..=199).contains(&status) || status == 204 || status == 205 || status == 304 {
        return None;
    }
    for (name, _) in value.get_headers() {
        if name.eq_ignore_ascii_case(CONTENT_ENCODING)
            || name.eq_ignore_ascii_case(TRANSFER_ENCODING)
        {
            return None;
        }
    }
    let mut resp: Response = Response::default();
    resp.set_status_code(status);
    for (name, val) in value.get_headers() {
        resp.set_header(name, val);
    }
    resp.set_body(value.get_body().as_slice());
    let without_diag: Vec<u8> = resp.build();
    let hdr_end: usize = without_diag
        .windows(CACHE_WIRE_HEADER_END.len())
        .position(|w: &[u8]| w == CACHE_WIRE_HEADER_END)?;
    let insert_pos: usize = hdr_end + CACHE_WIRE_CRLF.len();
    let mut with_diag_prefix: Vec<u8> =
        Vec::with_capacity(insert_pos + CACHE_WIRE_DIAG_PREFIX.len());
    with_diag_prefix.extend_from_slice(&without_diag[..insert_pos]);
    with_diag_prefix.extend_from_slice(CACHE_WIRE_DIAG_PREFIX);
    let tail_slice: &[u8] = &without_diag[insert_pos..];
    let mut with_diag_suffix: Vec<u8> =
        Vec::with_capacity(CACHE_WIRE_CRLF.len() + tail_slice.len());
    with_diag_suffix.extend_from_slice(CACHE_WIRE_CRLF);
    with_diag_suffix.extend_from_slice(tail_slice);
    Some(Box::new(CachedHttp11Wire {
        without_diag,
        with_diag_prefix,
        with_diag_suffix,
    }))
}

/// Computes the approximate heap footprint in bytes of a [`CachedValue`].
///
/// # Arguments
///
/// - `&str` - Cache key.
/// - `&CachedValue` - Cached response payload and headers.
///
/// # Returns
///
/// - `usize` - Estimated memory footprint in bytes.
#[inline]
pub(crate) fn estimate_entry_bytes(key: &str, value: &CachedValue) -> usize {
    let header_bytes: usize = value
        .get_headers()
        .iter()
        .map(|(k, v): &(String, String)| k.len() + v.len())
        .sum();
    key.len() + header_bytes + value.get_body().len() + 64
}

/// Strips an ASCII case-insensitive prefix from `input` without heap allocation.
///
/// # Arguments
///
/// - `&'a str` - Source text.
/// - `&str` - Expected lowercase ASCII prefix.
///
/// # Returns
///
/// - `Option<&'a str>` - Remaining suffix when prefix matches.
#[inline(always)]
pub(crate) fn strip_prefix_ignore_ascii_case<'a>(input: &'a str, prefix: &str) -> Option<&'a str> {
    if input.len() < prefix.len() {
        return None;
    }
    let (head, tail): (&'a str, &'a str) = input.split_at(prefix.len());
    if head.eq_ignore_ascii_case(prefix) {
        Some(tail)
    } else {
        None
    }
}

/// Parses an ASCII unsigned integer without allocating or invoking locale formatting.
///
/// # Arguments
///
/// - `&str` - Trimmed ASCII decimal digit slice.
///
/// # Returns
///
/// - `Option<u64>` - Parsed integer, or `None` when empty, non-digit, or overflowing.
#[inline(always)]
pub(crate) fn parse_u64_ascii(raw: &str) -> Option<u64> {
    let bytes: &[u8] = raw.as_bytes();
    if bytes.is_empty() {
        return None;
    }
    let mut acc: u64 = 0;
    for &b in bytes {
        if !b.is_ascii_digit() {
            return None;
        }
        acc = acc.checked_mul(10)?.checked_add((b - ASCII_ZERO) as u64)?;
    }
    Some(acc)
}

/// Parses `Cache-Control` directives to check whether caching is prohibited and extract optional `max-age` / `s-maxage`.
///
/// # Arguments
///
/// - `Option<&str>` - Raw `Cache-Control` header value.
///
/// # Returns
///
/// - `(bool, Option<u64>)` - `(cacheable, ttl_override_ms)`.
#[inline]
pub(crate) fn parse_cache_control(header: Option<&str>) -> (bool, Option<u64>) {
    let Some(raw) = header else {
        return (true, None);
    };
    let mut s_maxage_secs: Option<u64> = None;
    let mut max_age_secs: Option<u64> = None;
    for directive in raw.split(',') {
        let trimmed: &str = directive.trim();
        if trimmed.eq_ignore_ascii_case(CC_NO_STORE)
            || trimmed.eq_ignore_ascii_case(CC_NO_CACHE)
            || trimmed.eq_ignore_ascii_case(CC_PRIVATE)
        {
            return (false, None);
        }
        if let Some(secs_str) = strip_prefix_ignore_ascii_case(trimmed, CC_S_MAXAGE_PREFIX)
            && let Some(secs) = parse_u64_ascii(secs_str.trim())
        {
            s_maxage_secs = Some(secs);
        } else if let Some(secs_str) = strip_prefix_ignore_ascii_case(trimmed, CC_MAX_AGE_PREFIX)
            && let Some(secs) = parse_u64_ascii(secs_str.trim())
        {
            max_age_secs = Some(secs);
        }
    }
    let chosen: Option<u64> = s_maxage_secs.or(max_age_secs);
    if chosen == Some(0) {
        return (false, None);
    }
    (true, chosen.map(|secs: u64| secs.saturating_mul(1_000)))
}

/// Builds a canonical HTTP cache key borrowing the path directly when no query parameters exist.
///
/// # Arguments
///
/// - `&'a Context` - Incoming HTTP request context.
///
/// # Returns
///
/// - `Cow<'a, str>` - Borrowed path or owned deterministic `path?sorted_query` key.
#[inline]
pub(crate) fn build_http_cache_key_cow<'a>(ctx: &'a Context) -> Cow<'a, str> {
    let path: &'a str = ctx.get_request().get_path();
    let querys: &'a RequestQuerys = ctx.get_request().get_querys();
    if querys.is_empty() {
        return Cow::Borrowed(path);
    }
    let mut pairs: Vec<(&str, &VecDeque<String>)> = Vec::with_capacity(querys.len());
    let mut query_bytes: usize = 1;
    for (k, vals) in querys {
        pairs.push((k.as_str(), vals));
        for v in vals {
            query_bytes += k.len() + v.len() + 2;
        }
    }
    if pairs.len() > 1 {
        pairs.sort_unstable_by(
            |a: &(&str, &VecDeque<String>), b: &(&str, &VecDeque<String>)| a.0.cmp(b.0),
        );
    }
    let mut key: String = String::with_capacity(path.len() + query_bytes);
    key.push_str(path);
    key.push('?');
    let mut first: bool = true;
    for (k, vals) in pairs {
        for v in vals {
            if !first {
                key.push('&');
            }
            first = false;
            key.push_str(k);
            key.push('=');
            key.push_str(v);
        }
    }
    Cow::Owned(key)
}