kacrab 0.1.1

A Kafka client for Rust, built from the protocol up.
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
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
//! Metrics registry primitives mirroring Kafka's metrics model.

use std::{
    collections::{BTreeMap, BTreeSet, HashMap},
    fmt,
    hash::{Hash, Hasher},
    sync::{Arc, Mutex},
    time::{Duration, SystemTime, UNIX_EPOCH},
};

/// Numeric metric value.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MetricValue {
    /// Floating-point metric value.
    Number(f64),
}

impl MetricValue {
    const fn as_f64(self) -> f64 {
        match self {
            Self::Number(value) => value,
        }
    }
}

/// Metric identity (Kafka's `MetricName`).
#[derive(Clone, Eq)]
pub struct MetricName {
    name: String,
    group: String,
    description: String,
    tags: BTreeMap<String, String>,
}

impl MetricName {
    /// Create a metric name with no description or tags.
    #[must_use]
    pub fn new(name: impl Into<String>, group: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            group: group.into(),
            description: String::new(),
            tags: BTreeMap::new(),
        }
    }

    /// Set the human-readable metric description.
    #[must_use]
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = description.into();
        self
    }

    /// Add or replace a metric tag.
    #[must_use]
    pub fn tag(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        let _previous = self.tags.insert(key.into(), value.into());
        self
    }

    /// Metric name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Logical metric group.
    #[must_use]
    pub fn group(&self) -> &str {
        &self.group
    }

    /// Human-readable metric description.
    #[must_use]
    pub fn description(&self) -> &str {
        &self.description
    }

    /// Metric tags.
    #[must_use]
    pub const fn tags(&self) -> &BTreeMap<String, String> {
        &self.tags
    }
}

impl PartialEq for MetricName {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name && self.group == other.group && self.tags == other.tags
    }
}

impl Hash for MetricName {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.name.hash(state);
        self.group.hash(state);
        self.tags.hash(state);
    }
}

impl fmt::Debug for MetricName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MetricName")
            .field("name", &self.name)
            .field("group", &self.group)
            .field("description", &self.description)
            .field("tags", &self.tags)
            .finish()
    }
}

/// Template for creating [`MetricName`] values with a fixed tag set.
#[derive(Clone)]
pub struct MetricNameTemplate {
    name: String,
    group: String,
    description: String,
    tags: Vec<String>,
}

impl MetricNameTemplate {
    /// Create a template with tag names in preferred display order.
    #[must_use]
    pub fn new<I, T>(
        name: impl Into<String>,
        group: impl Into<String>,
        description: impl Into<String>,
        tag_names: I,
    ) -> Self
    where
        I: IntoIterator<Item = T>,
        T: Into<String>,
    {
        let mut seen = BTreeSet::new();
        let mut tags = Vec::new();
        for tag in tag_names {
            let tag = tag.into();
            if seen.insert(tag.clone()) {
                tags.push(tag);
            }
        }
        Self {
            name: name.into(),
            group: group.into(),
            description: description.into(),
            tags,
        }
    }

    /// Metric name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Metric group.
    #[must_use]
    pub fn group(&self) -> &str {
        &self.group
    }

    /// Metric description.
    #[must_use]
    pub fn description(&self) -> &str {
        &self.description
    }

    /// Ordered tag names used by this template.
    #[must_use]
    pub fn tags(&self) -> &[String] {
        &self.tags
    }

    fn tag_set(&self) -> BTreeSet<&str> {
        self.tags.iter().map(String::as_str).collect()
    }
}

impl PartialEq for MetricNameTemplate {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name && self.group == other.group && self.tag_set() == other.tag_set()
    }
}

impl Eq for MetricNameTemplate {}

impl Hash for MetricNameTemplate {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.name.hash(state);
        self.group.hash(state);
        for tag in self.tag_set() {
            tag.hash(state);
        }
    }
}

impl fmt::Debug for MetricNameTemplate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MetricNameTemplate")
            .field("name", &self.name)
            .field("group", &self.group)
            .field("description", &self.description)
            .field("tags", &self.tags)
            .finish()
    }
}

/// Upper or lower bound for a metric.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MetricQuota {
    bound: f64,
    upper: bool,
}

impl MetricQuota {
    /// Create an upper-bound quota.
    #[must_use]
    pub const fn upper_bound(bound: f64) -> Self {
        Self { bound, upper: true }
    }

    /// Create a lower-bound quota.
    #[must_use]
    pub const fn lower_bound(bound: f64) -> Self {
        Self {
            bound,
            upper: false,
        }
    }

    /// Return whether this quota is an upper bound.
    #[must_use]
    pub const fn is_upper_bound(self) -> bool {
        self.upper
    }

    /// Quota bound.
    #[must_use]
    pub const fn bound(self) -> f64 {
        self.bound
    }

    /// Return whether `value` is within the bound.
    #[must_use]
    pub fn acceptable(self, value: f64) -> bool {
        (self.upper && value <= self.bound) || (!self.upper && value >= self.bound)
    }
}

/// Metric configuration.
#[derive(Debug, Clone, PartialEq)]
pub struct MetricConfig {
    quota: Option<MetricQuota>,
    samples: usize,
    event_window: u64,
    time_window_ms: u64,
    tags: BTreeMap<String, String>,
    record_level: SensorRecordingLevel,
}

impl MetricConfig {
    /// Kafka default number of samples.
    pub const DEFAULT_NUM_SAMPLES: usize = 2;
    /// Kafka default time window in milliseconds.
    pub const DEFAULT_TIME_WINDOW_MS: u64 = 30_000;

    /// Create an empty metric configuration.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            quota: None,
            samples: Self::DEFAULT_NUM_SAMPLES,
            event_window: u64::MAX,
            time_window_ms: Self::DEFAULT_TIME_WINDOW_MS,
            tags: BTreeMap::new(),
            record_level: SensorRecordingLevel::Info,
        }
    }

    /// Set the metric quota.
    #[must_use]
    pub const fn with_quota(mut self, quota: MetricQuota) -> Self {
        self.quota = Some(quota);
        self
    }

    /// Configured quota, if any.
    #[must_use]
    pub const fn quota(&self) -> Option<MetricQuota> {
        self.quota
    }

    /// Kafka `MetricConfig.samples()`.
    #[must_use]
    pub const fn samples(&self) -> usize {
        self.samples
    }

    /// Set the number of samples.
    ///
    /// # Errors
    ///
    /// Returns an error when `samples` is less than one.
    pub fn with_samples(mut self, samples: usize) -> Result<Self, MetricsError> {
        if samples < 1 {
            return Err(MetricsError::InvalidMetricConfig {
                reason: "the number of samples must be at least 1".to_owned(),
            });
        }
        self.samples = samples;
        Ok(self)
    }

    /// Kafka `MetricConfig.eventWindow()`.
    #[must_use]
    pub const fn event_window(&self) -> u64 {
        self.event_window
    }

    /// Set the event window.
    #[must_use]
    pub const fn with_event_window(mut self, event_window: u64) -> Self {
        self.event_window = event_window;
        self
    }

    /// Kafka `MetricConfig.timeWindowMs()`.
    #[must_use]
    pub const fn time_window_ms(&self) -> u64 {
        self.time_window_ms
    }

    /// Set the time window in milliseconds.
    #[must_use]
    pub const fn with_time_window_ms(mut self, time_window_ms: u64) -> Self {
        self.time_window_ms = time_window_ms;
        self
    }

    /// Kafka `MetricConfig.tags()`.
    #[must_use]
    pub const fn tags(&self) -> &BTreeMap<String, String> {
        &self.tags
    }

    /// Add or replace a metric config tag.
    #[must_use]
    pub fn with_tag(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        let _previous = self.tags.insert(key.into(), value.into());
        self
    }

    /// Replace metric config tags.
    #[must_use]
    pub fn with_tags<I, K, V>(mut self, tags: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
        K: Into<String>,
        V: Into<String>,
    {
        self.tags = tags
            .into_iter()
            .map(|(key, value)| (key.into(), value.into()))
            .collect();
        self
    }

    /// Kafka `MetricConfig.recordLevel()`.
    #[must_use]
    pub const fn record_level(&self) -> SensorRecordingLevel {
        self.record_level
    }

    /// Set the recording level.
    #[must_use]
    pub const fn with_record_level(mut self, record_level: SensorRecordingLevel) -> Self {
        self.record_level = record_level;
        self
    }
}

impl Default for MetricConfig {
    fn default() -> Self {
        Self::new()
    }
}

/// Registered metric with a value provider.
#[derive(Clone)]
pub struct KafkaMetric {
    metric_name: MetricName,
    provider: Arc<dyn Fn(u64) -> MetricValue + Send + Sync>,
    config: Arc<Mutex<MetricConfig>>,
}

impl KafkaMetric {
    fn new(
        metric_name: MetricName,
        provider: impl Fn() -> MetricValue + Send + Sync + 'static,
    ) -> Self {
        Self::new_with_config(metric_name, MetricConfig::new(), provider)
    }

