apollo-router 2.13.1

A configurable, high-performance routing runtime for Apollo Federation 🚀
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
//! APIs for integrating with the router's metrics.
//!
//! The macros contained here are a replacement for the telemetry crate's `MetricsLayer`. We will
//! eventually convert all metrics to use these macros and deprecate the `MetricsLayer`.
//! The reason for this is that the `MetricsLayer` has:
//!
//! * No support for dynamic attributes
//! * No support dynamic metrics.
//! * Imperfect mapping to metrics API that can only be checked at runtime.
//!
//! New metrics should be added using these macros.
//!
//! Prefer using `_with_unit` types for all new macros. Units should conform to the
//! [OpenTelemetry semantic conventions](https://opentelemetry.io/docs/specs/semconv/general/metrics/#units),
//! some of which has been copied here for reference:
//! * Instruments that measure a count of something should only use annotations with curly braces to
//!   give additional meaning. For example, use `{packet}`, `{error}`, `{fault}`, etc., not `packet`,
//!   `error`, `fault`, etc.
//! * Other instrument units should be specified using the UCUM case sensitive (c/s) variant. For
//!   example, Cel for the unit with full name degree Celsius.
//! * When instruments are measuring durations, seconds (i.e. s) should be used.
//! * Instruments should use non-prefixed units (i.e. By instead of MiBy) unless there is good
//!   technical reason to not do so.
//!
//! NB: we have not yet modified the existing metrics because some metric exporters (notably
//! Prometheus) include the unit in the metric name, and changing the metric name will be a breaking
//! change for customers.
//!
//! ## Compatibility
//! This module uses types from the [opentelemetry] crates. Since OpenTelemetry for Rust is not yet
//! API-stable, we may update it in a minor version, which may require code changes to plugins.
//!
//!
//! # Examples
//! ```ignore
//! // Count a thing:
//! u64_counter!(
//!     "apollo.router.operations.frobbles",
//!     "The amount of frobbles we've operated on",
//!     1
//! );
//! // Count a thing with attributes:
//! u64_counter!(
//!     "apollo.router.operations.frobbles",
//!     "The amount of frobbles we've operated on",
//!     1,
//!     frobbles.color = "blue"
//! );
//! // Count a thing with dynamic attributes:
//! let attributes = vec![];
//! if (frobbled) {
//!     attributes.push(opentelemetry::KeyValue::new("frobbles.color".to_string(), "blue".into()));
//! }
//! u64_counter!(
//!     "apollo.router.operations.frobbles",
//!     "The amount of frobbles we've operated on",
//!     1,
//!     attributes
//! );
//! // Measure a thing with units:
//! f64_histogram_with_unit!(
//!     "apollo.router.operation.frobbles.time",
//!     "Duration to operate on frobbles",
//!     "s",
//!     1.0,
//!     frobbles.color = "red"
//! );
//! ```

#[cfg(test)]
use std::future::Future;
use std::marker::PhantomData;
#[cfg(test)]
use std::pin::Pin;
use std::sync::OnceLock;

#[cfg(test)]
use futures::FutureExt;
use opentelemetry::metrics::InstrumentProvider;

use crate::metrics::aggregation::AggregateMeterProvider;

pub(crate) mod aggregation;
pub(crate) mod filter;

/// A RAII guard for an up-down counter that automatically decrements on drop.
///
/// This guard implements the RAII (Resource Acquisition Is Initialization) pattern
/// to ensure that up-down counters are properly decremented when the guard goes out
/// of scope. This is particularly useful for tracking active operations, connections,
/// or other resources where the counter should reflect the current state.
///
/// It is essential that the same instrument is used for the decrement as was used for an increment
/// otherwise drift can occur.
#[derive(Debug)]
#[doc(hidden)]
#[must_use = "without holding the guard updown counters will immediately zero out"]
pub struct UpDownCounterGuard<T>
where
    T: std::ops::Neg<Output = T> + Copy,
{
    counter: opentelemetry::metrics::UpDownCounter<T>,
    value: T,
    attributes: Vec<opentelemetry::KeyValue>,
}

impl<T> UpDownCounterGuard<T>
where
    T: std::ops::Neg<Output = T> + Copy,
{
    /// Creates a new guard.
    #[doc(hidden)]
    pub fn new(
        counter: std::sync::Arc<opentelemetry::metrics::UpDownCounter<T>>,
        value: T,
        attributes: &[opentelemetry::KeyValue],
    ) -> Self {
        // Note that increment will already have been called via the macro, we only deal with drops
        // It is essential that we take the counter out of the arc otherwise it will break reload.
        // Instruments rely on weak references to allow callsite invalidation.
        // Therefore, if we hold onto the Arc then callsite invalidation won't work.
        Self {
            counter: (*counter).clone(),
            value,
            attributes: attributes.to_vec(),
        }
    }
}

impl<T> Drop for UpDownCounterGuard<T>
where
    T: std::ops::Neg<Output = T> + Copy,
{
    /// Decrements the counter when the guard is dropped.
    ///
    /// This automatically subtracts the original value from the counter,
    /// ensuring the metric accurately reflects the current state.
    fn drop(&mut self) {
        self.counter.add(-self.value, &self.attributes);
    }
}

/// Noop guard won't do anything. it serves to unify the logic UpDownCounterGuard
#[doc(hidden)]
pub struct NoopGuard<I, T> {
    _phantom: PhantomData<(I, T)>,
}
impl<I, T> NoopGuard<I, T> {
    /// Noop guard won't do anything. it serves to unify the logic UpDownCounterGuard
    #[doc(hidden)]
    pub fn new(_instrument: I, _value: T, _attributes: &[opentelemetry::KeyValue]) -> Self {
        NoopGuard {
            _phantom: Default::default(),
        }
    }
}

/// Noop InstrumentProvider - all methods use the default trait implementations
/// which return noop instruments.
// This can be replaced with NoopMeterProvider once the changes in
// https://github.com/open-telemetry/opentelemetry-rust/pull/3111
// are released.
struct NoopInstrumentProvider;
impl InstrumentProvider for NoopInstrumentProvider {}

#[cfg(test)]
pub(crate) mod test_utils {
    use std::cmp::Ordering;
    use std::collections::BTreeMap;
    use std::fmt::Debug;
    use std::fmt::Display;
    use std::sync::Arc;
    use std::sync::OnceLock;
    use std::sync::Weak;

    use itertools::Itertools;
    use num_traits::NumCast;
    use num_traits::ToPrimitive;
    use opentelemetry::Array;
    use opentelemetry::KeyValue;
    use opentelemetry::StringValue;
    use opentelemetry::Value;
    use opentelemetry_sdk::error::OTelSdkResult;
    use opentelemetry_sdk::metrics::InstrumentKind;
    use opentelemetry_sdk::metrics::ManualReader;
    use opentelemetry_sdk::metrics::MeterProviderBuilder;
    use opentelemetry_sdk::metrics::Pipeline;
    use opentelemetry_sdk::metrics::Temporality;
    use opentelemetry_sdk::metrics::data::AggregatedMetrics;
    use opentelemetry_sdk::metrics::data::GaugeDataPoint;
    use opentelemetry_sdk::metrics::data::HistogramDataPoint;
    use opentelemetry_sdk::metrics::data::Metric;
    use opentelemetry_sdk::metrics::data::MetricData;
    use opentelemetry_sdk::metrics::data::ResourceMetrics;
    use opentelemetry_sdk::metrics::data::SumDataPoint;
    use opentelemetry_sdk::metrics::reader::MetricReader;
    use serde::Serialize;
    use tokio::task_local;

    use crate::metrics::aggregation::AggregateMeterProvider;
    use crate::metrics::aggregation::MeterProviderType;
    use crate::metrics::filter::FilterMeterProvider;
    task_local! {
        pub(crate) static AGGREGATE_METER_PROVIDER_ASYNC: OnceLock<(AggregateMeterProvider, ClonableManualReader)>;
    }
    thread_local! {
        pub(crate) static AGGREGATE_METER_PROVIDER: OnceLock<(AggregateMeterProvider, ClonableManualReader)> = const { OnceLock::new() };
    }

    #[derive(Debug, Clone, Default)]
    pub(crate) struct ClonableManualReader {
        reader: Arc<ManualReader>,
    }

    impl MetricReader for ClonableManualReader {
        fn register_pipeline(&self, pipeline: Weak<Pipeline>) {
            self.reader.register_pipeline(pipeline)
        }

        fn collect(&self, rm: &mut ResourceMetrics) -> OTelSdkResult {
            self.reader.collect(rm)
        }

        fn force_flush(&self) -> OTelSdkResult {
            self.reader.force_flush()
        }

        fn shutdown_with_timeout(&self, timeout: std::time::Duration) -> OTelSdkResult {
            self.reader.shutdown_with_timeout(timeout)
        }

        fn temporality(&self, kind: InstrumentKind) -> Temporality {
            self.reader.temporality(kind)
        }
    }

    fn create_test_meter_provider() -> (AggregateMeterProvider, ClonableManualReader) {
        {
            let meter_provider = AggregateMeterProvider::default();
            let reader = ClonableManualReader::default();

            meter_provider.set(
                MeterProviderType::Public,
                FilterMeterProvider::all(
                    MeterProviderBuilder::default()
                        .with_reader(reader.clone())
                        .build(),
                ),
            );

            (meter_provider, reader)
        }
    }
    pub(crate) fn meter_provider_and_readers() -> (AggregateMeterProvider, ClonableManualReader) {
        if tokio::runtime::Handle::try_current().is_ok() {
            AGGREGATE_METER_PROVIDER_ASYNC
                .try_with(|cell| cell.get_or_init(create_test_meter_provider).clone())
                // We need to silently fail here.
                // Otherwise we fail every multi-threaded test that touches metrics
                .unwrap_or_default()
        } else {
            AGGREGATE_METER_PROVIDER
                .with(|cell| cell.get_or_init(create_test_meter_provider).clone())
        }
    }

    #[derive(Default)]
    pub(crate) struct Metrics {
        resource_metrics: ResourceMetrics,
    }

    pub(crate) fn collect_metrics() -> Metrics {
        let mut metrics = Metrics::default();
        let (_, reader) = meter_provider_and_readers();
        reader
            .collect(&mut metrics.resource_metrics)
            .expect("Failed to collect metrics. Did you forget to use `async{}.with_metrics()`? See dev-docs/metrics.md");
        metrics
    }

    impl Metrics {
        pub(crate) fn find(&self, name: &str) -> Option<&opentelemetry_sdk::metrics::data::Metric> {
            self.resource_metrics
                .scope_metrics()
                .flat_map(|scope_metrics| {
                    scope_metrics
                        .metrics()
                        .filter(|metric| metric.name() == name)
                })
                .next()
        }

