metrique-writer-core 0.1.21

Library for wide event metrics - writer-side interface core traits
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

use std::{
    borrow::Cow,
    ops::{Deref, DerefMut},
    time::SystemTime,
};

use smallvec::SmallVec;

use crate::{
    CowStr, Entry, EntryConfig, EntryWriter, MetricFlags, MetricValue, Observation, Unit,
    ValidationError, Value, ValueWriter, value::VALUES_INLINE_CAPACITY,
};

/// Adds a set of dimensions to a [Value] or [Entry] as (class, instance) pairs.
///
/// This will not work in [EMF] unless [split entry] mode is enabled - which is
/// normally not recommended in [EMF], since it loses the association between
/// different metrics in the same entry ([split entry] mode is normally used only
/// when an [Entry] represents a collection of independent metrics that is
/// collected periodically, as in the [metrics.rs integration]).
///
/// [EMF]: https://docs.rs/metrique-writer-format-emf/0.1/metrique_writer_format_emf/
/// [metrics.rs integration]: https://docs.rs/metrique-metricsrs/0.1/metrique_metricsrs/
/// [split entry]: crate::config::AllowSplitEntries
///
/// The const `N` defines how many of the pairs will be stored inline with the value before being spilled to the heap.
/// In most cases, the number of dimensions is known and setting `N` accordingly will avoid an allocation. It *is*
/// perfectly valid to pass either more or less than `N` dimensions in (though passing more than `N` will require
/// an heap allocation).
///
/// # Examples
///
/// ## Simple use
///
/// Using `metrique::unit_of_work::metrics`:
///
/// ```no_run
/// use metrique::ServiceMetrics;
/// use metrique::unit_of_work::metrics;
/// use metrique::writer::{GlobalEntrySink, MetricValue};
/// use metrique::writer::value::WithDimension;
///
/// #[metrics(subfield)]
/// struct EggCounter {
///     number_of_eggs: u32,
/// }
///
/// #[metrics]
/// struct MyEntry {
///     number_of_ducks: WithDimension<u32>,
///     #[metrics(flatten)]
///     egg_counter: WithDimension<EggCounter>,
/// }
///
/// let mut entry = MyEntry {
///     number_of_ducks: 0u32.with_dimension("Operation", "CountDucks"),
///     // for nested entries, use the constructor instead of `.with_dimension`
///     egg_counter:
///         WithDimension::new(EggCounter { number_of_eggs: 0 }, "Operation", "CountDucks"),
/// }.append_on_drop(ServiceMetrics::sink());
///
/// // WithDimensions implements Deref and DerefMut
/// *entry.number_of_ducks += 1;
/// entry.egg_counter.number_of_eggs += 2;
/// ```
///
/// ## Simple use (`Entry` API)
///
/// Using the `metrique_writer::Entry` API:
///
/// ```no_run
/// use metrique::ServiceMetrics;
/// use metrique_writer::{Entry, EntrySink, GlobalEntrySink, MetricValue};
/// use metrique_writer::value::WithDimension;
///
/// #[derive(Entry)]
/// struct EggCounter {
///     number_of_eggs: u32,
/// }
///
/// #[derive(Entry)]
/// struct MyEntry {
///     number_of_ducks: WithDimension<u32>,
///     #[entry(flatten)]
///     egg_counter: WithDimension<EggCounter>,
/// }
///
/// let mut entry = ServiceMetrics::sink().append_on_drop(MyEntry {
///     number_of_ducks: 0u32.with_dimension("Operation", "CountDucks"),
///     // for nested entries, use the constructor instead of `.with_dimension`
///     egg_counter:
///         WithDimension::new(EggCounter { number_of_eggs: 0 }, "Operation", "CountDucks"),
/// });
///
/// // WithDimensions implements Deref and DerefMut
/// *entry.number_of_ducks += 1;
/// entry.egg_counter.number_of_eggs += 2;
/// ```
///
/// ## Use with a dynamic number of dimensions
///
/// It is also possible to use `WithDimensions` with a dynamic number of dimensions. In order
/// to avoid allocations, make `N` the maximal number of possible dimensions.
///
/// For example:
/// ```no_run
/// use metrique::ServiceMetrics;
/// use metrique::unit_of_work::metrics;
/// use metrique::writer::GlobalEntrySink;
/// use metrique::writer::value::WithDimensions;
///
/// #[metrics]
/// struct MyEntry {
///     // always have a Year dimension, may have Season dimension
///     number_of_ducks: WithDimensions<u32, 2>,
/// }
///
/// // You can use a String as a dimension (tho creating the String is an
/// // allocation).
/// fn current_year() -> String {
///     "2025".to_string()
/// }
///
/// fn current_season() -> Option<&'static str> {
///     // get the (possibly-unknown) season
///     Some("Spring")
/// }
///
/// let mut entry = MyEntry {
///     // default constructor 0 dimensions
///     number_of_ducks: Default::default(),
/// }.append_on_drop(ServiceMetrics::sink());
///
/// // WithDimensions implements Deref and DerefMut
/// *entry.number_of_ducks += 1;
///
/// // add the dimensions
/// entry.number_of_ducks.add_dimension("Year", current_year());
/// if let Some(season) = current_season() {
///     entry.number_of_ducks.add_dimension("Season", season);
/// }
/// ```
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
pub struct WithDimensions<V, const N: usize> {
    value: V,
    dimensions: SmallVec<[(CowStr, CowStr); N]>,
}

