nametrics-core 2.0.1

Provider-neutral metric catalog with atomic series budgets and shared structured/Prometheus snapshots
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
//! 进程级 provider-neutral 指标核心。
//!
//! # 核心价值
//!
//! [`MetricHub`] 是一个进程内唯一的 descriptor catalog、记录 backend 和结构化快照源。领域 crate
//! (`nafana`/`naweb`/`nafka`)继续拥有自己的静态 family、低基数 label 与记录时机;本 crate 只统一
//! 冲突审计、容量和导出,不重新定义领域指标语义,也不依赖 OpenTelemetry、Prometheus client、
//! Axum 或 `napp`。
//!
//! # 运行架构与安全边界
//!
//! 原生记录入口只接受启动期登记且语义一致的 descriptor。受管兼容源通过
//! [`MetricHub::register_legacy_source_reserved`] 在同一临界区提交 descriptor、source 所有权和最坏
//! exposition series 预算;冲突、溢出或容量不足时三者都不改变。原生 cell 与显式预留共享
//! [`MAX_METRIC_SERIES`],目录自身的拒绝诊断预先占位,满载时仍能解释拒绝原因。
//!
//! Prometheus 文本和 OTLP adapter 都读取同一次结构化快照,不各自维护 registry。label 形状、单值
//! 大小、value kind、histogram 结构或基数不满足目录合同时拒绝当前样本,并以固定 `source/reason`
//! 计数,不把动态 label 内容写进诊断。动态结构化兼容源只使用扣除原生序列与显式预留后的余量,
//! 按 family/label 排序逐个接纳完整样本。仅文本的旧兼容源不在结构化容量保证内。

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, RwLock};

/// 固定桶与原子采集,供低开销领域 source 复用。
pub mod atomic;

/// 进程内原生、结构化兼容源与诊断按 histogram 展开后的公开序列硬上限。
pub const MAX_METRIC_SERIES: usize = 100_000;
/// 统一目录自身按两种来源和七种拒绝原因展开后的固定诊断序列数。
const INTERNAL_METRIC_SERIES: usize = 2 * SAMPLE_REJECTION_REASONS.len();

/// 单个 label 值允许占用的最大 UTF-8 字节数。
///
/// 该上限只约束单值内存,不限制 label 组合数量;基数仍由全局 cell 预算独立约束。
const MAX_LABEL_VALUE_BYTES: usize = 4 * 1024;

/// 指标类型。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MetricKind {
    /// 单调递增计数器。
    Counter,
    /// 可增可减的瞬时值。
    Gauge,
    /// 分桶分布(Prometheus `le` 累积桶 + sum + count)。
    Histogram,
}

impl MetricKind {
    /// 业务作用:为指标类型生成 Prometheus TYPE 声明中的固定名称。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:计数器、瞬时值和分桶指标分别返回 counter、gauge 和 histogram,不产生采集副作用。
    fn prometheus_type(self) -> &'static str {
        match self {
            MetricKind::Counter => "counter",
            MetricKind::Gauge => "gauge",
            MetricKind::Histogram => "histogram",
        }
    }
}

/// 一个指标 family 的静态描述。所有字段都是编译期常量,不含动态内容。
#[derive(Debug)]
pub struct MetricDescriptor {
    /// family 名称(如 `napp_web_requests_total`),进程内唯一。
    pub name: &'static str,
    /// `# HELP` 文本。
    pub help: &'static str,
    /// 单位(如 `seconds`、`bytes`;无单位用 `""`)。
    pub unit: &'static str,
    /// 指标类型。
    pub kind: MetricKind,
    /// 有序、低基数的 label 名;记录时按同一顺序提供 label 值。
    pub label_names: &'static [&'static str],
    /// histogram 的 `le` 上界(升序);非 histogram 用 `&[]`。
    pub histogram_bounds: &'static [f64],
}

static SAMPLE_REJECTIONS_TOTAL: MetricDescriptor = MetricDescriptor {
    name: "nametrics_samples_rejected_total",
    help: "统一指标目录拒绝的不合规样本累计数。",
    unit: "",
    kind: MetricKind::Counter,
    label_names: &["source", "reason"],
    histogram_bounds: &[],
};

#[derive(Clone, Copy)]
#[repr(usize)]
enum SampleRejectionReason {
    UnknownFamily,
    LabelShape,
    LabelValueTooLong,
    ValueKind,
    HistogramShape,
    UnregisteredDescriptor,
    CardinalityLimit,
}

const SAMPLE_REJECTION_REASONS: [SampleRejectionReason; 7] = [
    SampleRejectionReason::UnknownFamily,
    SampleRejectionReason::LabelShape,
    SampleRejectionReason::LabelValueTooLong,
    SampleRejectionReason::ValueKind,
    SampleRejectionReason::HistogramShape,
    SampleRejectionReason::UnregisteredDescriptor,
    SampleRejectionReason::CardinalityLimit,
];

impl SampleRejectionReason {
    /// 业务作用:返回拒绝原因在固定原子计数数组中的稳定位置。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:与 [`SAMPLE_REJECTION_REASONS`] 顺序一致的数组下标。
    const fn index(self) -> usize {
        self as usize
    }

    /// 业务作用:返回可用于低基数指标 label 的稳定拒绝原因。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:不包含动态输入或样本内容的固定原因文本。
    const fn label(self) -> &'static str {
        match self {
            Self::UnknownFamily => "unknown_family",
            Self::LabelShape => "label_shape",
            Self::LabelValueTooLong => "label_value_too_long",
            Self::ValueKind => "value_kind",
            Self::HistogramShape => "histogram_shape",
            Self::UnregisteredDescriptor => "unregistered_descriptor",
            Self::CardinalityLimit => "cardinality_limit",
        }
    }
}

#[derive(Clone, Copy)]
enum SampleRejectionSource {
    Native,
    Legacy,
}

impl SampleRejectionSource {
    /// 业务作用:返回可用于低基数指标 label 的稳定样本来源。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:`native` 表示直接记录入口,`legacy` 表示兼容源结构化快照。
    const fn label(self) -> &'static str {
        match self {
            Self::Native => "native",
            Self::Legacy => "legacy",
        }
    }
}