        pub(crate) fn assert<T: NumCast + Display + 'static>(
            &self,
            name: &str,
            ty: MetricType,
            value: T,
            // Useful for histogram to check the count and not the sum
            count: bool,
            attributes: &[KeyValue],
        ) -> bool {
            if let Some(value) = value.to_u64()
                && self.metric_matches_u64(name, &ty, value, count, attributes)
            {
                return true;
            }

            if let Some(value) = value.to_i64()
                && self.metric_matches_i64(name, &ty, value, count, attributes)
            {
                return true;
            }

            if let Some(value) = value.to_f64()
                && self.metric_matches_f64(name, &ty, value, count, attributes)
            {
                return true;
            }

            false
        }

        fn metric_matches_u64(
            &self,
            name: &str,
            ty: &MetricType,
            value: u64,
            count: bool,
            attributes: &[KeyValue],
        ) -> bool {
            // Try ALL metrics with this name, not just the first one
            for scope_metrics in self.resource_metrics.scope_metrics() {
                for metric in scope_metrics.metrics().filter(|m| m.name() == name) {
                    if let AggregatedMetrics::U64(metric_data) = metric.data()
                        && Self::check_metric_data(metric_data, ty, value, count, attributes)
                    {
                        return true;
                    }
                }
            }
            false
        }

        fn metric_matches_i64(
            &self,
            name: &str,
            ty: &MetricType,
            value: i64,
            count: bool,
            attributes: &[KeyValue],
        ) -> bool {
            // Try ALL metrics with this name, not just the first one
            for scope_metrics in self.resource_metrics.scope_metrics() {
                for metric in scope_metrics.metrics().filter(|m| m.name() == name) {
                    if let AggregatedMetrics::I64(metric_data) = metric.data()
                        && Self::check_metric_data(metric_data, ty, value, count, attributes)
                    {
                        return true;
                    }
                }
            }
            false
        }

        fn metric_matches_f64(
            &self,
            name: &str,
            ty: &MetricType,
            value: f64,
            count: bool,
            attributes: &[KeyValue],
        ) -> bool {
            // Try ALL metrics with this name across all scopes
            // (there can be multiple metrics with the same name but different types)
            for scope_metrics in self.resource_metrics.scope_metrics() {
                for metric in scope_metrics.metrics().filter(|m| m.name() == name) {
                    if let AggregatedMetrics::F64(metric_data) = metric.data()
                        && Self::check_metric_data(metric_data, ty, value, count, attributes)
                    {
                        return true;
                    }
                }
            }
            false
        }

        fn check_metric_data<T: Debug + PartialEq + Display + Copy + ToPrimitive + 'static>(
            metric_data: &MetricData<T>,
            ty: &MetricType,
            value: T,
            count: bool,
            attributes: &[KeyValue],
        ) -> bool {
            match metric_data {
                MetricData::Gauge(gauge) => {
                    if matches!(ty, MetricType::Gauge) {
                        return gauge.data_points().any(|datapoint| {
                            datapoint.value() == value
                                && Self::equal_attributes(attributes, datapoint.attributes())
                        });
                    }
                }
                MetricData::Sum(sum) => {
                    if matches!(ty, MetricType::Counter | MetricType::UpDownCounter) {
                        return sum.data_points().any(|datapoint| {
                            datapoint.value() == value
                                && Self::equal_attributes(attributes, datapoint.attributes())
                        });
                    }
                }
                MetricData::Histogram(histogram) => {
                    if matches!(ty, MetricType::Histogram) {
                        if count {
                            return histogram.data_points().any(|datapoint| {
                                datapoint.count() == value.to_u64().unwrap()
                                    && Self::equal_attributes(attributes, datapoint.attributes())
                            });
                        } else {
                            return histogram.data_points().any(|datapoint| {
                                datapoint.sum() == value
                                    && Self::equal_attributes(attributes, datapoint.attributes())
                            });
                        }
                    }
                }
                MetricData::ExponentialHistogram(_) => {}
            }
            false
        }

        #[must_use]
        pub(crate) fn metric_exists(
            &self,
            name: &str,
            ty: MetricType,
            attributes: &[KeyValue],
        ) -> bool {
            if let Some(metric) = self.find(name) {
                match metric.data() {
                    AggregatedMetrics::U64(metric_data) => {
                        return Self::check_metric_exists(metric_data, &ty, attributes);
                    }
                    AggregatedMetrics::I64(metric_data) => {
                        return Self::check_metric_exists(metric_data, &ty, attributes);
                    }
                    AggregatedMetrics::F64(metric_data) => {
                        return Self::check_metric_exists(metric_data, &ty, attributes);
                    }
                }
            }
            false
        }

        fn check_metric_exists<T: Debug + PartialEq + Display + Copy + 'static>(
            metric_data: &MetricData<T>,
            ty: &MetricType,
            attributes: &[KeyValue],
        ) -> bool {
            match metric_data {
                MetricData::Gauge(gauge) => {
                    if matches!(ty, MetricType::Gauge) {
                        return gauge.data_points().any(|datapoint| {
                            Self::equal_attributes(attributes, datapoint.attributes())
                        });
                    }
                }
                MetricData::Sum(sum) => {
                    if matches!(ty, MetricType::Counter | MetricType::UpDownCounter) {
                        return sum.data_points().any(|datapoint| {
                            Self::equal_attributes(attributes, datapoint.attributes())
                        });
                    }
                }
                MetricData::Histogram(histogram) => {
                    if matches!(ty, MetricType::Histogram) {
                        return histogram.data_points().any(|datapoint| {
                            Self::equal_attributes(attributes, datapoint.attributes())
                        });
                    }
                }
                MetricData::ExponentialHistogram(_) => {}
            }
            false
        }

        #[allow(dead_code)]
        pub(crate) fn all(&self) -> Vec<SerdeMetric> {
            self.resource_metrics
                .scope_metrics()
                .flat_map(|scope_metrics| {
                    scope_metrics.metrics().map(|metric| {
                        let serde_metric: SerdeMetric = metric.into();
                        serde_metric
                    })
                })
                .sorted()
                .collect()
        }

        #[allow(dead_code)]
        pub(crate) fn non_zero(&self) -> Vec<SerdeMetric> {
            self.all()
                .into_iter()
                .filter(|m| {
                    m.data.datapoints.iter().any(|d| {
                        d.value
                            .as_ref()
                            .map(|v| v.as_f64().unwrap_or_default() > 0.0)
                            .unwrap_or_default()
                            || d.sum
                                .as_ref()
                                .map(|v| v.as_f64().unwrap_or_default() > 0.0)
                                .unwrap_or_default()
                    })
                })
                .collect()
        }

        fn equal_attributes<'a>(
            expected: &[KeyValue],
            actual: impl Iterator<Item = &'a KeyValue>,
        ) -> bool {
            let mut actual_vec: Vec<_> = actual.collect();
            // If lengths are different, we can short circuit. This also accounts for a bug where
            // an empty attributes list would always be considered "equal" due to zip capping at
            // the shortest iter's length
            if expected.len() != actual_vec.len() {
                return false;
            }
            // Sort both sides by key for comparison (attributes may not be in same order)
            let mut expected_sorted: Vec<_> = expected.iter().collect();
            expected_sorted.sort_by(|a, b| a.key.cmp(&b.key));
            actual_vec.sort_by(|a, b| a.key.cmp(&b.key));

            expected_sorted
                .iter()
                .zip(actual_vec.iter())
                .all(|(exp, act)| {
                    exp.key == act.key
                        && (exp.value == act.value
                            || exp.value == Value::String(StringValue::from("<any>")))
                })
        }
    }

    #[derive(Serialize, Eq, PartialEq)]
    pub(crate) struct SerdeMetric {
        pub(crate) name: String,
        #[serde(skip_serializing_if = "String::is_empty")]
        pub(crate) description: String,
        #[serde(skip_serializing_if = "String::is_empty")]
        pub(crate) unit: String,
        pub(crate) data: SerdeMetricData,
    }

    impl Ord for SerdeMetric {
        fn cmp(&self, other: &Self) -> Ordering {
            self.name.cmp(&other.name)
        }
    }

    impl PartialOrd for SerdeMetric {
        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
            Some(self.cmp(other))
        }
    }

    #[derive(Clone, Serialize, Eq, PartialEq, Default)]
    pub(crate) struct SerdeMetricData {
        pub(crate) datapoints: Vec<SerdeMetricDataPoint>,
    }

    #[derive(Clone, Serialize, Eq, PartialEq)]
    pub(crate) struct SerdeMetricDataPoint {
        #[serde(skip_serializing_if = "Option::is_none")]
        pub(crate) value: Option<serde_json::Value>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub(crate) sum: Option<serde_json::Value>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub(crate) count: Option<u64>,
        pub(crate) attributes: BTreeMap<String, serde_json::Value>,
    }

    impl Ord for SerdeMetricDataPoint {
        fn cmp(&self, other: &Self) -> Ordering {
            //Horribly inefficient, but it's just for testing
            let self_string = serde_json::to_string(&self.attributes).expect("serde failed");
            let other_string = serde_json::to_string(&other.attributes).expect("serde failed");
            self_string.cmp(&other_string)
        }
    }

    impl PartialOrd for SerdeMetricDataPoint {
        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
            Some(self.cmp(other))
        }
    }

    impl SerdeMetricData {
        fn extract_datapoints_f64(metric_data: &mut SerdeMetricData, value: &MetricData<f64>) {
            match value {
                MetricData::Gauge(gauge) => {
                    gauge.data_points().for_each(|datapoint| {
                        metric_data.datapoints.push(datapoint.into());
                    });
                }
                MetricData::Sum(sum) => {
                    sum.data_points().for_each(|datapoint| {
                        metric_data.datapoints.push(datapoint.into());
                    });
                }
                MetricData::Histogram(histogram) => {
                    histogram.data_points().for_each(|datapoint| {
                        metric_data.datapoints.push(datapoint.into());
                    });
                }
                MetricData::ExponentialHistogram(_) => {}
            }
        }

        fn extract_datapoints_u64(metric_data: &mut SerdeMetricData, value: &MetricData<u64>) {
            match value {
                MetricData::Gauge(gauge) => {
                    gauge.data_points().for_each(|datapoint| {
                        metric_data.datapoints.push(datapoint.into());
                    });
                }
                MetricData::Sum(sum) => {
                    sum.data_points().for_each(|datapoint| {
                        metric_data.datapoints.push(datapoint.into());
                    });
                }
                MetricData::Histogram(histogram) => {
                    histogram.data_points().for_each(|datapoint| {
                        metric_data.datapoints.push(datapoint.into());
                    });
                }
                MetricData::ExponentialHistogram(_) => {}
            }
        }

        fn extract_datapoints_i64(metric_data: &mut SerdeMetricData, value: &MetricData<i64>) {
            match value {
                MetricData::Gauge(gauge) => {
                    gauge.data_points().for_each(|datapoint| {
                        metric_data.datapoints.push(datapoint.into());
                    });
                }
                MetricData::Sum(sum) => {
                    sum.data_points().for_each(|datapoint| {
                        metric_data.datapoints.push(datapoint.into());
                    });
                }
                MetricData::Histogram(histogram) => {
                    histogram.data_points().for_each(|datapoint| {
                        metric_data.datapoints.push(datapoint.into());
                    });
                }
                MetricData::ExponentialHistogram(_) => {}
            }
        }
    }

    impl From<&Metric> for SerdeMetric {
        fn from(value: &Metric) -> Self {
            let mut serde_metric = SerdeMetric {
                name: value.name().to_string(),
                description: value.description().to_string(),
                unit: value.unit().to_string(),
                data: value.data().into(),
            };
            // Sort the datapoints so that we can compare them
            serde_metric.data.datapoints.sort();

            // Redact duration metrics;
            if serde_metric.name.ends_with(".duration") {
                serde_metric
                    .data
                    .datapoints
                    .iter_mut()
                    .for_each(|datapoint| {
                        if let Some(sum) = &datapoint.sum
                            && sum.as_f64().unwrap_or_default() > 0.0
                        {
                            datapoint.sum = Some(0.1.into());
                        }
                    });
            }
            serde_metric
        }
    }

    impl<T> From<&GaugeDataPoint<T>> for SerdeMetricDataPoint
    where
        T: Into<serde_json::Value> + Copy,
    {
        fn from(value: &GaugeDataPoint<T>) -> Self {
            SerdeMetricDataPoint {
                value: Some(value.value().into()),
                sum: None,
                count: None,
                attributes: value
                    .attributes()
                    .map(|kv| (kv.key.to_string(), Self::convert(&kv.value)))
                    .collect(),
            }
        }
    }

    impl<T> From<&SumDataPoint<T>> for SerdeMetricDataPoint
    where
        T: Into<serde_json::Value> + Copy,
    {
        fn from(value: &SumDataPoint<T>) -> Self {
            SerdeMetricDataPoint {
                value: Some(value.value().into()),
                sum: None,
                count: None,
                attributes: value
                    .attributes()
                    .map(|kv| (kv.key.to_string(), Self::convert(&kv.value)))
                    .collect(),
            }
        }
    }

    impl SerdeMetricDataPoint {
        pub(crate) fn convert(v: &Value) -> serde_json::Value {
            match v.clone() {
                Value::Bool(v) => v.into(),
                Value::I64(v) => v.into(),
                Value::F64(v) => v.into(),
                Value::String(v) => v.to_string().into(),
                Value::Array(v) => match v {
                    Array::Bool(v) => v.into(),
                    Array::I64(v) => v.into(),
                    Array::F64(v) => v.into(),
                    Array::String(v) => v.iter().map(|v| v.to_string()).collect::<Vec<_>>().into(),
                    _ => unreachable!("unexpected opentelemetry::Array variant"),
                },
                _ => unreachable!("unexpected opentelemetry::Value variant"),
            }
        }
    }

    impl<T> From<&HistogramDataPoint<T>> for SerdeMetricDataPoint
    where
        T: Into<serde_json::Value> + Copy,
    {
        fn from(value: &HistogramDataPoint<T>) -> Self {
            SerdeMetricDataPoint {
                sum: Some(value.sum().into()),
                value: None,
                count: Some(value.count()),
                attributes: value
                    .attributes()
                    .map(|kv| (kv.key.to_string(), Self::convert(&kv.value)))
                    .collect(),
            }
        }
    }

    impl From<&AggregatedMetrics> for SerdeMetricData {
        fn from(value: &AggregatedMetrics) -> Self {
            let mut metric_data = SerdeMetricData::default();
            match value {
                AggregatedMetrics::F64(data) => {
                    Self::extract_datapoints_f64(&mut metric_data, data)
                }
                AggregatedMetrics::U64(data) => {
                    Self::extract_datapoints_u64(&mut metric_data, data)
                }
                AggregatedMetrics::I64(data) => {
                    Self::extract_datapoints_i64(&mut metric_data, data)
                }
            }
            metric_data
        }
    }

    pub(crate) enum MetricType {
        Counter,
        UpDownCounter,
        Histogram,
        Gauge,
    }
}