impl<V, const N: usize> WithDimensions<V, N> {
    /// Map the value within this [WithDimensions]
    pub fn map_value<U>(self, f: impl Fn(V) -> U) -> WithDimensions<U, N> {
        WithDimensions {
            value: f(self.value),
            dimensions: self.dimensions,
        }
    }
}

/// Type alias of [`WithDimensions`] for the common case of adding a single (class, instance) pair.
///
/// This will not work in [EMF] unless [split entry] mode is enabled - which is
/// normally not recommended in [EMF], since it loses the association between
/// different metrics in the same entry ([split entry] mode is normally used only
/// when an [Entry] represents a collection of independent metrics that is
/// collected periodically, as in the [metrics.rs integration]).
///
/// [EMF]: https://docs.rs/metrique-writer-format-emf/0.1/metrique_writer_format_emf/
/// [metrics.rs integration]: https://docs.rs/metrique-metricsrs/0.1/metrique_metricsrs/
/// [split entry]: crate::config::AllowSplitEntries
///
/// Note that more than one pair can be added, but they will trigger a spill to the heap.
pub type WithDimension<V> = WithDimensions<V, 1>;

/// Type alias of [`WithDimensions`] that will always store dimensions on the heap.
///
/// This will not work in [EMF] unless [split entry] mode is enabled - which is
/// normally not recommended in [EMF], since it loses the association between
/// different metrics in the same entry ([split entry] mode is normally used only
/// when an [Entry] represents a collection of independent metrics that is
/// collected periodically, as in the [metrics.rs integration]).
///
/// [EMF]: https://docs.rs/metrique-writer-format-emf/0.1/metrique_writer_format_emf/
/// [metrics.rs integration]: https://docs.rs/metrique-metricsrs/0.1/metrique_metricsrs/
/// [split entry]: crate::config::AllowSplitEntries
pub type WithVecDimensions<V> = WithDimensions<V, 0>;

impl<V, const N: usize> Deref for WithDimensions<V, N> {
    type Target = V;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl<V, const N: usize> DerefMut for WithDimensions<V, N> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.value
    }
}

impl<V, const N: usize> From<V> for WithDimensions<V, N> {
    fn from(value: V) -> Self {
        Self {
            value,
            dimensions: Default::default(),
        }
    }
}