    fn new_with_config(
        metric_name: MetricName,
        config: MetricConfig,
        provider: impl Fn() -> MetricValue + Send + Sync + 'static,
    ) -> Self {
        Self::new_with_shared_config(metric_name, Arc::new(Mutex::new(config)), move |_now_ms| {
            provider()
        })
    }

    fn new_with_shared_config(
        metric_name: MetricName,
        config: Arc<Mutex<MetricConfig>>,
        provider: impl Fn(u64) -> MetricValue + Send + Sync + 'static,
    ) -> Self {
        Self {
            metric_name,
            provider: Arc::new(provider),
            config,
        }
    }

    /// Create a metric from a value provider.
    #[must_use]
    pub fn from_fn(
        metric_name: MetricName,
        provider: impl Fn() -> MetricValue + Send + Sync + 'static,
    ) -> Self {
        Self::new(metric_name, provider)
    }

    /// Create a metric from a value provider and config.
    #[must_use]
    pub fn from_fn_with_config(
        metric_name: MetricName,
        config: MetricConfig,
        provider: impl Fn() -> MetricValue + Send + Sync + 'static,
    ) -> Self {
        Self::new_with_config(metric_name, config, provider)
    }

    /// Metric identity.
    #[must_use]
    pub const fn metric_name(&self) -> &MetricName {
        &self.metric_name
    }

    /// Read the current metric value.
    #[must_use]
    pub fn metric_value(&self) -> f64 {
        self.metric_value_at_ms(current_time_ms())
    }

    /// Read the metric value at an explicit millisecond timestamp.
    #[must_use]
    pub fn metric_value_at_ms(&self, time_ms: u64) -> f64 {
        (self.provider)(time_ms).as_f64()
    }

    /// Return a copy of the metric config.
    #[must_use]
    pub fn metric_config(&self) -> MetricConfig {
        self.config
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone()
    }

    /// Replace the metric config, matching Kafka `KafkaMetric.config(newConfig)`.
    pub fn set_metric_config(&self, config: MetricConfig) {
        *self
            .config
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = config;
    }

    fn quota(&self) -> Option<MetricQuota> {
        self.config
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .quota()
    }
}

impl fmt::Debug for KafkaMetric {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("KafkaMetric")
            .field("metric_name", &self.metric_name)
            .finish_non_exhaustive()
    }
}

/// Rust-native metrics reporter lifecycle.
pub trait MetricReporter: fmt::Debug + Send + Sync + 'static {
    /// Initialize reporter with currently registered metrics.
    fn init(&self, _metrics: &[KafkaMetric]) {}

    /// Observe a newly registered or changed metric.
    fn metric_change(&self, _metric: &KafkaMetric) {}

    /// Observe a removed metric.
    fn metric_removal(&self, _metric: &KafkaMetric) {}

    /// Release reporter resources.
    fn close(&self) {}
}

/// Sensor recording level.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum SensorRecordingLevel {
    /// Info level.
    #[default]
    Info,
    /// Debug level.
    Debug,
    /// Trace level.
    Trace,
}

impl SensorRecordingLevel {
    const fn should_record(self, configured: Self) -> bool {
        match configured {
            Self::Info => matches!(self, Self::Info),
            Self::Debug => matches!(self, Self::Info | Self::Debug),
            Self::Trace => true,
        }
    }
}

/// Opaque sensor identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SensorId(usize);

/// Metrics registry mirroring Kafka's `org.apache.kafka.common.metrics`.
#[derive(Debug, Default)]
pub struct Metrics {
    registered: BTreeMap<MetricName, KafkaMetric>,
    reporters: Vec<Arc<dyn MetricReporter>>,
    sensors: Vec<Option<SensorState>>,
    sensors_by_name: HashMap<String, SensorId>,
    recording_level: SensorRecordingLevel,
    default_tags: BTreeMap<String, String>,
    closed: bool,
    /// True once any registered metric carries a quota. Lets `record_inner`
    /// skip the per-record quota scan (a `BTreeMap<MetricName>` lookup per stat)
    /// entirely when no quotas are configured — the common producer case.
    any_quota: bool,
}

#[derive(Debug)]
struct SensorState {
    name: String,
    parents: Vec<SensorId>,
    stats: Vec<SensorStat>,
    recording_level: SensorRecordingLevel,
    inactive_expiration_ms: Option<u64>,
    last_record_time_ms: u64,
}

#[derive(Debug, Clone)]
struct SensorStat {
    metric_name: MetricName,
    state: SensorStatState,
}

#[derive(Debug, Clone, Copy)]
enum SensorStatRecordMode {
    Total,
    Value,
    Avg,
    Count,
    Min,
    Max,
    Rate,
    TokenBucket,
}

#[derive(Debug, Clone)]
enum SensorStatState {
    Scalar {
        value: Arc<Mutex<f64>>,
        record_mode: SensorStatRecordMode,
    },
    Avg {
        state: Arc<Mutex<AvgSensorStat>>,
    },
    Extrema {
        state: Arc<Mutex<ExtremaSensorStat>>,
        record_mode: SensorStatRecordMode,
    },
    Rate {
        state: Arc<Mutex<WindowedRateStat>>,
        config: Arc<Mutex<MetricConfig>>,
    },
    TokenBucket {
        state: Arc<Mutex<TokenBucketStat>>,
        config: Arc<Mutex<MetricConfig>>,
    },
    Frequency {
        state: Arc<Mutex<FrequencyStat>>,
        config: Arc<Mutex<MetricConfig>>,
    },
}

#[derive(Debug, Default)]
struct AvgSensorStat {
    total: f64,
    count: f64,
}

#[derive(Debug)]
struct ExtremaSensorStat {
    value: f64,
    count: f64,
}

#[derive(Debug)]
struct WindowedRateStat {
    samples: Vec<WindowedSample>,
    current: usize,
}

#[derive(Debug, Default)]
struct TokenBucketStat {
    tokens: f64,
    last_update_ms: u64,
}

#[derive(Debug)]
struct FrequencyStat {
    samples: Vec<FrequencySample>,
    current: usize,
    spec: FrequencySpec,
}

#[derive(Debug, Clone, Copy)]
struct FrequencySpec {
    center_value: f64,
    min: f64,
    max: f64,
    buckets: usize,
}

#[derive(Debug, Clone, Copy)]
struct WindowedSample {
    value: f64,
    event_count: u64,
    start_time_ms: u64,
    last_event_ms: u64,
}

impl WindowedRateStat {
    const fn new() -> Self {
        Self {
            samples: Vec::new(),
            current: 0,
        }
    }

    fn record(&mut self, config: &MetricConfig, value: f64, time_ms: u64) {
        self.ensure_current_sample(time_ms);
        if self
            .samples
            .get(self.current)
            .is_some_and(|sample| sample.is_complete(config, time_ms))
        {
            self.advance(config, time_ms);
        }
        self.ensure_current_sample(time_ms);
        if let Some(sample) = self.samples.get_mut(self.current) {
            sample.value += value;
            sample.event_count = sample.event_count.saturating_add(1);
            sample.last_event_ms = time_ms;
        }
    }

    fn measure(&mut self, config: &MetricConfig, now_ms: u64) -> f64 {
        self.purge_obsolete_samples(config, now_ms);
        let value = self.samples.iter().map(|sample| sample.value).sum::<f64>();
        let window_size_ms = u32::try_from(self.window_size_ms(config, now_ms)).unwrap_or(u32::MAX);
        value / (f64::from(window_size_ms) / 1000.0)
    }

    fn ensure_current_sample(&mut self, time_ms: u64) {
        if self.samples.is_empty() {
            self.samples.push(WindowedSample::new(time_ms));
        }
        if self.current >= self.samples.len() {
            self.current = self.samples.len().saturating_sub(1);
        }
    }

    fn advance(&mut self, config: &MetricConfig, time_ms: u64) {
        let max_samples = config.samples().saturating_add(1);
        self.current = self
            .current
            .saturating_add(1)
            .checked_rem(max_samples)
            .unwrap_or(0);
        if self.current >= self.samples.len() {
            self.samples.push(WindowedSample::new(time_ms));
        } else if let Some(sample) = self.samples.get_mut(self.current) {
            sample.reset(time_ms);
        }
    }

    fn purge_obsolete_samples(&mut self, config: &MetricConfig, now_ms: u64) {
        let expire_age_ms = u64::try_from(config.samples())
            .unwrap_or(u64::MAX)
            .saturating_mul(config.time_window_ms());
        for sample in &mut self.samples {
            if now_ms.saturating_sub(sample.last_event_ms) >= expire_age_ms {
                sample.reset(now_ms);
            }
        }
    }