/// Returns a MeterProvider, as a concrete type so we can use our own extensions.
///
/// During tests this is a task local so that we can test metrics without having to worry about other tests interfering.
#[cfg(test)]
pub(crate) fn meter_provider_internal() -> AggregateMeterProvider {
    test_utils::meter_provider_and_readers().0
}

#[cfg(test)]
pub(crate) use test_utils::collect_metrics;

#[cfg(not(test))]
static AGGREGATE_METER_PROVIDER: OnceLock<AggregateMeterProvider> = OnceLock::new();

/// Returns the currently configured global MeterProvider, as a concrete type
/// so we can use our own extensions.
#[cfg(not(test))]
pub(crate) fn meter_provider_internal() -> AggregateMeterProvider {
    AGGREGATE_METER_PROVIDER
        .get_or_init(Default::default)
        .clone()
}

/// Returns the currently configured global [`MeterProvider`].
///
/// See the [module-level documentation] for important details on the semver-compatibility guarantees of this API.
///
/// [`MeterProvider`]: opentelemetry::metrics::MeterProvider
/// [module-level documentation]: crate::metrics
pub fn meter_provider() -> impl opentelemetry::metrics::MeterProvider {
    meter_provider_internal()
}

/// Parse key/value attributes into `opentelemetry::KeyValue` structs. Should only be used within
/// this module, as a helper for the various metric macros (ie `u64_counter!`).
macro_rules! parse_attributes {
    ($($attr_key:literal = $attr_value:expr),+) => {[$(opentelemetry::KeyValue::new($attr_key, $attr_value)),+]};
    ($($($attr_key:ident).+ = $attr_value:expr),+) => {[$(opentelemetry::KeyValue::new(stringify!($($attr_key).+), $attr_value)),+]};
    ($attrs:expr) => {$attrs};
}

/// Get or create a `u64` monotonic counter metric and add a value to it.
/// The metric must include a description.
///
/// See the [module-level documentation](crate::metrics) for examples and details on the reasoning
/// behind this API.
#[allow(unused_macros)]
#[deprecated(since = "TBD", note = "use `u64_counter_with_unit` instead")]
macro_rules! u64_counter {
    ($($name:ident).+, $description:literal, $value: expr, $($attrs:tt)*) => {
        metric!(u64, counter, crate::metrics::NoopGuard, add, stringify!($($name).+), $description, $value, parse_attributes!($($attrs)*));
    };

    ($name:literal, $description:literal, $value: expr, $($attrs:tt)*) => {
        metric!(u64, counter, crate::metrics::NoopGuard, add, $name, $description, $value, parse_attributes!($($attrs)*));
    };

    ($name:literal, $description:literal, $value: expr) => {
        metric!(u64, counter, crate::metrics::NoopGuard, add, $name, $description, $value, []);
    }
}

/// Get or create a u64 monotonic counter metric and add a value to it.
/// The metric must include a description and a unit.
///
/// The units should conform to the [OpenTelemetry semantic conventions](https://opentelemetry.io/docs/specs/semconv/general/metrics/#units).
///
/// See the [module-level documentation](crate::metrics) for examples and details on the reasoning
/// behind this API.
#[allow(unused_macros)]
macro_rules! u64_counter_with_unit {
    ($($name:ident).+, $description:literal, $unit:literal, $value: expr, $($attrs:tt)*) => {
        metric!(u64, counter, crate::metrics::NoopGuard, add, stringify!($($name).+), $description, $unit, $value, parse_attributes!($($attrs)*));
    };

    ($name:literal, $description:literal, $unit:literal, $value: expr, $($attrs:tt)*) => {
        metric!(u64, counter, crate::metrics::NoopGuard, add, $name, $description, $unit, $value, parse_attributes!($($attrs)*));
    };

    ($name:literal, $description:literal, $unit:literal, $value: expr) => {
        metric!(u64, counter, crate::metrics::NoopGuard, add, $name, $description, $unit, $value, []);
    }
}

/// Get or create a f64 monotonic counter metric and add a value to it.
/// The metric must include a description.
///
/// See the [module-level documentation](crate::metrics) for examples and details on the reasoning
/// behind this API.
#[allow(unused_macros)]
#[deprecated(since = "TBD", note = "use `f64_counter_with_unit` instead")]
macro_rules! f64_counter {
    ($($name:ident).+, $description:literal, $value: expr, $($attrs:tt)*) => {
        metric!(f64, counter, crate::metrics::NoopGuard, add, stringify!($($name).+), $description, $value, parse_attributes!($($attrs)*));
    };

    ($name:literal, $description:literal, $value: expr, $($attrs:tt)*) => {
        metric!(f64, counter, crate::metrics::NoopGuard, add, $name, $description, $value, parse_attributes!($($attrs)*));
    };

    ($name:literal, $description:literal, $value: expr) => {
        metric!(f64, counter, crate::metrics::NoopGuard, add, $name, $description, $value, []);
    }
}

/// Get or create an f64 monotonic counter metric and add a value to it.
/// The metric must include a description and a unit.
///
/// The units should conform to the [OpenTelemetry semantic conventions](https://opentelemetry.io/docs/specs/semconv/general/metrics/#units).
///
/// See the [module-level documentation](crate::metrics) for examples and details on the reasoning
/// behind this API.
#[allow(unused_macros)]
macro_rules! f64_counter_with_unit {
    ($($name:ident).+, $description:literal, $unit:literal, $value: expr, $($attrs:tt)*) => {
        metric!(f64, counter, crate::metrics::NoopGuard, add, stringify!($($name).+), $description, $unit, $value, parse_attributes!($($attrs)*));
    };

    ($name:literal, $description:literal, $unit:literal, $value: expr, $($attrs:tt)*) => {
        metric!(f64, counter, crate::metrics::NoopGuard, add, $name, $description, $unit, $value, parse_attributes!($($attrs)*));
    };

    ($name:literal, $description:literal, $unit:literal, $value: expr) => {
        metric!(f64, counter, crate::metrics::NoopGuard, add, $name, $description, $unit, $value, []);
    }
}

