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
742
743
744
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under both the MIT license found in the
 * LICENSE-MIT file in the root directory of this source tree and the Apache
 * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
 * of this source tree.
 */

// This module defines only macros which don't show up on module level
// documentation anyway so hide it.
#![doc(hidden)]

#[doc(hidden)]
pub mod common_macro_prelude {
    pub use std::sync::Arc;
    pub use std::time::Duration;

    pub use once_cell::sync::Lazy;
    pub use perthread::PerThread;
    pub use perthread::ThreadMap;
    pub use stats_traits::dynamic_stat_types::DynamicStat;
    pub use stats_traits::dynamic_stat_types::DynamicStatSync;
    pub use stats_traits::field_stat_types::FieldStat;
    pub use stats_traits::field_stat_types::FieldStatThreadLocal;
    pub use stats_traits::stat_types::BoxCounter;
    pub use stats_traits::stat_types::BoxHistogram;
    pub use stats_traits::stat_types::BoxLocalCounter;
    pub use stats_traits::stat_types::BoxLocalHistogram;
    pub use stats_traits::stat_types::BoxLocalTimeseries;
    pub use stats_traits::stat_types::BoxSingletonCounter;
    pub use stats_traits::stat_types::BoxTimeseries;
    pub use stats_traits::stats_manager::AggregationType::*;
    pub use stats_traits::stats_manager::BoxStatsManager;
    pub use stats_traits::stats_manager::BucketConfig;
    pub use stats_traits::stats_manager::StatsManager;

    pub use crate::create_singleton_counter;
    pub use crate::create_stats_manager;
    pub use crate::thread_local_aggregator::create_map;
}