/// 业务作用:以固定来源和固定原因维度保存目录拒绝计数,使基数预算耗尽时仍能暴露拒绝事实。
struct SampleRejectionCounters {
    native: [AtomicU64; SAMPLE_REJECTION_REASONS.len()],
    legacy: [AtomicU64; SAMPLE_REJECTION_REASONS.len()],
}

impl SampleRejectionCounters {
    /// 业务作用:创建按固定来源和原因分组的拒绝计数器。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:全部计数从零开始的无锁计数器集合。
    fn new() -> Self {
        Self {
            native: std::array::from_fn(|_| AtomicU64::new(0)),
            legacy: std::array::from_fn(|_| AtomicU64::new(0)),
        }
    }

    /// 业务作用:累计一次被统一目录拒绝的样本检查事件。
    ///
    /// 参数说明:
    /// - `source`: 样本来自直接记录入口还是兼容源快照。
    /// - `reason`: 不包含动态内容的固定拒绝原因。
    ///
    /// 返回:无;对应来源与原因的累计值饱和前单调递增。
    fn increment(&self, source: SampleRejectionSource, reason: SampleRejectionReason) {
        let counters = match source {
            SampleRejectionSource::Native => &self.native,
            SampleRejectionSource::Legacy => &self.legacy,
        };
        let counter = &counters[reason.index()];
        let _ = counter.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
            Some(value.saturating_add(1))
        });
    }

    /// 业务作用:把非零拒绝计数转换为统一目录自身的结构化指标样本。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:按来源、原因稳定排序的累计 counter,不暴露被拒样本的 label 内容。
    fn snapshot(&self) -> Vec<MetricSample> {
        let mut samples = Vec::new();
        for (source, counters) in [
            (SampleRejectionSource::Native, &self.native),
            (SampleRejectionSource::Legacy, &self.legacy),
        ] {
            for reason in SAMPLE_REJECTION_REASONS {
                let value = counters[reason.index()].load(Ordering::Relaxed);
                if value == 0 {
                    continue;
                }
                samples.push(MetricSample {
                    name: SAMPLE_REJECTIONS_TOTAL.name,
                    labels: vec![
                        ("source", source.label().to_owned()),
                        ("reason", reason.label().to_owned()),
                    ],
                    value: MetricValue::Counter(value),
                });
            }
        }
        samples
    }
}

impl MetricDescriptor {
    /// 业务作用:比较两个同名指标描述的采集与导出语义。
    ///
    /// 参数说明:
    /// - `other`:待比较的同名指标描述,名称由调用方另行匹配。
    ///
    /// 返回:kind、unit、help、有序 label_names 和 histogram_bounds 全部相等时返回 true;不在此比较名称。
    fn semantically_eq(&self, other: &MetricDescriptor) -> bool {
        self.kind == other.kind
            && self.unit == other.unit
            && self.help == other.help
            && self.label_names == other.label_names
            && self.histogram_bounds == other.histogram_bounds
    }
}

/// 领域 crate 记录指标的入口。`napp` 持有唯一 `MetricHub` 实例并实现本 trait。
pub trait MetricRecorder: Send + Sync {
    /// 业务作用:按领域提供的描述和 label 值累加计数器。
    ///
    /// 参数说明:
    /// - `descriptor`:决定 family、类型及有序 label 合同的静态描述。
    /// - `delta`:本次非负增量。
    /// - `labels`:与描述中 label_names 顺序对应的业务 label 值。
    ///
    /// 返回:无返回值;接纳、拒绝及诊断由记录器实现负责,调用不提供持久化或导出完成确认。
    fn counter(&self, descriptor: &'static MetricDescriptor, delta: u64, labels: &[&str]);
    /// 业务作用:按领域提供的描述和 label 值设置瞬时值。
    ///
    /// 参数说明:
    /// - `descriptor`:决定 family、类型及有序 label 合同的静态描述。
    /// - `value`:本次要记录的瞬时数值。
    /// - `labels`:与描述中 label_names 顺序对应的业务 label 值。
    ///
    /// 返回:无返回值;接纳、拒绝及诊断由记录器实现负责,调用不提供持久化或导出完成确认。
    fn gauge(&self, descriptor: &'static MetricDescriptor, value: f64, labels: &[&str]);
    /// 业务作用:按领域提供的描述和 label 值记录一次分桶观测。
    ///
    /// 参数说明:
    /// - `descriptor`:决定 family、类型及有序 label 合同的静态描述。
    /// - `value`:本次待归入描述所声明桶的观测值。
    /// - `labels`:与描述中 label_names 顺序对应的业务 label 值。
    ///
    /// 返回:无返回值;接纳、拒绝及诊断由记录器实现负责,调用不提供持久化或导出完成确认。
    fn histogram(&self, descriptor: &'static MetricDescriptor, value: f64, labels: &[&str]);
}

/// descriptor 注册冲突。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MetricConflict {
    /// 冲突的 family 名称。
    pub name: &'static str,
}

/// 指标源在启动期登记 descriptor 与最坏序列预算时的失败分类。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MetricSourceRegistrationError {
    /// 任一 family 与已有目录的静态语义冲突。
    Conflict(MetricConflict),
    /// 本源最坏序列数会越过进程硬上限。
    SeriesBudgetExceeded,
}

impl From<MetricConflict> for MetricSourceRegistrationError {
    /// 业务作用:把既有 descriptor 冲突纳入原子指标源登记的统一失败分类。
    ///
    /// 参数说明:
    /// - `conflict`: 已包含稳定 family 名称的目录冲突。
    ///
    /// 返回:保持原始冲突事实的指标源登记错误。
    fn from(conflict: MetricConflict) -> Self {
        Self::Conflict(conflict)
    }
}

impl fmt::Display for MetricSourceRegistrationError {
    /// 业务作用:输出不携带动态 label 或指标样本内容的稳定登记失败分类。
    ///
    /// 参数说明:
    /// - `formatter`: 接收稳定错误文本的格式化目标。
    ///
    /// 返回:错误文本写入成功时完成,否则透传格式化失败。
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Conflict(conflict) => {
                write!(formatter, "metric descriptor `{}` conflicts", conflict.name)
            }
            Self::SeriesBudgetExceeded => formatter.write_str("metric series budget is exceeded"),
        }
    }
}

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

