encore-dev 2.0.0-beta.9

Rust SDK for Encore applications
Documentation
use encore_sdk_core::telemetry::metrics::{Data, Metric, NumberValue, Point, ScopeMetrics};
use encore_sdk_core::telemetry::testing::CumulativeCollector;

use super::*;

/// The meter provider metrics record through, one for every test.
pub(super) fn provider() -> &'static CoreMeterProvider {
    static PROVIDER: OnceLock<CoreMeterProvider> = OnceLock::new();
    PROVIDER.get_or_init(CoreMeterProvider::new)
}

/// Collects every meter's metrics as a cumulative destination is sent
/// them, so a test sees what it recorded whichever test collected first.
/// One collection at a time, as the provider's collection loop makes them:
/// observable instruments' readings are taken by the collection that made
/// them.
fn collect() -> Vec<ScopeMetrics> {
    static CUMULATIVE: OnceLock<std::sync::Mutex<CumulativeCollector>> = OnceLock::new();
    let collector = CUMULATIVE.get_or_init(Default::default);
    let mut collector = collector.lock().unwrap_or_else(|e| e.into_inner());
    collector.collect(provider())
}

/// The metric `name` of the meter `scope`, as collected.
fn collected(scope: &str, name: &str) -> Metric {
    collect()
        .into_iter()
        .filter(|s| s.scope.name() == scope)
        .flat_map(|s| s.metrics)
        .find(|m| m.name == name)
        .unwrap_or_else(|| panic!("{scope} has no {name}"))
}

/// A sum's or gauge's points, by their attributes.
fn numbers(metric: &Metric) -> Vec<(Vec<KeyValue>, NumberValue)> {
    let points: &[Point<NumberValue>] = match &metric.data {
        Data::Sum { points, .. } | Data::Gauge { points } => points,
        other => panic!("{}: not a sum or gauge: {other:?}", metric.name),
    };
    let mut found: Vec<_> = points
        .iter()
        .map(|p| (p.attributes.clone(), p.value))
        .collect();
    found.sort_by(|a, b| format!("{:?}", a.0).cmp(&format!("{:?}", b.0)));
    found
}

fn monotonic(metric: &Metric) -> bool {
    match &metric.data {
        Data::Sum { monotonic, .. } => *monotonic,
        other => panic!("{}: not a sum: {other:?}", metric.name),
    }
}

#[derive(Labels)]
struct Outcome<'a> {
    method: &'static str,
    status: u16,
    cached: bool,
    r#type: &'a str,
}

const OK: Outcome<'static> = Outcome {
    method: "GET",
    status: 200,
    cached: false,
    r#type: "page",
};

fn ok() -> Vec<KeyValue> {
    OK.attributes()
}

#[test]
fn labels_are_a_structs_fields() {
    assert_eq!(
        OK.attributes(),
        [
            KeyValue::new("method", "GET"),
            KeyValue::new("status", 200),
            KeyValue::new("cached", false),
            KeyValue::new("type", "page"),
        ]
    );
}

/// A service's own metric is exported as `<service>.<name>`.
#[test]
fn a_metric_is_an_instrument_of_the_encore_meter() {
    provider();
    /// Not the description: only the parser reads doc comments.
    static ORDERS: Counter = Counter::new("test_orders")
        .unit("{order}")
        .description("Orders placed.");

    ORDERS.increment();
    ORDERS.add(4);

    let scope = collect()
        .into_iter()
        .find(|s| s.metrics.iter().any(|m| m.name == "svc.test_orders"))
        .expect("collected")
        .scope;
    assert_eq!(scope.name(), "encore");
    assert_eq!(scope.version(), Some(env!("CARGO_PKG_VERSION")));

    let orders = collected("encore", "svc.test_orders");
    assert_eq!(orders.unit, "{order}");
    assert_eq!(orders.description, "Orders placed.");
    assert!(monotonic(&orders));
    assert_eq!(numbers(&orders), [(vec![], NumberValue::U64(5))]);
}

#[test]
fn each_kind_records_its_own_way() {
    provider();
    static SPENT: Counter<f64> = Counter::new("test_spent");
    static QUEUED: UpDownCounter = UpDownCounter::new("test_queued");
    static LOAD: Gauge = Gauge::new("test_load");
    static FREE: Gauge<u64> = Gauge::new("test_free");
    static LATENCY: Histogram = Histogram::new("test_latency")
        .unit("s")
        .buckets(&[0.1, 1.0]);

    SPENT.add(1.5);
    SPENT.increment();
    // A counter does not go down.
    SPENT.add(-10.0);
    QUEUED.add(3);
    QUEUED.decrement();
    LOAD.set(0.5);
    LOAD.set(0.75);
    FREE.set(7);
    for value in [0.05, 0.5, 0.7, 3.0] {
        LATENCY.record(value);
    }

    let spent = collected("encore", "svc.test_spent");
    assert!(monotonic(&spent));
    assert_eq!(numbers(&spent), [(vec![], NumberValue::F64(2.5))]);
    let queued = collected("encore", "svc.test_queued");
    assert!(!monotonic(&queued));
    assert_eq!(numbers(&queued), [(vec![], NumberValue::I64(2))]);
    let load = collected("encore", "svc.test_load");
    assert!(matches!(load.data, Data::Gauge { .. }));
    assert_eq!(numbers(&load), [(vec![], NumberValue::F64(0.75))]);
    assert_eq!(
        numbers(&collected("encore", "svc.test_free")),
        [(vec![], NumberValue::U64(7))]
    );

    let latency = collected("encore", "svc.test_latency");
    assert_eq!(latency.unit, "s");
    let Data::Histogram { points, .. } = &latency.data else {
        panic!("not a histogram: {latency:?}");
    };
    let [point] = &points[..] else {
        panic!("one point: {points:?}");
    };
    assert_eq!(&*point.value.boundaries, [0.1, 1.0]);
    assert_eq!(point.value.counts, [1, 2, 1]);
    assert_eq!(point.value.count, 4);
}