/// The macro to define STATS module that contains static variables, one per
/// counter you want to export. This is the main and recommended way to interact
/// with statistics provided by this crate. If non empty prefix is passed then
/// the exported counter name will be "{prefix}.{name}"
///
/// Examples:
/// ```
/// use stats::prelude::*;
/// use fbinit::FacebookInit;
///
/// define_stats! {
///     prefix = "my.test.counters";
///     manual_c: singleton_counter(),
///     test_c: counter(),
///     test_c2: counter("test_c.two"),
///     test_t: timeseries(Sum, Average),
///     test_t2: timeseries("test_t.two"; Sum, Average),
///     test_h: histogram(1, 0, 1000, Sum; P 99; P 50),
///     dtest_c: dynamic_counter("test_c.{}", (job: u64)),
///     dtest_t: dynamic_timeseries("test_t.{}", (region: &'static str); Rate, Sum),
///     dtest_t2: dynamic_timeseries("test_t.two.{}.{}", (job: u64, region: &'static str); Count),
///     dtest_h: dynamic_histogram("test_h.{}", (region: &'static str); 1, 0, 1000, Sum; P 99),
///     test_qs: quantile_stat("test_qs"; Count, Sum, Average; P 95, P 99; Duration::from_secs(60)),
///     test_qs_two: quantile_stat(Count, Sum, Average; P 95; Duration::from_secs(60)),
///     test_dynqs: dynamic_quantile_stat("test_dynqs_{}", (num: i32); Count, Sum, Average; P 95, P 99; Duration::from_secs(60)),
/// }
///
/// #[allow(non_snake_case)]
/// mod ALT_STATS {
///     use stats::define_stats;
///     define_stats! {
///         test_t: timeseries(Sum, Average),
///         test_t2: timeseries("test.two"; Sum, Average),
///     }
///     pub use self::STATS::*;
/// }
///
/// # #[allow(clippy::needless_doctest_main)]
/// #[fbinit::main]
/// fn main(fb: FacebookInit) {
///     STATS::manual_c.set_value(fb, 1);
///     STATS::test_c.increment_value(1);
///     STATS::test_c2.increment_value(100);
///     STATS::test_t.add_value(1);
///     STATS::test_t2.add_value_aggregated(79, 10);  // Add 79 and note it came from 10 samples
///     STATS::test_h.add_value(1);
///     STATS::test_h.add_repeated_value(1, 44);  // 44 times repeat adding 1
///     STATS::dtest_c.increment_value(7, (1000,));
///     STATS::dtest_t.add_value(77, ("lla",));
///     STATS::dtest_t2.add_value_aggregated(81, 12, (7, "lla"));
///     STATS::dtest_h.add_value(2, ("frc",));
///
///     ALT_STATS::test_t.add_value(1);
///     ALT_STATS::test_t2.add_value(1);
/// }
/// ```
///
/// # Reference
///
/// ## `singleton_counter`, `counter`
///
/// **DEPRECATED:** Use `timeseries` instead.
///
/// Raw counter types. These take an optional key parameter - if it is not
/// specified, then it's derived from the stat field name.
///
/// ## `timeseries`
/// The general syntax for `timeseries` is:
/// ```text
/// timeseries(<optional key>; <list of aggregations>; [optional intervals])
/// ```
///
/// If "optional key" is omitted then key is derived from the stat key name;
/// otherwise it's a string literal.
///
/// "List of aggregations" is a `,`-separated list of
/// [`AggregationType`](stats_traits::stats_manager::AggregationType) enum
/// values.
///
/// "Optional intervals" is a `,`-separated list of [`Duration`s](std::time::Duration). It
/// specifies over what time periods the aggregations aggregate. If not
/// specified, it typically defaults to 60 seconds.
///
/// This maps to a call to
/// [`StatsManager::create_timeseries`](stats_traits::stats_manager::StatsManager::create_histogram).
///
/// ## `histogram`
///
/// **DEPRECATED:** Use `quantile_stat` instead.
///
/// The general syntax for `histogram` is:
/// ```text
/// histogram(<optional key>; bucket-width, min, max, <list of aggregations>; <P XX percentiles>)
/// ```
/// If "optional key" is omitted then key is derived from the stat key name;
/// otherwise it's a string literal.
///
/// `bucket-width` specifies what range of values are accumulated into each
/// bucket; the larger it is the fewer buckets there are.
///
/// `min` and `max` specify the min and max of the expected range of samples.
/// Samples outside this range will be aggregated into out-of-range buckets,
/// which means they're not lost entirely but they lead to inaccurate stats.
///
/// Together the min, max and bucket width parameters determine how many buckets
/// are created.
///
/// "List of aggregations" is a `,`-separated list of
/// [`AggregationType`](stats_traits::stats_manager::AggregationType) enum
/// values.
///
/// Percentiles are specified as `P NN` in a `;`-separated list, such as `P 20;
/// P 50; P 90; P 99`...
///
/// This maps to a call to
/// [`StatsManager::create_histogram`](stats_traits::stats_manager::StatsManager::create_histogram).
///
/// ## `quantile_stat`
/// The general syntax for `quantile_stat` is:
/// ```text
/// quantile_stat(<optional key>; <list of aggregations>; <P XX percentiles>; <list of intervals>)
/// ```
///
/// "List of aggregations" is a `,`-separated list of
/// [`AggregationType`](stats_traits::stats_manager::AggregationType) enum
/// values.
///
/// Percentiles are specified as `P NN` or `P NN.N` in a `,`-separated list, such as `P 20,
/// P 50, P 90, P 99`...
/// You can also use floating point values as well such as `P 95.0, P 99.0, P 99.99`...
/// Please note that you provide "percentiles" instead of rates such as 0.95 like C++ API
///
/// "List of intervals" is a `,`-separated list of [`Duration`s](std::time::Duration). It
/// specifies over what time periods the aggregations aggregate.
///
/// `quantile_stat` measures the same statistics as `histogram`, but it
/// doesn't require buckets to be defined ahead of time. See [this workplace post](https://fb.workplace.com/notes/marc-celani/a-new-approach-to-quantile-estimation-in-c-services/212892662822481)
/// for more.
///
///  This maps to a call to
/// [`StatsManager::create_quantile_stat`](stats_traits::stats_manager::StatsManager::create_quantile_stat).
///
/// ## `dynamic_counter`, `dynamic_timeseries`, `dynamic_histogram`, `dynamic_quantile_stat`
///
/// These are equivalent to the corresponding `counter`/`timeseries`/`histogram`/`quantile_stat`
/// above, except that they allow the key to have a dynamic component. The key
/// is no longer optional, but is instead specified with `<format-string>,
/// (variable:type, ...)`. The format string is standard
/// [`format!`](std::format).
#[macro_export]
macro_rules! define_stats {
    // Fill the optional prefix with empty string, all matching is repeated here to avoid the
    // recursion limit reached error in case the macro is misused.
    ($( $name:ident: $stat_type:tt($( $params:tt )*), )*) =>
        (define_stats!(prefix = ""; $( $name: $stat_type($( $params )*), )*););

    (prefix = $prefix:expr;
     $( $name:ident: $stat_type:tt($( $params:tt )*), )*) => (
        #[allow(non_snake_case, non_upper_case_globals, unused_imports)]
        pub(crate) mod STATS {
            use $crate::macros::common_macro_prelude::*;

            static STATS_MAP: Lazy<Arc<ThreadMap<BoxStatsManager>>> = Lazy::new(|| create_map());
            static STATS_MANAGER: Lazy<BoxStatsManager> = Lazy::new(|| create_stats_manager());

            thread_local! {
                static TL_STATS: PerThread<BoxStatsManager> =
                    STATS_MAP.register(create_stats_manager());
            }

            $( $crate::__define_stat!($prefix; $name: $stat_type($( $params )*)); )*
        }
    );
}