/// Creates or retrieves an i64 up-down counter and returns a RAII guard.
///
/// This macro increments the counter immediately and returns an [`I64UpDownCounterGuard`]
/// that automatically decrements the counter when dropped. This ensures accurate tracking
/// of active resources, operations, or connections.
///
/// **Important:** The returned guard must be stored in a variable to keep the counter
/// incremented. If the guard is immediately dropped, the counter will be decremented.
///
/// # Returns
///
/// An [`I64UpDownCounterGuard`] that decrements the counter on drop.
///
/// # Examples
///
/// ```ignore
/// // Counter is incremented to 1
/// let _guard = i64_up_down_counter!(
///     "active_connections",
///     "Number of active connections",
///     1,
///     connection.type = "websocket"
/// );
/// // Counter remains at 1 while _guard is in scope
///
/// // When _guard is dropped, counter is automatically decremented back to 0
/// ```
///
/// See the [module-level documentation](crate::metrics) for more details.
#[allow(unused_macros)]
#[deprecated(since = "TBD", note = "use `i64_up_down_counter_with_unit` instead")]
macro_rules! i64_up_down_counter {
    ($($name:ident).+, $description:literal, $value: expr, $($attrs:tt)*) => {
        metric!(i64, up_down_counter, crate::metrics::UpDownCounterGuard::<i64>, add, stringify!($($name).+), $description, $value, parse_attributes!($($attrs)*))
    };

    ($name:literal, $description:literal, $value: expr, $($attrs:tt)*) => {
        metric!(i64, up_down_counter, crate::metrics::UpDownCounterGuard::<i64>, add, $name, $description, $value, parse_attributes!($($attrs)*))
    };

    ($name:literal, $description:literal, $value: expr) => {
        metric!(i64, up_down_counter, crate::metrics::UpDownCounterGuard::<i64>, add, $name, $description, $value, [])
    };
}

/// Creates or retrieves an i64 up-down counter with a unit and returns a RAII guard.
///
/// This macro increments the counter immediately and returns an [`UpDownCounterGuard<i64>`]
/// that automatically decrements the counter when dropped. This ensures accurate tracking
/// of active resources, operations, or connections.
///
/// The units should conform to the [OpenTelemetry semantic conventions](https://opentelemetry.io/docs/specs/semconv/general/metrics/#units).
///
/// **Important:** The returned guard must be stored in a variable to keep the counter
/// incremented. If the guard is immediately dropped, the counter will be decremented.
///
/// # Returns
///
/// An [`UpDownCounterGuard<i64>`] that decrements the counter on drop.
///
/// # Examples
///
/// ```ignore
/// // Counter is incremented to 1
/// let _active_job = i64_up_down_counter_with_unit!(
///     "compute.active_jobs",
///     "Number of active computation jobs",
///     "{job}",
///     1,
///     job.type = "query_planning"
/// );
/// // Counter remains at 1 while _active_job is in scope
///
/// // When _active_job is dropped, counter is automatically decremented back to 0
/// ```
///
/// See the [module-level documentation](crate::metrics) for more details.
#[allow(unused_macros)]
macro_rules! i64_up_down_counter_with_unit {
    ($($name:ident).+, $description:literal, $unit:literal, $value: expr, $($attrs:tt)*) => {
        metric!(i64, up_down_counter, crate::metrics::UpDownCounterGuard::<i64>, add, stringify!($($name).+), $description, $unit, $value, parse_attributes!($($attrs)*))
    };

    ($name:literal, $description:literal, $unit:literal, $value: expr, $($attrs:tt)*) => {
        metric!(i64, up_down_counter, crate::metrics::UpDownCounterGuard::<i64>, add, $name, $description, $unit, $value, parse_attributes!($($attrs)*))
    };

    ($name:literal, $description:literal, $unit:literal, $value: expr) => {
        metric!(i64, up_down_counter, crate::metrics::UpDownCounterGuard::<i64>, add, $name, $description, $unit, $value, [])
    }
}

/// Creates or retrieves an f64 up-down counter and returns a RAII guard.
///
/// This macro increments the counter immediately and returns an [`UpDownCounterGuard<f64>`]
/// that automatically decrements the counter when dropped. This ensures accurate tracking
/// of active resources, operations, or connections.
///
/// **Important:** The returned guard must be stored in a variable to keep the counter
/// incremented. If the guard is immediately dropped, the counter will be decremented.
///
/// # Returns
///
/// An [`UpDownCounterGuard<f64>`] that decrements the counter on drop.
///
/// # Examples
///
/// ```ignore
/// // Counter is incremented by 1.5
/// let _guard = f64_up_down_counter!(
///     "active_load",
///     "Current system load",
///     1.5,
///     load.type = "cpu"
/// );
/// // Counter remains at 1.5 while _guard is in scope
///
/// // When _guard is dropped, counter is automatically decremented by 1.5
/// ```
///
/// See the [module-level documentation](crate::metrics) for more details.
#[allow(unused_macros)]
#[deprecated(since = "TBD", note = "use `f64_up_down_counter_with_unit` instead")]
macro_rules! f64_up_down_counter {
    ($($name:ident).+, $description:literal, $value: expr, $($attrs:tt)*) => {
        metric!(f64, up_down_counter, crate::metrics::UpDownCounterGuard::<f64>, add, stringify!($($name).+), $description, $value, parse_attributes!($($attrs)*))
    };

    ($name:literal, $description:literal, $value: expr, $($attrs:tt)*) => {
        metric!(f64, up_down_counter, crate::metrics::UpDownCounterGuard::<f64>, add, $name, $description, $value, parse_attributes!($($attrs)*))
    };

    ($name:literal, $description:literal, $value: expr) => {
        metric!(f64, up_down_counter, crate::metrics::UpDownCounterGuard::<f64>, add, $name, $description, $value, [])
    };
}

/// Creates or retrieves an f64 up-down counter with a unit and returns a RAII guard.
///
/// This macro increments the counter immediately and returns an [`UpDownCounterGuard<f64>`]
/// that automatically decrements the counter when dropped. This ensures accurate tracking
/// of active resources, operations, or connections.
///
/// The units should conform to the [OpenTelemetry semantic conventions](https://opentelemetry.io/docs/specs/semconv/general/metrics/#units).
///
/// **Important:** The returned guard must be stored in a variable to keep the counter
/// incremented. If the guard is immediately dropped, the counter will be decremented.
///
/// # Returns
///
/// An [`UpDownCounterGuard<f64>`] that decrements the counter on drop.
///
/// # Examples
///
/// ```ignore
/// // Counter is incremented by 2.5
/// let _memory_usage = f64_up_down_counter_with_unit!(
///     "memory.active_usage",
///     "Active memory usage",
///     "MB",
///     2.5,
///     memory.type = "heap"
/// );
/// // Counter remains at 2.5 while _memory_usage is in scope
///
/// // When _memory_usage is dropped, counter is automatically decremented by 2.5
/// ```
///
/// See the [module-level documentation](crate::metrics) for more details.
#[allow(unused_macros)]
macro_rules! f64_up_down_counter_with_unit {
    ($($name:ident).+, $description:literal, $unit:literal, $value: expr, $($attrs:tt)*) => {
        metric!(f64, up_down_counter, crate::metrics::UpDownCounterGuard::<f64>, add, stringify!($($name).+), $description, $unit, $value, parse_attributes!($($attrs)*))
    };

    ($name:literal, $description:literal, $unit:literal, $value: expr, $($attrs:tt)*) => {
        metric!(f64, up_down_counter, crate::metrics::UpDownCounterGuard::<f64>, add, $name, $description, $unit, $value, parse_attributes!($($attrs)*))
    };

    ($name:literal, $description:literal, $unit:literal, $value: expr) => {
        metric!(f64, up_down_counter, crate::metrics::UpDownCounterGuard::<f64>, add, $name, $description, $unit, $value, [])
    }
}

/// Get or create an f64 histogram metric and add a value to it.
/// The metric must include a description.
///
/// See the [module-level documentation](crate::metrics) for examples and details on the reasoning
/// behind this API.
#[allow(unused_macros)]
#[deprecated(since = "TBD", note = "use `f64_histogram_with_unit` instead")]
macro_rules! f64_histogram {
    ($($name:ident).+, $description:literal, $value: expr, $($attrs:tt)*) => {
        metric!(f64, histogram, crate::metrics::NoopGuard, record, stringify!($($name).+), $description, $value, parse_attributes!($($attrs)*));
    };

    ($name:literal, $description:literal, $value: expr, $($attrs:tt)*) => {
        metric!(f64, histogram, crate::metrics::NoopGuard,record, $name, $description, $value, parse_attributes!($($attrs)*));
    };

    ($name:literal, $description:literal, $value: expr) => {
        metric!(f64, histogram, crate::metrics::NoopGuard,record, $name, $description, $value, []);
    };
}

/// Get or create an f64 histogram metric and add a value to it.
/// The metric must include a description and a unit.
///
/// The units should conform to the [OpenTelemetry semantic conventions](https://opentelemetry.io/docs/specs/semconv/general/metrics/#units).
///
/// See the [module-level documentation](crate::metrics) for examples and details on the reasoning
/// behind this API.
///
/// ## Caveat
///
/// Two metrics with the same name but different descriptions and/or units will be created as
/// _separate_ metrics.
///
/// ```ignore
/// f64_histogram_with_unit!("test", "test description", "s", 1.0, "attr" = "val");
/// assert_histogram_sum!("test", 1, "attr" = "val");
///
/// f64_histogram_with_unit!("test", "test description", "Hz", 1.0, "attr" = "val");
/// assert_histogram_sum!("test", 1, "attr" = "val");
/// ```
#[allow(unused_macros)]
macro_rules! f64_histogram_with_unit {
    ($($name:ident).+, $description:literal, $unit:literal, $value: expr, $($attrs:tt)*) => {
        metric!(f64, histogram, crate::metrics::NoopGuard, record, stringify!($($name).+), $description, $unit, $value, parse_attributes!($($attrs)*));
    };

    ($name:literal, $description:literal, $unit:literal, $value: expr, $($attrs:tt)*) => {
        metric!(f64, histogram, crate::metrics::NoopGuard, record, $name, $description, $unit, $value, parse_attributes!($($attrs)*));
    };

    ($name:literal, $description:literal, $unit:literal, $value: expr) => {
        metric!(f64, histogram, crate::metrics::NoopGuard, record, $name, $description, $unit, $value, []);
    };
}

/// Get or create a u64 histogram metric and add a value to it.
/// The metric must include a description.
///
/// See the [module-level documentation](crate::metrics) for examples and details on the reasoning
/// behind this API.
#[allow(unused_macros)]
#[deprecated(since = "TBD", note = "use `u64_histogram_with_unit` instead")]
macro_rules! u64_histogram {
    ($($name:ident).+, $description:literal, $value: expr, $($attrs:tt)*) => {
        metric!(u64, histogram, crate::metrics::NoopGuard, record, stringify!($($name).+), $description, $value, parse_attributes!($($attrs)*));
    };

    ($name:literal, $description:literal, $value: expr, $($attrs:tt)*) => {
        metric!(u64, histogram, crate::metrics::NoopGuard, record, $name, $description, $value, parse_attributes!($($attrs)*));
    };

    ($name:literal, $description:literal, $value: expr) => {
        metric!(u64, histogram, crate::metrics::NoopGuard, record, $name, $description, $value, []);
    };
}