#[test]
fn a_group_records_its_labels_as_attributes() {
    provider();
    static REQUESTS: CounterGroup<Outcome<'static>> = CounterGroup::new("test_requests");
    static OPEN: GaugeGroup<Outcome<'static>, f64> = GaugeGroup::new("test_open");
    static SIZES: HistogramGroup<Outcome<'static>> =
        HistogramGroup::new("test_sizes").buckets(&[10.0]);

    let failed = Outcome { status: 500, ..OK };
    REQUESTS.with(&OK).increment();
    REQUESTS.with(&failed).add(5);
    // One that is kept records to the same series.
    let ok_requests = REQUESTS.with(&OK);
    ok_requests.increment();
    OPEN.with(&OK).set(1.5);
    SIZES.with(&OK).record(512.0);

    let failed = failed.attributes();
    assert_eq!(
        numbers(&collected("encore", "svc.test_requests")),
        [(ok(), NumberValue::U64(2)), (failed, NumberValue::U64(5))]
    );
    assert_eq!(
        numbers(&collected("encore", "svc.test_open")),
        [(ok(), NumberValue::F64(1.5))]
    );
    let sizes = collected("encore", "svc.test_sizes");
    let Data::Histogram { points, .. } = &sizes.data else {
        panic!("not a histogram: {sizes:?}");
    };
    assert_eq!(points[0].attributes, ok());
    assert_eq!(points[0].value.counts, [0, 1]);
}

#[test]
fn every_scope_has_every_kind_of_metric() {
    provider();
    static SIGNUPS: Counter = Counter::new("test_shared_signups").shared();
    static BY_OUTCOME: CounterGroup<Outcome<'static>, f64> =
        CounterGroup::new("test_shared_by_outcome").shared();
    static IN_FLIGHT: UpDownCounterGroup<Outcome<'static>> =
        UpDownCounterGroup::new("test_global_in_flight").global();
    static LOAD: Gauge<f64> = Gauge::new("test_global_load").global();
    // The scope is an option like any other, chained in any order.
    static LATENCY: Histogram = Histogram::new("test_shared_latency")
        .unit("s")
        .shared()
        .buckets(&[1.0]);

    SIGNUPS.increment();
    // A group's metric is of the group's scope.
    let by_outcome: Counter<f64> = BY_OUTCOME.with(&OK);
    by_outcome.add(1.5);
    let in_flight: UpDownCounter = IN_FLIGHT.with(&OK);
    in_flight.increment();
    LOAD.set(0.75);
    LATENCY.record(0.25);

    // A metric is handed to other code as itself.
    fn record(requests: &CounterGroup<Outcome<'static>, f64>) {
        requests.with(&OK).add(0.5);
    }
    record(BY_OUTCOME.reference());
    let signups: &'static Counter = SIGNUPS.reference();
    signups.increment();

    // Never prefixed with the service's name.
    assert_eq!(
        numbers(&collected("encore", "test_shared_signups")),
        [(vec![], NumberValue::U64(2))]
    );
    assert_eq!(
        numbers(&collected("encore", "test_shared_by_outcome")),
        [(ok(), NumberValue::F64(2.0))]
    );
    assert_eq!(
        numbers(&collected("encore", "test_global_in_flight")),
        [(ok(), NumberValue::I64(1))]
    );
    assert_eq!(
        numbers(&collected("encore", "test_global_load")),
        [(vec![], NumberValue::F64(0.75))]
    );
    assert_eq!(collected("encore", "test_shared_latency").unit, "s");
}

#[test]
fn a_named_metric_takes_its_declarations_unit_and_buckets() {
    use encore_sdk_core::telemetry::metrics::Declared;
    provider().declare([(
        "test_named_latency".to_string(),
        Declared {
            unit: "s".into(),
            description: String::new(),
            boundaries: Some(vec![1.0]),
        },
    )]);
    static LATENCY: Histogram = Histogram::named("test_named_latency");
    LATENCY.record(0.5);

    // Never prefixed with the service's name.
    let metric = collected("encore", "test_named_latency");
    assert_eq!(metric.unit, "s");
    let Data::Histogram { points, .. } = &metric.data else {
        panic!("not a histogram: {:?}", metric.data);
    };
    assert_eq!(points[0].value.counts, [1, 0]);
}

#[test]
fn the_otel_api_records_alongside() {
    let meter = meter_provider().meter("app");
    let counter = meter.u64_counter("test_direct").with_unit("{call}").build();
    counter.add(2, &[KeyValue::new("route", "/users/:id")]);

    let direct = collected("app", "test_direct");
    assert_eq!(direct.unit, "{call}");
    assert_eq!(
        numbers(&direct),
        [(
            vec![KeyValue::new("route", "/users/:id")],
            NumberValue::U64(2)
        )]
    );
}

#[test]
fn without_a_metrics_provider_nothing_is_aggregated() {
    let provider = MeterProvider::of(None);
    assert!(!provider.aggregates());
    provider.meter("app").u64_counter("c").build().add(1, &[]);
}

#[test]
fn a_static_str_label_is_not_copied() {
    let attributes = OK.attributes();
    let Value::String(method) = &attributes[0].value else {
        panic!("method: {:?}", attributes[0].value);
    };
    assert_eq!(method.as_ref().as_ptr(), OK.method.as_ptr());
}