impl<V> WithDimension<V> {
    /// Add the (`class`, `instance`) dimension to `value`.
    pub fn new(value: V, class: impl Into<CowStr>, instance: impl Into<CowStr>) -> Self {
        Self::new_with_dimensions(value, [(class, instance)])
    }
}

impl<V, const N: usize> WithDimensions<V, N> {
    /// Creates a `WithDimensions` with no dimensions (similar to `WithDimensions::from()`) that can be used in `const` contexts
    pub const fn new_const(value: V) -> Self {
        Self {
            value,
            dimensions: SmallVec::new_const(),
        }
    }

    /// Add all of the given dimensions to `value`.
    ///
    /// Note that `N` should be chosen to match the upper bound length of `dimensions`. If the upper bound is unknown or
    /// large enough that it should always be heap allocated, `N` can be chosen to be 0 (see [`WithVecDimensions`]).
    pub fn new_with_dimensions<C, I>(value: V, dimensions: impl IntoIterator<Item = (C, I)>) -> Self
    where
        C: Into<CowStr>,
        I: Into<CowStr>,
    {
        Self {
            value,
            dimensions: dimensions
                .into_iter()
                .map(|(c, i)| (c.into(), i.into()))
                .collect(),
        }
    }

    /// The set of dimensions that this [WithDimensions] will add
    pub fn dimensions(&self) -> &[(CowStr, CowStr)] {
        &self.dimensions
    }

    /// Add a `(key, value)` to this [WithDimensions]
    pub fn add_dimension(&mut self, key: impl Into<CowStr>, value: impl Into<CowStr>) -> &mut Self {
        self.dimensions.push((key.into(), value.into()));
        self
    }

    /// Clear the dimensions in this [WithDimensions]. You can add
    /// new dimensions afterwards by using [Self::add_dimension].
    pub fn clear_dimensions(&mut self) {
        self.dimensions.clear()
    }

    /// Allow wrapping an [EntryWriter]
    pub fn entry_writer_wrapper<'a, 'b, W: EntryWriter<'b>>(
        &'a self,
        writer: W,
    ) -> impl EntryWriter<'b> + use<'a, 'b, W, V, N> {
        Wrapper {
            value: writer,
            dimensions: &self.dimensions,
        }
    }
}

#[derive(Debug)]
struct Wrapper<'a, V> {
    value: V,
    dimensions: &'a [(CowStr, CowStr)],
}

impl<'a, W: EntryWriter<'a>> EntryWriter<'a> for Wrapper<'_, W> {
    fn timestamp(&mut self, timestamp: SystemTime) {
        self.value.timestamp(timestamp);
    }

    fn value(&mut self, name: impl Into<Cow<'a, str>>, value: &(impl Value + ?Sized)) {
        self.value.value(
            name,
            &Wrapper {
                value,
                dimensions: self.dimensions,
            },
        )
    }

    fn config(&mut self, config: &'a dyn EntryConfig) {
        self.value.config(config);
    }
}

impl<V: Value> Value for Wrapper<'_, V> {
    const SHAPE: crate::descriptor::FieldShape<'static> = V::SHAPE;
    const UNIT: crate::Unit = V::UNIT;

    fn write(&self, writer: impl ValueWriter) {
        self.value.write(Wrapper {
            value: writer,
            dimensions: self.dimensions,
        })
    }
}

