hyperlane-plugin-metrics 23.4.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::*;

/// Lock-free monotonically increasing 64-bit counter metric.
#[derive(Debug, Default)]
pub struct Counter {
    /// Atomic counter value.
    pub(crate) value: AtomicU64,
}

/// Lock-free signed 64-bit gauge metric that may increment or decrement.
#[derive(Debug, Default)]
pub struct Gauge {
    /// Atomic gauge value.
    pub(crate) value: AtomicI64,
}

/// Lock-free fixed-bucket latency/size histogram metric.
#[derive(Debug)]
pub struct Histogram {
    /// Sorted finite upper bucket bounds.
    pub(crate) bounds: Box<[f64]>,
    /// Pre-formatted bound text slices matching `bounds` for fast Prometheus rendering.
    pub(crate) bound_labels: Box<[String]>,
    /// Per-bucket observation counts (`bounds.len() + 1` including `+Inf`).
    pub(crate) bucket_counts: Box<[AtomicU64]>,
    /// Total count of all observations.
    pub(crate) total_count: AtomicU64,
    /// IEEE-754 `f64::to_bits` cumulative sum of observed values.
    pub(crate) sum_bits: AtomicU64,
}

/// Registered custom counter entry with prebuilt Prometheus header text.
pub(crate) struct RegisteredCounter {
    /// Pre-formatted `# HELP ... # TYPE ... counter\n<name> ` prefix.
    pub(crate) prom_prefix: String,
    /// Lock-free atomic counter handle.
    pub(crate) metric: Arc<Counter>,
}

/// Registered custom gauge entry with prebuilt Prometheus header text.
pub(crate) struct RegisteredGauge {
    /// Pre-formatted `# HELP ... # TYPE ... gauge\n<name> ` prefix.
    pub(crate) prom_prefix: String,
    /// Lock-free atomic gauge handle.
    pub(crate) metric: Arc<Gauge>,
}

/// Registered custom histogram entry with pre-formatted Prometheus line prefixes.
pub(crate) struct RegisteredHistogram {
    /// Pre-formatted `# HELP ... # TYPE ... histogram\n` header.
    pub(crate) prom_header: String,
    /// Pre-formatted `<name>_bucket{le="<bound>"} ` prefix for each finite bucket.
    pub(crate) prom_bucket_prefixes: Box<[String]>,
    /// Pre-formatted `<name>_bucket{le="+Inf"} ` prefix.
    pub(crate) prom_inf_prefix: String,
    /// Pre-formatted `<name>_sum ` prefix.
    pub(crate) prom_sum_prefix: String,
    /// Pre-formatted `<name>_count ` prefix.
    pub(crate) prom_count_prefix: String,
    /// Lock-free atomic histogram handle.
    pub(crate) metric: Arc<Histogram>,
}

/// Configuration for [`MetricsPlugin`] and [`MetricsRequestHook`].
#[derive(Clone, Data, Debug, Eq, PartialEq)]
pub struct MetricsConfig {
    /// HTTP path serving Prometheus text format 0.0.4 (default `"/metrics"`).
    pub(crate) endpoint: String,
    /// Metric name prefix namespace (default `"hyperlane"`).
    pub(crate) namespace: String,
    /// Optional bearer token required to scrape the metrics endpoint.
    #[get(type(clone))]
    pub(crate) bearer_token: Option<String>,
}

/// Cache-line-aligned per-worker shard eliminating cross-core contention on built-in HTTP metrics.
#[repr(align(64))]
pub(crate) struct BuiltinMetricsShard {
    /// HTTP request counters partitioned by status class (`[1xx, 2xx, 3xx, 4xx, 5xx, other]`).
    pub(crate) status_class_counts: [AtomicU64; 6],
    /// Signed delta gauge tracking active in-flight HTTP requests on this shard.
    pub(crate) in_flight: AtomicI64,
    /// Cumulative HTTP response payload bytes recorded on this shard.
    pub(crate) response_bytes_total: AtomicU64,
    /// Per-bucket latency observation counts (`12` finite bounds plus `+Inf`).
    pub(crate) duration_buckets: [AtomicU64; 13],
    /// Total latency observations recorded on this shard.
    pub(crate) duration_count: AtomicU64,
    /// Cumulative observed latency in integer nanoseconds on this shard.
    pub(crate) duration_nanos_sum: AtomicU64,
}