#[doc(hidden)]
#[macro_export]
macro_rules! __define_key_generator {
    ($name:ident($prefix:expr, $key:expr; $( $placeholder:ident: $type:ty ),+)) => (
        fn $name(&($( ref $placeholder, )+): &($( $type, )+)) -> String {
            let key = format!($key, $( $placeholder ),+);
            if $prefix.is_empty() {
                key
            } else {
                [$prefix, &key].join(".")
            }
        }
    );
}

#[doc(hidden)]
#[macro_export]
macro_rules! __define_stat {
    ($prefix:expr; $name:ident: singleton_counter()) => (
        $crate::__define_stat!($prefix; $name: singleton_counter(stringify!($name)));
    );

    ($prefix:expr; $name:ident: singleton_counter($key:expr)) => (
        pub static $name: Lazy<BoxSingletonCounter> = Lazy::new(|| create_singleton_counter($crate::__create_stat_key!($prefix, $key).to_string()));
    );

    ($prefix:expr; $name:ident: counter()) => (
        $crate::__define_stat!($prefix; $name: counter(stringify!($name)));
    );

    ($prefix:expr; $name:ident: counter($key:expr)) => (
        thread_local! {
            pub static $name: BoxLocalCounter = TL_STATS.with(|stats| {
                stats.create_counter(&$crate::__create_stat_key!($prefix, $key))
            });
        }
    );

    // There are 4 inputs we use to produce a timeseries: the the prefix, the name (used in
    // STATS::name), the key (used in ODS or to query the key), the export types (SUM, RATE, etc.),
    // and the intervals (e.g. 60, 600). The key defaults to the name, and the intervals default to
    // whatever default Folly uses (which happens to be 60, 600, 3600);
    ($prefix:expr; $name:ident: timeseries($( $aggregation_type:expr ),*)) => (
        $crate::__define_stat!($prefix; $name: timeseries(stringify!($name); $( $aggregation_type ),*));
    );
    ($prefix:expr; $name:ident: timeseries($key:expr; $( $aggregation_type:expr ),*)) => (
        $crate::__define_stat!($prefix; $name: timeseries($key; $( $aggregation_type ),* ; ));
    );
    ($prefix:expr; $name:ident: timeseries($key:expr; $( $aggregation_type:expr ),* ; $( $interval: expr ),*)) => (
        thread_local! {
            pub static $name: BoxLocalTimeseries = TL_STATS.with(|stats| {
                stats.create_timeseries(
                    &$crate::__create_stat_key!($prefix, $key),
                    &[$( $aggregation_type ),*],
                    &[$( $interval ),*]
                )
            });
        }
    );

    ($prefix:expr;
     $name:ident: histogram($bucket_width:expr,
                            $min:expr,
                            $max:expr
                            $(, $aggregation_type:expr )*
                            $(; P $percentile:expr )*)) => (
        $crate::__define_stat!($prefix;
                      $name: histogram(stringify!($name);
                                       $bucket_width,
                                       $min,
                                       $max
                                       $(, $aggregation_type )*
                                       $(; P $percentile )*));
    );

    ($prefix:expr;
     $name:ident: histogram($key:expr;
                            $bucket_width:expr,
                            $min:expr,
                            $max:expr
                            $(, $aggregation_type:expr )*
                            $(; P $percentile:expr )*)) => (
        thread_local! {
            pub static $name: BoxLocalHistogram = TL_STATS.with(|stats| {
                stats.create_histogram(
                    &$crate::__create_stat_key!($prefix, $key),
                    &[$( $aggregation_type ),*],
                    BucketConfig {
                        width: $bucket_width,
                        min: $min,
                        max: $max,
                    },
                    &[$( $percentile ),*])
            });
        }
    );

    ($prefix:expr;
        $name:ident: quantile_stat(
            $( $aggregation_type:expr ),*
            ; $( P $percentile:expr ),*
            ; $( $interval:expr ),*
        )) => (
            $crate::__define_stat!($prefix;
                 $name: quantile_stat(stringify!($name)
                                     ; $( $aggregation_type ),*
                                     ; $( P $percentile ),*
                                     ; $( $interval ),*));
       );

    ($prefix:expr;
        $name:ident: quantile_stat($key:expr
            ; $( $aggregation_type:expr ),*
            ; $( P $percentile:expr ),*
            ; $( $interval:expr ),*
        )) => (
                pub static $name: Lazy<BoxHistogram> = Lazy::new(|| {
                    STATS_MANAGER.create_quantile_stat(
                        &$crate::__create_stat_key!($prefix, $key),
                        &[$( $aggregation_type ),*],
                        &[$( $percentile as f32 ),*],
                        &[$( $interval ),*],
                    )
                });

       );

    ($prefix:expr;
     $name:ident: dynamic_singleton_counter($key:expr, ($( $placeholder:ident: $type:ty ),+))) => (
        thread_local! {
            pub static $name: DynamicStat<($( $type, )+), BoxSingletonCounter> = {
                $crate::__define_key_generator!(
                    __key_generator($prefix, $key; $( $placeholder: $type ),+)
                );

                fn __stat_generator(key: &str) -> BoxSingletonCounter {
                    create_singleton_counter(key.to_string())
                }

                DynamicStat::new(__key_generator, __stat_generator)
            }
        }
    );

    ($prefix:expr;
     $name:ident: dynamic_counter($key:expr, ($( $placeholder:ident: $type:ty ),+))) => (
        thread_local! {
            pub static $name: DynamicStat<($( $type, )+), BoxLocalCounter> = {
                $crate::__define_key_generator!(
                    __key_generator($prefix, $key; $( $placeholder: $type ),+)
                );

                fn __stat_generator(key: &str) -> BoxLocalCounter {
                    TL_STATS.with(|stats| {
                        stats.create_counter(key)
                    })
                }

                DynamicStat::new(__key_generator, __stat_generator)
            }
        }
    );

    ($prefix:expr;
     $name:ident: dynamic_timeseries($key:expr, ($( $placeholder:ident: $type:ty ),+);
                                     $( $aggregation_type:expr ),*)) => (
        $crate::__define_stat!(
            $prefix;
            $name: dynamic_timeseries(
                $key,
                ($( $placeholder: $type ),+);
                $( $aggregation_type ),* ;
            )
        );
    );

    ($prefix:expr;
     $name:ident: dynamic_timeseries($key:expr, ($( $placeholder:ident: $type:ty ),+);
                                     $( $aggregation_type:expr ),* ; $( $interval:expr ),*)) => (
        thread_local! {
            pub static $name: DynamicStat<($( $type, )+), BoxLocalTimeseries> = {
                $crate::__define_key_generator!(
                    __key_generator($prefix, $key; $( $placeholder: $type ),+)
                );

                fn __stat_generator(key: &str) -> BoxLocalTimeseries {
                    TL_STATS.with(|stats| {
                        stats.create_timeseries(key, &[$( $aggregation_type ),*], &[$( $interval ),*])
                    })
                }

                DynamicStat::new(__key_generator, __stat_generator)
            };
        }
    );

    ($prefix:expr;
     $name:ident: dynamic_histogram($key:expr, ($( $placeholder:ident: $type:ty ),+);
                                    $bucket_width:expr,
                                    $min:expr,
                                    $max:expr
                                    $(, $aggregation_type:expr )*
                                    $(; P $percentile:expr )*)) => (
        thread_local! {
            pub static $name: DynamicStat<($( $type, )+), BoxLocalHistogram> = {
                $crate::__define_key_generator!(
                    __key_generator($prefix, $key; $( $placeholder: $type ),+)
                );

                fn __stat_generator(key: &str) -> BoxLocalHistogram {
                    TL_STATS.with(|stats| {
                        stats.create_histogram(key,
                                               &[$( $aggregation_type ),*],
                                               BucketConfig {
                                                   width: $bucket_width,
                                                   min: $min,
                                                   max: $max,
                                               },
                                               &[$( $percentile ),*])
                    })
                }

                DynamicStat::new(__key_generator, __stat_generator)
            };
        }
    );

    ($prefix:expr;
     $name:ident: dynamic_quantile_stat($key:expr, ($( $placeholder:ident: $type:ty ),+) ;
                                        $( $aggregation_type:expr ),* ;
                                        $( P $percentile:expr ),* ;
                                        $( $interval:expr ),*)) => (
                pub static $name: Lazy<DynamicStatSync<($( $type, )+), BoxHistogram>> = Lazy::new(|| {
                    $crate::__define_key_generator!(
                        __key_generator($prefix, $key; $( $placeholder: $type ),+)
                    );

                    fn __stat_generator(key: &str) -> BoxHistogram {
                        STATS_MANAGER.create_quantile_stat(
                            key,
                            &[$( $aggregation_type ),*],
                            &[$( $percentile as f32 ),*],
                            &[$( $interval ),*],
                        )
                    }
                    DynamicStatSync::new(__key_generator, __stat_generator)
                });
       );
}

