encore-dev 2.0.0-beta.16

Rust SDK for Encore applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
//! 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` 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`, of this SDK's
/// version, from Encore's meter provider.
fn meter() -> Meter {
    meter_provider().meter_with_scope(
        InstrumentationScope::builder("encore")
            .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;