hyperlane-plugin-metrics 23.3.2

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

/// Formats an unsigned 64-bit integer followed by `'\n'` into the tail of `buf` using 4-digit chunks.
///
/// # Arguments
///
/// - `u64` - Unsigned integer to format.
/// - `&mut [u8; INT_STACK_BUF_LEN]` - Destination stack byte buffer.
///
/// # Returns
///
/// - `usize` - Start offset in `buf` of the formatted ASCII slice ending at `INT_STACK_BUF_LEN`.
#[inline(always)]
pub(crate) fn format_u64_nl_into(mut value: u64, buf: &mut [u8; INT_STACK_BUF_LEN]) -> usize {
    let mut pos: usize = INT_STACK_BUF_LEN - 1;
    buf[pos] = b'\n';
    while value >= 10_000 {
        let chunk: usize = (value % 10_000) as usize;
        value /= 10_000;
        let lo_pair: usize = (chunk % 100) * 2;
        let hi_pair: usize = (chunk / 100) * 2;
        pos -= 4;
        buf[pos] = PROM_DEC_DIGITS_LUT[hi_pair];
        buf[pos + 1] = PROM_DEC_DIGITS_LUT[hi_pair + 1];
        buf[pos + 2] = PROM_DEC_DIGITS_LUT[lo_pair];
        buf[pos + 3] = PROM_DEC_DIGITS_LUT[lo_pair + 1];
    }
    if value >= 100 {
        let pair: usize = ((value % 100) as usize) * 2;
        value /= 100;
        pos -= 2;
        buf[pos] = PROM_DEC_DIGITS_LUT[pair];
        buf[pos + 1] = PROM_DEC_DIGITS_LUT[pair + 1];
    }
    if value < 10 {
        pos -= 1;
        buf[pos] = ASCII_ZERO + (value as u8);
    } else {
        let pair: usize = (value as usize) * 2;
        pos -= 2;
        buf[pos] = PROM_DEC_DIGITS_LUT[pair];
        buf[pos + 1] = PROM_DEC_DIGITS_LUT[pair + 1];
    }
    pos
}

/// Appends an unsigned 64-bit integer followed by `'\n'` to `out` using LUT fast paths.
///
/// # Arguments
///
/// - `u64` - Unsigned integer to format.
/// - `&mut String` - Destination text buffer.
#[inline(always)]
pub(crate) fn push_u64_nl(value: u64, out: &mut String) {
    if value < 100 {
        out.push_str(PROM_DEC_0_99_NL[value as usize]);
        return;
    }
    let mut buf: [u8; INT_STACK_BUF_LEN] = [0u8; INT_STACK_BUF_LEN];
    let pos: usize = format_u64_nl_into(value, &mut buf);
    if let Ok(text) = from_utf8(&buf[pos..]) {
        out.push_str(text);
    }
}

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

/// Appends a floating-point sum followed by `'\n'` to `out`, fast-pathing exact zero.
///
/// # Arguments
///
/// - `f64` - Floating-point value to format.
/// - `&mut String` - Destination text buffer.
#[inline(always)]
pub(crate) fn push_f64_nl(value: f64, out: &mut String) {
    if value == 0.0 {
        out.push_str(PROM_DEC_0_99_NL[0]);
        return;
    }
    let _: fmt::Result = writeln!(out, "{value}");
}

/// 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,
        }
    }
}