encore-dev 2.0.0-beta.10

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
//! Metrics: counters, gauges and histograms of what an app does.
//!
//! A metric is declared as a `static` and used wherever the thing it measures
//! happens. Its doc comment is 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}");
//!
//! /// The temperature of the oven.
//! static OVEN: Gauge = Gauge::new("oven_temperature").unit("Cel");
//!
//! /// How long an order takes to place.
//! 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 is an instrument of the [OpenTelemetry Metrics API](crate::opentelemetry::metrics),
//! of the meter `encore`, named as declared, a service's own prefixed with
//! its service's name (`orders_placed` of the service `shop` is exported as
//! `shop.orders_placed`), created when it is first recorded to. Its data is
//! exported with the rest of the app's: the process's resource names the
//! service recording it. Instruments of the API itself made with Encore's
//! [meter provider](meter_provider) are exported alongside: observable
//! instruments are made with it. Encore installs no 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 | What it is | Values |
//! |---|---|---|
//! | [`Counter`] | a total that only goes up | `u64`, `f64` |
//! | [`UpDownCounter`] | a total that goes up and down | `i64`, `f64` |
//! | [`Gauge`] | what something is right now | `f64`, `i64`, `u64` |
//! | [`Histogram`] | how values are distributed | `f64` |
//!
//! The first type in each list is the default. A unit is given as it is to be
//! exported: [UCUM](https://ucum.org/ucum) is the convention (`"s"`, `"By"`,
//! `"{request}"`). A description given with `.description(…)`, where there is
//! no doc comment, is the instrument's too.
//!
//! # Scope
//!
//! How a metric is declared says who records to it, as with
//! [secrets](crate::secrets#scope):
//!
//! - `Counter::new("requests")`, `Gauge::new(…)`, … belongs to the service that
//!   declares it, and only that service records to it. Its name is unique in
//!   the service: two services may each declare a `requests` counter, exported
//!   as `<service>.requests`. It must be declared inside a service.
//! - `Counter::new("signups").shared()` is shared between services, under one
//!   name in the app. Each service that records to it is recorded as using it.
//! - `Counter::new("requests").global()` is the whole app's. Any code may
//!   record to it — a library outside every service too — and who does is not
//!   recorded.
//!
//! The groups, below, are scoped the same way: `CounterGroup::new("…").shared()`.
//! The scope is chained with the other options in any order, and written out
//! as the name is: Encore reads both from the source.
//!
//! ```ignore
//! /// Users signed up, whichever service signed them up.
//! static SIGNUPS: Counter = Counter::new("signups").shared().unit("{user}");
//! ```
//!
//! A shared or global metric is declared once in the app, as a [shared
//! secret](crate::secrets#scope) is. Other code records to it by importing
//! the declaration, or, from another service's crate or another language, by
//! binding it by name:
//!
//! ```ignore
//! static SERVED: CounterGroup<Served> = CounterGroup::named("greetings.served");
//! ```
//!
//! A named metric is of the declaration's kind and labels, and takes its
//! scope, unit, description and buckets; it is exported under the name as
//! written, never prefixed with a service's. To hand a metric to other code,
//! pass [`reference()`](Counter::reference): it counts as recording to it.
//!
//! # Labels
//!
//! A metric that is one number is a [`Counter`], [`Gauge`], … A *group* —
//! [`CounterGroup`], [`GaugeGroup`], … — is one number for each combination of
//! its labels, which are the fields of a struct, each an attribute of what is
//! recorded:
//!
//! ```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();
//! ```
//!
//! Every distinct combination is a time series of its own: a label is for a
//! handful of values — a status, a region — and not for a user id. For
//! attributes of any other shape, record with the OpenTelemetry API.
//!
//! # Histograms
//!
//! A [`Histogram`] counts what it records in buckets, to say how it is
//! distributed: the median latency, the 99th percentile. Its
//! [`buckets`](Histogram::buckets) are part of its definition, exported as
//! they are declared.
//!
//! # Under test
//!
//! Under `encore test`, as wherever the runtime exports no metrics, metrics
//! record nothing.

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 is a label,
/// named as the field is, whose type is a [`LabelValue`].
pub use encore_macros::Labels;

/// Encore's meter provider, an OpenTelemetry
/// [`MeterProvider`](otel::MeterProvider), which Encore metrics record
/// through. 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()
    }
}

/// Encore's meter provider: the runtime's, or, when the runtime exports no
/// metrics, one recording nothing.
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
    }};
}

/// What a [`Counter`] counts in: `u64`, or `f64` for amounts that are not
/// whole.
pub trait CounterValue: sealed::Counter + Copy + Send + Sync + 'static {}

/// What an [`UpDownCounter`] counts in: `i64`, or `f64` for amounts that are
/// not whole.
pub trait UpDownCounterValue:
    sealed::UpDownCounter + Copy + std::ops::Neg<Output = Self> + Send + Sync + 'static
{
}

/// What a [`Gauge`] holds: `f64`, `i64` or `u64`.
pub trait GaugeValue: sealed::Gauge + Copy + Send + Sync + 'static {}

/// What a [`Histogram`] records: `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()
    }
}