/// 兼容期桥:旧指标源先实现本 trait,启动期用 `descriptors()` 做全局冲突审计,文本与非文本出口
/// 优先读取 `snapshot()` 的同源结构化值;明确返回 `None` 的旧源仅在文本抓取时回落到
/// `render_prometheus()`。迁移完成后弃用。
pub trait LegacyMetricsSource: Send + Sync {
    /// 业务作用:本源拥有的静态 descriptor,用于启动期冲突审计。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:本源拥有且在启动期登记的全部 descriptor。
    fn descriptors(&self) -> &'static [&'static MetricDescriptor];
    /// 业务作用:导出与文本端点同源的结构化当前值,供 OTLP 等非文本后端复用。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:`Some` 表示该源支持结构化快照,即使当前没有样本也返回 `Some(Vec::new())`;`None`
    /// 表示旧源只支持 Prometheus 自渲染,不会进入非文本 exporter。
    fn snapshot(&self) -> Option<Vec<MetricSample>> {
        None
    }
    /// 业务作用:追加渲染本源的 Prometheus 文本(保持既有 family/HELP/TYPE/label 语义)。
    ///
    /// 参数说明:
    /// - `output`: 接收本源文本的目标缓冲区。
    ///
    /// 返回:无;在现有缓冲区尾部追加,不清空已有内容。
    fn render_prometheus(&self, output: &mut String);
}

/// 单个 (family, label 值) 组合的进程内值。
enum Cell {
    Counter(u64),
    Gauge(f64),
    Histogram {
        /// 长度 = `bounds.len() + 1`,最后一个为 `+Inf` 桶;每个是"落入该桶"的观测数(非累积)。
        buckets: Vec<u64>,
        sum: f64,
        count: u64,
    },
}

#[derive(Clone)]
struct RegisteredSource {
    source: Arc<dyn LegacyMetricsSource>,
    budget: Option<usize>,
}

/// 唯一进程级指标 backend:descriptor catalog(带冲突审计)+ 进程内记录 + 结构化/Prometheus 导出。
pub struct MetricHub {
    descriptors: RwLock<BTreeMap<&'static str, &'static MetricDescriptor>>,
    /// (family 名, label 值序列) → 值。BTreeMap 使导出顺序稳定,便于 golden 对比。
    cells: RwLock<BTreeMap<(&'static str, Vec<String>), Cell>>,
    /// 兼容领域源(nafana/naweb 等)的 registry;其 descriptor 已并入 catalog,结构化快照由
    /// hub 统一导出,只有明确不支持结构化快照的旧源才使用自身 Prometheus 文本入口。
    sources: RwLock<Vec<RegisteredSource>>,
    /// 原生 cell 展开为公开序列后的占用;写入与 cell 创建共用 cells 写锁。
    native_series: AtomicUsize,
    /// 启动期已由受管指标源原子提交的最坏导出序列数;与运行期原生 cell 共用进程硬上限。
    reserved_series: Mutex<usize>,
    /// 所有拒绝原因均为固定低基数 label;不保存被拒样本的动态内容。
    rejections: SampleRejectionCounters,
}

impl MetricHub {
    /// 业务作用:创建只预留统一目录拒绝指标、尚未登记业务指标源的 hub。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:可执行 descriptor 冲突审计、记录和双出口快照的独立指标目录。
    pub fn new() -> Self {
        let mut descriptors = BTreeMap::new();
        descriptors.insert(SAMPLE_REJECTIONS_TOTAL.name, &SAMPLE_REJECTIONS_TOTAL);
        Self {
            descriptors: RwLock::new(descriptors),
            cells: RwLock::new(BTreeMap::new()),
            sources: RwLock::new(Vec::new()),
            native_series: AtomicUsize::new(0),
            // 内部拒绝族必须在任何业务预留之前占位,保证目录满载时仍能解释后续拒绝。
            reserved_series: Mutex::new(INTERNAL_METRIC_SERIES),
            rejections: SampleRejectionCounters::new(),
        }
    }

    /// 业务作用:注册一个静态 descriptor 并审计冲突。
    ///
    /// 参数说明:
    /// - `descriptor`: 需要纳入进程唯一目录的静态指标语义。
    ///
    /// 返回:首次登记或同一业务 descriptor 幂等登记时成功;内部诊断 family 与业务 family
    /// 语义冲突时失败,目录保持原状。
    ///
    /// # 错误
    ///
    /// 同名但语义不同(kind/unit/help/label_names/histogram_bounds 任一不同)时返回
    /// [`MetricConflict`];同名且完全一致是幂等的(返回 `Ok`)。
    pub fn register(&self, descriptor: &'static MetricDescriptor) -> Result<(), MetricConflict> {
        validate_descriptor(descriptor)?;
        if descriptor.name == SAMPLE_REJECTIONS_TOTAL.name
            && !std::ptr::eq(descriptor, &SAMPLE_REJECTIONS_TOTAL)
        {
            return Err(MetricConflict {
                name: descriptor.name,
            });
        }
        let mut descriptors = self
            .descriptors
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(existing) = descriptors.get(descriptor.name) {
            if existing.semantically_eq(descriptor) {
                return Ok(());
            }
            return Err(MetricConflict {
                name: descriptor.name,
            });
        }
        descriptors.insert(descriptor.name, descriptor);
        Ok(())
    }