#[doc(hidden)]
#[macro_export]
macro_rules! __create_stat_key {
    ($prefix:expr, $key:expr) => {{
        use std::borrow::Cow;
        if $prefix.is_empty() {
            Cow::Borrowed($key)
        } else {
            Cow::Owned(format!("{}.{}", $prefix, $key))
        }
    }};
}

/// Define a group of stats with dynamic names all parameterized by the same set of parameters.
/// The intention is that when setting up a structure for some entity with associated stats, then
/// the type produced by this macro can be included in that structure, and initialized with the
/// appropriate name(s). This is more efficient than using single static "dynamic_" versions of
/// the counters.
///
/// ```
/// use stats::prelude::*;
///
/// define_stats_struct! {
///    // struct name, key prefix template, key template params
///    MyThingStat("things.{}.{}", mything_name: String, mything_idx: usize),
///    cache_miss: counter() // default name from the field
/// }
///
/// struct MyThing {
///    stats: MyThingStat,
/// }
///
/// impl MyThing {
///    fn new(somename: String, someidx: usize) -> Self {
///        MyThing {
///           stats: MyThingStat::new(somename, someidx),
///           //...
///        }
///    }
/// }
/// #
/// # fn main() {}
/// ```
#[macro_export]
macro_rules! define_stats_struct {
    // Handle trailing comma
    ($name:ident ($key:expr, $($pr_name:ident: $pr_type:ty),*) ,
        $( $stat_name:ident: $stat_type:tt($( $params:tt )*) , )+) => {
        define_stats_struct!($name ( $key, $($pr_name: $pr_type),*),
            $($stat_name: $stat_type($($params)*)),* );
    };

    // Handle no params
    ($name:ident ($key:expr) ,
        $( $stat_name:ident: $stat_type:tt($( $params:tt )*) ),*) => {
        define_stats_struct!($name ( $key, ),
            $($stat_name: $stat_type($($params)*)),* );
    };
    ($name:ident ($key:expr) ,
        $( $stat_name:ident: $stat_type:tt($( $params:tt )*) , )+) => {
        define_stats_struct!($name ( $key, ),
            $($stat_name: $stat_type($($params)*)),* );
    };

    // Define struct and its methods.
    ($name:ident ($key:expr, $($pr_name:ident: $pr_type:ty),*) ,
        $( $stat_name:ident: $stat_type:tt($( $params:tt )*) ),*) => {
        #[allow(missing_docs)]
        pub struct $name {
            $(pub $stat_name: $crate::__struct_field_type!($stat_type), )*
        }
        impl $name {
            #[allow(unused_imports, missing_docs, non_upper_case_globals)]
            pub fn new($($pr_name: $pr_type),*) -> $name {
                use $crate::macros::common_macro_prelude::*;


                static STATS_MAP: Lazy<Arc<ThreadMap<BoxStatsManager>>> = Lazy::new(|| create_map());
                static STATS_MANAGER: Lazy<BoxStatsManager> = Lazy::new(|| create_stats_manager());

                thread_local! {
                    static TL_STATS: PerThread<BoxStatsManager> =
                        STATS_MAP.register(create_stats_manager());
                }

                $(
                    $crate::__struct_thread_local_init! { $stat_name, $stat_type, $($params)* }
                )*

                let __prefix = format!($key, $($pr_name),*);

                $name {
                    $($stat_name: $crate::__struct_field_init!(__prefix, $stat_name, $stat_type, $($params)*)),*
                }
            }
        }
        impl std::fmt::Debug for $name {
            fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(fmt, "<{}>", stringify!($name))
            }
        }
    }
}