/// Shared interior state of [`MetricsRegistry`].
pub(crate) struct MetricsRegistryInner {
    /// Precomputed byte capacity estimate covering all built-in Prometheus lines.
    pub(crate) builtin_est_bytes: usize,
    /// Pre-formatted `# HELP` + `# TYPE` header for built-in HTTP request counter.
    pub(crate) prom_req_header: String,
    /// Pre-formatted line prefixes for each of the 6 status class counters.
    pub(crate) prom_req_lines: [String; 6],
    /// Pre-formatted `# HELP` + `# TYPE` + metric prefix for in-flight gauge.
    pub(crate) prom_in_flight_prefix: String,
    /// Pre-formatted `# HELP` + `# TYPE` + metric prefix for response bytes counter.
    pub(crate) prom_resp_bytes_prefix: String,
    /// Pre-formatted `# HELP` + `# TYPE` header for built-in latency histogram.
    pub(crate) prom_dur_header: String,
    /// Pre-formatted bucket line prefixes for each built-in latency bucket.
    pub(crate) prom_dur_bucket_prefixes: Box<[String]>,
    /// Pre-formatted `+Inf` bucket line prefix for built-in latency histogram.
    pub(crate) prom_dur_inf_prefix: String,
    /// Pre-formatted `_sum ` prefix for built-in latency histogram.
    pub(crate) prom_dur_sum_prefix: String,
    /// Pre-formatted `_count ` prefix for built-in latency histogram.
    pub(crate) prom_dur_count_prefix: String,
    /// Cache-line-aligned per-worker built-in HTTP metric shards.
    pub(crate) builtin_shards: Box<[BuiltinMetricsShard; METRICS_SHARD_COUNT]>,
    /// Overflow IEEE-754 `f64::to_bits` latency sum for negative or ultra-large manual observations.
    pub(crate) duration_extra_sum_bits: AtomicU64,
    /// Lock-free count of registered custom counters (skips read lock when zero).
    pub(crate) custom_counter_count: AtomicUsize,
    /// Lock-free count of registered custom gauges (skips read lock when zero).
    pub(crate) custom_gauge_count: AtomicUsize,
    /// Lock-free count of registered custom histograms (skips read lock when zero).
    pub(crate) custom_histogram_count: AtomicUsize,
    /// Lock-free estimated output bytes for all registered custom metrics (eliminates reallocations).
    pub(crate) custom_est_bytes: AtomicUsize,
    /// Custom user-registered counters.
    pub(crate) custom_counters: RwLock<HashMapXxHash3_64<String, RegisteredCounter>>,
    /// Custom user-registered gauges.
    pub(crate) custom_gauges: RwLock<HashMapXxHash3_64<String, RegisteredGauge>>,
    /// Custom user-registered histograms.
    pub(crate) custom_histograms: RwLock<HashMapXxHash3_64<String, RegisteredHistogram>>,
}

/// Lock-free HTTP and custom application metrics registry with Prometheus 0.0.4 exposition.
#[derive(Clone)]
pub struct MetricsRegistry {
    /// Shared registry state.
    pub(crate) inner: Arc<MetricsRegistryInner>,
}

/// Process-wide [`MetricsPlugin`] singleton storing [`MetricsConfig`] and [`MetricsRegistry`].
#[derive(Clone)]
pub struct MetricsPlugin {
    /// Endpoint and scrape-auth configuration.
    pub(crate) config: MetricsConfig,
    /// Shared lock-free metrics registry.
    pub(crate) registry: MetricsRegistry,
}

/// Opt-in request middleware incrementing in-flight gauges and serving `/metrics` scrapes.
#[derive(Clone, Copy, Debug, Default)]
#[hyperlane::request_middleware(-115)]
pub struct MetricsRequestHook;

/// Opt-in response middleware recording status class, response bytes, and request duration.
#[derive(Clone, Copy, Debug, Default)]
#[hyperlane::response_middleware(95)]
pub struct MetricsResponseHook;