    /// 业务作用:审计一个 [`LegacyMetricsSource`] 的 descriptor 纳入统一 catalog,并保存该源以便导出。
    ///
    /// 审计通过后,`Some` 结构化快照同时进入 Prometheus 与非文本出口;明确返回 `None` 的旧源
    /// 只进入 `render_prometheus` 回落路径。原生渲染循环跳过文本旧源声明的族名,避免重复
    /// HELP/TYPE。
    ///
    /// 参数说明:
    /// - `source`:为拥有独立 family 的兼容指标源。
    ///
    /// 返回:目录无冲突时登记;结构化快照只使用全进程预留之外的动态余量,超额样本在导出时拒绝。
    ///
    /// # 错误
    ///
    /// 任一 descriptor 与已注册项冲突时返回首个 [`MetricConflict`],此时源不会被保存。
    pub fn register_legacy_source(
        &self,
        source: Arc<dyn LegacyMetricsSource>,
    ) -> Result<(), MetricConflict> {
        {
            let sources = self
                .sources
                .read()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if sources
                .iter()
                .any(|existing| Arc::ptr_eq(&existing.source, &source))
            {
                return Ok(());
            }
        }
        let candidates = source.descriptors();
        for descriptor in candidates {
            validate_descriptor(descriptor)?;
        }
        let mut descriptors = self
            .descriptors
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        // 兼容源拥有它声明的 family;即使语义相同,也不能与原生/另一兼容源双重拥有并渲染。
        if let Some(conflict) = candidates
            .iter()
            .find(|descriptor| descriptors.contains_key(descriptor.name))
        {
            return Err(MetricConflict {
                name: conflict.name,
            });
        }
        for descriptor in source.descriptors() {
            descriptors.insert(descriptor.name, descriptor);
        }
        drop(descriptors);
        self.sources
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .push(RegisteredSource {
                source,
                budget: None,
            });
        Ok(())
    }

    /// 业务作用:在一个临界区内校验并提交兼容指标源的 descriptor、所有权与最坏序列预算。
    ///
    /// 参数说明:
    /// - `source`: 只产生 sealed label domain 的结构化指标源。
    /// - `worst_case_series`: 该源全部 family 展开 label 与 histogram 后的最大公开序列数。
    ///
    /// 返回:目录无冲突且进程预留不超过 [`MAX_METRIC_SERIES`] 时原子提交;失败时 descriptor、source
    /// 和预留计数均保持不变,不会留下半份公开指标源。
    pub fn register_legacy_source_reserved(
        &self,
        source: Arc<dyn LegacyMetricsSource>,
        worst_case_series: usize,
    ) -> Result<(), MetricSourceRegistrationError> {
        let candidates = source.descriptors();
        for descriptor in candidates {
            validate_descriptor(descriptor)?;
        }
        let mut descriptors = self
            .descriptors
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let mut sources = self
            .sources
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if sources
            .iter()
            .any(|existing| Arc::ptr_eq(&existing.source, &source))
        {
            return Ok(());
        }
        if let Some(conflict) = candidates
            .iter()
            .find(|descriptor| descriptors.contains_key(descriptor.name))
        {
            return Err(MetricConflict {
                name: conflict.name,
            }
            .into());
        }
        let cells = self
            .cells
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let mut reserved = self
            .reserved_series
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let next = reserved
            .checked_add(worst_case_series)
            .and_then(|total| {
                total
                    .checked_add(self.native_series.load(Ordering::Relaxed))
                    .map(|used| (total, used))
            })
            .filter(|(_, used)| *used <= MAX_METRIC_SERIES)
            .map(|(total, _)| total)
            .ok_or(MetricSourceRegistrationError::SeriesBudgetExceeded)?;

        // 三类状态只在全部门禁通过后一起发布;任何前置失败都不能占用预算或暴露部分 family。
        for descriptor in candidates {
            descriptors.insert(descriptor.name, descriptor);
        }
        sources.push(RegisteredSource {
            source,
            budget: Some(worst_case_series),
        });
        drop(cells);
        *reserved = next;
        Ok(())
    }