#[macro_export]
#[doc(hidden)]
macro_rules! __struct_field_type {
    (singleton_counter) => {
        $crate::macros::common_macro_prelude::BoxSingletonCounter
    };
    (counter) => {
        $crate::macros::common_macro_prelude::BoxCounter
    };
    (timeseries) => {
        $crate::macros::common_macro_prelude::BoxTimeseries
    };
    (histogram) => {
        $crate::macros::common_macro_prelude::BoxHistogram
    };
    (quantile_stat) => {
        $crate::macros::common_macro_prelude::BoxHistogram
    };
}

#[macro_export]
#[doc(hidden)]
macro_rules! __struct_thread_local_init {
    ($name:ident, singleton_counter, ) => {
        $crate::__struct_thread_local_init!($name, singleton_counter, stringify!($name))
    };
    ($name:ident, singleton_counter, $key:expr) => {};

    ($name:ident, counter, ) => {
        $crate::__struct_thread_local_init! { $name, counter, stringify!($name)}
    };
    ($name:ident, counter, $key:expr) => {
        $crate::__struct_thread_local_init! { $name, counter, $key ; }
    };
    ($name:ident, counter, $key:expr ; ) => {
        thread_local! {
            static $name: FieldStatThreadLocal<BoxLocalCounter> = {

                fn __stat_generator(key: &str) -> BoxLocalCounter {
                    TL_STATS.with(|stats| {
                        stats.create_counter(key)
                    })
                }

                FieldStatThreadLocal::new(__stat_generator)
            };
        }
    };

    ($name:ident, timeseries, $( $aggregation_type:expr ),+) => {
        $crate::__struct_thread_local_init! { $name, timeseries, stringify!($name) ; $($aggregation_type),*}
    };
    ($name:ident, timeseries, $key:expr ; $( $aggregation_type:expr ),* ) => {
        $crate::__struct_thread_local_init! { $name, timeseries, $key ; $($aggregation_type),* ;}
    };
    ($name:ident, timeseries, $key:expr ; $( $aggregation_type:expr ),* ; $( $interval:expr ),* ) => {
        thread_local! {

            static $name: FieldStatThreadLocal<BoxLocalTimeseries> = {

                fn __stat_generator(key: &str) -> BoxLocalTimeseries {
                    TL_STATS.with(|stats| {
                        stats.create_timeseries(key, &[$( $aggregation_type ),*], &[$( $interval ),*])
                    })
                }

                FieldStatThreadLocal::new(__stat_generator)
            };
        }
    };

    ($name:ident, histogram,
        $bucket_width:expr, $min:expr, $max:expr $(, $aggregation_type:expr)*
        $(; P $percentile:expr )*) => {
        $crate::__struct_thread_local_init! { $name, histogram,
            stringify!($name) ; $bucket_width, $min, $max $(, $aggregation_type)*
            $(; P $percentile)* }
    };
    ($name:ident, histogram, $key:expr ;
        $bucket_width:expr, $min:expr, $max:expr $(, $aggregation_type:expr)*
        $(; P $percentile:expr )*) => {

        thread_local! {
            static $name: FieldStatThreadLocal<BoxLocalHistogram> = {

                fn __stat_generator(key: &str) -> BoxLocalHistogram {
                    TL_STATS.with(|stats| {
                        stats.create_histogram(key,
                                               &[$( $aggregation_type ),*],
                                               BucketConfig {
                                                   width: $bucket_width,
                                                   min: $min,
                                                   max: $max,
                                               },
                                               &[$( $percentile ),*])
                    })
                }

                FieldStatThreadLocal::new(__stat_generator)
            };
        }
    };
    ($name:ident, quantile_stat,
        $( $aggregation_type:expr ),*
        ; $( P $percentile:expr ),*
        ; $( $interval:expr ),*) => ();
    ($name:ident, quantile_stat, $key:expr
        ; $( $aggregation_type:expr ),*
        ; $( P $percentile:expr ),*
        ; $( $interval:expr ),*) => ();
}

