hyperlane-plugin-metrics 22.14.0

A lock-free atomic Prometheus/OpenMetrics observability plugin for the Hyperlane framework with built-in HTTP request counters, in-flight gauges, latency histograms, custom user metric registration, and a scrapeable /metrics endpoint.
Documentation
use super::*;

/// 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: &RequestHeadersValue| values.back())
        .map(String::as_str)
}

/// Appends an unsigned 64-bit integer to `out` using a stack buffer without `fmt::Arguments` overhead.
///
/// # Arguments
///
/// - `u64` - Unsigned integer to format.
/// - `&mut String` - Destination text buffer.
#[inline(always)]
pub(crate) fn push_u64(mut value: u64, out: &mut String) {
    let mut buf: [u8; INT_STACK_BUF_LEN] = [0u8; INT_STACK_BUF_LEN];
    let mut pos: usize = INT_STACK_BUF_LEN;
    if value == 0 {
        pos -= 1;
        buf[pos] = b'0';
    } else {
        while value > 0 {
            pos -= 1;
            buf[pos] = b'0' + (value % 10) as u8;
            value /= 10;
        }
    }
    if let Ok(text) = from_utf8(&buf[pos..]) {
        out.push_str(text);
    }
}

/// Appends a signed 64-bit integer to `out` using a stack buffer without `fmt::Arguments` overhead.
///
/// # Arguments
///
/// - `i64` - Signed integer to format.
/// - `&mut String` - Destination text buffer.
#[inline(always)]
pub(crate) fn push_i64(value: i64, out: &mut String) {
    if value < 0 {
        out.push('-');
    }
    push_u64(value.unsigned_abs(), out);
}

/// Compares two byte slices in constant time for optional bearer token authentication.
///
/// # Arguments
///
/// - `&[u8]` - First byte slice.
/// - `&[u8]` - Second byte slice.
///
/// # Returns
///
/// - `bool` - `true` iff both slices match identically.
#[inline]
pub(crate) fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut diff: u8 = 0;
    for i in 0..a.len() {
        diff |= a[i] ^ b[i];
    }
    diff == 0
}

/// Checks optional `Authorization: Bearer <token>` header against `expected_token`.
///
/// # Arguments
///
/// - `&Context` - Incoming request context.
/// - `Option<&str>` - Expected secret bearer token (`None` permits public scrape).
///
/// # Returns
///
/// - `bool` - `true` when access to `/metrics` is authorized.
#[inline]
pub(crate) fn is_scrape_authorized(ctx: &Context, expected_token: Option<&str>) -> bool {
    let Some(expected) = expected_token else {
        return true;
    };
    let Some(header) = request_header_back(ctx.get_request(), AUTHORIZATION) else {
        return false;
    };
    let trimmed: &str = header.trim();
    if trimmed.len() < PREFIX_BEARER.len() {
        return false;
    }
    let (scheme, token): (&str, &str) = trimmed.split_at(PREFIX_BEARER.len());
    scheme.eq_ignore_ascii_case(PREFIX_BEARER)
        && constant_time_eq(token.trim().as_bytes(), expected.as_bytes())
}

/// Atomically adds `delta` to an `f64` stored in `target` via IEEE-754 bit CAS loop.
///
/// # Arguments
///
/// - `&AtomicU64` - Atomic bit storage holding `f64::to_bits`.
/// - `f64` - Floating-point increment.
#[inline(always)]
pub(crate) fn atomic_f64_add(target: &AtomicU64, delta: f64) {
    let mut observed: u64 = target.load(Ordering::Relaxed);
    loop {
        let next: u64 = (f64::from_bits(observed) + delta).to_bits();
        match target.compare_exchange_weak(observed, next, Ordering::Relaxed, Ordering::Relaxed) {
            Ok(_) => break,
            Err(actual) => observed = actual,
        }
    }
}