/// Get or create a u64 histogram metric and add a value to it.
/// The metric must include a description and a unit.
///
/// The units should conform to the [OpenTelemetry semantic conventions](https://opentelemetry.io/docs/specs/semconv/general/metrics/#units).
///
/// See the [module-level documentation](crate::metrics) for examples and details on the reasoning
/// behind this API.
#[allow(unused_macros)]
macro_rules! u64_histogram_with_unit {
    ($($name:ident).+, $description:literal, $unit:literal, $value: expr, $($attrs:tt)*) => {
        metric!(u64, histogram, crate::metrics::NoopGuard, record, stringify!($($name).+), $description, $unit, $value, parse_attributes!($($attrs)*));
    };

    ($name:literal, $description:literal, $unit:literal, $value: expr, $($attrs:tt)*) => {
        metric!(u64, histogram, crate::metrics::NoopGuard, record, $name, $description, $unit, $value, parse_attributes!($($attrs)*));
    };

    ($name:literal, $description:literal, $unit:literal, $value: expr) => {
        metric!(u64, histogram, crate::metrics::NoopGuard, record, $name, $description, $unit, $value, []);
    };
}

thread_local! {
    // This is used exactly once in testing callsite caching.
    #[cfg(test)]
    pub(crate) static CACHE_CALLSITE: std::sync::atomic::AtomicBool = const {std::sync::atomic::AtomicBool::new(false)};
}
macro_rules! metric {
    ($ty:ident, $instrument:ident, $guard: ty, $mutation:ident, $name:expr, $description:literal, $unit:literal, $value:expr, $attrs:expr) => {
        // The way this works is that we have a static at each call site that holds a weak reference to the instrument.
        // We make a call we try to upgrade the weak reference. If it succeeds we use the instrument.
        // Otherwise we create a new instrument and update the static.
        // The aggregate meter provider is used to hold on to references of all instruments that have been created and will clear references when the underlying configuration has changed.
        // There is a Mutex involved, however it is only locked for the duration of the upgrade once the instrument has been created.
        // The Reason a Mutex is used rather than an RwLock is that we are not holding the lock for any significant period of time and the cost of an RwLock is potentially higher.
        // If we profile and deem it's worth switching to RwLock then we can do that.

        paste::paste! {
            {
                // There is a single test for caching callsites. Other tests do not cache because they will interfere with each other due to them using a task local meter provider to aid testing.
                #[cfg(test)]
                let cache_callsite = crate::metrics::CACHE_CALLSITE.with(|cell| cell.load(std::sync::atomic::Ordering::SeqCst));

                // The compiler will optimize this in non test builds
                #[cfg(not(test))]
                let cache_callsite = true;

                let create_instrument_fn = |meter: opentelemetry::metrics::Meter| {
                    let mut builder = meter.[<$ty _ $instrument>]($name);
                    builder = builder.with_description($description);

                    if !$unit.is_empty() {
                        builder = builder.with_unit($unit);
                    }

                    builder.build()
                };

                if cache_callsite {
                    static INSTRUMENT_CACHE: std::sync::OnceLock<parking_lot::Mutex<std::sync::Weak<opentelemetry::metrics::[<$instrument:camel>]<$ty>>>> = std::sync::OnceLock::new();

                    let mut instrument_guard = INSTRUMENT_CACHE
                        .get_or_init(|| {
                            let meter_provider = crate::metrics::meter_provider_internal();
                            let instrument_ref = meter_provider.create_registered_instrument(|p| create_instrument_fn(p.meter("apollo/router")));
                            parking_lot::Mutex::new(std::sync::Arc::downgrade(&instrument_ref))
                        })
                        .lock();
                    let instrument = if let Some(instrument) = instrument_guard.upgrade() {
                        // Fast path, we got the instrument, drop the mutex guard immediately.
                        drop(instrument_guard);
                        instrument
                    } else {
                        // Slow path, we need to obtain the instrument again.
                        let meter_provider = crate::metrics::meter_provider_internal();
                        let instrument_ref = meter_provider.create_registered_instrument(|p| create_instrument_fn(p.meter("apollo/router")));
                        *instrument_guard = std::sync::Arc::downgrade(&instrument_ref);
                        // We've updated the instrument and got a strong reference to it. We can drop the mutex guard now.
                        drop(instrument_guard);
                        instrument_ref
                    };
                    let attrs : &[opentelemetry::KeyValue] = &$attrs;
                    instrument.$mutation($value, attrs);
                    $guard::new(instrument.clone(), $value, attrs)
                }
                else {
                    // This is only for testing.
                    // The reason it is not cfg test is that we have a legitimate test for callsite caching though
                    // cache_callsite is always true for not test
                    let meter_provider = crate::metrics::meter_provider();
                    let meter = opentelemetry::metrics::MeterProvider::meter(&meter_provider, "apollo/router");
                    let instrument = create_instrument_fn(meter);
                    let attrs : &[opentelemetry::KeyValue] = &$attrs;
                    instrument.$mutation($value, attrs);
                    $guard::new(std::sync::Arc::new(instrument.clone()), $value, attrs)
                }
            }
        }
    };

    ($ty:ident, $instrument:ident, $guard: ty, $mutation:ident, $name:expr, $description:literal, $value: expr, $attrs: expr) => {
        metric!($ty, $instrument, $guard, $mutation, $name, $description, "", $value, $attrs)
    }
}

#[cfg(test)]
macro_rules! assert_metric {
    ($result:expr, $name:expr, $value:expr, $sum:expr, $count:expr, $attrs:expr) => {
        if !$result {
            let metric = crate::metrics::test_utils::SerdeMetric {
                name: $name.to_string(),
                description: "".to_string(),
                unit: "".to_string(),
                data: crate::metrics::test_utils::SerdeMetricData {
                    datapoints: [crate::metrics::test_utils::SerdeMetricDataPoint {
                        value: $value,
                        sum: $sum,
                        count: $count,
                        attributes: $attrs
                            .iter()
                            .map(|kv: &opentelemetry::KeyValue| {
                                (
                                    kv.key.to_string(),
                                    crate::metrics::test_utils::SerdeMetricDataPoint::convert(
                                        &kv.value,
                                    ),
                                )
                            })
                            .collect::<std::collections::BTreeMap<_, _>>(),
                    }]
                    .to_vec(),
                },
            };
            panic!(
                "metric not found:\n{}\nmetrics present:\n{}",
                serde_yaml::to_string(&metric).unwrap(),
                serde_yaml::to_string(&crate::metrics::collect_metrics().all()).unwrap()
            )
        }
    };
}

#[cfg(test)]
macro_rules! assert_no_metric {
    ($result:expr, $name:expr, $value:expr, $sum:expr, $count:expr, $attrs:expr) => {
        if $result {
            let metric = crate::metrics::test_utils::SerdeMetric {
                name: $name.to_string(),
                description: "".to_string(),
                unit: "".to_string(),
                data: crate::metrics::test_utils::SerdeMetricData {
                    datapoints: [crate::metrics::test_utils::SerdeMetricDataPoint {
                        value: $value,
                        sum: $sum,
                        count: $count,
                        attributes: $attrs
                            .iter()
                            .map(|kv: &opentelemetry::KeyValue| {
                                (
                                    kv.key.to_string(),
                                    crate::metrics::test_utils::SerdeMetricDataPoint::convert(
                                        &kv.value,
                                    ),
                                )
                            })
                            .collect::<std::collections::BTreeMap<_, _>>(),
                    }]
                    .to_vec(),
                },
            };
            panic!(
                "unexpected metric found:\n{}\nmetrics present:\n{}",
                serde_yaml::to_string(&metric).unwrap(),
                serde_yaml::to_string(&crate::metrics::collect_metrics().all()).unwrap()
            )
        }
    };
}

/// Assert the value of a counter metric that has the given name and attributes.
///
/// In asynchronous tests, you must use [`FutureMetricsExt::with_metrics`]. See dev-docs/metrics.md
/// for details: <https://github.com/apollographql/router/blob/4fc63d55104c81c77e6e0a3cca615eac28e39dc3/dev-docs/metrics.md#testing>
#[cfg(test)]
macro_rules! assert_counter {
    ($($name:ident).+, $value: expr, $($attr_key:literal = $attr_value:expr),+) => {
        let name = stringify!($($name).+);
        let attributes = &[$(opentelemetry::KeyValue::new($attr_key, $attr_value)),+];
        let result = crate::metrics::collect_metrics().assert(name, crate::metrics::test_utils::MetricType::Counter, $value, false, attributes);
        assert_metric!(result, name, Some($value.into()), None, None, &attributes);
    };

    ($($name:ident).+, $value: expr, $($($attr_key:ident).+ = $attr_value:expr),+) => {
        let name = stringify!($($name).+);
        let attributes = &[$(opentelemetry::KeyValue::new(stringify!($($attr_key).+), $attr_value)),+];
        let result = crate::metrics::collect_metrics().assert(name, crate::metrics::test_utils::MetricType::Counter, $value, false, attributes);
        assert_metric!(result, name, Some($value.into()), None, None, &attributes);
    };

    ($name:literal, $value: expr, $($attr_key:literal = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new($attr_key, $attr_value)),+];
        let result = crate::metrics::collect_metrics().assert($name, crate::metrics::test_utils::MetricType::Counter, $value, false, attributes);
        assert_metric!(result, $name, Some($value.into()), None, None, &attributes);
    };

    ($name:literal, $value: expr, $($($attr_key:ident).+ = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new(stringify!($($attr_key).+), $attr_value)),+];
        let result = crate::metrics::collect_metrics().assert($name, crate::metrics::test_utils::MetricType::Counter, $value, false, attributes);
        assert_metric!(result, $name, Some($value.into()), None, None, &attributes);
    };

    ($name:literal, $value: expr, $attributes: expr) => {
        let result = crate::metrics::collect_metrics().assert($name, crate::metrics::test_utils::MetricType::Counter, $value, false, $attributes);
        assert_metric!(result, $name, Some($value.into()), None, None, &$attributes);
    };

    ($name:literal, $value: expr) => {
        let result = crate::metrics::collect_metrics().assert($name, crate::metrics::test_utils::MetricType::Counter, $value, false, &[]);
        assert_metric!(result, $name, Some($value.into()), None, None, &[]);
    };
}