    fn window_size_ms(&mut self, config: &MetricConfig, now_ms: u64) -> u64 {
        if self.samples.is_empty() {
            self.samples.push(WindowedSample::new(now_ms));
        }
        let oldest_start_ms = self
            .samples
            .iter()
            .map(|sample| sample.start_time_ms)
            .min()
            .unwrap_or(now_ms);
        let mut total_elapsed_ms = now_ms.saturating_sub(oldest_start_ms);
        let window_ms = config.time_window_ms().max(1);
        let full_windows =
            usize::try_from(total_elapsed_ms.checked_div(window_ms).unwrap_or(0)).unwrap_or(0);
        let min_full_windows = config.samples().saturating_sub(1);
        if full_windows < min_full_windows {
            let missing = min_full_windows.saturating_sub(full_windows);
            let missing_ms = u64::try_from(missing)
                .unwrap_or(u64::MAX)
                .saturating_mul(window_ms);
            total_elapsed_ms = total_elapsed_ms.saturating_add(missing_ms);
        }
        total_elapsed_ms.max(1)
    }
}

impl WindowedSample {
    const fn new(time_ms: u64) -> Self {
        Self {
            value: 0.0,
            event_count: 0,
            start_time_ms: time_ms,
            last_event_ms: time_ms,
        }
    }

    const fn reset(&mut self, time_ms: u64) {
        *self = Self::new(time_ms);
    }

    const fn is_complete(self, config: &MetricConfig, time_ms: u64) -> bool {
        time_ms.saturating_sub(self.start_time_ms) >= config.time_window_ms()
            || self.event_count >= config.event_window()
    }
}

#[derive(Debug, Clone)]
struct FrequencySample {
    counts: Vec<f64>,
    event_count: u64,
    start_time_ms: u64,
    last_event_ms: u64,
}

impl TokenBucketStat {
    fn record(&mut self, config: &MetricConfig, value: f64, time_ms: u64) {
        let Some(quota) = config.quota() else {
            return;
        };
        let burst = Self::burst(config, quota);
        self.refill(quota.bound(), burst, time_ms);
        self.tokens = (self.tokens - value).min(burst);
    }

    fn measure(&mut self, config: &MetricConfig, time_ms: u64) -> f64 {
        let Some(quota) = config.quota() else {
            return f64::MAX;
        };
        let burst = Self::burst(config, quota);
        self.refill(quota.bound(), burst, time_ms);
        self.tokens
    }

    fn refill(&mut self, quota: f64, burst: f64, time_ms: u64) {
        let elapsed_ms = time_ms.saturating_sub(self.last_update_ms);
        self.tokens = quota
            .mul_add(millis_to_seconds(elapsed_ms), self.tokens)
            .min(burst);
        self.last_update_ms = time_ms;
    }

    fn burst(config: &MetricConfig, quota: MetricQuota) -> f64 {
        let samples = u32::try_from(config.samples()).unwrap_or(u32::MAX);
        f64::from(samples) * millis_to_seconds(config.time_window_ms()) * quota.bound()
    }
}

fn millis_to_seconds(time_ms: u64) -> f64 {
    f64::from(u32::try_from(time_ms).unwrap_or(u32::MAX)) / 1000.0
}

impl FrequencyStat {
    fn new(spec: FrequencySpec) -> Result<Self, MetricsError> {
        let FrequencySpec {
            buckets,
            min,
            max,
            center_value,
        } = spec;
        if max < min {
            return Err(MetricsError::InvalidMetricConfig {
                reason: format!("maximum value {max} must be greater than minimum value {min}"),
            });
        }
        if buckets < 1 {
            return Err(MetricsError::InvalidMetricConfig {
                reason: "must be at least 1 bucket".to_owned(),
            });
        }
        if center_value < min || center_value > max {
            return Err(MetricsError::InvalidMetricConfig {
                reason: format!(
                    "frequency center value {center_value} is not within range [{min},{max}]"
                ),
            });
        }
        Ok(Self {
            samples: Vec::new(),
            current: 0,
            spec,
        })
    }

    fn record(&mut self, config: &MetricConfig, value: f64, time_ms: u64) {
        self.ensure_current_sample(time_ms);
        if self
            .samples
            .get(self.current)
            .is_some_and(|sample| sample.is_complete(config, time_ms))
        {
            self.advance(config, time_ms);
        }
        let bin = self.to_bin(value);
        if let Some(sample) = self.samples.get_mut(self.current)
            && let Some(count) = sample.counts.get_mut(bin)
        {
            *count += 1.0;
            sample.event_count = sample.event_count.saturating_add(1);
            sample.last_event_ms = time_ms;
        }
    }

    fn measure(&mut self, config: &MetricConfig, now_ms: u64) -> f64 {
        self.purge_obsolete_samples(config, now_ms);
        let total_count = self
            .samples
            .iter()
            .map(|sample| sample.event_count)
            .sum::<u64>();
        if total_count == 0 {
            return 0.0;
        }
        let bin = self.to_bin(self.spec.center_value);
        let count = self
            .samples
            .iter()
            .filter_map(|sample| sample.counts.get(bin))
            .sum::<f64>();
        count / f64::from(u32::try_from(total_count).unwrap_or(u32::MAX))
    }

    fn ensure_current_sample(&mut self, time_ms: u64) {
        if self.samples.is_empty() {
            self.samples
                .push(FrequencySample::new(self.spec.buckets, time_ms));
        }
        if self.current >= self.samples.len() {
            self.current = self.samples.len().saturating_sub(1);
        }
    }

    fn advance(&mut self, config: &MetricConfig, time_ms: u64) {
        let max_samples = config.samples().saturating_add(1);
        self.current = self
            .current
            .saturating_add(1)
            .checked_rem(max_samples)
            .unwrap_or(0);
        if self.current >= self.samples.len() {
            self.samples
                .push(FrequencySample::new(self.spec.buckets, time_ms));
        } else if let Some(sample) = self.samples.get_mut(self.current) {
            sample.reset(self.spec.buckets, time_ms);
        }
    }

    fn purge_obsolete_samples(&mut self, config: &MetricConfig, now_ms: u64) {
        let expire_age_ms = u64::try_from(config.samples())
            .unwrap_or(u64::MAX)
            .saturating_mul(config.time_window_ms());
        for sample in &mut self.samples {
            if now_ms.saturating_sub(sample.last_event_ms) >= expire_age_ms {
                sample.reset(self.spec.buckets, now_ms);
            }
        }
    }

    fn to_bin(&self, value: f64) -> usize {
        if self.spec.buckets <= 1 || self.spec.max <= self.spec.min {
            return 0;
        }
        let denominator = self.spec.buckets.saturating_sub(1);
        let half_bucket_width = (self.spec.max - self.spec.min)
            / f64::from(u32::try_from(denominator).unwrap_or(u32::MAX))
            / 2.0;
        let min = self.spec.min - half_bucket_width;
        let max = self.spec.max + half_bucket_width;
        let bucket_width =
            (max - min) / f64::from(u32::try_from(self.spec.buckets).unwrap_or(u32::MAX));
        if !bucket_width.is_finite() || value <= min {
            return 0;
        }
        let mut upper = min + bucket_width;
        for bin in 0..self.spec.buckets.saturating_sub(1) {
            if value < upper {
                return bin;
            }
            upper += bucket_width;
        }
        self.spec.buckets.saturating_sub(1)
    }
}

impl FrequencySample {
    fn new(buckets: usize, time_ms: u64) -> Self {
        Self {
            counts: vec![0.0; buckets],
            event_count: 0,
            start_time_ms: time_ms,
            last_event_ms: time_ms,
        }
    }

    fn reset(&mut self, buckets: usize, time_ms: u64) {
        *self = Self::new(buckets, time_ms);
    }

    const fn is_complete(&self, config: &MetricConfig, time_ms: u64) -> bool {
        time_ms.saturating_sub(self.start_time_ms) >= config.time_window_ms()
            || self.event_count >= config.event_window()
    }
}

impl SensorStat {
    fn new(
        metric_name: MetricName,
        record_mode: SensorStatRecordMode,
        config: MetricConfig,
    ) -> (Self, KafkaMetric) {
        match record_mode {
            SensorStatRecordMode::Total
            | SensorStatRecordMode::Value
            | SensorStatRecordMode::Count => {
                let value = Arc::new(Mutex::new(0.0));
                let metric_value = Arc::clone(&value);
                let metric = KafkaMetric::new_with_config(metric_name.clone(), config, move || {
                    let value = metric_value
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    MetricValue::Number(*value)
                });
                (
                    Self {
                        metric_name,
                        state: SensorStatState::Scalar { value, record_mode },
                    },
                    metric,
                )
            },
            SensorStatRecordMode::Avg => {
                let state = Arc::new(Mutex::new(AvgSensorStat::default()));
                let metric_state = Arc::clone(&state);
                let metric = KafkaMetric::new_with_config(metric_name.clone(), config, move || {
                    let state = metric_state
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    if state.count == 0.0 {
                        return MetricValue::Number(f64::NAN);
                    }
                    MetricValue::Number(state.total / state.count)
                });
                (
                    Self {
                        metric_name,
                        state: SensorStatState::Avg { state },
                    },
                    metric,
                )
            },
            SensorStatRecordMode::Min | SensorStatRecordMode::Max => {
                let initial_value = if matches!(record_mode, SensorStatRecordMode::Min) {
                    f64::MAX
                } else {
                    f64::NEG_INFINITY
                };
                let state = Arc::new(Mutex::new(ExtremaSensorStat {
                    value: initial_value,
                    count: 0.0,
                }));
                let metric_state = Arc::clone(&state);
                let metric = KafkaMetric::new_with_config(metric_name.clone(), config, move || {
                    let state = metric_state
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    if state.count == 0.0 {
                        return MetricValue::Number(f64::NAN);
                    }
                    MetricValue::Number(state.value)
                });
                (
                    Self {
                        metric_name,
                        state: SensorStatState::Extrema { state, record_mode },
                    },
                    metric,
                )
            },
            SensorStatRecordMode::Rate => Self::new_rate(metric_name, config),
            SensorStatRecordMode::TokenBucket => Self::new_token_bucket(metric_name, config),
        }
    }