impl<W: ValueWriter> ValueWriter for Wrapper<'_, W> {
    fn string(self, value: &str) {
        // dimensions are ignored for strings
        self.value.string(value);
    }

    fn metric<'a>(
        self,
        distribution: impl IntoIterator<Item = Observation>,
        unit: Unit,
        dimensions: impl IntoIterator<Item = (&'a str, &'a str)>,
        flags: MetricFlags<'_>,
    ) {
        #[allow(clippy::map_identity)]
        // https://github.com/rust-lang/rust-clippy/issues/9280
        self.value.metric(
            distribution,
            unit,
            dimensions
                .into_iter()
                .map(|(k, v)| (k, v)) // reborrow to align lifetimes
                .chain(self.dimensions.iter().map(|(c, i)| (&**c, &**i))),
            flags,
        )
    }

    fn error(self, error: ValidationError) {
        self.value.error(error)
    }

    fn values<'a, V: Value + 'a>(self, values: impl IntoIterator<Item = &'a V>) {
        // Wrap each element so `metric()` calls still get the dimensions.
        let dimensions = self.dimensions;
        let wrapped: SmallVec<[Wrapper<'_, &'a V>; VALUES_INLINE_CAPACITY]> = values
            .into_iter()
            .map(|value| Wrapper { value, dimensions })
            .collect();
        self.value.values(wrapped.iter())
    }
}

impl<V: Value, const N: usize> Value for WithDimensions<V, N> {
    const SHAPE: crate::descriptor::FieldShape<'static> = V::SHAPE;
    const UNIT: crate::Unit = V::UNIT;

    fn write(&self, writer: impl ValueWriter) {
        self.value.write(Wrapper {
            value: writer,
            dimensions: self.dimensions(),
        })
    }
}

impl<V: MetricValue, const N: usize> MetricValue for WithDimensions<V, N> {
    type Unit = V::Unit;
}

impl<E: Entry, const N: usize> Entry for WithDimensions<E, N> {
    fn write<'a>(&'a self, writer: &mut impl EntryWriter<'a>) {
        self.value.write(&mut self.entry_writer_wrapper(writer))
    }

    fn descriptors(&self) -> crate::Descriptors<'_> {
        self.value.descriptors()
    }
}

#[cfg(test)]
mod tests {
    use std::time::{Duration, SystemTime};

    use metrique_writer::{
        Entry, EntryConfig, EntryWriter, MetricFlags, Observation, Unit, ValidationError, Value,
        ValueWriter,
        unit::{Millisecond, UnitTag as _},
        value::MetricValue,
        value::{WithDimension, WithDimensions},
    };

    #[test]
    fn adds_dimensions() {
        struct Writer;
        impl ValueWriter for Writer {
            fn string(self, value: &str) {
                panic!("shouldn't have written {value}");
            }

            fn metric<'a>(
                self,
                distribution: impl IntoIterator<Item = Observation>,
                unit: Unit,
                dimensions: impl IntoIterator<Item = (&'a str, &'a str)>,
                _flags: MetricFlags<'_>,
            ) {
                let distribution = distribution.into_iter().collect::<Vec<_>>();
                let dimensions = dimensions.into_iter().collect::<Vec<_>>();

                assert_eq!(distribution, &[Observation::Floating(42.0)]);
                assert_eq!(unit, Millisecond::UNIT);
                assert_eq!(dimensions, &[("foo", "bar")]);
            }

            fn error(self, error: ValidationError) {
                panic!("unexpected error {error}");
            }
        }

