use parking_lot::Mutex;
use prometheus::{
Counter, CounterVec, Encoder, GaugeVec, HistogramVec, TextEncoder, register_counter_vec,
register_gauge_vec, register_histogram_vec,
};
use std::collections::HashMap;
use std::sync::LazyLock;
pub static REQUESTS_TOTAL: LazyLock<CounterVec> = LazyLock::new(|| {
register_counter_vec!(
"rift_requests_total",
"Total number of requests processed by the proxy",
&["method", "status"]
)
.unwrap()
});
pub static ACCEPTED_CONNECTIONS_TOTAL: LazyLock<CounterVec> = LazyLock::new(|| {
register_counter_vec!(
"rift_accepted_connections_total",
"Connections accepted, labeled by accept-loop worker slot (RFC-712 skew observability)",
&["worker"]
)
.unwrap()
});
pub static ACCEPT_ERRORS_TOTAL: LazyLock<CounterVec> = LazyLock::new(|| {
register_counter_vec!(
"rift_accept_errors_total",
"Accept errors by listener and class",
&["listener", "class"]
)
.expect("metric can be created")
});
pub static PREFACE_FAILURES_TOTAL: LazyLock<CounterVec> = LazyLock::new(|| {
register_counter_vec!(
"rift_preface_failures_total",
"Connections dropped before an HTTP/1-or-HTTP/2 decision, by listener and cause",
&["listener", "kind"]
)
.expect("metric can be created")
});
pub static BLOCKED_CONNECTIONS_TOTAL: LazyLock<CounterVec> = LazyLock::new(|| {
register_counter_vec!(
"rift_blocked_connections_total",
"Connections refused at accept because the client is not loopback (--local-only)",
&["listener"]
)
.expect("metric can be created")
});
pub static ACCEPT_ERROR_OUTAGE: LazyLock<GaugeVec> = LazyLock::new(|| {
register_gauge_vec!(
"rift_accept_error_outage",
"1 while a listener is in a systemic accept-error outage, 0 otherwise",
&["listener"]
)
.expect("metric can be created")
});
pub static FAULTS_INJECTED_TOTAL: LazyLock<CounterVec> = LazyLock::new(|| {
register_counter_vec!(
"rift_faults_injected_total",
"Total number of faults injected",
&["type", "rule_id", "source"] )
.unwrap()
});
pub static LATENCY_INJECTED_MS: LazyLock<HistogramVec> = LazyLock::new(|| {
register_histogram_vec!(
"rift_latency_injected_ms",
"Histogram of injected latency in milliseconds",
&["rule_id"],
vec![
10.0, 50.0, 100.0, 250.0, 500.0, 1000.0, 2500.0, 5000.0, 10000.0
]
)
.unwrap()
});
pub static ERROR_STATUS_TOTAL: LazyLock<CounterVec> = LazyLock::new(|| {
register_counter_vec!(
"rift_error_status_total",
"Count of error status codes injected",
&["status", "rule_id"]
)
.unwrap()
});
pub static SCRIPT_EXECUTION_DURATION_MS: LazyLock<HistogramVec> = LazyLock::new(|| {
register_histogram_vec!(
"rift_script_execution_duration_ms",
"Histogram of script execution time in milliseconds",
&["rule_id", "result"], vec![0.1, 0.5, 1.0, 2.5, 5.0, 10.0, 25.0, 50.0, 100.0]
)
.unwrap()
});
pub static FLOW_STATE_OPS_TOTAL: LazyLock<CounterVec> = LazyLock::new(|| {
register_counter_vec!(
"rift_flow_state_ops_total",
"Total number of flow state operations",
&["operation", "result"] )
.unwrap()
});
pub static UPSTREAM_REQUEST_DURATION_MS: LazyLock<HistogramVec> = LazyLock::new(|| {
register_histogram_vec!(
"rift_upstream_request_duration_ms",
"Duration of upstream requests (excluding fault injection)",
&["method", "status"]
)
.unwrap()
});
pub static SCRIPT_ERRORS_TOTAL: LazyLock<CounterVec> = LazyLock::new(|| {
register_counter_vec!(
"rift_script_errors_total",
"Total number of script execution errors",
&["rule_id", "error_type"] )
.unwrap()
});
pub static WASM_TRAPS_TOTAL: LazyLock<CounterVec> = LazyLock::new(|| {
register_counter_vec!(
"rift_wasm_traps_total",
"Total number of wasm script calls that trapped or returned a guest error",
&["kind"] )
.expect("rift_wasm_traps_total registers once")
});
pub static WASM_INSTANCES: LazyLock<prometheus::IntGauge> = LazyLock::new(|| {
prometheus::register_int_gauge!(
"rift_wasm_instances",
"Number of instance: \"imposter\" wasm instances alive"
)
.expect("rift_wasm_instances registers once")
});
pub static WASM_INSTANCE_DROPS_TOTAL: LazyLock<CounterVec> = LazyLock::new(|| {
register_counter_vec!(
"rift_wasm_instance_drops_total",
"Total number of instance: \"imposter\" wasm instances dropped",
&["reason"] )
.expect("rift_wasm_instance_drops_total registers once")
});
pub fn collect_metrics() -> String {
let encoder = TextEncoder::new();
let metric_families = prometheus::gather();
let mut buffer = Vec::new();
encoder.encode(&metric_families, &mut buffer).unwrap();
String::from_utf8(buffer).unwrap()
}
pub fn record_request(method: &str, status: u16) {
REQUESTS_TOTAL
.with_label_values(&[method, &status.to_string()])
.inc();
}
pub fn record_fault_injection(fault_type: &str, rule_id: &str, source: &str) {
FAULTS_INJECTED_TOTAL
.with_label_values(&[fault_type, rule_id, source])
.inc();
}
pub fn record_latency_injection(rule_id: &str, duration_ms: u64, source: &str) {
LATENCY_INJECTED_MS
.with_label_values(&[rule_id])
.observe(duration_ms as f64);
record_fault_injection("latency", rule_id, source);
}
pub fn record_error_injection(rule_id: &str, status: u16, source: &str) {
ERROR_STATUS_TOTAL
.with_label_values(&[&status.to_string(), rule_id])
.inc();
record_fault_injection("error", rule_id, source);
}
pub fn record_script_execution(rule_id: &str, duration_ms: f64, result: &str) {
SCRIPT_EXECUTION_DURATION_MS
.with_label_values(&[rule_id, result])
.observe(duration_ms);
}
pub fn record_script_fault(fault_type: &str, rule_id: &str, duration_ms: Option<u64>) {
match (fault_type, duration_ms) {
("latency", Some(ms)) => record_latency_injection(rule_id, ms, "script"),
_ => record_fault_injection(fault_type, rule_id, "script"),
}
}
pub fn record_flow_state_op(operation: &str, success: bool) {
let result = if success { "success" } else { "error" };
FLOW_STATE_OPS_TOTAL
.with_label_values(&[operation, result])
.inc();
}
static ACCEPT_OUTAGE_DEPTH: LazyLock<Mutex<HashMap<&'static str, usize>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
#[derive(Debug)]
pub struct AcceptOutageGuard {
listener: &'static str,
in_outage: bool,
}
impl AcceptOutageGuard {
#[must_use]
pub fn new(listener: &'static str) -> Self {
Self::adjust(listener, 0);
Self {
listener,
in_outage: false,
}
}
pub fn enter(&mut self) {
if !self.in_outage {
self.in_outage = true;
Self::adjust(self.listener, 1);
}
}
pub fn exit(&mut self) {
if self.in_outage {
self.in_outage = false;
Self::adjust(self.listener, -1);
}
}
fn adjust(listener: &'static str, delta: isize) {
let mut depth = ACCEPT_OUTAGE_DEPTH.lock();
let entry = depth.entry(listener).or_insert(0);
*entry = entry.saturating_add_signed(delta);
let any = *entry > 0;
ACCEPT_ERROR_OUTAGE
.with_label_values(&[listener])
.set(if any { 1.0 } else { 0.0 });
}
}
impl Drop for AcceptOutageGuard {
fn drop(&mut self) {
self.exit();
}
}
#[derive(Debug, Clone)]
pub struct AcceptErrorCounters {
transient: Counter,
systemic: Counter,
}
impl AcceptErrorCounters {
#[must_use]
pub fn new(listener: &'static str) -> Self {
Self {
transient: ACCEPT_ERRORS_TOTAL.with_label_values(&[listener, "transient"]),
systemic: ACCEPT_ERRORS_TOTAL.with_label_values(&[listener, "systemic"]),
}
}
pub fn record_transient(&self) {
self.transient.inc();
}
pub fn record_systemic(&self) {
self.systemic.inc();
}
}
#[derive(Debug)]
pub struct PeerCheck {
policy: crate::proxy::PeerPolicy,
listener: &'static str,
port: u16,
blocked: Option<Counter>,
warned: bool,
}
impl PeerCheck {
#[must_use]
pub fn new(policy: crate::proxy::PeerPolicy, listener: &'static str, port: u16) -> Self {
let blocked = (policy != crate::proxy::PeerPolicy::Any)
.then(|| BLOCKED_CONNECTIONS_TOTAL.with_label_values(&[listener]));
Self {
policy,
listener,
port,
blocked,
warned: false,
}
}
pub fn admits(&mut self, peer: std::net::SocketAddr) -> bool {
if self.policy.admits(peer.ip()) {
return true;
}
if let Some(blocked) = &self.blocked {
blocked.inc();
}
let (listener, port) = (self.listener, self.port);
if self.warned {
tracing::debug!(listener, port, %peer, "refused a non-loopback client (--local-only)");
} else {
self.warned = true;
tracing::warn!(
listener,
port,
%peer,
"refusing non-loopback client {peer} on {listener} port {port}: --local-only \
(logged once per listener; further refusals log at debug)"
);
}
false
}
}
const PREFACE_FAILURE_KINDS: [&str; 3] = ["timeout", "eof", "io"];
fn preface_failure_kind(err: &crate::proxy::preface::PrefaceError) -> &'static str {
use crate::proxy::preface::PrefaceError;
match err {
PrefaceError::Timeout(_) => "timeout",
PrefaceError::Eof => "eof",
PrefaceError::Io(_) => "io",
}
}
pub fn record_preface_failure(listener: &'static str, err: &crate::proxy::preface::PrefaceError) {
PREFACE_FAILURES_TOTAL
.with_label_values(&[listener, preface_failure_kind(err)])
.inc();
}
pub fn materialize_preface_failure_counters(listener: &'static str) {
for kind in PREFACE_FAILURE_KINDS {
PREFACE_FAILURES_TOTAL.with_label_values(&[listener, kind]);
}
}
pub fn record_upstream_duration(method: &str, status: u16, duration_ms: f64) {
UPSTREAM_REQUEST_DURATION_MS
.with_label_values(&[method, &status.to_string()])
.observe(duration_ms);
}
pub fn record_script_error(rule_id: &str, error_type: &str) {
SCRIPT_ERRORS_TOTAL
.with_label_values(&[rule_id, error_type])
.inc();
}
#[cfg_attr(not(feature = "wasm"), allow(dead_code))]
pub(crate) fn wasm_instances_gauge(delta: i64) {
WASM_INSTANCES.add(delta);
}
#[cfg_attr(not(feature = "wasm"), allow(dead_code))]
pub(crate) fn record_wasm_instance_drop(reason: &str) {
WASM_INSTANCE_DROPS_TOTAL.with_label_values(&[reason]).inc();
}
#[cfg_attr(not(feature = "wasm"), allow(dead_code))]
pub(crate) fn record_wasm_trap(kind: &str) {
WASM_TRAPS_TOTAL.with_label_values(&[kind]).inc();
}
#[cfg(test)]
mod tests {
use super::*;
fn preface_count(listener: &str, kind: &str) -> f64 {
PREFACE_FAILURES_TOTAL
.with_label_values(&[listener, kind])
.get()
}
#[test]
fn preface_failures_are_counted_under_the_variant_that_caused_them() {
use crate::proxy::preface::PrefaceError;
use std::time::Duration;
let l = "test-variants";
let before = ["timeout", "eof", "io"].map(|k| preface_count(l, k));
record_preface_failure(l, &PrefaceError::Timeout(Duration::from_secs(1)));
record_preface_failure(l, &PrefaceError::Eof);
record_preface_failure(
l,
&PrefaceError::Io(std::io::Error::other("upstream read failed")),
);
for (i, kind) in ["timeout", "eof", "io"].iter().enumerate() {
assert_eq!(
preface_count(l, kind) - before[i],
1.0,
"one `{kind}` failure must land on the `{kind}` child and nowhere else"
);
}
}
#[test]
fn materializing_makes_all_three_kinds_present_at_zero() {
let l = "test-materialize";
materialize_preface_failure_counters(l);
let scrape = collect_metrics();
for kind in ["timeout", "eof", "io"] {
let series =
format!(r#"rift_preface_failures_total{{kind="{kind}",listener="{l}"}} 0"#);
assert!(
scrape.contains(&series),
"expected `{series}` at zero in the scrape;\n{scrape}"
);
}
}
#[test]
fn test_metrics_collection() {
record_request("GET", 200);
record_latency_injection("test-rule", 100, "rift");
let metrics = collect_metrics();
assert!(metrics.contains("rift_requests_total"));
assert!(metrics.contains("rift_faults_injected_total"));
assert!(metrics.contains("rift_latency_injected_ms"));
}
#[test]
fn test_script_metrics() {
record_script_execution("script-rule", 1.5, "inject");
record_script_fault("error", "script-rule", None);
record_script_error("bad-script", "runtime");
let metrics = collect_metrics();
assert!(metrics.contains("rift_script_execution_duration_ms"));
assert!(metrics.contains("rift_script_errors_total"));
}
#[test]
fn test_flow_state_metrics() {
record_flow_state_op("increment", true);
record_flow_state_op("get", false);
let metrics = collect_metrics();
assert!(metrics.contains("rift_flow_state_ops_total"));
}
#[test]
fn test_record_request_various_methods() {
record_request("GET", 200);
record_request("POST", 201);
record_request("PUT", 204);
record_request("DELETE", 200);
record_request("PATCH", 200);
let metrics = collect_metrics();
assert!(metrics.contains("rift_requests_total"));
}
#[test]
fn test_record_request_error_codes() {
record_request("GET", 400);
record_request("GET", 401);
record_request("GET", 403);
record_request("GET", 404);
record_request("GET", 500);
record_request("GET", 502);
record_request("GET", 503);
let metrics = collect_metrics();
assert!(metrics.contains("rift_requests_total"));
}
#[test]
fn test_record_fault_injection_types() {
record_fault_injection("latency", "rule-1", "v1");
record_fault_injection("error", "rule-2", "v1");
record_fault_injection("latency", "rule-3", "script");
record_fault_injection("error", "rule-4", "script");
let metrics = collect_metrics();
assert!(metrics.contains("rift_faults_injected_total"));
}
#[test]
fn test_record_latency_injection_various_durations() {
record_latency_injection("slow-rule", 5, "rift");
record_latency_injection("slow-rule", 50, "rift");
record_latency_injection("slow-rule", 100, "rift");
record_latency_injection("slow-rule", 500, "rift");
record_latency_injection("slow-rule", 1000, "rift");
record_latency_injection("slow-rule", 5000, "rift");
let metrics = collect_metrics();
assert!(metrics.contains("rift_latency_injected_ms"));
}
#[test]
fn test_record_error_injection_status_codes() {
record_error_injection("error-rule", 400, "rift");
record_error_injection("error-rule", 401, "rift");
record_error_injection("error-rule", 403, "rift");
record_error_injection("error-rule", 404, "rift");
record_error_injection("error-rule", 500, "rift");
record_error_injection("error-rule", 502, "rift");
record_error_injection("error-rule", 503, "rift");
let metrics = collect_metrics();
assert!(metrics.contains("rift_error_status_total"));
}
#[test]
fn test_record_script_execution_results() {
record_script_execution("script-1", 0.5, "inject");
record_script_execution("script-1", 1.0, "pass");
record_script_execution("script-1", 0.1, "error");
let metrics = collect_metrics();
assert!(metrics.contains("rift_script_execution_duration_ms"));
}
#[test]
fn test_record_script_fault_with_latency() {
record_script_fault("latency", "latency-rule", Some(500));
record_script_fault("latency", "latency-rule", Some(1000));
record_script_fault("error", "error-rule", None);
let metrics = collect_metrics();
assert!(metrics.contains("rift_faults_injected_total"));
}
#[test]
fn test_record_flow_state_ops_all_types() {
record_flow_state_op("get", true);
record_flow_state_op("get", false);
record_flow_state_op("set", true);
record_flow_state_op("set", false);
record_flow_state_op("increment", true);
record_flow_state_op("increment", false);
record_flow_state_op("exists", true);
record_flow_state_op("exists", false);
record_flow_state_op("delete", true);
record_flow_state_op("delete", false);
let metrics = collect_metrics();
assert!(metrics.contains("rift_flow_state_ops_total"));
}
#[test]
fn test_record_upstream_duration() {
record_upstream_duration("GET", 200, 15.5);
record_upstream_duration("POST", 201, 25.0);
record_upstream_duration("GET", 404, 5.0);
record_upstream_duration("GET", 500, 100.0);
let metrics = collect_metrics();
assert!(metrics.contains("rift_upstream_request_duration_ms"));
}
#[test]
fn test_record_script_error_types() {
record_script_error("bad-script", "syntax");
record_script_error("bad-script", "runtime");
record_script_error("bad-script", "flow_state");
record_script_error("bad-script", "timeout");
let metrics = collect_metrics();
assert!(metrics.contains("rift_script_errors_total"));
}
#[test]
fn test_accept_error_counters_record_by_listener_and_class() {
let counters = AcceptErrorCounters::new("test-counter");
counters.record_systemic();
counters.record_systemic();
counters.record_transient();
assert_eq!(
ACCEPT_ERRORS_TOTAL
.with_label_values(&["test-counter", "systemic"])
.get(),
2.0
);
assert_eq!(
ACCEPT_ERRORS_TOTAL
.with_label_values(&["test-counter", "transient"])
.get(),
1.0
);
let again = AcceptErrorCounters::new("test-counter");
again.record_transient();
assert_eq!(
ACCEPT_ERRORS_TOTAL
.with_label_values(&["test-counter", "transient"])
.get(),
2.0,
"re-resolving a label must return the same child, not a new counter"
);
let rendered = collect_metrics();
assert!(rendered.contains("rift_accept_errors_total"));
}
#[test]
fn test_accept_outage_gauge_tracks_depth_not_last_writer() {
let listener = "test-depth";
let mut a = AcceptOutageGuard::new(listener);
let mut b = AcceptOutageGuard::new(listener);
assert_eq!(
ACCEPT_ERROR_OUTAGE.with_label_values(&[listener]).get(),
0.0,
"the series exists at 0 before any outage, so alerts can reference it"
);
a.enter();
b.enter();
assert_eq!(
ACCEPT_ERROR_OUTAGE.with_label_values(&[listener]).get(),
1.0
);
let _late = AcceptOutageGuard::new(listener);
assert_eq!(
ACCEPT_ERROR_OUTAGE.with_label_values(&[listener]).get(),
1.0,
"constructing a guard must not zero a gauge another loop is holding up"
);
a.exit();
assert_eq!(
ACCEPT_ERROR_OUTAGE.with_label_values(&[listener]).get(),
1.0,
"one loop recovering must NOT clear the gauge while another is still wedged"
);
b.exit();
assert_eq!(
ACCEPT_ERROR_OUTAGE.with_label_values(&[listener]).get(),
0.0,
"the gauge clears only when the last wedged loop recovers"
);
}
#[test]
fn test_accept_outage_guard_clears_on_drop() {
let listener = "test-drop";
{
let mut g = AcceptOutageGuard::new(listener);
g.enter();
assert_eq!(
ACCEPT_ERROR_OUTAGE.with_label_values(&[listener]).get(),
1.0
);
}
assert_eq!(
ACCEPT_ERROR_OUTAGE.with_label_values(&[listener]).get(),
0.0,
"dropping a wedged loop must release its outage"
);
}
#[test]
fn test_collect_metrics_returns_string() {
record_request("GET", 200);
let metrics = collect_metrics();
assert!(!metrics.is_empty() || metrics.is_empty()); }
#[test]
fn test_collect_metrics_after_recording() {
record_request("POST", 201);
record_fault_injection("latency", "format-test", "v1");
let metrics = collect_metrics();
assert!(metrics.contains("rift_requests_total") || metrics.is_empty());
}
#[test]
fn test_multiple_rules_same_metric() {
record_latency_injection("rule-a", 100, "rift");
record_latency_injection("rule-b", 200, "rift");
record_latency_injection("rule-c", 300, "rift");
record_error_injection("rule-a", 500, "rift");
record_error_injection("rule-b", 503, "rift");
let metrics = collect_metrics();
assert!(metrics.contains("rift_latency_injected_ms"));
assert!(metrics.contains("rift_error_status_total"));
}
#[test]
fn test_high_precision_duration() {
record_script_execution("fast-script", 0.001, "pass");
record_script_execution("fast-script", 0.01, "pass");
record_script_execution("fast-script", 0.1, "pass");
let metrics = collect_metrics();
assert!(metrics.contains("rift_script_execution_duration_ms"));
}
#[test]
fn test_histogram_buckets_coverage() {
let durations = [
0.1, 0.5, 1.0, 2.5, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0, 500.0, 1000.0,
];
for (i, duration) in durations.iter().enumerate() {
record_script_execution(&format!("bucket-test-{i}"), *duration, "pass");
}
let metrics = collect_metrics();
assert!(metrics.contains("rift_script_execution_duration_ms"));
}
}