    fn new_rate(metric_name: MetricName, config: MetricConfig) -> (Self, KafkaMetric) {
        let state = Arc::new(Mutex::new(WindowedRateStat::new()));
        let metric_state = Arc::clone(&state);
        let config = Arc::new(Mutex::new(config));
        let metric_config = Arc::clone(&config);
        let metric = KafkaMetric::new_with_shared_config(
            metric_name.clone(),
            Arc::clone(&config),
            move |now_ms| {
                let config = metric_config
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .clone();
                let mut state = metric_state
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                MetricValue::Number(state.measure(&config, now_ms))
            },
        );
        (
            Self {
                metric_name,
                state: SensorStatState::Rate { state, config },
            },
            metric,
        )
    }

    fn new_token_bucket(metric_name: MetricName, config: MetricConfig) -> (Self, KafkaMetric) {
        let state = Arc::new(Mutex::new(TokenBucketStat::default()));
        let metric_state = Arc::clone(&state);
        let config = Arc::new(Mutex::new(config));
        let metric_config = Arc::clone(&config);
        let metric = KafkaMetric::new_with_shared_config(
            metric_name.clone(),
            Arc::clone(&config),
            move |now_ms| {
                let config = metric_config
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .clone();
                let mut state = metric_state
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                MetricValue::Number(state.measure(&config, now_ms))
            },
        );
        (
            Self {
                metric_name,
                state: SensorStatState::TokenBucket { state, config },
            },
            metric,
        )
    }

    fn new_frequency(
        metric_name: MetricName,
        config: MetricConfig,
        spec: FrequencySpec,
    ) -> Result<(Self, KafkaMetric), MetricsError> {
        let state = Arc::new(Mutex::new(FrequencyStat::new(spec)?));
        let metric_state = Arc::clone(&state);
        let config = Arc::new(Mutex::new(config));
        let metric_config = Arc::clone(&config);
        let metric = KafkaMetric::new_with_shared_config(
            metric_name.clone(),
            Arc::clone(&config),
            move |now_ms| {
                let config = metric_config
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .clone();
                let mut state = metric_state
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                MetricValue::Number(state.measure(&config, now_ms))
            },
        );
        Ok((
            Self {
                metric_name,
                state: SensorStatState::Frequency { state, config },
            },
            metric,
        ))
    }

    fn record(&self, value: f64, time_ms: u64) {
        match &self.state {
            SensorStatState::Scalar {
                value: current,
                record_mode,
            } => {
                let mut current = current
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                match record_mode {
                    SensorStatRecordMode::Total => *current += value,
                    SensorStatRecordMode::Value => *current = value,
                    SensorStatRecordMode::Count => *current += 1.0,
                    SensorStatRecordMode::Avg
                    | SensorStatRecordMode::Min
                    | SensorStatRecordMode::Max
                    | SensorStatRecordMode::Rate
                    | SensorStatRecordMode::TokenBucket => {},
                }
            },
            SensorStatState::Avg { state } => {
                let mut state = state
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                state.total += value;
                state.count += 1.0;
            },
            SensorStatState::Extrema { state, record_mode } => {
                let mut state = state
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                match record_mode {
                    SensorStatRecordMode::Min => state.value = state.value.min(value),
                    SensorStatRecordMode::Max => state.value = state.value.max(value),
                    SensorStatRecordMode::Total
                    | SensorStatRecordMode::Value
                    | SensorStatRecordMode::Avg
                    | SensorStatRecordMode::Count
                    | SensorStatRecordMode::Rate
                    | SensorStatRecordMode::TokenBucket => {},
                }
                state.count += 1.0;
            },
            SensorStatState::Rate { state, config } => {
                let config = config
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .clone();
                let mut state = state
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                state.record(&config, value, time_ms);
            },
            SensorStatState::TokenBucket { state, config } => {
                let config = config
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .clone();
                let mut state = state
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                state.record(&config, value, time_ms);
            },
            SensorStatState::Frequency { state, config } => {
                let config = config
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .clone();
                let mut state = state
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                state.record(&config, value, time_ms);
            },
        }
    }

    const fn is_token_bucket(&self) -> bool {
        matches!(self.state, SensorStatState::TokenBucket { .. })
    }
}

impl Metrics {
    /// Create an empty metrics registry.
    #[must_use]
    pub fn new() -> Self {
        Self {
            registered: BTreeMap::new(),
            reporters: Vec::new(),
            sensors: Vec::new(),
            sensors_by_name: HashMap::new(),
            recording_level: SensorRecordingLevel::Info,
            default_tags: BTreeMap::new(),
            closed: false,
            any_quota: false,
        }
    }

    /// Set the registry-wide recording level.
    #[must_use]
    pub const fn with_recording_level(mut self, recording_level: SensorRecordingLevel) -> Self {
        self.recording_level = recording_level;
        self
    }

    /// Add or replace one default tag used by [`Self::metric_name`].
    #[must_use]
    pub fn with_default_tag(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        let _previous = self.default_tags.insert(key.into(), value.into());
        self
    }

    /// Create a metric name.
    #[must_use]
    pub fn metric_name(&self, name: &str, group: &str, description: &str) -> MetricName {
        self.metric_name_with_tags(name, group, description, [])
    }