/// The labels of a metric group: a struct whose fields are the labels.
/// Derive it:
///
/// ```ignore
/// #[derive(Labels)]
/// struct Outcome {
///     method: &'static str,
///     status: u16,
/// }
/// ```
pub trait Labels {
    /// Each label as an attribute, keyed by its name.
    fn attributes(&self) -> Vec<KeyValue>;
}

/// A type a label's value can be: strings, integers, `bool` and `char` are.
/// Implement it for an enum of your own to use it as a label:
///
/// ```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 {
    /// A string, an integer or a `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 {
            /// An `i64`: one above `i64::MAX` is `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!("Makes the ", $what, " shared between services, under one name in the app, rather than the declaring service's own: each service that records to it is recorded as using it. See [scope](self#scope).")]
        pub const fn shared(mut self) -> Self {
            self.declaration.own = false;
            self
        }

        #[doc = concat!("Makes the ", $what, " the whole app's: any code may record to it, a library outside every service too, and who does is not recorded. See [scope](self#scope).")]
        pub const fn global(mut self) -> Self {
            self.declaration.own = false;
            self
        }

        #[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
        }

        #[doc = concat!("Tags the ", $what, " with `key` and `value`: key/value classification, such as `.tag(\"data\", \"pii\")`, for policies to read. One call per tag, each with its own key. Encore reads them from the source, so both are string literals. A key is lowercase letters, digits, `_` and `-`, starting with a letter and not with `encore`, which is kept for Encore's own tags; a value is the same characters, or empty. Each is at most 63 characters, and a ", $what, " has at most 32 tags.")]
        ///
        /// Not to be confused with the labels a group's records carry: a tag
        /// classifies the metric itself, and is never recorded.
        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 {
    () => {
        /// The upper bounds of the buckets, increasing: what is recorded is
        /// counted in the first it is no greater than, or one past the last.
        /// Without them, the OpenTelemetry SDK's defaults.
        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 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, true),
                    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.")]
            ///
            /// A metric is otherwise used where it is declared, by name, which
            /// is how Encore sees which service records to it. Passing one on
            /// says so explicitly, and counts as recording to it.
            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, true),
                    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.")]
            ///
            /// A metric is otherwise used where it is declared, by name, which
            /// is how Encore sees which service records to it. Passing one on
            /// says so explicitly, and counts as recording to it.
            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 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,
                }
            }
        }
    };
}

recorded!(
    /// A number that only goes up: how many times something happened, or how
    /// much of something there has been. See the [module documentation](self).
    ///
    /// Declared as a module-level `static`. It is the declaring service's own
    /// unless declared [`shared`](Self::shared) or [`global`](Self::global):
    /// see [scope](self#scope).
    Counter,
    /// A [`Counter`] for each combination of the labels `L`.
    CounterGroup,
    "counter",
    CounterValue = u64,
    Counter::counter,
    {}
    {
        /// Adds one.
        pub fn increment(&self) {
            self.add(N::ONE);
        }

        /// Adds `amount`. A counter does not go down: an amount below zero is
        /// ignored.
        pub fn add(&self, amount: N) {
            self.instrument().add(amount, &self.attributes);
        }
    }
);

recorded!(
    /// A number that goes up and down by what is added to it: how many
    /// requests are in flight, how many jobs are queued. See the [module
    /// documentation](self).
    ///
    /// Declared as a module-level `static`. It is the declaring service's own
    /// unless declared [`shared`](Self::shared) or [`global`](Self::global):
    /// see [scope](self#scope).
    UpDownCounter,
    /// An [`UpDownCounter`] for each combination of the labels `L`.
    UpDownCounterGroup,
    "up-down counter",
    UpDownCounterValue = i64,
    UpDownCounter::up_down_counter,
    {}
    {
        /// Adds one.
        pub fn increment(&self) {
            self.add(N::ONE);
        }

        /// Takes one away.
        pub fn decrement(&self) {
            self.add(-N::ONE);
        }

        /// Adds `amount`, which may be below zero.
        pub fn add(&self, amount: N) {
            self.instrument().add(amount, &self.attributes);
        }
    }
);

recorded!(
    /// A number that is what it was last set to: what something is right now.
    /// See the [module documentation](self).
    ///
    /// Declared as a module-level `static`. It is the declaring service's own
    /// unless declared [`shared`](Self::shared) or [`global`](Self::global):
    /// see [scope](self#scope).
    Gauge,
    /// A [`Gauge`] for each combination of the labels `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!(
    /// How what is recorded is distributed: how long requests take, how large
    /// uploads are. See the [module documentation](self).
    ///
    /// Declared as a module-level `static`. It is the declaring service's own
    /// unless declared [`shared`](Self::shared) or [`global`](Self::global):
    /// see [scope](self#scope).
    Histogram,
    /// A [`Histogram`] for each combination of the labels `L`.
    HistogramGroup,
    "histogram",
    HistogramValue = f64,
    Histogram::histogram,
    { histogram_options!(); }
    {
        /// Records `value`.
        pub fn record(&self, value: N) {
            self.instrument().record(value, &self.attributes);
        }
    }
);

#[cfg(test)]
mod tests;