/// Assert that a counter metric does not exist with the given name and attributes.
///
/// In asynchronous tests, you must use [`FutureMetricsExt::with_metrics`]. See dev-docs/metrics.md
/// for details: <https://github.com/apollographql/router/blob/4fc63d55104c81c77e6e0a3cca615eac28e39dc3/dev-docs/metrics.md#testing>
#[cfg(test)]
macro_rules! assert_counter_not_exists {

    ($($name:ident).+, $value: ty, $($attr_key:literal = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new($attr_key, $attr_value)),+];
        let result = crate::metrics::collect_metrics().metric_exists(stringify!($($name).+), crate::metrics::test_utils::MetricType::Counter, attributes);
        assert_no_metric!(result, $name, None, None, None, attributes);
    };

    ($($name:ident).+, $value: ty, $($($attr_key:ident).+ = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new(stringify!($($attr_key).+), $attr_value)),+];
        let result = crate::metrics::collect_metrics().metric_exists(stringify!($($name).+), crate::metrics::test_utils::MetricType::Counter, attributes);
        assert_no_metric!(result, $name, None, None, None, attributes);
    };

    ($name:literal, $value: ty, $($attr_key:literal = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new($attr_key, $attr_value)),+];
        let result = crate::metrics::collect_metrics().metric_exists($name, crate::metrics::test_utils::MetricType::Counter, attributes);
        assert_no_metric!(result, $name, None, None, None, attributes);
    };

    ($name:literal, $value: ty, $($($attr_key:ident).+ = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new(stringify!($($attr_key).+), $attr_value)),+];
        let result = crate::metrics::collect_metrics().metric_exists($name, crate::metrics::test_utils::MetricType::Counter, attributes);
        assert_no_metric!(result, $name, None, None, None, attributes);
    };


    ($name:literal, $value: ty, $attributes: expr) => {
        let result = crate::metrics::collect_metrics().metric_exists($name, crate::metrics::test_utils::MetricType::Counter, $attributes);
        assert_no_metric!(result, $name, None, None, None, &$attributes);
    };

    ($name:literal, $value: ty) => {
        let result = crate::metrics::collect_metrics().metric_exists($name, crate::metrics::test_utils::MetricType::Counter, &[]);
        assert_no_metric!(result, $name, None, None, None, &[]);
    };
}

/// Assert the value of a counter metric that has the given name and attributes.
///
/// In asynchronous tests, you must use [`FutureMetricsExt::with_metrics`]. See dev-docs/metrics.md
/// for details: <https://github.com/apollographql/router/blob/4fc63d55104c81c77e6e0a3cca615eac28e39dc3/dev-docs/metrics.md#testing>
#[cfg(test)]
macro_rules! assert_up_down_counter {

    ($($name:ident).+, $value: expr, $($attr_key:literal = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new($attr_key, $attr_value)),+];
        let result = crate::metrics::collect_metrics().assert(stringify!($($name).+), crate::metrics::test_utils::MetricType::UpDownCounter, $value, false, attributes);
        assert_metric!(result, $name, Some($value.into()), None, None, attributes);
    };

    ($($name:ident).+, $value: expr, $($($attr_key:ident).+ = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new(stringify!($($attr_key).+), $attr_value)),+];
        let result = crate::metrics::collect_metrics().assert(stringify!($($name).+), crate::metrics::test_utils::MetricType::UpDownCounter, $value, false, attributes);
        assert_metric!(result, $name, Some($value.into()), None, None, attributes);
    };

    ($name:literal, $value: expr, $($attr_key:literal = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new($attr_key, $attr_value)),+];
        let result = crate::metrics::collect_metrics().assert($name, crate::metrics::test_utils::MetricType::UpDownCounter, $value, false, attributes);
        assert_metric!(result, $name, Some($value.into()), None, None, attributes);
    };

    ($name:literal, $value: expr, $($($attr_key:ident).+ = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new(stringify!($($attr_key).+), $attr_value)),+];
        let result = crate::metrics::collect_metrics().assert($name, crate::metrics::test_utils::MetricType::UpDownCounter, $value, false, attributes);
        assert_metric!(result, $name, Some($value.into()), None, None, attributes);
    };

    ($name:literal, $value: expr) => {
        let result = crate::metrics::collect_metrics().assert($name, crate::metrics::test_utils::MetricType::UpDownCounter, $value, false, &[]);
        assert_metric!(result, $name, Some($value.into()), None, None, &[]);
    };
}

/// Assert the value of a gauge metric that has the given name and attributes.
///
/// In asynchronous tests, you must use [`FutureMetricsExt::with_metrics`]. See dev-docs/metrics.md
/// for details: <https://github.com/apollographql/router/blob/4fc63d55104c81c77e6e0a3cca615eac28e39dc3/dev-docs/metrics.md#testing>
#[cfg(test)]
macro_rules! assert_gauge {

    ($($name:ident).+, $value: expr, $($attr_key:literal = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new($attr_key, $attr_value)),+];
        let result = crate::metrics::collect_metrics().assert(stringify!($($name).+), crate::metrics::test_utils::MetricType::Gauge, $value, false, attributes);
        assert_metric!(result, $name, Some($value.into()), None, None, attributes);
    };

    ($($name:ident).+, $value: expr, $($($attr_key:ident).+ = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new(stringify!($($attr_key).+), $attr_value)),+];
        let result = crate::metrics::collect_metrics().assert(stringify!($($name).+), crate::metrics::test_utils::MetricType::Gauge, $value, false, attributes);
        assert_metric!(result, $name, Some($value.into()), None, None, attributes);
    };

    ($name:literal, $value: expr, $($attr_key:literal = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new($attr_key, $attr_value)),+];
        let result = crate::metrics::collect_metrics().assert($name, crate::metrics::test_utils::MetricType::Gauge, $value, false, attributes);
        assert_metric!(result, $name, Some($value.into()), None, None, attributes);
    };

    ($name:literal, $value: expr, $($($attr_key:ident).+ = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new(stringify!($($attr_key).+), $attr_value)),+];
        let result = crate::metrics::collect_metrics().assert($name, crate::metrics::test_utils::MetricType::Gauge, $value, false, attributes);
        assert_metric!(result, $name, Some($value.into()), None, None, attributes);
    };

    ($name:literal, $value: expr) => {
        let result = crate::metrics::collect_metrics().assert($name, crate::metrics::test_utils::MetricType::Gauge, $value, false, &[]);
        assert_metric!(result, $name, Some($value.into()), None, None, &[]);
    };
}

#[cfg(test)]
macro_rules! assert_histogram_count {

    ($($name:ident).+, $value: expr, $($attr_key:literal = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new($attr_key, $attr_value)),+];
        let result = crate::metrics::collect_metrics().assert(stringify!($($name).+), crate::metrics::test_utils::MetricType::Histogram, $value, true, attributes);
        assert_metric!(result, $name, None, Some($value.into()), Some(num_traits::ToPrimitive::to_u64(&$value).expect("count should be convertible to u64")), attributes);
    };

    ($($name:ident).+, $value: expr, $($($attr_key:ident).+ = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new(stringify!($($attr_key).+), $attr_value)),+];
        let result = crate::metrics::collect_metrics().assert(stringify!($($name).+), crate::metrics::test_utils::MetricType::Histogram, $value, true, attributes);
        assert_metric!(result, $name, None, Some($value.into()), Some(num_traits::ToPrimitive::to_u64(&$value).expect("count should be convertible to u64")), attributes);
    };

    ($name:literal, $value: expr, $($attr_key:literal = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new($attr_key, $attr_value)),+];
        let result = crate::metrics::collect_metrics().assert($name, crate::metrics::test_utils::MetricType::Histogram, $value, true, attributes);
        assert_metric!(result, $name, None, Some($value.into()), Some(num_traits::ToPrimitive::to_u64(&$value).expect("count should be convertible to u64")), attributes);
    };

    ($name:literal, $value: expr, $($($attr_key:ident).+ = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new(stringify!($($attr_key).+), $attr_value)),+];
        let result = crate::metrics::collect_metrics().assert($name, crate::metrics::test_utils::MetricType::Histogram, $value, attributes);
        assert_metric!(result, $name, None, Some($value.into()), Some(num_traits::ToPrimitive::to_u64(&$value).expect("count should be convertible to u64")), attributes);
    };

    ($name:literal, $value: expr) => {
        let result = crate::metrics::collect_metrics().assert($name, crate::metrics::test_utils::MetricType::Histogram, $value, true, &[]);
        assert_metric!(result, $name, None, Some($value.into()), Some(num_traits::ToPrimitive::to_u64(&$value).expect("count should be convertible to u64")), &[]);
    };
}

/// Assert the sum value of a histogram metric with the given name and attributes.
///
/// In asynchronous tests, you must use [`FutureMetricsExt::with_metrics`]. See dev-docs/metrics.md
/// for details: <https://github.com/apollographql/router/blob/4fc63d55104c81c77e6e0a3cca615eac28e39dc3/dev-docs/metrics.md#testing>
#[cfg(test)]
macro_rules! assert_histogram_sum {

    ($($name:ident).+, $value: expr, $($attr_key:literal = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new($attr_key, $attr_value)),+];
        let result = crate::metrics::collect_metrics().assert(stringify!($($name).+), crate::metrics::test_utils::MetricType::Histogram, $value, false, attributes);
        assert_metric!(result, $name, None, Some($value.into()), None, attributes);
    };

    ($($name:ident).+, $value: expr, $($($attr_key:ident).+ = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new(stringify!($($attr_key).+), $attr_value)),+];
        let result = crate::metrics::collect_metrics().assert(stringify!($($name).+), crate::metrics::test_utils::MetricType::Histogram, $value, false, attributes);
        assert_metric!(result, $name, None, Some($value.into()), None, attributes);
    };

    ($name:literal, $value: expr, $($attr_key:literal = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new($attr_key, $attr_value)),+];
        let result = crate::metrics::collect_metrics().assert($name, crate::metrics::test_utils::MetricType::Histogram, $value, false, attributes);
        assert_metric!(result, $name, None, Some($value.into()), None, attributes);
    };

    ($name:literal, $value: expr, $($($attr_key:ident).+ = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new(stringify!($($attr_key).+), $attr_value)),+];
        let result = crate::metrics::collect_metrics().assert($name, crate::metrics::test_utils::MetricType::Histogram, $value, false, attributes);
        assert_metric!(result, $name, None, Some($value.into()), None, attributes);
    };

    ($name:literal, $value: expr) => {
        let result = crate::metrics::collect_metrics().assert($name, crate::metrics::test_utils::MetricType::Histogram, $value, false, &[]);
        assert_metric!(result, $name, None, Some($value.into()), None, &[]);
    };
}

