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;
pub use encore_macros::Labels;
#[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)),
}
}
}
struct NoInstruments;
impl otel::InstrumentProvider for NoInstruments {}
impl MeterProvider {
fn of(provider: Option<&CoreMeterProvider>) -> Self {
MeterProvider(provider.cloned())
}
#[cfg(test)]
fn aggregates(&self) -> bool {
self.0.is_some()
}
}
pub fn meter_provider() -> MeterProvider {
MeterProvider::of(provider())
}
fn meter() -> Meter {
meter_provider().meter_with_scope(
InstrumentationScope::builder("encore")
.with_version(env!("CARGO_PKG_VERSION"))
.build(),
)
}
#[cfg(not(test))]
fn provider() -> Option<&'static CoreMeterProvider> {
crate::runtime::core().resources().meter_provider()
}
#[cfg(test)]
fn provider() -> Option<&'static CoreMeterProvider> {
Some(tests::provider())
}
#[cfg(not(test))]
fn hosted_service() -> Option<&'static str> {
crate::runtime::core()
.runtime_config()
.current_service
.as_deref()
}
#[cfg(test)]
fn hosted_service() -> Option<&'static str> {
Some("svc")
}
mod sealed {
use std::borrow::Cow;
use super::{hosted_service, otel, Meter};
#[derive(Debug, Clone, Copy)]
pub struct Declaration {
pub(super) name: &'static str,
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,
}
}
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>;
}
}
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
}};
}
pub trait CounterValue: sealed::Counter + Copy + Send + Sync + 'static {}
pub trait UpDownCounterValue:
sealed::UpDownCounter + Copy + std::ops::Neg<Output = Self> + Send + Sync + 'static
{
}
pub trait GaugeValue: sealed::Gauge + Copy + Send + Sync + 'static {}
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()
}
}
pub trait Labels {
fn attributes(&self) -> Vec<KeyValue>;
}
pub trait LabelValue {
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 {
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()
}
}
macro_rules! options {
($what:literal) => {
#[doc = concat!("What the ", $what, " measures in, as exported: `\"s\"`, `\"By\"`, `\"{request}\"`.")]
pub const fn unit(mut self, unit: &'static str) -> Self {
self.declaration.unit = Some(unit);
self
}
#[doc = concat!("What the ", $what, " measures, for one without a doc comment.")]
pub const fn description(mut self, description: &'static str) -> Self {
self.declaration.description = Some(description);
self
}
};
}
macro_rules! histogram_options {
() => {
pub const fn buckets(mut self, bounds: &'static [f64]) -> Self {
self.declaration.buckets = Some(bounds);
self
}
};
}
macro_rules! recorded {
(
$(#[$doc:meta])* $name:ident,
$(#[$group_doc:meta])* $group:ident,
own = $own:literal,
$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 the ", $what, " `name`: a letter, then letters, digits, `_`, `.`, `-` and `/`. It must be a string literal: Encore reads it from the source.")]
pub const fn new(name: &'static str) -> Self {
Self {
declaration: Declaration::new(name, $own),
attributes: Vec::new(),
instrument: OnceLock::new(),
}
}
options!($what);
$($options)*
#[doc = concat!("The ", $what, " itself, to hand to other code: a function that takes a `&", stringify!($name), "` records to whichever it is given.")]
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 the ", $what, " group `name`: a letter, then letters, digits, `_`, `.`, `-` and `/`. It must be a string literal: Encore reads it from the source.")]
pub const fn new(name: &'static str) -> Self {
Self {
declaration: Declaration::new(name, $own),
instrument: OnceLock::new(),
_labels: PhantomData,
}
}
options!($what);
$($options)*
#[doc = concat!("The ", $what, " for `labels`. Worth keeping where it is used often: making it takes the labels' attributes.")]
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!("The group itself, to hand to other code: a function that takes a `&", stringify!($group), "<L>` records to whichever it is given.")]
pub fn reference(&self) -> &Self {
self
}
}
};
}
macro_rules! named {
(false, $($_:tt)*) => {};
(true, $name:ident, $group:ident, $value:ident, $what:literal) => {
impl<N: $value> $name<N> {
#[doc = concat!("Binds the shared or global ", $what, " `name` declared elsewhere — by another service, possibly in another language — rather than declaring one. It is the declaration's kind and scope, and takes its unit, description and buckets: it has no options of its own. It is exported as `name`, never prefixed with a service's name. The name must be a string literal: Encore reads it from the source.")]
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 the shared or global ", $what, " group `name` declared elsewhere — by another service, possibly in another language — rather than declaring one. Its labels and scope are the declaration's, and it takes its unit, description and buckets: it has no options of its own. It is exported as `name`, never prefixed with a service's name. The name must be a string literal: Encore reads it from the source.")]
pub const fn named(name: &'static str) -> Self {
Self {
declaration: Declaration::new(name, false),
instrument: OnceLock::new(),
_labels: PhantomData,
}
}
}
};
}
macro_rules! counter_types {
($own:tt, $(#[$doc:meta])* $name:ident, $(#[$group_doc:meta])* $group:ident) => {
recorded!(
$(#[$doc])* $name,
$(#[$group_doc])* $group,
own = $own,
"counter",
CounterValue = u64,
Counter::counter,
{}
{
pub fn increment(&self) {
self.add(N::ONE);
}
pub fn add(&self, amount: N) {
self.instrument().add(amount, &self.attributes);
}
}
);
named!($own, $name, $group, CounterValue, "counter");
};
}
counter_types!(
true,
Counter,
CounterGroup
);
counter_types!(
false,
SharedCounter,
SharedCounterGroup
);
counter_types!(
false,
GlobalCounter,
GlobalCounterGroup
);
macro_rules! up_down_counter_types {
($own:tt, $(#[$doc:meta])* $name:ident, $(#[$group_doc:meta])* $group:ident) => {
recorded!(
$(#[$doc])* $name,
$(#[$group_doc])* $group,
own = $own,
"up-down counter",
UpDownCounterValue = i64,
UpDownCounter::up_down_counter,
{}
{
pub fn increment(&self) {
self.add(N::ONE);
}
pub fn decrement(&self) {
self.add(-N::ONE);
}
pub fn add(&self, amount: N) {
self.instrument().add(amount, &self.attributes);
}
}
);
named!($own, $name, $group, UpDownCounterValue, "up-down counter");
};
}
up_down_counter_types!(
true,
UpDownCounter,
UpDownCounterGroup
);
up_down_counter_types!(
false,
SharedUpDownCounter,
SharedUpDownCounterGroup
);
up_down_counter_types!(
false,
GlobalUpDownCounter,
GlobalUpDownCounterGroup
);
macro_rules! gauge_types {
($own:tt, $(#[$doc:meta])* $name:ident, $(#[$group_doc:meta])* $group:ident) => {
recorded!(
$(#[$doc])* $name,
$(#[$group_doc])* $group,
own = $own,
"gauge",
GaugeValue = f64,
Gauge::gauge,
{}
{
pub fn set(&self, value: N) {
self.instrument().record(value, &self.attributes);
}
}
);
named!($own, $name, $group, GaugeValue, "gauge");
};
}
gauge_types!(
true,
Gauge,
GaugeGroup
);
gauge_types!(
false,
SharedGauge,
SharedGaugeGroup
);
gauge_types!(
false,
GlobalGauge,
GlobalGaugeGroup
);
macro_rules! histogram_types {
($own:tt, $(#[$doc:meta])* $name:ident, $(#[$group_doc:meta])* $group:ident) => {
recorded!(
$(#[$doc])* $name,
$(#[$group_doc])* $group,
own = $own,
"histogram",
HistogramValue = f64,
Histogram::histogram,
{ histogram_options!(); }
{
pub fn record(&self, value: N) {
self.instrument().record(value, &self.attributes);
}
}
);
named!($own, $name, $group, HistogramValue, "histogram");
};
}
histogram_types!(
true,
Histogram,
HistogramGroup
);
histogram_types!(
false,
SharedHistogram,
SharedHistogramGroup
);
histogram_types!(
false,
GlobalHistogram,
GlobalHistogramGroup
);
#[cfg(test)]
mod tests;