//! Application metrics: counters, up-down counters, gauges, and histograms.
//!
//! Declare metrics as module-level `static`s and record measurements wherever
//! the relevant events occur. A metric's doc comment is used as its description:
//!
//! ```ignore
//! use encore::metrics::{Counter, Gauge, Histogram, UpDownCounter};
//!
//! /// Orders placed.
//! static ORDERS: Counter = Counter::new("orders_placed");
//!
//! /// Jobs waiting for a worker.
//! static QUEUED: UpDownCounter = UpDownCounter::new("jobs_queued").unit("{job}");
//!
//! /// Oven temperature.
//! static OVEN: Gauge = Gauge::new("oven_temperature").unit("Cel");
//!
//! /// Time taken to place an order.
//! static LATENCY: Histogram = Histogram::new("order_latency").unit("s");
//!
//! ORDERS.increment();
//! QUEUED.add(12);
//! OVEN.set(180.5);
//! LATENCY.record(started.elapsed().as_secs_f64());
//! ```
//!
//! Each metric is backed by an instrument from the
//! [OpenTelemetry Metrics API](crate::opentelemetry::metrics) under the
//! `encore.sdk` meter and is created on first use. Service-scoped metrics are
//! automatically prefixed with the service name when exported (for example,
//! `orders_placed` in service `shop` is exported as `shop.orders_placed`).
//!
//! You can also create custom OpenTelemetry instruments (including observable
//! instruments) using [`meter_provider`]; they are exported alongside Encore
//! metrics. Encore does not install a global meter provider:
//!
//! ```ignore
//! use encore::opentelemetry::metrics::MeterProvider as _;
//! let meter = encore::metrics::meter_provider().meter("my-app");
//! let requests = meter.u64_counter("requests").build();
//! requests.add(1, &[]);
//! ```
//!
//! | Metric | Purpose | Supported value types |
//! |---|---|---|
//! | [`Counter`] | Monotonically increasing total | `u64`, `f64` |
//! | [`UpDownCounter`] | Total that can increase or decrease | `i64`, `f64` |
//! | [`Gauge`] | Point-in-time measurement | `f64`, `i64`, `u64` |
//! | [`Histogram`] | Distribution of recorded values | `f64` |
//!
//! The first type listed for each metric is the default. Units follow the
//! [UCUM](https://ucum.org/ucum) convention (for example, `"s"`, `"By"`,
//! `"{request}"`). When a metric has no doc comment, you can provide a
//! description with `.description(...)`.
//!
//! # Scope
//!
//! A metric's declaration determines which services can record to it, just like
//! [secrets](crate::secrets#scope):
//!
//! - `Counter::new("requests")` (and `Gauge::new(...)`, etc.) belongs to the
//! declaring service, and only that service may record to it. Names are
//! unique per service: two services may each declare a `requests` counter,
//! exported as `<service>.requests`. Must be declared inside a service.
//! - `Counter::new("signups").shared()` is shared across services under a
//! single app-wide name. Every service that records to it is tracked as a
//! user.
//! - `Counter::new("requests").global()` is available app-wide to any code
//! (including shared libraries outside any service) without per-service
//! tracking.
//!
//! Metric groups support the same scopes (for example,
//! `CounterGroup::new("...").shared()`). Scope and option methods can be
//! chained in any order, and both the name and scope must be written directly
//! in the declaration so Encore can parse them statically.
//!
//! ```ignore
//! /// Users signed up across all services.
//! static SIGNUPS: Counter = Counter::new("signups").shared().unit("{user}");
//! ```
//!
//! Declare a shared or global metric once in the app (just like a
//! [shared secret](crate::secrets#scope)). Other code can record to it either
//! by importing the `static` or, from another crate or language, by binding it
//! with `named`:
//!
//! ```ignore
//! static SERVED: CounterGroup<Served> = CounterGroup::named("greetings.served");
//! ```
//!
//! A bound metric inherits the declaration's kind, labels, scope, unit,
//! description, and histogram buckets, and is exported under the exact name
//! given (never prefixed with a service name). To pass a metric to helper
//! functions, use [`reference()`](Counter::reference); calling `reference()`
//! counts as recording to the metric for static analysis.
//!
//! # Labels
//!
//! A plain metric ([`Counter`], [`Gauge`], etc.) records a single series. A
//! *group* ([`CounterGroup`], [`GaugeGroup`], etc.) records a separate series
//! for each combination of label values, defined as fields on a struct
//! deriving [`Labels`]:
//!
//! ```ignore
//! use encore::metrics::{CounterGroup, Labels};
//!
//! #[derive(Labels)]
//! struct Outcome {
//! method: &'static str,
//! status: u16,
//! }
//!
//! /// Requests handled, by method and status.
//! static REQUESTS: CounterGroup<Outcome> = CounterGroup::new("requests_handled");
//!
//! REQUESTS.with(&Outcome { method: "GET", status: 200 }).increment();
//! ```
//!
//! Each distinct label combination creates its own time series. Keep label
//! cardinality low (such as status codes or regions) and avoid unbounded values
//! like user IDs. For arbitrary attributes, use the OpenTelemetry API directly.
//!
//! # Histograms
//!
//! A [`Histogram`] aggregates measurements into buckets to measure
//! distributions such as median or p99 latency. Custom
//! [`buckets`](Histogram::buckets) are part of the metric definition and are
//! exported as declared.
//!
//! # Testing
//!
//! Under `encore test` (and whenever the runtime does not export metrics),
//! recording methods are no-ops.
use std::marker::PhantomData;
use std::sync::{Arc, OnceLock};
use crate::opentelemetry::metrics::{self as otel, Meter, MeterProvider as _};
use crate::opentelemetry::{InstrumentationScope, KeyValue, Value};
use encore_sdk_core::telemetry::MeterProvider as CoreMeterProvider;
use sealed::Declaration;
/// Derives [`Labels`] for a struct with named fields. Each field becomes a
/// metric label with the field's name and a value implementing [`LabelValue`].
pub use encore_macros::Labels;
/// OpenTelemetry [`MeterProvider`](otel::MeterProvider) backed by the Encore
/// runtime. Cheap to clone.
#[derive(Debug, Clone)]
pub struct MeterProvider(Option<CoreMeterProvider>);
impl otel::MeterProvider for MeterProvider {
fn meter_with_scope(&self, scope: InstrumentationScope) -> Meter {
match &self.0 {
Some(provider) => provider.meter_with_scope(scope),
None => Meter::new(Arc::new(NoInstruments)),
}
}
}
/// Makes instruments recording nothing.
struct NoInstruments;
impl otel::InstrumentProvider for NoInstruments {}
impl MeterProvider {
/// Over `provider`, the runtime's; for none, recording nothing.
fn of(provider: Option<&CoreMeterProvider>) -> Self {
MeterProvider(provider.cloned())
}
/// Whether measurements are aggregated.
#[cfg(test)]
fn aggregates(&self) -> bool {
self.0.is_some()
}
}
/// Returns Encore's OpenTelemetry [`MeterProvider`], or a no-op provider when
/// the runtime does not export metrics.
pub fn meter_provider() -> MeterProvider {
MeterProvider::of(provider())
}
/// The meter every metric is an instrument of: `encore.sdk`, of this SDK's
/// version, from Encore's meter provider.
fn meter() -> Meter {
meter_provider().meter_with_scope(
InstrumentationScope::builder(encore_sdk_core::telemetry::scope::SDK)
.with_version(env!("CARGO_PKG_VERSION"))
.build(),
)
}
/// The runtime's meter provider; none when the runtime exports no metrics.
#[cfg(not(test))]
fn provider() -> Option<&'static CoreMeterProvider> {
crate::runtime::core().resources().meter_provider()
}
// This crate's own tests run without a runtime.
#[cfg(test)]
fn provider() -> Option<&'static CoreMeterProvider> {
Some(tests::provider())
}
/// The service this process hosts, if any.
#[cfg(not(test))]
fn hosted_service() -> Option<&'static str> {
crate::runtime::core()
.runtime_config()
.current_service
.as_deref()
}
// This crate's own tests host `svc`.
#[cfg(test)]
fn hosted_service() -> Option<&'static str> {
Some("svc")
}
/// What a metric's value types make its instruments with, and its
/// declaration: neither nameable outside this module.
mod sealed {
use std::borrow::Cow;
use super::{hosted_service, otel, Meter};
/// What a metric is declared with.
#[derive(Debug, Clone, Copy)]
pub struct Declaration {
pub(super) name: &'static str,
/// The declaring service's alone, exported as `<service>.<name>`.
pub(super) own: bool,
pub(super) unit: Option<&'static str>,
pub(super) description: Option<&'static str>,
pub(super) buckets: Option<&'static [f64]>,
}
impl Declaration {
pub(super) const fn new(name: &'static str, own: bool) -> Self {
Self {
name,
own,
unit: None,
description: None,
buckets: None,
}
}
/// The instrument name: a service's own metric's is
/// `<service>.<name>`, of the service this process hosts.
pub(super) fn exported_name(&self) -> Cow<'static, str> {
match hosted_service() {
Some(service) if self.own => format!("{service}.{}", self.name).into(),
_ => self.name.into(),
}
}
}
pub trait Counter: Sized {
const ONE: Self;
fn counter(meter: &Meter, declaration: &Declaration) -> otel::Counter<Self>;
}
pub trait UpDownCounter: Sized {
const ONE: Self;
fn up_down_counter(meter: &Meter, declaration: &Declaration) -> otel::UpDownCounter<Self>;
}
pub trait Gauge: Sized {
fn gauge(meter: &Meter, declaration: &Declaration) -> otel::Gauge<Self>;
}
pub trait Histogram: Sized {
fn histogram(meter: &Meter, declaration: &Declaration) -> otel::Histogram<Self>;
}
}
/// An instrument builder with a declaration's unit and description.
macro_rules! describe {
($builder:expr, $declaration:expr) => {{
let mut builder = $builder;
if let Some(unit) = $declaration.unit {
builder = builder.with_unit(unit);
}
if let Some(description) = $declaration.description {
builder = builder.with_description(description);
}
builder
}};
}
/// Numeric types supported by [`Counter`]: `u64` (default) and `f64`.
pub trait CounterValue: sealed::Counter + Copy + Send + Sync + 'static {}
/// Numeric types supported by [`UpDownCounter`]: `i64` (default) and `f64`.
pub trait UpDownCounterValue:
sealed::UpDownCounter + Copy + std::ops::Neg<Output = Self> + Send + Sync + 'static
{
}
/// Numeric types supported by [`Gauge`]: `f64` (default), `i64`, and `u64`.
pub trait GaugeValue: sealed::Gauge + Copy + Send + Sync + 'static {}
/// Numeric types supported by [`Histogram`]: `f64`.
pub trait HistogramValue: sealed::Histogram + Copy + Send + Sync + 'static {}
macro_rules! counter_value {
($ty:ty, $one:expr, $counter:ident) => {
impl CounterValue for $ty {}
impl sealed::Counter for $ty {
const ONE: Self = $one;
fn counter(meter: &Meter, declaration: &Declaration) -> otel::Counter<Self> {
describe!(meter.$counter(declaration.exported_name()), declaration).build()
}
}
};
}
counter_value!(u64, 1, u64_counter);
counter_value!(f64, 1.0, f64_counter);
macro_rules! up_down_counter_value {
($ty:ty, $one:expr, $counter:ident) => {
impl UpDownCounterValue for $ty {}
impl sealed::UpDownCounter for $ty {
const ONE: Self = $one;
fn up_down_counter(
meter: &Meter,
declaration: &Declaration,
) -> otel::UpDownCounter<Self> {
describe!(meter.$counter(declaration.exported_name()), declaration).build()
}
}
};
}
up_down_counter_value!(i64, 1, i64_up_down_counter);
up_down_counter_value!(f64, 1.0, f64_up_down_counter);
macro_rules! gauge_value {
($ty:ty, $gauge:ident) => {
impl GaugeValue for $ty {}
impl sealed::Gauge for $ty {
fn gauge(meter: &Meter, declaration: &Declaration) -> otel::Gauge<Self> {
describe!(meter.$gauge(declaration.exported_name()), declaration).build()
}
}
};
}
gauge_value!(f64, f64_gauge);
gauge_value!(i64, i64_gauge);
gauge_value!(u64, u64_gauge);
impl HistogramValue for f64 {}
impl sealed::Histogram for f64 {
fn histogram(meter: &Meter, declaration: &Declaration) -> otel::Histogram<Self> {
let mut builder = describe!(
meter.f64_histogram(declaration.exported_name()),
declaration
);
if let Some(buckets) = declaration.buckets {
builder = builder.with_boundaries(buckets.to_vec());
}
builder.build()
}
}
/// Label set for a metric group, typically derived on a struct with named
/// fields:
///
/// ```ignore
/// #[derive(Labels)]
/// struct Outcome {
/// method: &'static str,
/// status: u16,
/// }
/// ```
pub trait Labels {
/// Converts the label fields into OpenTelemetry key-value attributes.
fn attributes(&self) -> Vec<KeyValue>;
}
/// Value types that can be used as metric labels.
///
/// Implemented out of the box for strings, integers, `bool`, and `char`.
/// Implement this trait for custom enums to use them as labels:
///
/// ```ignore
/// enum Plan { Free, Paid }
///
/// impl LabelValue for Plan {
/// fn label_value(&self) -> Value {
/// match self {
/// Plan::Free => "free",
/// Plan::Paid => "paid",
/// }
/// .into()
/// }
/// }
/// ```
pub trait LabelValue {
/// Converts this value into an OpenTelemetry attribute [`Value`] (string,
/// integer, or `bool`).
fn label_value(&self) -> Value;
}
impl LabelValue for str {
fn label_value(&self) -> Value {
self.to_string().into()
}
}
impl LabelValue for String {
fn label_value(&self) -> Value {
self.clone().into()
}
}
impl LabelValue for std::borrow::Cow<'_, str> {
fn label_value(&self) -> Value {
self.to_string().into()
}
}
impl LabelValue for char {
fn label_value(&self) -> Value {
self.to_string().into()
}
}
impl LabelValue for bool {
fn label_value(&self) -> Value {
Value::Bool(*self)
}
}
macro_rules! integer_label_values {
($($ty:ty),*) => {$(
impl LabelValue for $ty {
/// Converts to an `i64` attribute value, clamping values above `i64::MAX`.
fn label_value(&self) -> Value {
Value::I64(i64::try_from(*self).unwrap_or(i64::MAX))
}
}
)*};
}
integer_label_values!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize);
impl<T: LabelValue + ?Sized> LabelValue for &T {
fn label_value(&self) -> Value {
(**self).label_value()
}
}
/// The options every metric is declared with.
macro_rules! options {
($what:literal) => {
#[doc = concat!("Declares the ", $what, " with shared app-wide scope rather than service scope. Any service may record to it, and each service that does is tracked as a user. See [scope](self#scope).")]
pub const fn shared(mut self) -> Self {
self.declaration.own = false;
self
}
#[doc = concat!("Declares the ", $what, " with global app-wide scope so any code (including shared libraries outside any service) may record to it without per-service tracking. See [scope](self#scope).")]
pub const fn global(mut self) -> Self {
self.declaration.own = false;
self
}
#[doc = concat!("Sets the exported unit of the ", $what, " (using UCUM notation such as `\"s\"`, `\"By\"`, or `\"{request}\"`).")]
pub const fn unit(mut self, unit: &'static str) -> Self {
self.declaration.unit = Some(unit);
self
}
#[doc = concat!("Sets the description of the ", $what, " when no doc comment is present.")]
pub const fn description(mut self, description: &'static str) -> Self {
self.declaration.description = Some(description);
self
}
#[doc = concat!("Attaches a key/value tag to the ", $what, " (for example, `.tag(\"data\", \"pii\")`) for policy and governance tooling. Call once per tag with unique keys. Both `key` and `value` must be string literals so Encore can parse them statically. Keys must start with a letter, contain only lowercase letters, digits, `_`, and `-`, and must not start with `encore` (reserved for Encore's own tags). Values use the same character set or may be empty. Each key and value is at most 63 characters, and a ", $what, " may have at most 32 tags.")]
///
/// Tags classify the metric declaration itself and are distinct from
/// recorded metric labels.
pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
self
}
};
}
/// The options a histogram is declared with, which a group's are too.
macro_rules! histogram_options {
() => {
/// Sets explicit increasing upper bucket boundaries.
///
/// Each recorded value is counted in the first bucket whose upper bound
/// is greater than or equal to the value (or in an overflow bucket if
/// larger than all bounds). If omitted, OpenTelemetry's default bucket
/// boundaries are used.
pub const fn buckets(mut self, bounds: &'static [f64]) -> Self {
self.declaration.buckets = Some(bounds);
self
}
};
}
/// A metric recorded to, its group, and their options.
macro_rules! recorded {
(
$(#[$doc:meta])* $name:ident,
$(#[$group_doc:meta])* $group:ident,
$what:literal,
$value:ident = $default:ty,
$instrument:ident :: $make:ident,
{ $($options:tt)* }
{ $($record:tt)* }
) => {
$(#[$doc])*
pub struct $name<N: $value = $default> {
declaration: Declaration,
attributes: Vec<KeyValue>,
instrument: OnceLock<otel::$instrument<N>>,
}
impl<N: $value> $name<N> {
#[doc = concat!("Declares a ", $what, " with the given `name`. Names must start with a letter and contain only letters, digits, `_`, `.`, `-`, and `/`. `name` must be a string literal so Encore can parse it statically.")]
pub const fn new(name: &'static str) -> Self {
Self {
declaration: Declaration::new(name, true),
attributes: Vec::new(),
instrument: OnceLock::new(),
}
}
options!($what);
$($options)*
#[doc = concat!("Returns a reference to this ", $what, " that can be passed to helper functions taking `&", stringify!($name), "`.")]
///
/// Calling `reference()` explicitly signals to Encore's static
/// analyzer that the calling service records to this metric.
pub fn reference(&self) -> &Self {
self
}
$($record)*
fn instrument(&self) -> &otel::$instrument<N> {
self.instrument
.get_or_init(|| N::$make(&meter(), &self.declaration))
}
}
$(#[$group_doc])*
pub struct $group<L: Labels, N: $value = $default> {
declaration: Declaration,
instrument: OnceLock<otel::$instrument<N>>,
_labels: PhantomData<fn(&L)>,
}
impl<L: Labels, N: $value> $group<L, N> {
#[doc = concat!("Declares a ", $what, " group with the given `name`. Names must start with a letter and contain only letters, digits, `_`, `.`, `-`, and `/`. `name` must be a string literal so Encore can parse it statically.")]
pub const fn new(name: &'static str) -> Self {
Self {
declaration: Declaration::new(name, true),
instrument: OnceLock::new(),
_labels: PhantomData,
}
}
options!($what);
$($options)*
#[doc = concat!("Returns a ", $what, " bound to the given `labels`. Cache the returned handle on hot paths to avoid recomputing label attributes on every recording.")]
pub fn with(&self, labels: &L) -> $name<N> {
let instrument = self
.instrument
.get_or_init(|| N::$make(&meter(), &self.declaration));
$name {
declaration: self.declaration,
attributes: labels.attributes(),
instrument: OnceLock::from(instrument.clone()),
}
}
#[doc = concat!("Returns a reference to this ", $what, " group that can be passed to helper functions taking `&", stringify!($group), "<L>`.")]
///
/// Calling `reference()` explicitly signals to Encore's static
/// analyzer that the calling service records to this metric group.
pub fn reference(&self) -> &Self {
self
}
}
named!($name, $group, $value, $what);
};
}
/// `named`, which every metric type and its group have: the bound metric's
/// scope is its declaration's.
macro_rules! named {
($name:ident, $group:ident, $value:ident, $what:literal) => {
impl<N: $value> $name<N> {
#[doc = concat!("Binds a shared or global ", $what, " named `name` that was declared elsewhere (for example, in another service or language). It inherits the declaration's kind, scope, unit, description, and buckets, and is exported as `name` without a service prefix. `name` must be a string literal so Encore can parse it statically.")]
pub const fn named(name: &'static str) -> Self {
Self {
declaration: Declaration::new(name, false),
attributes: Vec::new(),
instrument: OnceLock::new(),
}
}
}
impl<L: Labels, N: $value> $group<L, N> {
#[doc = concat!("Binds a shared or global ", $what, " group named `name` that was declared elsewhere (for example, in another service or language). It inherits the declaration's labels, scope, unit, description, and buckets, and is exported as `name` without a service prefix. `name` must be a string literal so Encore can parse it statically.")]
pub const fn named(name: &'static str) -> Self {
Self {
declaration: Declaration::new(name, false),
instrument: OnceLock::new(),
_labels: PhantomData,
}
}
}
};
}
recorded!(
/// A monotonically increasing counter for tracking event counts or
/// cumulative totals. See the [module documentation](self).
///
/// Declare as a module-level `static`. Service-scoped by default unless
/// marked [`shared`](Self::shared) or [`global`](Self::global); see
/// [scope](self#scope).
Counter,
/// A [`Counter`] partitioned by labels of type `L`.
CounterGroup,
"counter",
CounterValue = u64,
Counter::counter,
{}
{
/// Increments the counter by 1.
pub fn increment(&self) {
self.add(N::ONE);
}
/// Adds `amount` to the counter. Negative values are ignored because
/// counters are monotonically increasing.
pub fn add(&self, amount: N) {
self.instrument().add(amount, &self.attributes);
}
}
);
recorded!(
/// A counter that can increase or decrease, useful for tracking values
/// such as in-flight requests or queue depth. See the
/// [module documentation](self).
///
/// Declare as a module-level `static`. Service-scoped by default unless
/// marked [`shared`](Self::shared) or [`global`](Self::global); see
/// [scope](self#scope).
UpDownCounter,
/// An [`UpDownCounter`] partitioned by labels of type `L`.
UpDownCounterGroup,
"up-down counter",
UpDownCounterValue = i64,
UpDownCounter::up_down_counter,
{}
{
/// Increments the counter by 1.
pub fn increment(&self) {
self.add(N::ONE);
}
/// Decrements the counter by 1.
pub fn decrement(&self) {
self.add(-N::ONE);
}
/// Adds `amount` to the counter (may be negative).
pub fn add(&self, amount: N) {
self.instrument().add(amount, &self.attributes);
}
}
);
recorded!(
/// A point-in-time gauge holding its most recently recorded value. See the
/// [module documentation](self).
///
/// Declare as a module-level `static`. Service-scoped by default unless
/// marked [`shared`](Self::shared) or [`global`](Self::global); see
/// [scope](self#scope).
Gauge,
/// A [`Gauge`] partitioned by labels of type `L`.
GaugeGroup,
"gauge",
GaugeValue = f64,
Gauge::gauge,
{}
{
/// Sets the gauge to `value`.
pub fn set(&self, value: N) {
self.instrument().record(value, &self.attributes);
}
}
);
recorded!(
/// A histogram for tracking value distributions such as request latencies
/// or payload sizes. See the [module documentation](self).
///
/// Declare as a module-level `static`. Service-scoped by default unless
/// marked [`shared`](Self::shared) or [`global`](Self::global); see
/// [scope](self#scope).
Histogram,
/// A [`Histogram`] partitioned by labels of type `L`.
HistogramGroup,
"histogram",
HistogramValue = f64,
Histogram::histogram,
{ histogram_options!(); }
{
/// Records a single observation `value`.
pub fn record(&self, value: N) {
self.instrument().record(value, &self.attributes);
}
}
);
#[cfg(test)]
mod tests;