/// Assert that a histogram metric exists with the given name and attributes.
///
/// In asynchronous tests, you must use [`FutureMetricsExt::with_metrics`]. See dev-docs/metrics.md
/// for details: <https://github.com/apollographql/router/blob/4fc63d55104c81c77e6e0a3cca615eac28e39dc3/dev-docs/metrics.md#testing>
#[cfg(test)]
macro_rules! assert_histogram_exists {

    ($($name:ident).+, $value: ty, $($attr_key:literal = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new($attr_key, $attr_value)),+];
        let result = crate::metrics::collect_metrics().metric_exists(stringify!($($name).+), crate::metrics::test_utils::MetricType::Histogram, attributes);
        assert_metric!(result, $name, None, None, None, attributes);
    };

    ($($name:ident).+, $value: ty, $($($attr_key:ident).+ = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new(stringify!($($attr_key).+), $attr_value)),+];
        let result = crate::metrics::collect_metrics().metric_exists(stringify!($($name).+), crate::metrics::test_utils::MetricType::Histogram, attributes);
        assert_metric!(result, $name, None, None, None, attributes);
    };

    ($name:literal, $value: ty, $($attr_key:literal = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new($attr_key, $attr_value)),+];
        let result = crate::metrics::collect_metrics().metric_exists($name, crate::metrics::test_utils::MetricType::Histogram, attributes);
        assert_metric!(result, $name, None, None, None, attributes);
    };

    ($name:literal, $value: ty, $($($attr_key:ident).+ = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new(stringify!($($attr_key).+), $attr_value)),+];
        let result = crate::metrics::collect_metrics().metric_exists($name, crate::metrics::test_utils::MetricType::Histogram, attributes);
        assert_metric!(result, $name, None, None, None, attributes);
    };

    ($name:literal, $value: ty) => {
        let result = crate::metrics::collect_metrics().metric_exists($name, crate::metrics::test_utils::MetricType::Histogram, &[]);
        assert_metric!(result, $name, None, None, None, &[]);
    };
}

/// Assert that a histogram metric does not exist with the given name and attributes.
///
/// In asynchronous tests, you must use [`FutureMetricsExt::with_metrics`]. See dev-docs/metrics.md
/// for details: <https://github.com/apollographql/router/blob/4fc63d55104c81c77e6e0a3cca615eac28e39dc3/dev-docs/metrics.md#testing>
#[cfg(test)]
macro_rules! assert_histogram_not_exists {

    ($($name:ident).+, $value: ty, $($attr_key:literal = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new($attr_key, $attr_value)),+];
        let result = crate::metrics::collect_metrics().metric_exists(stringify!($($name).+), crate::metrics::test_utils::MetricType::Histogram, attributes);
        assert_no_metric!(result, $name, None, None, None, attributes);
    };

    ($($name:ident).+, $value: ty, $($($attr_key:ident).+ = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new(stringify!($($attr_key).+), $attr_value)),+];
        let result = crate::metrics::collect_metrics().metric_exists(stringify!($($name).+), crate::metrics::test_utils::MetricType::Histogram, attributes);
        assert_no_metric!(result, $name, None, None, None, attributes);
    };

    ($name:literal, $value: ty, $($attr_key:literal = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new($attr_key, $attr_value)),+];
        let result = crate::metrics::collect_metrics().metric_exists($name, crate::metrics::test_utils::MetricType::Histogram, attributes);
        assert_no_metric!(result, $name, None, None, None, attributes);
    };

    ($name:literal, $value: ty, $($($attr_key:ident).+ = $attr_value:expr),+) => {
        let attributes = &[$(opentelemetry::KeyValue::new(stringify!($($attr_key).+), $attr_value)),+];
        let result = crate::metrics::collect_metrics().metric_exists($name, crate::metrics::test_utils::MetricType::Histogram, attributes);
        assert_no_metric!(result, $name, None, None, None, attributes);
    };

    ($name:literal, $value: ty) => {
        let result = crate::metrics::collect_metrics().metric_exists($name, crate::metrics::test_utils::MetricType::Histogram, &[]);
        assert_no_metric!(result, $name, None, None, None, &[]);
    };
}

/// Assert that all metrics match an [insta] snapshot.
///
/// Consider using [assert_non_zero_metrics_snapshot] to produce more grokkable snapshots if
/// zero-valued metrics are not relevant to your test.
///
/// In asynchronous tests, you must use [`FutureMetricsExt::with_metrics`]. See dev-docs/metrics.md
/// for details: <https://github.com/apollographql/router/blob/4fc63d55104c81c77e6e0a3cca615eac28e39dc3/dev-docs/metrics.md#testing>
#[cfg(test)]
#[allow(unused_macros)]
macro_rules! assert_metrics_snapshot {
    ($file_name: expr) => {
        insta::with_settings!({sort_maps => true, snapshot_suffix => $file_name}, {
            let metrics = crate::metrics::collect_metrics();
            insta::assert_yaml_snapshot!(&metrics.all());
        });

    };
    () => {
        insta::with_settings!({sort_maps => true}, {
            let metrics = crate::metrics::collect_metrics();
            insta::assert_yaml_snapshot!(&metrics.all());
        });
    };
}

/// Assert that all metrics with a non-zero value match an [insta] snapshot.
///
/// In asynchronous tests, you must use [`FutureMetricsExt::with_metrics`]. See dev-docs/metrics.md
/// for details: <https://github.com/apollographql/router/blob/4fc63d55104c81c77e6e0a3cca615eac28e39dc3/dev-docs/metrics.md#testing>
#[cfg(test)]
#[allow(unused_macros)]
macro_rules! assert_non_zero_metrics_snapshot {
    ($file_name: expr) => {
        insta::with_settings!({sort_maps => true, snapshot_suffix => $file_name}, {
            let metrics = crate::metrics::collect_metrics();
            insta::assert_yaml_snapshot!(&metrics.non_zero());
        });
    };
    () => {
        insta::with_settings!({sort_maps => true}, {
            let metrics = crate::metrics::collect_metrics();
            insta::assert_yaml_snapshot!(&metrics.non_zero());
        });
    };
}

#[cfg(test)]
pub(crate) type MetricFuture<T> = Pin<Box<dyn Future<Output = <T as Future>::Output>>>;

/// Extension trait for Futures that wish to test metrics.
pub(crate) trait FutureMetricsExt<T> {
    /// Wraps a Future with metrics collection capabilities.
    ///
    /// This method creates a new Future that will:
    /// 1. Initialize the meter provider before executing the Future
    /// 2. Execute the original Future
    /// 3. Shutdown the meter provider after completion
    ///
    /// This is useful for testing scenarios where you need to ensure metrics are properly
    /// collected throughout the entire Future's execution.
    ///
    /// # Example
    /// ```rust
    /// # use apollo_router::metrics::FutureMetricsExt;
    /// # async fn example() {
    /// let future = async { /* your async code that produces metrics */ };
    /// let result = future.with_metrics().await;
    /// # }
    /// ```
    #[cfg(test)]
    fn with_metrics(
        self,
    ) -> tokio::task::futures::TaskLocalFuture<
        OnceLock<(AggregateMeterProvider, test_utils::ClonableManualReader)>,
        MetricFuture<Self>,
    >
    where
        Self: Sized + Future + 'static,
        <Self as Future>::Output: 'static,
    {
        test_utils::AGGREGATE_METER_PROVIDER_ASYNC.scope(
            Default::default(),
            async move {
                // We want to eagerly create the meter provider, the reason is that this will be shared among subtasks that use `with_current_meter_provider`.
                let _ = meter_provider_internal();
                let result = self.await;
                let _ = tokio::task::spawn_blocking(|| meter_provider_internal().shutdown()).await;
                result
            }
            .boxed_local(),
        )
    }

    /// Propagates the current meter provider to child tasks during test execution.
    ///
    /// This method ensures that the meter provider is properly shared across tasks
    /// during test scenarios. In non-test contexts, it returns the original Future
    /// unchanged.
    ///
    /// # Example
    /// ```rust
    /// # use apollo_router::metrics::FutureMetricsExt;
    /// # async fn example() {
    /// let result = tokio::task::spawn(async { /* your async code that produces metrics */ }.with_current_meter_provider()).await;
    /// # }
    /// ```
    #[cfg(test)]
    fn with_current_meter_provider(
        self,
    ) -> tokio::task::futures::TaskLocalFuture<
        OnceLock<(AggregateMeterProvider, test_utils::ClonableManualReader)>,
        Self,
    >
    where
        Self: Sized + Future + 'static,
        <Self as Future>::Output: 'static,
    {
        // We need to determine if the meter was set. If not then we can use default provider which is empty
        let meter_provider_set = test_utils::AGGREGATE_METER_PROVIDER_ASYNC
            .try_with(|_| {})
            .is_ok();
        if meter_provider_set {
            test_utils::AGGREGATE_METER_PROVIDER_ASYNC
                .scope(test_utils::AGGREGATE_METER_PROVIDER_ASYNC.get(), self)
        } else {
            test_utils::AGGREGATE_METER_PROVIDER_ASYNC.scope(Default::default(), self)
        }
    }

    #[cfg(not(test))]
    fn with_current_meter_provider(self) -> Self
    where
        Self: Sized + Future + 'static,
    {
        // This is intentionally a noop. In the real world meter provider is a global variable.
        self
    }
}

impl<T> FutureMetricsExt<T> for T where T: Future {}

#[cfg(test)]
mod test {
    use opentelemetry::KeyValue;
    use opentelemetry::metrics::MeterProvider;

    use crate::metrics::FutureMetricsExt;
    use crate::metrics::meter_provider;
    use crate::metrics::meter_provider_internal;

    fn assert_unit(name: &str, unit: &str) {
        let collected_metrics = crate::metrics::collect_metrics();
        let metric = collected_metrics.find(name).unwrap();
        assert_eq!(metric.unit(), unit);
    }

    #[test]
    fn test_gauge() {
        // Observables are cleaned up when they dropped, so keep this around.
        let _gauge = meter_provider()
            .meter("test")
            .u64_observable_gauge("test")
            .with_callback(|m| m.observe(5, &[]))
            .build();
        assert_gauge!("test", 5);
    }

    #[test]
    fn test_gauge_record() {
        let gauge = meter_provider().meter("test").u64_gauge("test").build();
        gauge.record(5, &[]);
        assert_gauge!("test", 5);
    }

    #[test]
    fn test_no_attributes() {
        u64_counter!("test", "test description", 1);
        assert_counter!("test", 1);
    }

    #[test]
    fn test_dynamic_attributes() {
        let attributes = vec![KeyValue::new("attr", "val")];
        u64_counter!("test", "test description", 1, attributes);
        assert_counter!("test", 1, "attr" = "val");
        assert_counter!("test", 1, &attributes);
    }