    /// Create a metric name with explicit tags overriding default tags.
    #[must_use]
    pub fn metric_name_with_tags<'a, I>(
        &self,
        name: &str,
        group: &str,
        description: &str,
        tags: I,
    ) -> MetricName
    where
        I: IntoIterator<Item = (&'a str, &'a str)>,
    {
        let mut metric_name = MetricName::new(name, group).with_description(description);
        for (key, value) in &self.default_tags {
            metric_name = metric_name.tag(key.as_str(), value.as_str());
        }
        for (key, value) in tags {
            metric_name = metric_name.tag(key, value);
        }
        metric_name
    }

    /// Create a metric name from a template and runtime tags.
    ///
    /// # Errors
    ///
    /// Returns an error when default plus runtime tag keys do not exactly
    /// match the template tag keys.
    pub fn metric_instance<'a, I>(
        &self,
        template: &MetricNameTemplate,
        tags: I,
    ) -> Result<MetricName, MetricsError>
    where
        I: IntoIterator<Item = (&'a str, &'a str)>,
    {
        let tags = tags.into_iter().collect::<Vec<_>>();
        let mut runtime_tag_keys = self
            .default_tags
            .keys()
            .map(String::as_str)
            .collect::<BTreeSet<_>>();
        runtime_tag_keys.extend(tags.iter().map(|(key, _value)| *key));
        let template_tag_keys = template.tag_set();
        if runtime_tag_keys != template_tag_keys {
            return Err(MetricsError::InvalidMetricConfig {
                reason: format!(
                    "runtime-defined metric tags do not match template tags for '{}'",
                    template.name()
                ),
            });
        }
        Ok(self.metric_name_with_tags(
            template.name(),
            template.group(),
            template.description(),
            tags,
        ))
    }

    /// Return a sensor by name, creating it when missing.
    pub fn sensor(&mut self, name: impl Into<String>) -> SensorId {
        self.sensor_with_parents(name, SensorRecordingLevel::Info, [])
    }

    /// Return a sensor by name with parents, creating it when missing.
    pub fn sensor_with_parents<I>(
        &mut self,
        name: impl Into<String>,
        recording_level: SensorRecordingLevel,
        parents: I,
    ) -> SensorId
    where
        I: IntoIterator<Item = SensorId>,
    {
        let name = name.into();
        if let Some(sensor) = self.sensors_by_name.get(&name).copied() {
            return sensor;
        }
        let sensor = SensorId(self.sensors.len());
        self.sensors.push(Some(SensorState {
            name: name.clone(),
            parents: parents.into_iter().collect(),
            stats: Vec::new(),
            recording_level,
            inactive_expiration_ms: None,
            last_record_time_ms: current_time_ms(),
        }));
        let _previous = self.sensors_by_name.insert(name, sensor);
        sensor
    }

    /// Return a sensor by name with inactive expiration, creating it when missing.
    pub fn sensor_with_expiration<I>(
        &mut self,
        name: impl Into<String>,
        recording_level: SensorRecordingLevel,
        inactive_expiration: Duration,
        parents: I,
    ) -> SensorId
    where
        I: IntoIterator<Item = SensorId>,
    {
        let name = name.into();
        if let Some(sensor) = self.sensors_by_name.get(&name).copied() {
            return sensor;
        }
        let sensor = SensorId(self.sensors.len());
        self.sensors.push(Some(SensorState {
            name: name.clone(),
            parents: parents.into_iter().collect(),
            stats: Vec::new(),
            recording_level,
            inactive_expiration_ms: u64::try_from(inactive_expiration.as_millis()).ok(),
            last_record_time_ms: 0,
        }));
        let _previous = self.sensors_by_name.insert(name, sensor);
        sensor
    }

    /// Set an existing sensor's recording level.
    ///
    /// # Errors
    ///
    /// Returns an error when `sensor` does not exist.
    pub fn sensor_set_recording_level(
        &mut self,
        sensor: SensorId,
        recording_level: SensorRecordingLevel,
    ) -> Result<(), MetricsError> {
        let state = self.sensor_mut(sensor)?;
        state.recording_level = recording_level;
        Ok(())
    }

    /// Return an existing sensor's name.
    ///
    /// # Errors
    ///
    /// Returns an error when `sensor` does not exist.
    pub fn sensor_name(&self, sensor: SensorId) -> Result<&str, MetricsError> {
        self.sensor_state(sensor).map(|state| state.name.as_str())
    }

    /// Return whether a sensor has registered metrics.
    ///
    /// # Errors
    ///
    /// Returns an error when `sensor` does not exist.
    pub fn sensor_has_metrics(&self, sensor: SensorId) -> Result<bool, MetricsError> {
        self.sensor_state(sensor)
            .map(|state| !state.stats.is_empty())
    }

    /// Return a copy of a sensor's registered metrics.
    ///
    /// # Errors
    ///
    /// Returns an error when `sensor` does not exist.
    pub fn sensor_metrics(&self, sensor: SensorId) -> Result<Vec<KafkaMetric>, MetricsError> {
        self.sensor_state(sensor).map(|state| {
            state
                .stats
                .iter()
                .filter_map(|stat| self.registered.get(&stat.metric_name).cloned())
                .collect()
        })
    }

    /// Return whether a sensor is eligible for removal at `now_ms`.
    ///
    /// # Errors
    ///
    /// Returns an error when `sensor` does not exist.
    pub fn sensor_has_expired_at_ms(
        &self,
        sensor: SensorId,
        now_ms: u64,
    ) -> Result<bool, MetricsError> {
        self.sensor_state(sensor)
            .map(|state| is_sensor_expired(state, now_ms))
    }

    /// Add a total statistic to a sensor.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_total(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
    ) -> Result<(), MetricsError> {
        self.sensor_add_total_with_config(sensor, metric_name, MetricConfig::new())
    }

    /// Add a total statistic with a metric config to a sensor.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_total_with_config(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
        config: MetricConfig,
    ) -> Result<(), MetricsError> {
        self.sensor_add_stat(sensor, metric_name, SensorStatRecordMode::Total, config)
    }

    /// Add a total statistic with a quota to a sensor.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_total_with_quota(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
        quota: MetricQuota,
    ) -> Result<(), MetricsError> {
        self.sensor_add_total_with_config(
            sensor,
            metric_name,
            MetricConfig::new().with_quota(quota),
        )
    }

    /// Add a latest-value statistic to a sensor.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_value(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
    ) -> Result<(), MetricsError> {
        self.sensor_add_value_with_config(sensor, metric_name, MetricConfig::new())
    }

    /// Add a latest-value statistic with a metric config to a sensor.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_value_with_config(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
        config: MetricConfig,
    ) -> Result<(), MetricsError> {
        self.sensor_add_stat(sensor, metric_name, SensorStatRecordMode::Value, config)
    }

    /// Add a latest-value statistic with a quota to a sensor.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_value_with_quota(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
        quota: MetricQuota,
    ) -> Result<(), MetricsError> {
        self.sensor_add_value_with_config(
            sensor,
            metric_name,
            MetricConfig::new().with_quota(quota),
        )
    }

    /// Add an average statistic to a sensor.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_avg(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
    ) -> Result<(), MetricsError> {
        self.sensor_add_avg_with_config(sensor, metric_name, MetricConfig::new())
    }

    /// Add an average statistic with a metric config to a sensor.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_avg_with_config(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
        config: MetricConfig,
    ) -> Result<(), MetricsError> {
        self.sensor_add_stat(sensor, metric_name, SensorStatRecordMode::Avg, config)
    }

    /// Add an average statistic with a quota to a sensor.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_avg_with_quota(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
        quota: MetricQuota,
    ) -> Result<(), MetricsError> {
        self.sensor_add_avg_with_config(sensor, metric_name, MetricConfig::new().with_quota(quota))
    }

    /// Add a cumulative count statistic to a sensor.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_count(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
    ) -> Result<(), MetricsError> {
        self.sensor_add_count_with_config(sensor, metric_name, MetricConfig::new())
    }

    /// Add a cumulative count statistic with a metric config to a sensor.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_count_with_config(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
        config: MetricConfig,
    ) -> Result<(), MetricsError> {
        self.sensor_add_stat(sensor, metric_name, SensorStatRecordMode::Count, config)
    }

    /// Add a cumulative count statistic with a quota to a sensor.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_count_with_quota(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
        quota: MetricQuota,
    ) -> Result<(), MetricsError> {
        self.sensor_add_count_with_config(
            sensor,
            metric_name,
            MetricConfig::new().with_quota(quota),
        )
    }

    /// Add a Kafka `Rate` statistic to a sensor using seconds as the unit.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_rate(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
    ) -> Result<(), MetricsError> {
        self.sensor_add_rate_with_config(sensor, metric_name, MetricConfig::new())
    }

    /// Add a Kafka `Rate` statistic with a metric config.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_rate_with_config(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
        config: MetricConfig,
    ) -> Result<(), MetricsError> {
        self.sensor_add_stat(sensor, metric_name, SensorStatRecordMode::Rate, config)
    }

    /// Add a Kafka `TokenBucket` statistic to a sensor.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_token_bucket(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
    ) -> Result<(), MetricsError> {
        self.sensor_add_token_bucket_with_config(sensor, metric_name, MetricConfig::new())
    }

    /// Add a Kafka `TokenBucket` statistic with a metric config.
    ///
    /// The quota bound is the refill rate in tokens per second. The effective
    /// burst is `samples * time_window * bound`, matching Kafka `TokenBucket`.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_token_bucket_with_config(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
        config: MetricConfig,
    ) -> Result<(), MetricsError> {
        self.sensor_add_stat(
            sensor,
            metric_name,
            SensorStatRecordMode::TokenBucket,
            config,
        )
    }

    /// Add Kafka `Frequencies.forBooleanValues(falseMetric, trueMetric)`.
    ///
    /// Pass `None` for either metric name to skip that side. At least one
    /// metric name must be present, matching Kafka's null-name validation.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, both metric names are absent,
    /// or a metric name is already registered to a different metric. Re-adding a
    /// metric already on this sensor is a no-op.
    pub fn sensor_add_boolean_frequencies(
        &mut self,
        sensor: SensorId,
        false_metric_name: Option<MetricName>,
        true_metric_name: Option<MetricName>,
    ) -> Result<(), MetricsError> {
        self.sensor_add_boolean_frequencies_with_config(
            sensor,
            false_metric_name,
            true_metric_name,
            MetricConfig::new(),
        )
    }

    /// Add Kafka `Frequencies.forBooleanValues` with a metric config.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, both metric names are absent,
    /// or a metric name is already registered to a different metric. Re-adding a
    /// metric already on this sensor is a no-op.
    pub fn sensor_add_boolean_frequencies_with_config(
        &mut self,
        sensor: SensorId,
        false_metric_name: Option<MetricName>,
        true_metric_name: Option<MetricName>,
        config: MetricConfig,
    ) -> Result<(), MetricsError> {
        if false_metric_name.is_none() && true_metric_name.is_none() {
            return Err(MetricsError::InvalidMetricConfig {
                reason: "must specify at least one metric name".to_owned(),
            });
        }
        if let Some(metric_name) = false_metric_name {
            self.sensor_add_frequency_with_config(
                sensor,
                metric_name,
                config.clone(),
                FrequencySpec {
                    buckets: 2,
                    min: 0.0,
                    max: 1.0,
                    center_value: 0.0,
                },
            )?;
        }
        if let Some(metric_name) = true_metric_name {
            self.sensor_add_frequency_with_config(
                sensor,
                metric_name,
                config,
                FrequencySpec {
                    buckets: 2,
                    min: 0.0,
                    max: 1.0,
                    center_value: 1.0,
                },
            )?;
        }
        Ok(())
    }

    /// Add a Kafka `Meter` compound statistic: cumulative total plus rate.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when either metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_meter(
        &mut self,
        sensor: SensorId,
        rate_metric_name: MetricName,
        total_metric_name: MetricName,
    ) -> Result<(), MetricsError> {
        self.sensor_add_meter_with_config(
            sensor,
            rate_metric_name,
            total_metric_name,
            MetricConfig::new(),
        )
    }

    /// Add a Kafka `Meter` compound statistic with a metric config.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when either metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_meter_with_config(
        &mut self,
        sensor: SensorId,
        rate_metric_name: MetricName,
        total_metric_name: MetricName,
        config: MetricConfig,
    ) -> Result<(), MetricsError> {
        self.sensor_add_total_with_config(sensor, total_metric_name, config.clone())?;
        self.sensor_add_rate_with_config(sensor, rate_metric_name, config)
    }

    /// Add a minimum statistic to a sensor.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_min(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
    ) -> Result<(), MetricsError> {
        self.sensor_add_min_with_config(sensor, metric_name, MetricConfig::new())
    }

    /// Add a minimum statistic with a metric config to a sensor.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_min_with_config(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
        config: MetricConfig,
    ) -> Result<(), MetricsError> {
        self.sensor_add_stat(sensor, metric_name, SensorStatRecordMode::Min, config)
    }

    /// Add a minimum statistic with a quota to a sensor.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_min_with_quota(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
        quota: MetricQuota,
    ) -> Result<(), MetricsError> {
        self.sensor_add_min_with_config(sensor, metric_name, MetricConfig::new().with_quota(quota))
    }

    /// Add a maximum statistic to a sensor.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_max(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
    ) -> Result<(), MetricsError> {
        self.sensor_add_max_with_config(sensor, metric_name, MetricConfig::new())
    }

    /// Add a maximum statistic with a metric config to a sensor.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_max_with_config(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
        config: MetricConfig,
    ) -> Result<(), MetricsError> {
        self.sensor_add_stat(sensor, metric_name, SensorStatRecordMode::Max, config)
    }

    /// Add a maximum statistic with a quota to a sensor.
    ///
    /// # Errors
    ///
    /// Returns an error when the sensor is missing, or when the metric name is
    /// already registered to a different metric. Re-adding a metric already on
    /// this sensor is a no-op.
    pub fn sensor_add_max_with_quota(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
        quota: MetricQuota,
    ) -> Result<(), MetricsError> {
        self.sensor_add_max_with_config(sensor, metric_name, MetricConfig::new().with_quota(quota))
    }

    fn sensor_add_stat(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
        record_mode: SensorStatRecordMode,
        config: MetricConfig,
    ) -> Result<(), MetricsError> {
        if self
            .sensor_state(sensor)?
            .stats
            .iter()
            .any(|stat| stat.metric_name == metric_name)
        {
            return Ok(());
        }
        let (stat, metric) = SensorStat::new(metric_name.clone(), record_mode, config);
        self.add_kafka_metric(metric_name, metric)?;
        self.sensor_mut(sensor)?.stats.push(stat);
        Ok(())
    }

    fn sensor_add_frequency_with_config(
        &mut self,
        sensor: SensorId,
        metric_name: MetricName,
        config: MetricConfig,
        spec: FrequencySpec,
    ) -> Result<(), MetricsError> {
        if self
            .sensor_state(sensor)?
            .stats
            .iter()
            .any(|stat| stat.metric_name == metric_name)
        {
            return Ok(());
        }
        let (stat, metric) = SensorStat::new_frequency(metric_name.clone(), config, spec)?;
        self.add_kafka_metric(metric_name, metric)?;
        self.sensor_mut(sensor)?.stats.push(stat);
        Ok(())
    }

    /// Record a sensor value and propagate it to parent sensors.
    ///
    /// # Errors
    ///
    /// Returns an error when `sensor` does not exist or the record violates a quota.
    pub fn record(&mut self, sensor: SensorId, value: f64) -> Result<(), MetricsError> {
        self.record_at_ms(sensor, value, current_time_ms())
    }

    /// Record a sensor value with explicit quota enforcement, matching Kafka
    /// `Sensor.record(value, timeMs, checkQuotas)`.
    ///
    /// # Errors
    ///
    /// Returns an error when `sensor` does not exist or the record violates a
    /// quota while `check_quotas` is true.
    pub fn record_with_quota_check(
        &mut self,
        sensor: SensorId,
        value: f64,
        check_quotas: bool,
    ) -> Result<(), MetricsError> {
        self.record_with_quota_check_at_ms(sensor, value, current_time_ms(), check_quotas)
    }

    /// Record a sensor value at an explicit millisecond timestamp.
    ///
    /// # Errors
    ///
    /// Returns an error when `sensor` does not exist or the record violates a quota.
    pub fn record_at_ms(
        &mut self,
        sensor: SensorId,
        value: f64,
        time_ms: u64,
    ) -> Result<(), MetricsError> {
        self.record_with_quota_check_at_ms(sensor, value, time_ms, true)
    }

    /// Record a sensor value at an explicit timestamp with explicit quota enforcement.
    ///
    /// # Errors
    ///
    /// Returns an error when `sensor` does not exist or the record violates a
    /// quota while `check_quotas` is true.
    pub fn record_with_quota_check_at_ms(
        &mut self,
        sensor: SensorId,
        value: f64,
        time_ms: u64,
        check_quotas: bool,
    ) -> Result<(), MetricsError> {
        self.record_inner(sensor, value, time_ms, check_quotas)
    }

    /// Record one occurrence, matching Kafka `Sensor.record()`.
    ///
    /// # Errors
    ///
    /// Returns an error when `sensor` does not exist.
    pub fn record_once(&mut self, sensor: SensorId) -> Result<(), MetricsError> {
        self.record(sensor, 1.0)
    }

    /// Check all configured sensor stat quotas against current measured values.
    ///
    /// # Errors
    ///
    /// Returns an error when `sensor` does not exist, a sensor metric is missing,
    /// or the first metric value violates its configured quota.
    pub fn check_sensor_quotas(&self, sensor: SensorId) -> Result<(), MetricsError> {
        self.check_sensor_quotas_at_ms(sensor, current_time_ms())
    }

    /// Check sensor stat quotas at an explicit millisecond timestamp.
    ///
    /// # Errors
    ///
    /// Returns an error when `sensor` does not exist, a sensor metric is missing,
    /// or the first metric value violates its configured quota.
    pub fn check_sensor_quotas_at_ms(
        &self,
        sensor: SensorId,
        time_ms: u64,
    ) -> Result<(), MetricsError> {
        for stat in &self.sensor_state(sensor)?.stats {
            let metric = self
                .registered
                .get(&stat.metric_name)
                .ok_or_else(|| MetricsError::UnknownMetric(stat.metric_name.clone()))?;
            let Some(quota) = metric.quota() else {
                continue;
            };
            let value = metric.metric_value_at_ms(time_ms);
            if stat.is_token_bucket() {
                if value >= 0.0 {
                    continue;
                }
            } else if quota.acceptable(value) {
                continue;
            }
            {
                return Err(MetricsError::QuotaViolation {
                    metric_name: stat.metric_name.clone(),
                    value,
                    bound: quota.bound(),
                });
            }
        }
        Ok(())
    }

    /// Add a standalone metric.
    ///
    /// # Errors
    ///
    /// Returns an error when a metric with the same Kafka identity already exists.
    pub fn add_metric(
        &mut self,
        metric_name: MetricName,
        provider: impl Fn() -> MetricValue + Send + Sync + 'static,
    ) -> Result<(), MetricsError> {
        let metric = KafkaMetric::new(metric_name.clone(), provider);
        self.add_kafka_metric(metric_name, metric)
    }

    fn add_kafka_metric(
        &mut self,
        metric_name: MetricName,
        metric: KafkaMetric,
    ) -> Result<(), MetricsError> {
        if self.registered.contains_key(&metric_name) {
            return Err(MetricsError::DuplicateMetric(metric_name));
        }
        if metric.quota().is_some() {
            self.any_quota = true;
        }
        for reporter in &self.reporters {
            reporter.metric_change(&metric);
        }
        let _previous = self.registered.insert(metric_name, metric);
        Ok(())
    }

    /// Add a standalone metric unless one with the same Kafka identity exists.
    ///
    /// Returns the existing metric when present, matching Kafka `Metrics.addMetricIfAbsent`.
    pub fn add_metric_if_absent(
        &mut self,
        metric_name: MetricName,
        provider: impl Fn() -> MetricValue + Send + Sync + 'static,
    ) -> KafkaMetric {
        if let Some(metric) = self.registered.get(&metric_name) {
            return metric.clone();
        }
        let metric = KafkaMetric::new(metric_name.clone(), provider);
        for reporter in &self.reporters {
            reporter.metric_change(&metric);
        }
        let _previous = self.registered.insert(metric_name, metric.clone());
        metric
    }

    /// Add a metrics reporter and initialize it with current metrics.
    pub fn add_reporter(&mut self, reporter: impl MetricReporter) {
        let reporter = Arc::new(reporter);
        let metrics = self.registered.values().cloned().collect::<Vec<_>>();
        reporter.init(&metrics);
        self.reporters.push(reporter);
    }

    /// Remove a metric.
    ///
    /// # Errors
    ///
    /// Returns an error when the metric does not exist.
    pub fn remove_metric(&mut self, metric_name: &MetricName) -> Result<KafkaMetric, MetricsError> {
        let Some(metric) = self.registered.remove(metric_name) else {
            return Err(MetricsError::UnknownMetric(metric_name.clone()));
        };
        for reporter in &self.reporters {
            reporter.metric_removal(&metric);
        }
        Ok(metric)
    }

    /// Remove a metric when present.
    ///
    /// Returns `None` when the metric does not exist, matching Kafka `Metrics.removeMetric`.
    #[must_use]
    pub fn remove_metric_if_present(&mut self, metric_name: &MetricName) -> Option<KafkaMetric> {
        let metric = self.registered.remove(metric_name)?;
        for reporter in &self.reporters {
            reporter.metric_removal(&metric);
        }
        Some(metric)
    }

    /// Remove a sensor and its child sensors, including their registered metrics.
    ///
    /// Returns `false` when no sensor with `name` exists, matching Kafka's no-op removal.
    pub fn remove_sensor(&mut self, name: &str) -> bool {
        let Some(sensor) = self.sensors_by_name.remove(name) else {
            return false;
        };
        self.remove_sensor_by_id(sensor)
    }

    /// Remove expired sensors and their children, matching Kafka's expire sensor task.
    ///
    /// Returns the number of sensors removed, including children removed with an
    /// expired parent.
    pub fn expire_sensors_at_ms(&mut self, now_ms: u64) -> usize {
        let expired = self
            .sensors
            .iter()
            .enumerate()
            .filter_map(|(index, state)| {
                state
                    .as_ref()
                    .and_then(|state| is_sensor_expired(state, now_ms).then_some(SensorId(index)))
            })
            .collect::<Vec<_>>();
        let before = self.sensors.iter().flatten().count();
        for sensor in expired {
            let _removed = self.remove_sensor_by_id(sensor);
        }
        let after = self.sensors.iter().flatten().count();
        before.saturating_sub(after)
    }

    /// Return a registered metric.
    #[must_use]
    pub fn metric(&self, metric_name: &MetricName) -> Option<&KafkaMetric> {
        self.registered.get(metric_name)
    }

    /// Iterate every registered metric and its current value handle.
    pub fn registered_metrics(&self) -> impl Iterator<Item = (&MetricName, &KafkaMetric)> {
        self.registered.iter()
    }

    /// Close all reporters once.
    pub fn close(&mut self) {
        if self.closed {
            return;
        }
        self.closed = true;
        for reporter in &self.reporters {
            reporter.close();
        }
    }

    fn record_inner(
        &mut self,
        sensor: SensorId,
        value: f64,
        time_ms: u64,
        check_quotas: bool,
    ) -> Result<(), MetricsError> {
        let should_record = self
            .sensor_state(sensor)?
            .recording_level
            .should_record(self.recording_level);
        if !should_record {
            return Ok(());
        }
        let parents = {
            let state = self.sensor_mut(sensor)?;
            state.last_record_time_ms = time_ms;
            for stat in &state.stats {
                stat.record(value, time_ms);
            }
            state.parents.clone()
        };
        if check_quotas && self.any_quota {
            self.check_sensor_quotas_at_ms(sensor, time_ms)?;
        }
        for parent in parents {
            self.record_inner(parent, value, time_ms, check_quotas)?;
        }
        Ok(())
    }

    fn sensor_state(&self, sensor: SensorId) -> Result<&SensorState, MetricsError> {
        self.sensors
            .get(sensor.0)
            .and_then(Option::as_ref)
            .ok_or(MetricsError::UnknownSensor { sensor })
    }

    fn sensor_mut(&mut self, sensor: SensorId) -> Result<&mut SensorState, MetricsError> {
        self.sensors
            .get_mut(sensor.0)
            .and_then(Option::as_mut)
            .ok_or(MetricsError::UnknownSensor { sensor })
    }

    fn remove_sensor_by_id(&mut self, sensor: SensorId) -> bool {
        let child_sensors = self.child_sensors(sensor);
        let Some(state) = self.sensors.get_mut(sensor.0).and_then(Option::take) else {
            return false;
        };
        let _removed = self.sensors_by_name.remove(&state.name);
        for stat in state.stats {
            let _removed = self.remove_metric(&stat.metric_name);
        }
        for child in child_sensors {
            let _removed = self.remove_sensor_by_id(child);
        }
        self.remove_parent_link(sensor);
        true
    }

    fn child_sensors(&self, parent: SensorId) -> Vec<SensorId> {
        self.sensors
            .iter()
            .enumerate()
            .filter_map(|(index, state)| {
                state
                    .as_ref()
                    .and_then(|state| state.parents.contains(&parent).then_some(SensorId(index)))
            })
            .collect()
    }

    fn remove_parent_link(&mut self, removed: SensorId) {
        for state in &mut self.sensors {
            let Some(state) = state else {
                continue;
            };
            state.parents.retain(|parent| *parent != removed);
        }
    }
}