#[macro_export]
#[doc(hidden)]
macro_rules! __struct_field_init {
    ($prefix:expr, $name:ident, singleton_counter, ) => {
        $crate::__struct_field_init!($prefix, $name, singleton_counter, stringify!($name))
    };
    ($prefix:expr, $name:ident, singleton_counter, $key:expr) => {{ create_singleton_counter(format!("{}.{}", $prefix, $key)) }};

    ($prefix:expr, $name:ident, counter, ) => {
        $crate::__struct_field_init!($prefix, $name, counter, stringify!($name) ;)
    };
    ($prefix:expr, $name:ident, counter, $key:expr) => {
        $crate::__struct_field_init!($prefix, $name, counter, $key ;)
    };
    ($prefix:expr, $name:ident, counter, $key:expr ; $(params:tt)*) => {{ Box::new(FieldStat::new(&$name, format!("{}.{}", $prefix, $key))) }};


    ($prefix:expr, $name:ident, timeseries, $( $aggregation_type:expr ),+) => {
        $crate::__struct_field_init!($prefix, $name, timeseries, stringify!($name) ; $($aggregation_type),*)
    };
    ($prefix:expr, $name:ident, timeseries, $key:expr ; $( $aggregation_type:expr ),* ) => {
        $crate::__struct_field_init!($prefix, $name, timeseries, $key ; $($aggregation_type),* ;)
    };
    ($prefix:expr, $name:ident, timeseries, $key:expr ; $( $aggregation_type:expr ),* ; $( $interval:expr ),* ) => {{
        Box::new(FieldStat::new(&$name, format!("{}.{}", $prefix, $key)))
    }};

    ($prefix:expr, $name:ident, histogram,
        $bucket_width:expr, $min:expr, $max:expr $(, $aggregation_type:expr)*
        $(; P $percentile:expr )*) => {
        $crate::__struct_field_init!($prefix, $name, histogram,
            stringify!($name) ; $bucket_width, $min, $max $(, $aggregation_type)*
            $(; P $percentile)*)
    };
    ($prefix:expr, $name:ident, histogram, $key:expr ;
        $bucket_width:expr, $min:expr, $max:expr $(, $aggregation_type:expr)*
        $(; P $percentile:expr )*) => {{ Box::new(FieldStat::new(&$name, format!("{}.{}", $prefix, $key))) }};
    ($prefix:expr, $name:ident, quantile_stat,
        $( $aggregation_type:expr ),*
        ; $( P $percentile:expr ),*
        ; $( $interval:expr ),*) => {
            $crate::__struct_field_init!($prefix, $name, quantile_stat,
                stringify!($name)
                ; $( $aggregation_type ),*
                ; $( P $percentile ),*
                ; $( $interval ),*)
    };
    ($prefix:expr, $name:ident, quantile_stat,
        $key:expr
        ; $( $aggregation_type:expr ),*
        ; $( P $percentile:expr ),*
        ; $( $interval:expr ),*) => {{
            STATS_MANAGER.create_quantile_stat(
                &$crate::__create_stat_key!($prefix, $key),
                &[$( $aggregation_type ),*],
                &[$( $percentile as f32 ),*],
                &[$( $interval ),*],
            )

    }};
}