    #[test]
    fn test_multiple_calls() {
        fn my_method(val: &'static str) {
            u64_counter!("test", "test description", 1, "attr" = val);
        }

        my_method("jill");
        my_method("jill");
        my_method("bob");
        assert_counter!("test", 2, "attr" = "jill");
        assert_counter!("test", 1, "attr" = "bob");
    }

    #[test]
    fn test_non_async() {
        // Each test is run in a separate thread, metrics are stored in a thread local.
        u64_counter!("test", "test description", 1, "attr" = "val");
        assert_counter!("test", 1, "attr" = "val");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_async_multi() {
        // Multi-threaded runtime needs to use a tokio task local to avoid tests interfering with each other
        async {
            u64_counter!("test", "test description", 1, "attr" = "val");
            assert_counter!("test", 1, "attr" = "val");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    async fn test_async_single() {
        async {
            // It's a single threaded tokio runtime, so we can still use a thread local
            u64_counter!("test", "test description", 1, "attr" = "val");
            assert_counter!("test", 1, "attr" = "val");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    async fn test_u64_counter() {
        async {
            u64_counter!("test", "test description", 1, attr = "val");
            u64_counter!("test", "test description", 1, attr.test = "val");
            u64_counter!("test", "test description", 1, attr.test_underscore = "val");
            u64_counter!(
                test.dot,
                "test description",
                1,
                "attr.test_underscore" = "val"
            );
            u64_counter!(
                test.dot,
                "test description",
                1,
                attr.test_underscore = "val"
            );
            assert_counter!("test", 1, "attr" = "val");
            assert_counter!("test", 1, "attr.test" = "val");
            assert_counter!("test", 1, attr.test_underscore = "val");
            assert_counter!(test.dot, 2, attr.test_underscore = "val");
            assert_counter!(test.dot, 2, "attr.test_underscore" = "val");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    async fn test_f64_counter() {
        async {
            f64_counter!("test", "test description", 1.5, "attr" = "val");
            assert_counter!("test", 1.5, "attr" = "val");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    async fn test_i64_up_down_counter() {
        async {
            let _guard = i64_up_down_counter!("test", "test description", 1, "attr" = "val");
            assert_up_down_counter!("test", 1, "attr" = "val");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    async fn test_f64_up_down_counter() {
        async {
            let _guard = f64_up_down_counter!("test", "test description", 1.5, "attr" = "val");
            assert_up_down_counter!("test", 1.5, "attr" = "val");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    async fn test_i64_up_down_counter_guard_auto_decrement() {
        async {
            // Test that dropping the guard decrements the counter
            {
                let _guard =
                    i64_up_down_counter!("test_guard", "test description", 1, "attr" = "val");
                assert_up_down_counter!("test_guard", 1, "attr" = "val");
            }
            // After guard is dropped, counter should be back to 0
            assert_up_down_counter!("test_guard", 0, "attr" = "val");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    async fn test_i64_up_down_counter_guard_multiple() {
        async {
            // Test multiple guards with the same metric
            let _guard1 = i64_up_down_counter!("test_multi", "test description", 1, "attr" = "val");
            assert_up_down_counter!("test_multi", 1, "attr" = "val");

            let _guard2 = i64_up_down_counter!("test_multi", "test description", 1, "attr" = "val");
            assert_up_down_counter!("test_multi", 2, "attr" = "val");

            let _guard3 = i64_up_down_counter!("test_multi", "test description", 1, "attr" = "val");
            assert_up_down_counter!("test_multi", 3, "attr" = "val");

            drop(_guard2);
            assert_up_down_counter!("test_multi", 2, "attr" = "val");

            drop(_guard1);
            assert_up_down_counter!("test_multi", 1, "attr" = "val");

            drop(_guard3);
            assert_up_down_counter!("test_multi", 0, "attr" = "val");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    async fn test_i64_up_down_counter_guard_different_attributes() {
        async {
            // Test guards with different attributes
            let _guard1 =
                i64_up_down_counter!("test_attrs", "test description", 1, "attr" = "val1");
            let _guard2 =
                i64_up_down_counter!("test_attrs", "test description", 1, "attr" = "val2");

            assert_up_down_counter!("test_attrs", 1, "attr" = "val1");
            assert_up_down_counter!("test_attrs", 1, "attr" = "val2");

            drop(_guard1);
            assert_up_down_counter!("test_attrs", 0, "attr" = "val1");
            assert_up_down_counter!("test_attrs", 1, "attr" = "val2");

            drop(_guard2);
            assert_up_down_counter!("test_attrs", 0, "attr" = "val2");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    async fn test_f64_up_down_counter_guard_auto_decrement() {
        async {
            // Test that dropping the guard decrements the counter
            {
                let _guard =
                    f64_up_down_counter!("test_f64_guard", "test description", 2.5, "attr" = "val");
                assert_up_down_counter!("test_f64_guard", 2.5, "attr" = "val");
            }
            // After guard is dropped, counter should be back to 0
            assert_up_down_counter!("test_f64_guard", 0.0, "attr" = "val");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    async fn test_u64_histogram() {
        async {
            u64_histogram!("test", "test description", 1, "attr" = "val");
            assert_histogram_sum!("test", 1, "attr" = "val");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    async fn test_f64_histogram() {
        async {
            f64_histogram!("test", "test description", 1.0, "attr" = "val");
            assert_histogram_sum!("test", 1, "attr" = "val");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    #[should_panic]
    async fn test_type_histogram() {
        async {
            f64_histogram!("test", "test description", 1.0, "attr" = "val");
            assert_counter!("test", 1, "attr" = "val");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    #[should_panic]
    async fn test_type_counter() {
        async {
            f64_counter!("test", "test description", 1.0, "attr" = "val");
            assert_histogram_sum!("test", 1, "attr" = "val");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    #[should_panic]
    async fn test_type_up_down_counter() {
        async {
            let _ = f64_up_down_counter!("test", "test description", 1.0, "attr" = "val");
            assert_histogram_sum!("test", 1, "attr" = "val");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    #[should_panic]
    async fn test_type_gauge() {
        async {
            let _gauge = meter_provider()
                .meter("test")
                .u64_observable_gauge("test")
                .with_callback(|m| m.observe(5, &[]))
                .build();
            assert_histogram_sum!("test", 1, "attr" = "val");
        }
        .with_metrics()
        .await;
    }

    #[test]
    fn parse_attributes_should_handle_multiple_input_types() {
        let variable = 123;
        let parsed_idents = parse_attributes!(hello = "world", my.variable = variable);
        let parsed_literals = parse_attributes!("hello" = "world", "my.variable" = variable);
        let parsed_provided = parse_attributes!(vec![
            KeyValue::new("hello", "world"),
            KeyValue::new("my.variable", variable)
        ]);

        assert_eq!(parsed_idents, parsed_literals);
        assert_eq!(parsed_idents.as_slice(), parsed_provided.as_slice());
        assert_eq!(parsed_literals.as_slice(), parsed_provided.as_slice());
    }

    #[test]
    fn test_callsite_caching() {
        // Creating instruments may be slow due to multiple levels of locking that needs to happen through the various metrics layers.
        // Callsite caching is implemented to prevent this happening on every call.
        // See the metric macro above to see more information.
        super::CACHE_CALLSITE.with(|cell| cell.store(true, std::sync::atomic::Ordering::SeqCst));
        fn test() {
            // This is a single callsite so should only have one metric
            u64_counter!("test", "test description", 1, "attr" = "val");
        }

        // Callsite hasn't been used yet, so there should be no metrics
        assert_eq!(meter_provider_internal().registered_instruments(), 0);

        // Call the metrics, it will be registered
        test();
        assert_counter!("test", 1, "attr" = "val");
        assert_eq!(meter_provider_internal().registered_instruments(), 1);

        // Call the metrics again, but the second call will not register a new metric because it will have be retrieved from the static
        test();
        assert_counter!("test", 2, "attr" = "val");
        assert_eq!(meter_provider_internal().registered_instruments(), 1);

        // Force invalidation of instruments
        meter_provider_internal().invalidate();
        assert_eq!(meter_provider_internal().registered_instruments(), 0);

        // Slow path
        test();
        assert_eq!(meter_provider_internal().registered_instruments(), 1);

        // Fast path
        test();
        assert_eq!(meter_provider_internal().registered_instruments(), 1);
    }

    #[tokio::test]
    async fn test_f64_histogram_with_unit() {
        async {
            f64_histogram_with_unit!("test", "test description", "m/s", 1.0, "attr" = "val");
            assert_histogram_sum!("test", 1, "attr" = "val");
            assert_unit("test", "m/s");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    async fn test_u64_counter_with_unit() {
        async {
            u64_counter_with_unit!("test", "test description", "Hz", 1, attr = "val");
            assert_counter!("test", 1, "attr" = "val");
            assert_unit("test", "Hz");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    async fn test_i64_up_down_counter_with_unit() {
        async {
            let _guard = i64_up_down_counter_with_unit!(
                "test",
                "test description",
                "{request}",
                1,
                attr = "val"
            );
            assert_up_down_counter!("test", 1, "attr" = "val");
            assert_unit("test", "{request}");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    async fn test_f64_up_down_counter_with_unit() {
        async {
            let _guard = f64_up_down_counter_with_unit!(
                "test",
                "test description",
                "kg",
                1.5,
                "attr" = "val"
            );
            assert_up_down_counter!("test", 1.5, "attr" = "val");
            assert_unit("test", "kg");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    async fn test_u64_histogram_with_unit() {
        async {
            u64_histogram_with_unit!("test", "test description", "{packet}", 1, "attr" = "val");
            assert_histogram_sum!("test", 1, "attr" = "val");
            assert_unit("test", "{packet}");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    async fn test_f64_counter_with_unit() {
        async {
            f64_counter_with_unit!("test", "test description", "s", 1.5, "attr" = "val");
            assert_counter!("test", 1.5, "attr" = "val");
            assert_unit("test", "s");
        }
        .with_metrics()
        .await;
    }

    #[tokio::test]
    async fn test_metrics_across_tasks() {
        async {
            // Initial metric in the main task
            u64_counter!("apollo.router.test", "metric", 1);
            assert_counter!("apollo.router.test", 1);

            // Spawn a task that also records metrics
            let handle = tokio::spawn(
                async move {
                    u64_counter!("apollo.router.test", "metric", 2);
                }
                .with_current_meter_provider(),
            );

            // Wait for the spawned task to complete
            handle.await.unwrap();

            // The metric should now be 3 since both tasks contributed
            assert_counter!("apollo.router.test", 3);
        }
        .with_metrics()
        .await;
    }
}