hyperlane-plugin-etag 23.3.1

An opt-in automatic ETag and HTTP conditional request plugin for the Hyperlane framework providing strong/weak XxHash3_64 entity tags, zero-allocation If-None-Match 304 Not Modified, and If-Match 412 Precondition Failed optimistic concurrency.
Documentation
use super::*;

/// Computes a 64-bit `XxHash3_64` digest of `body`.
///
/// # Arguments
///
/// - `&[u8]` - Response body bytes.
///
/// # Returns
///
/// - `u64` - 64-bit digest.
#[inline(always)]
pub fn hash_entity_bytes(body: &[u8]) -> u64 {
    let mut hasher: XxHash3_64 = XxHash3_64::default();
    hasher.write(body);
    hasher.finish()
}

/// Formats `digest` as a stack-allocated quoted strong ETag (`"<16 hex>"`).
///
/// # Arguments
///
/// - `u64` - 64-bit entity digest.
///
/// # Returns
///
/// - `[u8; 18]` - ASCII strong ETag bytes.
#[inline(always)]
pub(crate) fn format_strong_etag_stack(digest: u64) -> [u8; 18] {
    let mut out: [u8; 18] = [b'"'; 18];
    let bytes: [u8; 8] = digest.to_be_bytes();
    for i in 0..8usize {
        out[1 + i * 2] = HEX_LOWER[(bytes[i] >> 4) as usize];
        out[2 + i * 2] = HEX_LOWER[(bytes[i] & 0x0f) as usize];
    }
    out
}

/// Formats `digest` as a stack-allocated weak ETag (`W/"<16 hex>"`).
///
/// # Arguments
///
/// - `u64` - 64-bit entity digest.
///
/// # Returns
///
/// - `[u8; 20]` - ASCII weak ETag bytes.
#[inline(always)]
pub(crate) fn format_weak_etag_stack(digest: u64) -> [u8; 20] {
    let mut out: [u8; 20] = [b'"'; 20];
    out[0] = b'W';
    out[1] = b'/';
    let bytes: [u8; 8] = digest.to_be_bytes();
    for i in 0..8usize {
        out[3 + i * 2] = HEX_LOWER[(bytes[i] >> 4) as usize];
        out[4 + i * 2] = HEX_LOWER[(bytes[i] & 0x0f) as usize];
    }
    out
}

/// Computes a formatted strong or weak ETag string for `body`.
///
/// # Arguments
///
/// - `&[u8]` - Representation bytes.
/// - `EtagStrength` - Strong or weak tag format.
///
/// # Returns
///
/// - `String` - Formatted HTTP `ETag` header value.
pub fn compute_etag(body: &[u8], strength: EtagStrength) -> String {
    let digest: u64 = hash_entity_bytes(body);
    match strength {
        EtagStrength::Strong => {
            let buf: [u8; 18] = format_strong_etag_stack(digest);
            from_utf8(&buf).unwrap_or_default().to_owned()
        }
        EtagStrength::Weak => {
            let buf: [u8; 20] = format_weak_etag_stack(digest);
            from_utf8(&buf).unwrap_or_default().to_owned()
        }
    }
}

/// Evaluates an RFC 9110 ยง13.1.1 `If-Match` header against `current_etag` using strong comparison.
///
/// # Arguments
///
/// - `&str` - Raw `If-Match` header value.
/// - `Option<&str>` - Current entity tag of the target resource (`None` if resource does not exist).
///
/// # Returns
///
/// - `bool` - `true` when the `If-Match` precondition succeeds.
pub fn matches_if_match_strong(header_value: &str, current_etag: Option<&str>) -> bool {
    let trimmed: &str = header_value.trim();
    if trimmed == "*" {
        return current_etag.is_some();
    }
    let Some(current) = current_etag else {
        return false;
    };
    if current.starts_with(WEAK_PREFIX) {
        return false;
    }
    for token in trimmed.split(',') {
        let cand: &str = token.trim();
        if !cand.starts_with(WEAK_PREFIX) && cand == current {
            return true;
        }
    }
    false
}

/// Reports whether `status` carries no body (`1xx`, `204`, `304`).
///
/// # Arguments
///
/// - `usize` - HTTP status code.
///
/// # Returns
///
/// - `bool` - `true` when bodyless.
#[inline(always)]
pub(crate) fn status_has_no_body(status: usize) -> bool {
    (100..200).contains(&status) || status == 204 || status == 304
}

/// Normalizes a path prefix by ensuring a leading `/` and trimming trailing `/`.
///
/// # Arguments
///
/// - `&str` - Raw path prefix.
///
/// # Returns
///
/// - `String` - Normalized prefix.
pub(crate) fn normalize_prefix(raw: &str) -> String {
    let trimmed: &str = raw.trim().trim_end_matches('/');
    if trimmed.is_empty() || trimmed == ROOT_SLASH {
        return ROOT_SLASH.to_owned();
    }
    if trimmed.starts_with('/') {
        trimmed.to_owned()
    } else {
        format!("/{trimmed}")
    }
}

/// Reports whether `path` matches `prefix` on a segment boundary.
///
/// # Arguments
///
/// - `&str` - Incoming request path.
/// - `&str` - Normalized path prefix.
///
/// # Returns
///
/// - `bool` - `true` when matched.
#[inline]
pub(crate) fn path_matches_prefix(path: &str, prefix: &str) -> bool {
    if prefix == ROOT_SLASH {
        return true;
    }
    if let Some(rest) = path.strip_prefix(prefix) {
        rest.is_empty() || rest.starts_with('/')
    } else {
        false
    }
}