    /// 业务作用:读取启动期已提交的最坏公开序列预留,供 Ready 门禁与诊断核对全进程余量。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:目录自身诊断族与显式登记源的预留之和;原生 cell 的实际展开占用另行参与同一总量门禁。
    pub fn reserved_series(&self) -> usize {
        *self
            .reserved_series
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// 业务作用:为出口启动门禁读取已承诺的完整公开序列占用,包含已创建的原生指标。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:内部诊断与显式源的最坏预留,加上原生 cell 的展开占用;histogram 包含全部桶、sum 和 count。
    /// 无预留的兼容源与检查之后新增的原生 label 不在此值内,调用方仍需单独约束动态增长。
    pub fn committed_series(&self) -> usize {
        // 沿用创建 cell 和登记 source 的 cells → reserved 锁顺序,保证两个占用来自同一时刻,
        // 不能让并发登记或原生首次写入在 Ready 核对时落入两个读数之间的空隙。
        let _cells = self
            .cells
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let reserved = self
            .reserved_series
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        reserved.saturating_add(self.native_series.load(Ordering::Relaxed))
    }

    /// 业务作用:校验直接记录入口的 label 数量与单值内存上限。
    ///
    /// 参数说明:
    /// - `descriptor`: 已声明 label 顺序的静态指标语义。
    /// - `labels`: 调用方按 descriptor 顺序提交的 label 值。
    ///
    /// 返回:满足数量和单值上限时成功,否则返回稳定拒绝原因。
    fn validate_labels(
        descriptor: &MetricDescriptor,
        labels: &[&str],
    ) -> Result<(), SampleRejectionReason> {
        if labels.len() != descriptor.label_names.len() {
            return Err(SampleRejectionReason::LabelShape);
        }
        if labels
            .iter()
            .any(|value| value.len() > MAX_LABEL_VALUE_BYTES)
        {
            return Err(SampleRejectionReason::LabelValueTooLong);
        }
        Ok(())
    }

    /// 业务作用:确认调用方使用的是已登记且语义完全一致的 descriptor,防止同名漂移写入。
    ///
    /// 参数说明:
    /// - `descriptor`: 本次记录入口携带的静态 descriptor。
    ///
    /// 返回:业务 descriptor 与目录语义一致时返回 `true`;内部拒绝指标只接受目录私有实例。
    fn is_registered(&self, descriptor: &MetricDescriptor) -> bool {
        if descriptor.name == SAMPLE_REJECTIONS_TOTAL.name {
            return std::ptr::eq(descriptor, &SAMPLE_REJECTIONS_TOTAL);
        }
        self.descriptors
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .get(descriptor.name)
            .is_some_and(|registered| registered.semantically_eq(descriptor))
    }

    /// 业务作用:在原生 cell 写锁保护下检查并预占新样本完整导出序列预算。
    ///
    /// 参数说明:
    /// - `cells`:调用方已持写锁的当前原生样本表。
    /// - `key`:本次 family 名称和有序 label 值组合。
    /// - `descriptor`:决定新 cell 所需导出序列数的指标定义。
    ///
    /// 返回:已存在组合直接允许;新组合及预留总数不超过硬上限时先增加原生占用并返回 true。溢出或容量不足返回 false,不修改占用;实际 cell 插入由调用方在同一锁范围完成。
    fn can_insert_cell(
        &self,
        cells: &BTreeMap<(&'static str, Vec<String>), Cell>,
        key: &(&'static str, Vec<String>),
        descriptor: &MetricDescriptor,
    ) -> bool {
        if cells.contains_key(key) {
            return true;
        }
        let reserved = *self
            .reserved_series
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let used = self.native_series.load(Ordering::Relaxed);
        let cost = descriptor_series(descriptor);
        // 完整 histogram 在创建前一次性占位,避免桶、sum、count 越过进程硬限。
        if used
            .checked_add(cost)
            .and_then(|total| total.checked_add(reserved))
            .is_none_or(|total| total > MAX_METRIC_SERIES)
        {
            return false;
        }
        self.native_series.store(used + cost, Ordering::Relaxed);
        true
    }

    /// 业务作用:将指标名称与借用的有序 label 值固化为样本表键。
    ///
    /// 参数说明:
    /// - `descriptor`:提供静态 family 名称的指标定义。
    /// - `labels`:与描述声明顺序一致的 label 值。
    ///
    /// 返回:返回静态名称和拥有内容的 label 值向量,不检查形状、长度或登记资格。
    fn key(descriptor: &MetricDescriptor, labels: &[&str]) -> (&'static str, Vec<String>) {
        (
            descriptor.name,
            labels.iter().map(|value| (*value).to_owned()).collect(),
        )
    }

    /// 业务作用:导出全部原生与兼容源指标的结构化快照,family 与 label 组合按名称有序。
    ///
    /// 兼容源必须直接读取自己的原子 registry,不从 Prometheus 文本反解析。源返回的 family、label
    /// 或 value kind 与启动期 descriptor 不一致时,该样本会被拒绝,避免非文本出口绕过 catalog。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:按 family 与 label 有序且符合全局公开序列预算的当前快照;拒绝事实在同次快照中可见,
    /// 读取不会清零计数或 histogram。
    pub fn snapshot(&self) -> Vec<MetricSample> {
        self.collect_snapshot().0
    }

    /// 业务作用:一次性收集原生与结构化兼容源样本,并识别只能自渲染文本的旧源。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:第一项是经过 descriptor 校验的统一快照,第二项是明确返回 `None` 的文本旧源;结构化
    /// 源即使当前为空或全部样本被拒绝也不会退回另一条数据路径。
    fn collect_snapshot(&self) -> (Vec<MetricSample>, Vec<Arc<dyn LegacyMetricsSource>>) {
        let mut out = Vec::new();
        let mut text_only_sources = Vec::new();
        let sources = self
            .sources
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        let native = self.native_snapshot();
        let native_count = native
            .iter()
            .filter(|sample| sample.name != SAMPLE_REJECTIONS_TOTAL.name)
            .map(sample_series)
            .sum::<usize>();
        let reserved = sources
            .iter()
            .filter_map(|entry| entry.budget)
            .sum::<usize>();
        let mut remaining = MAX_METRIC_SERIES
            .saturating_sub(INTERNAL_METRIC_SERIES)
            .saturating_sub(native_count)
            .saturating_sub(reserved);
        for entry in sources {
            let source = entry.source;
            let Some(mut samples) = source.snapshot() else {
                text_only_sources.push(source);
                continue;
            };
            let owned: BTreeMap<&'static str, &'static MetricDescriptor> = source
                .descriptors()
                .iter()
                .map(|descriptor| (descriptor.name, *descriptor))
                .collect();
            // 固定排序使容量拒绝不依赖兼容源的枚举顺序;受管源不能挤占其它源已承诺的预算。
            samples.sort_by(|left, right| {
                left.name
                    .cmp(right.name)
                    .then_with(|| left.labels.cmp(&right.labels))
            });
            let mut available = entry.budget.unwrap_or(remaining);
            for sample in samples {
                let Some(descriptor) = owned.get(sample.name).copied() else {
                    self.rejections.increment(
                        SampleRejectionSource::Legacy,
                        SampleRejectionReason::UnknownFamily,
                    );
                    continue;
                };
                match validate_sample(&sample, descriptor) {
                    Ok(()) => {
                        let cost = sample_series(&sample);
                        // 容量不足时拒绝整个样本,不能发布缺少部分桶或 sum/count 的 histogram。
                        if cost > available {
                            self.rejections.increment(
                                SampleRejectionSource::Legacy,
                                SampleRejectionReason::CardinalityLimit,
                            );
                            continue;
                        }
                        available -= cost;
                        out.push(sample);
                    }
                    Err(reason) => self
                        .rejections
                        .increment(SampleRejectionSource::Legacy, reason),
                }
            }
            if entry.budget.is_none() {
                remaining = available;
            }
        }
        out.extend(
            native
                .into_iter()
                .filter(|sample| sample.name != SAMPLE_REJECTIONS_TOTAL.name),
        );
        // 拒绝发生后再读固定诊断,使本次导出本身就能解释容量损失。
        out.extend(self.rejections.snapshot());
        out.sort_by(|left, right| {
            left.name
                .cmp(right.name)
                .then_with(|| left.labels.cmp(&right.labels))
        });
        (out, text_only_sources)
    }

    /// 业务作用:导出由 hub 直接记录的指标值,不触发兼容源的快照副作用。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:按 hub 有序 cell 生成的当前值以及非零拒绝诊断;调用时不清零任何计数。
    fn native_snapshot(&self) -> Vec<MetricSample> {
        let descriptors = self
            .descriptors
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let cells = self
            .cells
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let mut out = Vec::with_capacity(cells.len());
        for ((name, label_values), cell) in cells.iter() {
            let Some(descriptor) = descriptors.get(name) else {
                continue;
            };
            let labels: Vec<(&'static str, String)> = descriptor
                .label_names
                .iter()
                .copied()
                .zip(label_values.iter().cloned())
                .collect();
            let value = match cell {
                Cell::Counter(v) => MetricValue::Counter(*v),
                Cell::Gauge(v) => MetricValue::Gauge(*v),
                Cell::Histogram {
                    buckets,
                    sum,
                    count,
                } => MetricValue::Histogram {
                    bounds: descriptor.histogram_bounds,
                    buckets: buckets.clone(),
                    sum: *sum,
                    count: *count,
                },
            };
            out.push(MetricSample {
                name,
                labels,
                value,
            });
        }
        drop(cells);
        drop(descriptors);
        out.extend(self.rejections.snapshot());
        out
    }

    /// 业务作用:把当前值按启动期 descriptor 聚合成可直接编码的指标 family 快照。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:只包含当前至少有一个样本的 family;名称、说明、单位、类型与 histogram 边界均来自
    /// 唯一 catalog,OTLP 与 Prometheus 不会各自维护第二份指标语义。
    pub fn family_snapshot(&self) -> Vec<MetricFamilySnapshot> {
        let samples = self.snapshot();
        let descriptors = self
            .descriptors
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let mut families: BTreeMap<&'static str, MetricFamilySnapshot> = BTreeMap::new();
        for sample in samples {
            let Some(descriptor) = descriptors.get(sample.name).copied() else {
                continue;
            };
            families
                .entry(descriptor.name)
                .or_insert_with(|| MetricFamilySnapshot {
                    name: descriptor.name,
                    description: descriptor.help,
                    unit: descriptor.unit,
                    kind: descriptor.kind,
                    histogram_bounds: descriptor.histogram_bounds,
                    samples: Vec::new(),
                })
                .samples
                .push(sample);
        }
        families.into_values().collect()
    }

    /// 业务作用:把 hub 拥有的全部指标渲染为 Prometheus 文本(HELP/TYPE + 样本),追加到 `output`。
    ///
    /// 渲染顺序:先按名称有序输出原生 family 和结构化兼容源,再按注册顺序处理文本旧源。返回
    /// `Some(Vec::new())` 的结构化源只表示当前无样本,不会调用另一份自渲染入口。
    /// 同一 family 始终只有一组 HELP/TYPE,结构化源与 OTLP 共用同一值和边界。
    ///
    /// 参数说明:
    /// - `output`: 接收完整 Prometheus exposition 的目标缓冲区。
    ///
    /// 返回:无;在现有缓冲区尾部追加,不清空已有内容。
    pub fn render_prometheus(&self, output: &mut String) {
        use std::fmt::Write as _;
        // 单次收集同时决定结构化与文本旧源,避免“结构化快照为空”在不同出口被解释成不同数据源。
        let (samples, text_only_sources) = self.collect_snapshot();
        let text_only_names: BTreeSet<&'static str> = text_only_sources
            .iter()
            .flat_map(|source| source.descriptors().iter().map(|d| d.name))
            .collect();
        let descriptors = self
            .descriptors
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        // 按 family 分组渲染原生族,每个 family 一组 HELP/TYPE。
        for (name, descriptor) in descriptors.iter() {
            if text_only_names.contains(name) {
                continue;
            }
            if *name == SAMPLE_REJECTIONS_TOTAL.name
                && !samples.iter().any(|sample| sample.name == *name)
            {
                continue;
            }
            let _ = writeln!(output, "# HELP {name} {}", descriptor.help);
            let _ = writeln!(
                output,
                "# TYPE {name} {}",
                descriptor.kind.prometheus_type()
            );
            for sample in samples.iter().filter(|s| s.name == *name) {
                sample.render_prometheus(output);
            }
        }
        drop(descriptors);
        // 只有显式声明不支持结构化快照的旧源使用自身文本入口;结构化源的文本与 OTLP 始终共用上面的值。
        for source in text_only_sources {
            source.render_prometheus(output);
        }
    }
}

/// 业务作用:计算 descriptor 的一个 label 组合占用的公开序列数。
///
/// 参数说明:
/// - `descriptor`:为已校验的静态指标语义。
///
/// 返回:普通样本占一条,histogram 包括所有有限桶、+Inf、sum 和 count。
fn descriptor_series(descriptor: &MetricDescriptor) -> usize {
    if descriptor.kind == MetricKind::Histogram {
        descriptor.histogram_bounds.len() + 3
    } else {
        1
    }
}

/// 业务作用:按实际样本结构核算出口容量。
///
/// 参数说明:
/// - `sample`:为已经过 descriptor 校验的完整样本。
///
/// 返回:与 Prometheus 展开结果一致的序列数。
fn sample_series(sample: &MetricSample) -> usize {
    match &sample.value {
        MetricValue::Histogram {
            bounds,
            ..
        } => bounds.len() + 3,
        _ => 1,
    }
}

/// 业务作用:验证兼容源样本与启动期 descriptor 的名称、label 顺序、资源上限和 value kind 完全一致。
///
/// 参数说明:
/// - `sample`: 兼容源从自身 registry 读取的当前值。
/// - `descriptor`: 该源在注册时提交并通过冲突审计的静态语义。
///
/// 返回:样本可安全进入统一快照时成功;不符合合同则返回可观测的固定拒绝原因。
fn validate_sample(
    sample: &MetricSample,
    descriptor: &MetricDescriptor,
) -> Result<(), SampleRejectionReason> {
    if sample.name != descriptor.name
        || sample.labels.len() != descriptor.label_names.len()
        || sample
            .labels
            .iter()
            .zip(descriptor.label_names)
            .any(|((actual, _), expected)| actual != expected)
    {
        return Err(SampleRejectionReason::LabelShape);
    }
    if sample
        .labels
        .iter()
        .any(|(_, value)| value.len() > MAX_LABEL_VALUE_BYTES)
    {
        return Err(SampleRejectionReason::LabelValueTooLong);
    }
    match (&sample.value, descriptor.kind) {
        (MetricValue::Counter(_), MetricKind::Counter)
        | (MetricValue::Gauge(_), MetricKind::Gauge) => Ok(()),
        (
            MetricValue::Histogram {
                bounds,
                buckets,
                count,
                ..
            },
            MetricKind::Histogram,
        ) => {
            if *bounds == descriptor.histogram_bounds
                && buckets.len() == bounds.len() + 1
                && buckets.iter().copied().fold(0_u64, u64::saturating_add) == *count
            {
                Ok(())
            } else {
                Err(SampleRejectionReason::HistogramShape)
            }
        }
        _ => Err(SampleRejectionReason::ValueKind),
    }
}

impl Default for MetricHub {
    /// 业务作用:构造预留内部拒绝指标的进程指标目录。
    ///
    /// 参数说明: 无。
    ///
    /// 返回:与 new 相同,返回含内部描述和预算预留、尚无业务源和原生样本的独立目录。
    fn default() -> Self {
        Self::new()
    }
}

impl MetricRecorder for MetricHub {
    /// 业务作用:对已登记 counter 做饱和累加,并对不合规写入累计固定原因诊断。
    ///
    /// 参数说明:
    /// - `descriptor`: 启动期登记的静态 counter 语义。
    /// - `delta`: 本次需要累计的非负增量。
    /// - `labels`: 按 descriptor 顺序提供的低基数 label 值。
    ///
    /// 返回:无;合法写入饱和累加,非法 descriptor、label 或超基数写入不改变业务样本。
    fn counter(&self, descriptor: &'static MetricDescriptor, delta: u64, labels: &[&str]) {
        if let Err(reason) = Self::validate_labels(descriptor, labels) {
            self.rejections
                .increment(SampleRejectionSource::Native, reason);
            return;
        }
        if !self.is_registered(descriptor) {
            self.rejections.increment(
                SampleRejectionSource::Native,
                SampleRejectionReason::UnregisteredDescriptor,
            );
            return;
        }
        let mut cells = self
            .cells
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let key = Self::key(descriptor, labels);
        if !self.can_insert_cell(&cells, &key, descriptor) {
            self.rejections.increment(
                SampleRejectionSource::Native,
                SampleRejectionReason::CardinalityLimit,
            );
            return;
        }
        match cells.entry(key).or_insert(Cell::Counter(0)) {
            Cell::Counter(v) => *v = v.saturating_add(delta),
            _ => debug_assert!(false, "metric `{}` kind mismatch", descriptor.name),
        }
    }

    /// 业务作用:覆盖已登记 gauge 的当前值,并对不合规写入累计固定原因诊断。
    ///
    /// 参数说明:
    /// - `descriptor`: 启动期登记的静态 gauge 语义。
    /// - `value`: 需要发布的当前值。
    /// - `labels`: 按 descriptor 顺序提供的低基数 label 值。
    ///
    /// 返回:无;合法写入覆盖当前值,非法 descriptor、label 或超基数写入不改变业务样本。
    fn gauge(&self, descriptor: &'static MetricDescriptor, value: f64, labels: &[&str]) {
        if let Err(reason) = Self::validate_labels(descriptor, labels) {
            self.rejections
                .increment(SampleRejectionSource::Native, reason);
            return;
        }
        if !self.is_registered(descriptor) {
            self.rejections.increment(
                SampleRejectionSource::Native,
                SampleRejectionReason::UnregisteredDescriptor,
            );
            return;
        }
        let mut cells = self
            .cells
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let key = Self::key(descriptor, labels);
        if !self.can_insert_cell(&cells, &key, descriptor) {
            self.rejections.increment(
                SampleRejectionSource::Native,
                SampleRejectionReason::CardinalityLimit,
            );
            return;
        }
        match cells.entry(key).or_insert(Cell::Gauge(0.0)) {
            Cell::Gauge(v) => *v = value,
            _ => debug_assert!(false, "metric `{}` kind mismatch", descriptor.name),
        }
    }

    /// 业务作用:把观测值计入首个匹配边界或 `+Inf` 桶,并对不合规写入累计固定原因诊断。
    ///
    /// 参数说明:
    /// - `descriptor`: 启动期登记的静态 histogram 语义与边界。
    /// - `value`: 本次观测值。
    /// - `labels`: 按 descriptor 顺序提供的低基数 label 值。
    ///
    /// 返回:无;合法写入同步累计 bucket、sum、count,非法写入不改变业务样本。
    fn histogram(&self, descriptor: &'static MetricDescriptor, value: f64, labels: &[&str]) {
        if let Err(reason) = Self::validate_labels(descriptor, labels) {
            self.rejections
                .increment(SampleRejectionSource::Native, reason);
            return;
        }
        if !self.is_registered(descriptor) {
            self.rejections.increment(
                SampleRejectionSource::Native,
                SampleRejectionReason::UnregisteredDescriptor,
            );
            return;
        }
        let bounds = descriptor.histogram_bounds;
        let mut cells = self
            .cells
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let key = Self::key(descriptor, labels);
        if !self.can_insert_cell(&cells, &key, descriptor) {
            self.rejections.increment(
                SampleRejectionSource::Native,
                SampleRejectionReason::CardinalityLimit,
            );
            return;
        }
        let cell = cells.entry(key).or_insert_with(|| Cell::Histogram {
            buckets: vec![0; bounds.len() + 1],
            sum: 0.0,
            count: 0,
        });
        if let Cell::Histogram {
            buckets,
            sum,
            count,
        } = cell
        {
            // 落入第一个 `value <= bound` 的桶;都不满足则落入 +Inf 桶(最后一个)。
            let index = bounds
                .iter()
                .position(|bound| value <= *bound)
                .unwrap_or(bounds.len());
            buckets[index] = buckets[index].saturating_add(1);
            *sum += value;
            *count = count.saturating_add(1);
        } else {
            debug_assert!(false, "metric `{}` kind mismatch", descriptor.name);
        }
    }
}

/// 业务作用:在登记前检查指标名、label 定义与分桶边界的结构合法性。
///
/// 参数说明:
/// - `descriptor`:待登记的静态指标定义。
///
/// 返回:名称、单行非空说明、唯一合法 label 和与类型相符的桶定义有效时成功;非法时返回包含 family 名称的 MetricConflict,不修改目录。直方图边界须非空、有限且严格递增。
fn validate_descriptor(descriptor: &'static MetricDescriptor) -> Result<(), MetricConflict> {
    let valid_name = |name: &str| {
        let mut bytes = name.bytes();
        bytes
            .next()
            .is_some_and(|byte| byte.is_ascii_alphabetic() || matches!(byte, b'_' | b':'))
            && bytes.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b':'))
    };
    let valid_label = |name: &str| {
        let mut bytes = name.bytes();
        bytes
            .next()
            .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
            && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
    };
    let labels: BTreeSet<&str> = descriptor.label_names.iter().copied().collect();
    let invalid = !valid_name(descriptor.name)
        || descriptor.help.is_empty()
        || descriptor.help.contains(['\n', '\r'])
        || labels.len() != descriptor.label_names.len()
        || descriptor
            .label_names
            .iter()
            .any(|name| !valid_label(name) || *name == "le")
        || match descriptor.kind {
            MetricKind::Histogram => {
                descriptor.histogram_bounds.is_empty()
                    || descriptor
                        .histogram_bounds
                        .iter()
                        .any(|bound| !bound.is_finite())
                    || descriptor
                        .histogram_bounds
                        .windows(2)
                        .any(|pair| pair[0] >= pair[1])
            }
            MetricKind::Counter | MetricKind::Gauge => !descriptor.histogram_bounds.is_empty(),
        };
    if invalid {
        Err(MetricConflict {
            name: descriptor.name,
        })
    } else {
        Ok(())
    }
}

/// 单个指标样本(family + label 组合 + 值)的结构化快照。
#[derive(Debug, Clone)]
pub struct MetricSample {
    /// family 名称。
    pub name: &'static str,
    /// (label 名, label 值) 有序对。
    pub labels: Vec<(&'static str, String)>,
    /// 样本值。
    pub value: MetricValue,
}

/// 一个带唯一 descriptor 语义的指标 family 当前快照。
#[derive(Debug, Clone)]
pub struct MetricFamilySnapshot {
    /// family 名称。
    pub name: &'static str,
    /// 稳定业务说明。
    pub description: &'static str,
    /// UCUM 单位;无单位时为空串。
    pub unit: &'static str,
    /// counter、gauge 或 histogram 类型。
    pub kind: MetricKind,
    /// histogram 显式边界;其它类型为空切片。
    pub histogram_bounds: &'static [f64],
    /// 按 label 有序的当前数据点。
    pub samples: Vec<MetricSample>,
}

impl MetricSample {
    /// 业务作用:将样本直接追加到 Prometheus 文本缓冲区,避免为每行标签建立临时字符串集合。
    ///
    /// 参数说明:
    /// - `output`: 接收不含 HELP/TYPE 的完整样本行,原有内容保留。
    ///
    /// 返回:追加标量或直方图累积桶、sum 和 count,不改变样本及标签顺序。
    fn render_prometheus(&self, output: &mut String) {
        use std::fmt::Write as _;
        match &self.value {
            MetricValue::Counter(v) => {
                output.push_str(self.name);
                self.render_labels(output, &[]);
                let _ = writeln!(output, " {v}");
            }
            MetricValue::Gauge(v) => {
                output.push_str(self.name);
                self.render_labels(output, &[]);
                let _ = writeln!(output, " {v}");
            }
            MetricValue::Histogram {
                bounds,
                buckets,
                sum,
                count,
            } => {
                // 累积 `le` 桶。
                let mut cumulative = 0u64;
                for (i, bound) in bounds.iter().enumerate() {
                    cumulative = cumulative.saturating_add(buckets[i]);
                    let le = format!("{bound}");
                    let _ = write!(output, "{}_bucket", self.name);
                    self.render_labels(output, &[("le", le.as_str())]);
                    let _ = writeln!(output, " {cumulative}");
                }
                cumulative = cumulative.saturating_add(buckets[bounds.len()]);
                let _ = write!(output, "{}_bucket", self.name);
                self.render_labels(output, &[("le", "+Inf")]);
                let _ = writeln!(output, " {cumulative}");
                let _ = write!(output, "{}_sum", self.name);
                self.render_labels(output, &[]);
                let _ = writeln!(output, " {sum}");
                let _ = write!(output, "{}_count", self.name);
                self.render_labels(output, &[]);
                let _ = writeln!(output, " {count}");
            }
        }
    }

    /// 业务作用:按样本标签和附加标签的既定顺序编码集合,不分配逐标签中间结果。
    ///
    /// 参数说明:
    /// - `output`: 接收标签集合的文本缓冲区。
    /// - `extra`: 追加在样本标签之后的标签,如直方图的 `le`。
    ///
    /// 返回:有标签时追加花括号、逗号和已转义值;无标签时不写入内容。
    fn render_labels(&self, output: &mut String, extra: &[(&str, &str)]) {
        if self.labels.is_empty() && extra.is_empty() {
            return;
        }
        output.push('{');
        for (index, (key, value)) in self
            .labels
            .iter()
            .map(|(key, value)| (*key, value.as_str()))
            .chain(extra.iter().copied())
            .enumerate()
        {
            if index != 0 {
                output.push(',');
            }
            output.push_str(key);
            output.push_str("=\"");
            append_escaped_label(output, value);
            output.push('"');
        }
        output.push('}');
    }
}

/// 业务作用:直接追加符合 Prometheus 文本协议的标签值,防止引号、反斜杠或换行改变样本结构。
///
/// 参数说明:
/// - `output`: 接收已转义标签值的文本缓冲区。
/// - `value`: 原始 UTF-8 标签值,不包含外围引号。
///
/// 返回:仅转义反斜杠、双引号和换行,其他 UTF-8 内容按原字节保留。
fn append_escaped_label(output: &mut String, value: &str) {
    let mut start = 0;
    for (index, byte) in value.bytes().enumerate() {
        let escaped = match byte {
            b'\\' => "\\\\",
            b'"' => "\\\"",
            b'\n' => "\\n",
            _ => continue,
        };
        // 只在单字节 ASCII 字符处切分,保持多字节 UTF-8 标签的边界完整。
        output.push_str(&value[start..index]);
        output.push_str(escaped);
        start = index + 1;
    }
    output.push_str(&value[start..]);
}

/// 指标样本值。
#[derive(Debug, Clone)]
pub enum MetricValue {
    /// 计数器当前值。
    Counter(u64),
    /// gauge 当前值。
    Gauge(f64),
    /// histogram 分布。
    Histogram {
        /// `le` 上界(升序)。
        bounds: &'static [f64],
        /// 每桶观测数(非累积;长度 = `bounds.len() + 1`)。
        buckets: Vec<u64>,
        /// 观测值之和。
        sum: f64,
        /// 观测次数。
        count: u64,
    },
}