hyperlane-plugin-idempotency 22.14.0

A production HTTP Idempotency-Key middleware plugin for the Hyperlane framework featuring XxHash3_64 request fingerprinting (422 mismatch), 64-way sharded bounded InMemoryIdempotencyStore + async IdempotencyStore trait, InFlight concurrent duplicate guard (409 Conflict), and zero-copy cached response replay with Idempotent-Replayed headers.
Documentation
use super::*;

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

/// Computes the 64-way shard index for `key` using `XxHash3_64`.
///
/// # Arguments
///
/// - `&str` - Scoped idempotency key.
///
/// # Returns
///
/// - `usize` - Shard index in `0..IDEMPOTENCY_SHARD_COUNT`.
#[inline]
pub(crate) fn idempotency_shard_index(key: &str) -> usize {
    let mut hasher: XxHash3_64 = XxHash3_64::default();
    hasher.write(key.as_bytes());
    (hasher.finish() as usize) & (IDEMPOTENCY_SHARD_COUNT - 1)
}

/// Computes a zero-allocation `XxHash3_64` fingerprint over `(method, path, body)`.
///
/// # Arguments
///
/// - `&Method` - HTTP request method.
/// - `&str` - Request path.
/// - `&[u8]` - Raw request body bytes.
///
/// # Returns
///
/// - `u64` - Deterministic 64-bit request payload fingerprint.
#[inline]
pub fn compute_request_fingerprint(method: &Method, path: &str, body: &[u8]) -> u64 {
    let mut hasher: XxHash3_64 = XxHash3_64::default();
    let method_tag: u8 = match method {
        Method::Get => 1,
        Method::Post => 2,
        Method::Put => 3,
        Method::Delete => 4,
        Method::Patch => 5,
        Method::Head => 6,
        Method::Options => 7,
        Method::Connect => 8,
        Method::Trace => 9,
        Method::Unknown(_) => 10,
    };
    hasher.write(&[method_tag]);
    if let Method::Unknown(raw) = method {
        hasher.write(raw.as_bytes());
    }
    hasher.write(FINGERPRINT_SEPARATOR);
    hasher.write(path.as_bytes());
    hasher.write(FINGERPRINT_SEPARATOR);
    hasher.write(body);
    hasher.finish()
}

/// Builds a scoped storage key combining HTTP method, request path, and client `Idempotency-Key`.
///
/// # Arguments
///
/// - `&Method` - HTTP request method.
/// - `&str` - Request path.
/// - `&str` - Trimmed client `Idempotency-Key`.
///
/// # Returns
///
/// - `String` - Scoped storage key isolating identical client keys across distinct endpoints.
pub(crate) fn build_storage_key(method: &Method, path: &str, client_key: &str) -> String {
    let method_str: String = method.to_string();
    let mut out: String =
        String::with_capacity(method_str.len() + path.len() + client_key.len() + 2);
    out.push_str(&method_str);
    out.push('|');
    out.push_str(path);
    out.push('|');
    out.push_str(client_key);
    out
}

/// Looks up a header value without cloning using an `O(1)` lowercase fast path.
///
/// # Arguments
///
/// - `&'a RequestHeaders` - Request header map.
/// - `&str` - Canonical lowercase header name.
///
/// # Returns
///
/// - `Option<&'a str>` - Last header value slice if present.
#[inline]
pub(crate) fn find_header_back_ref<'a>(
    headers: &'a RequestHeaders,
    lower_name: &str,
) -> Option<&'a str> {
    if let Some(vals) = headers.get(lower_name) {
        return vals.back().map(String::as_str);
    }
    headers
        .iter()
        .find(|(k, _): &(&String, &VecDeque<String>)| k.eq_ignore_ascii_case(lower_name))
        .and_then(|(_, v): (&String, &VecDeque<String>)| v.back().map(String::as_str))
}

/// Validates a client `Idempotency-Key` header value for non-emptiness, length cap, and absence of control bytes.
///
/// # Arguments
///
/// - `&str` - Trimmed header value.
/// - `usize` - Maximum allowed byte length.
///
/// # Returns
///
/// - `bool` - `true` when valid.
#[inline]
pub(crate) fn is_valid_idempotency_key(key: &str, max_len: usize) -> bool {
    !key.is_empty() && key.len() <= max_len && key.bytes().all(|b: u8| b >= 0x20 && b != 0x7F)
}

/// Normalizes a path prefix by stripping trailing slashes while preserving `"/"`.
///
/// # Arguments
///
/// - `&str` - Raw prefix string.
///
/// # Returns
///
/// - `String` - Normalized prefix.
pub(crate) fn normalize_prefix(prefix: &str) -> String {
    let trimmed: &str = prefix.trim();
    if trimmed == "/" {
        return "/".to_owned();
    }
    let stripped: &str = trimmed.trim_end_matches('/');
    if stripped.is_empty() {
        "/".to_owned()
    } else {
        stripped.to_owned()
    }
}

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

/// Estimates heap byte usage of one completed [`StoredIdempotentResponse`] plus its storage key.
///
/// # Arguments
///
/// - `&str` - Scoped storage key.
/// - `&StoredIdempotentResponse` - Cached response payload and wire buffer.
///
/// # Returns
///
/// - `usize` - Estimated memory footprint in bytes.
pub(crate) fn estimate_response_bytes(key: &str, resp: &StoredIdempotentResponse) -> usize {
    let header_bytes: usize = resp
        .get_headers()
        .iter()
        .map(|(k, v): &(String, String)| k.len() + v.len())
        .sum();
    key.len()
        + header_bytes
        + resp.get_body().len()
        + resp.get_replayed_wire().len()
        + ENTRY_OVERHEAD_BYTES
}

/// Prebuilds an error HTTP wire response buffer (`400`/`409`/`422`).
///
/// # Arguments
///
/// - `HttpStatus` - HTTP error status.
/// - `&[u8]` - Static plain-text body bytes.
/// - `Option<&str>` - Optional `Retry-After` header value.
///
/// # Returns
///
/// - `ResponseData` - Pre-serialized HTTP wire bytes.
pub(crate) fn build_static_error_wire(
    status: HttpStatus,
    body: &[u8],
    retry_after: Option<&str>,
) -> ResponseData {
    let mut resp: Response = Response::default();
    resp.set_status_code(status.code())
        .set_header(CONTENT_TYPE, ERROR_CONTENT_TYPE)
        .set_body(body);
    if let Some(retry) = retry_after {
        resp.set_header(RETRY_AFTER, retry);
    }
    resp.build()
}