impl Drop for Metrics {
    fn drop(&mut self) {
        self.close();
    }
}

fn current_time_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .ok()
        .and_then(|duration| u64::try_from(duration.as_millis()).ok())
        .unwrap_or(u64::MAX)
}

fn is_sensor_expired(state: &SensorState, now_ms: u64) -> bool {
    state
        .inactive_expiration_ms
        .is_some_and(|expiration| now_ms.saturating_sub(state.last_record_time_ms) > expiration)
}

/// Metrics registry error.
#[derive(Debug, Clone, PartialEq)]
pub enum MetricsError {
    /// Metric already exists.
    DuplicateMetric(MetricName),
    /// Metric was not found.
    UnknownMetric(MetricName),
    /// Sensor was not found.
    UnknownSensor {
        /// Missing sensor id.
        sensor: SensorId,
    },
    /// Metric value is outside its configured quota.
    QuotaViolation {
        /// Metric that violated its quota.
        metric_name: MetricName,
        /// Measured value.
        value: f64,
        /// Configured quota bound.
        bound: f64,
    },
    /// Metric configuration is invalid.
    InvalidMetricConfig {
        /// Human-readable validation reason.
        reason: String,
    },
}

impl fmt::Display for MetricsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DuplicateMetric(metric) => {
                write!(f, "metric already exists: {}", metric.name())
            },
            Self::UnknownMetric(metric) => write!(f, "unknown metric: {}", metric.name()),
            Self::UnknownSensor { sensor } => write!(f, "unknown sensor: {}", sensor.0),
            Self::QuotaViolation {
                metric_name,
                value,
                bound,
            } => write!(
                f,
                "metric '{}' violated quota: actual {}, bound {}",
                metric_name.name(),
                value,
                bound
            ),
            Self::InvalidMetricConfig { reason } => write!(f, "invalid metric config: {reason}"),
        }
    }
}