        WithDimension::new(Duration::from_millis(42), "foo", "bar").write(Writer);
    }

    #[test]
    fn runs_on_entries() {
        #[derive(Entry)]
        struct TestEntry {
            #[entry(timestamp)]
            ts: SystemTime,

            #[entry(flatten)]
            config: TestConfigEntry,

            f1: Duration,
            f2: Duration,
        }

        #[derive(Debug)]
        struct TestConfig;
        impl EntryConfig for TestConfig {}
        struct TestConfigEntry;
        impl Entry for TestConfigEntry {
            fn write<'a>(&'a self, writer: &mut impl EntryWriter<'a>) {
                writer.config(&TestConfig);
            }
        }

        let entry = WithDimensions::new(
            TestEntry {
                ts: SystemTime::UNIX_EPOCH,
                config: TestConfigEntry,
                f1: Duration::from_millis(42),
                f2: Duration::from_millis(43),
            },
            "foo",
            "bar",
        );

        let entry = metrique_writer::test_util::to_test_entry(&entry);
        assert_eq!(entry.metrics["f1"], 42);
        assert_eq!(
            entry.metrics["f1"].dimensions,
            vec![("foo".to_string(), "bar".to_string())]
        );
        assert_eq!(entry.metrics["f2"], 43);
        assert_eq!(
            entry.metrics["f2"].dimensions,
            vec![("foo".to_string(), "bar".to_string())]
        );
        assert!(entry.timestamp.is_some());
    }

    #[test]
    fn appends_after_existing_dimensions() {
        struct Writer;
        impl ValueWriter for Writer {
            fn string(self, value: &str) {
                panic!("shouldn't have written {value}");
            }

            fn metric<'a>(
                self,
                distribution: impl IntoIterator<Item = Observation>,
                unit: Unit,
                dimensions: impl IntoIterator<Item = (&'a str, &'a str)>,
                _flags: MetricFlags<'_>,
            ) {
                let distribution = distribution.into_iter().collect::<Vec<_>>();
                let dimensions = dimensions.into_iter().collect::<Vec<_>>();

                assert_eq!(distribution, &[Observation::Floating(42.0)]);
                assert_eq!(unit, Millisecond::UNIT);
                assert_eq!(dimensions, &[("foo", "bar"), ("a", "b"), ("c", "d")]);
            }

            fn error(self, error: ValidationError) {
                panic!("unexpected error {error}");
            }
        }

        let existing = Duration::from_millis(42).with_dimension("foo", "bar");
        WithDimension::new_with_dimensions(existing, [("a", "b"), ("c", "d")]).write(Writer);
    }

    #[test]
    fn test_const_with_dimensions() {
        let empty_with_dimensions: WithDimensions<Duration, 1> =
            WithDimensions::new_const(Duration::from_millis(19));
        let from_with_dimensions = WithDimensions::from(Duration::from_millis(19));

        assert_eq!(empty_with_dimensions, from_with_dimensions);
    }

    #[test]
    fn forwards_values_with_dimensions() {
        #[derive(Debug, PartialEq)]
        enum Event {
            String(String),
            ValuesStart,
            Metric {
                value: u64,
                dimensions: Vec<(String, String)>,
            },
        }

        struct Recorder<'a>(&'a mut Vec<Event>);

        impl ValueWriter for Recorder<'_> {
            fn string(self, value: &str) {
                self.0.push(Event::String(value.to_string()));
            }

            fn metric<'a>(
                self,
                distribution: impl IntoIterator<Item = Observation>,
                _unit: Unit,
                dimensions: impl IntoIterator<Item = (&'a str, &'a str)>,
                _flags: MetricFlags<'_>,
            ) {
                let Some(Observation::Unsigned(value)) = distribution.into_iter().next() else {
                    panic!("unexpected distribution");
                };
                self.0.push(Event::Metric {
                    value,
                    dimensions: dimensions
                        .into_iter()
                        .map(|(k, v)| (k.to_string(), v.to_string()))
                        .collect(),
                });
            }

            fn error(self, error: ValidationError) {
                panic!("unexpected error {error}");
            }

            // Distinguishes a forwarded `values()` call from the default
            // comma-joined `string()` fallback.
            fn values<'a, V: Value + 'a>(self, values: impl IntoIterator<Item = &'a V>) {
                self.0.push(Event::ValuesStart);
                for value in values {
                    value.write(Recorder(self.0));
                }
            }
        }

        let mut events = Vec::new();
        WithDimension::new(vec![1u64, 2u64], "foo", "bar").write(Recorder(&mut events));
        let dimensions = vec![("foo".to_string(), "bar".to_string())];
        assert_eq!(
            events,
            [
                Event::ValuesStart,
                Event::Metric {
                    value: 1,
                    dimensions: dimensions.clone()
                },
                Event::Metric {
                    value: 2,
                    dimensions
                },
            ],
        );
    }
}