impl std::error::Error for MetricsError {}

impl Ord for MetricName {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.group
            .cmp(&other.group)
            .then_with(|| self.name.cmp(&other.name))
            .then_with(|| self.tags.cmp(&other.tags))
    }
}

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

#[cfg(test)]
mod tests {
    #![allow(
        clippy::expect_used,
        clippy::float_cmp,
        clippy::missing_assert_message,
        clippy::unwrap_used,
        reason = "Unit tests for the metrics library assert exact recorded values and fail \
                  fastest with contextual expect calls."
    )]

    use std::{
        sync::{
            Arc,
            atomic::{AtomicUsize, Ordering},
        },
        time::Duration,
    };

    use super::{
        KafkaMetric, MetricConfig, MetricName, MetricNameTemplate, MetricQuota, MetricReporter,
        MetricValue, Metrics, MetricsError, SensorRecordingLevel,
    };

    #[derive(Debug, Default, Clone)]
    struct CountingReporter {
        inits: Arc<AtomicUsize>,
        changes: Arc<AtomicUsize>,
        removals: Arc<AtomicUsize>,
        closes: Arc<AtomicUsize>,
    }

    impl MetricReporter for CountingReporter {
        fn init(&self, _metrics: &[KafkaMetric]) {
            let _previous = self.inits.fetch_add(1, Ordering::Relaxed);
        }
        fn metric_change(&self, _metric: &KafkaMetric) {
            let _previous = self.changes.fetch_add(1, Ordering::Relaxed);
        }
        fn metric_removal(&self, _metric: &KafkaMetric) {
            let _previous = self.removals.fetch_add(1, Ordering::Relaxed);
        }
        fn close(&self) {
            let _previous = self.closes.fetch_add(1, Ordering::Relaxed);
        }
    }

    fn value_of(metrics: &Metrics, name: &MetricName) -> f64 {
        metrics
            .metric(name)
            .map(KafkaMetric::metric_value)
            .expect("metric is registered")
    }

    #[test]
    fn metric_quota_bounds_and_acceptability() {
        let upper = MetricQuota::upper_bound(10.0);
        assert!(upper.is_upper_bound());
        assert_eq!(upper.bound(), 10.0);
        assert!(upper.acceptable(10.0));
        assert!(!upper.acceptable(10.1));

        let lower = MetricQuota::lower_bound(3.0);
        assert!(!lower.is_upper_bound());
        assert!(lower.acceptable(3.0));
        assert!(!lower.acceptable(2.9));
    }

    #[test]
    fn metric_config_builders_and_getters() {
        let config = MetricConfig::new()
            .with_quota(MetricQuota::upper_bound(5.0))
            .with_event_window(64)
            .with_time_window_ms(1_000)
            .with_record_level(SensorRecordingLevel::Debug)
            .with_tag("client-id", "c1")
            .with_tags([("topic", "orders"), ("node", "7")])
            .with_samples(4)
            .expect("samples >= 1");

        assert_eq!(config.quota(), Some(MetricQuota::upper_bound(5.0)));
        assert_eq!(config.event_window(), 64);
        assert_eq!(config.time_window_ms(), 1_000);
        assert_eq!(config.record_level(), SensorRecordingLevel::Debug);
        assert_eq!(config.samples(), 4);
        // with_tags replaces, so "client-id" from with_tag is gone.
        assert_eq!(
            config.tags().get("topic").map(String::as_str),
            Some("orders")
        );
        assert!(config.tags().get("client-id").is_none());

        assert!(matches!(
            MetricConfig::new().with_samples(0),
            Err(MetricsError::InvalidMetricConfig { .. })
        ));
        assert_eq!(MetricConfig::default(), MetricConfig::new());
    }

    #[test]
    fn recording_level_gates_records() {
        // Sensor at Debug level under an Info-level registry must not record.
        let mut metrics = Metrics::new();
        let name = metrics.metric_name("v", "g", "d");
        let sensor = metrics.sensor_with_parents(
            "s",
            SensorRecordingLevel::Debug,
            std::iter::empty::<super::SensorId>(),
        );
        metrics
            .sensor_add_value(sensor, name.clone())
            .expect("add value");
        metrics.record(sensor, 42.0).expect("record");
        assert_eq!(value_of(&metrics, &name), 0.0); // gated out

        // A Trace-level registry records everything.
        let mut trace = Metrics::new().with_recording_level(SensorRecordingLevel::Trace);
        let tname = trace.metric_name("v", "g", "d");
        let tsensor = trace.sensor("s");
        trace
            .sensor_add_value(tsensor, tname.clone())
            .expect("add value");
        trace.record(tsensor, 7.0).expect("record");
        assert_eq!(value_of(&trace, &tname), 7.0);
    }

    #[test]
    fn sensor_stats_record_expected_values() {
        let mut metrics = Metrics::new().with_default_tag("client-id", "c1");
        let sensor = metrics.sensor("throughput");

        let max = metrics.metric_name("max", "g", "max stat");
        let min = metrics.metric_name("min", "g", "min stat");
        let avg = metrics.metric_name("avg", "g", "avg stat");
        let total = metrics.metric_name("total", "g", "total stat");
        let count = metrics.metric_name("count", "g", "count stat");
        let value = metrics.metric_name("value", "g", "value stat");
        let rate = metrics.metric_name("rate", "g", "rate stat");
        let meter_rate = metrics.metric_name("m-rate", "g", "meter rate");
        let meter_total = metrics.metric_name("m-total", "g", "meter total");

        metrics.sensor_add_max(sensor, max.clone()).expect("max");
        metrics.sensor_add_min(sensor, min.clone()).expect("min");
        metrics.sensor_add_avg(sensor, avg.clone()).expect("avg");
        metrics
            .sensor_add_total(sensor, total.clone())
            .expect("total");
        metrics
            .sensor_add_count(sensor, count.clone())
            .expect("count");
        metrics
            .sensor_add_value(sensor, value.clone())
            .expect("value");
        metrics.sensor_add_rate(sensor, rate).expect("rate");
        metrics
            .sensor_add_meter(sensor, meter_rate, meter_total.clone())
            .expect("meter");

        assert!(metrics.sensor_has_metrics(sensor).expect("has metrics"));
        assert_eq!(metrics.sensor_name(sensor).expect("name"), "throughput");

        for sample in [2.0, 8.0, 5.0] {
            metrics.record(sensor, sample).expect("record");
        }

        assert_eq!(value_of(&metrics, &max), 8.0);
        assert_eq!(value_of(&metrics, &min), 2.0);
        assert_eq!(value_of(&metrics, &avg), 5.0);
        assert_eq!(value_of(&metrics, &total), 15.0);
        assert_eq!(value_of(&metrics, &count), 3.0);
        assert_eq!(value_of(&metrics, &value), 5.0);
        assert_eq!(value_of(&metrics, &meter_total), 15.0);
    }

    #[test]
    fn quota_and_config_stat_variants_plus_special_stats() {
        let mut metrics = Metrics::new();
        let sensor = metrics.sensor("s");

        let q_value = metrics.metric_name("qv", "g", "value w/ quota");
        let c_max = metrics.metric_name("cmax", "g", "max w/ config");
        let tb = metrics.metric_name("tb", "g", "token bucket");
        let f_false = metrics.metric_name("ff", "g", "false freq");
        let f_true = metrics.metric_name("ft", "g", "true freq");

        metrics
            .sensor_add_value_with_quota(sensor, q_value, MetricQuota::upper_bound(100.0))
            .expect("value w/ quota");
        metrics
            .sensor_add_max_with_config(sensor, c_max, MetricConfig::new().with_event_window(8))
            .expect("max w/ config");
        metrics
            .sensor_add_min_with_quota(
                sensor,
                metrics.metric_name("qmin", "g", "min quota"),
                MetricQuota::lower_bound(0.0),
            )
            .expect("min w/ quota");
        metrics
            .sensor_add_token_bucket(sensor, tb)
            .expect("token bucket");
        metrics
            .sensor_add_boolean_frequencies(sensor, Some(f_false), Some(f_true))
            .expect("frequencies");

        metrics.record(sensor, 1.0).expect("record");
        metrics.check_sensor_quotas(sensor).expect("within quota");
    }

    #[test]
    fn reporters_observe_metric_lifecycle_and_close() {
        let reporter = CountingReporter::default();
        let inits = Arc::clone(&reporter.inits);
        let changes = Arc::clone(&reporter.changes);
        let removals = Arc::clone(&reporter.removals);
        let closes = Arc::clone(&reporter.closes);

        let mut metrics = Metrics::new();
        metrics.add_reporter(reporter);
        assert_eq!(inits.load(Ordering::Relaxed), 1);

        let name = metrics.metric_name("g", "grp", "gauge");
        metrics
            .add_metric(name.clone(), || MetricValue::Number(3.0))
            .expect("add metric");
        assert_eq!(changes.load(Ordering::Relaxed), 1);
        assert_eq!(value_of(&metrics, &name), 3.0);
        assert_eq!(metrics.registered_metrics().count(), 1);

        let removed = metrics.remove_metric(&name).expect("removed");
        assert_eq!(removed.metric_value(), 3.0);
        assert_eq!(removals.load(Ordering::Relaxed), 1);
        assert!(metrics.remove_metric_if_present(&name).is_none());

        metrics.close();
        assert_eq!(closes.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn sensor_expiration_and_removal() {
        let mut metrics = Metrics::new();
        let sensor = metrics.sensor_with_expiration(
            "ephemeral",
            SensorRecordingLevel::Info,
            Duration::from_millis(100),
            std::iter::empty::<super::SensorId>(),
        );
        let name = metrics.metric_name("e", "g", "ephemeral value");
        metrics.sensor_add_value(sensor, name).expect("add value");
        metrics.record_at_ms(sensor, 1.0, 1_000).expect("record");

        assert!(
            !metrics
                .sensor_has_expired_at_ms(sensor, 1_050)
                .expect("not expired")
        );
        assert!(
            metrics
                .sensor_has_expired_at_ms(sensor, 2_000)
                .expect("expired")
        );
        assert_eq!(metrics.expire_sensors_at_ms(2_000), 1);

        assert!(!metrics.remove_sensor("missing"));
    }

    #[test]
    fn metric_name_template_instance_and_ordering() {
        let metrics = Metrics::new();
        let template =
            MetricNameTemplate::new("lag", "grp", "consumer lag", ["client-id", "topic"]);
        let instance = metrics
            .metric_instance(&template, [("client-id", "c1"), ("topic", "orders")])
            .expect("instance");
        assert_eq!(instance.name(), "lag");

        let tagged = metrics.metric_name_with_tags("lag", "grp", "d", [("client-id", "c2")]);
        assert!(instance < tagged || tagged < instance || instance == tagged);

        // KafkaMetric Debug + MetricsError Display.
        let metric = KafkaMetric::from_fn(instance, || MetricValue::Number(1.0));
        assert!(format!("{metric:?}").contains("KafkaMetric"));
        let err = MetricsError::InvalidMetricConfig {
            reason: "bad".to_owned(),
        };
        assert!(format!("{err}").contains("bad"));
    }
}