Skip to main content

nametrics_core/
lib.rs

1//! 进程级 provider-neutral 指标核心。
2//!
3//! # 核心价值
4//!
5//! [`MetricHub`] 是一个进程内唯一的 descriptor catalog、记录 backend 和结构化快照源。领域 crate
6//! (`nafana`/`naweb`/`nafka`)继续拥有自己的静态 family、低基数 label 与记录时机;本 crate 只统一
7//! 冲突审计、容量和导出,不重新定义领域指标语义,也不依赖 OpenTelemetry、Prometheus client、
8//! Axum 或 `napp`。
9//!
10//! # 运行架构与安全边界
11//!
12//! 原生记录入口只接受启动期登记且语义一致的 descriptor。受管兼容源通过
13//! [`MetricHub::register_legacy_source_reserved`] 在同一临界区提交 descriptor、source 所有权和最坏
14//! exposition series 预算;冲突、溢出或容量不足时三者都不改变。原生 cell 与显式预留共享
15//! [`MAX_METRIC_SERIES`],目录自身的拒绝诊断预先占位,满载时仍能解释拒绝原因。
16//!
17//! Prometheus 文本和 OTLP adapter 都读取同一次结构化快照,不各自维护 registry。label 形状、单值
18//! 大小、value kind、histogram 结构或基数不满足目录合同时拒绝当前样本,并以固定 `source/reason`
19//! 计数,不把动态 label 内容写进诊断。动态结构化兼容源只使用扣除原生序列与显式预留后的余量,
20//! 按 family/label 排序逐个接纳完整样本。仅文本的旧兼容源不在结构化容量保证内。
21
22use std::collections::{BTreeMap, BTreeSet};
23use std::fmt;
24use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
25use std::sync::{Arc, Mutex, RwLock};
26
27/// 固定桶与原子采集,供低开销领域 source 复用。
28pub mod atomic;
29
30/// 进程内原生、结构化兼容源与诊断按 histogram 展开后的公开序列硬上限。
31pub const MAX_METRIC_SERIES: usize = 100_000;
32/// 统一目录自身按两种来源和七种拒绝原因展开后的固定诊断序列数。
33const INTERNAL_METRIC_SERIES: usize = 2 * SAMPLE_REJECTION_REASONS.len();
34
35/// 单个 label 值允许占用的最大 UTF-8 字节数。
36///
37/// 该上限只约束单值内存,不限制 label 组合数量;基数仍由全局 cell 预算独立约束。
38const MAX_LABEL_VALUE_BYTES: usize = 4 * 1024;
39
40/// 指标类型。
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum MetricKind {
43    /// 单调递增计数器。
44    Counter,
45    /// 可增可减的瞬时值。
46    Gauge,
47    /// 分桶分布(Prometheus `le` 累积桶 + sum + count)。
48    Histogram,
49}
50
51impl MetricKind {
52    /// 业务作用:为指标类型生成 Prometheus TYPE 声明中的固定名称。
53    ///
54    /// 参数说明: 无。
55    ///
56    /// 返回:计数器、瞬时值和分桶指标分别返回 counter、gauge 和 histogram,不产生采集副作用。
57    fn prometheus_type(self) -> &'static str {
58        match self {
59            MetricKind::Counter => "counter",
60            MetricKind::Gauge => "gauge",
61            MetricKind::Histogram => "histogram",
62        }
63    }
64}
65
66/// 一个指标 family 的静态描述。所有字段都是编译期常量,不含动态内容。
67#[derive(Debug)]
68pub struct MetricDescriptor {
69    /// family 名称(如 `napp_web_requests_total`),进程内唯一。
70    pub name: &'static str,
71    /// `# HELP` 文本。
72    pub help: &'static str,
73    /// 单位(如 `seconds`、`bytes`;无单位用 `""`)。
74    pub unit: &'static str,
75    /// 指标类型。
76    pub kind: MetricKind,
77    /// 有序、低基数的 label 名;记录时按同一顺序提供 label 值。
78    pub label_names: &'static [&'static str],
79    /// histogram 的 `le` 上界(升序);非 histogram 用 `&[]`。
80    pub histogram_bounds: &'static [f64],
81}
82
83static SAMPLE_REJECTIONS_TOTAL: MetricDescriptor = MetricDescriptor {
84    name: "nametrics_samples_rejected_total",
85    help: "统一指标目录拒绝的不合规样本累计数。",
86    unit: "",
87    kind: MetricKind::Counter,
88    label_names: &["source", "reason"],
89    histogram_bounds: &[],
90};
91
92#[derive(Clone, Copy)]
93#[repr(usize)]
94enum SampleRejectionReason {
95    UnknownFamily,
96    LabelShape,
97    LabelValueTooLong,
98    ValueKind,
99    HistogramShape,
100    UnregisteredDescriptor,
101    CardinalityLimit,
102}
103
104const SAMPLE_REJECTION_REASONS: [SampleRejectionReason; 7] = [
105    SampleRejectionReason::UnknownFamily,
106    SampleRejectionReason::LabelShape,
107    SampleRejectionReason::LabelValueTooLong,
108    SampleRejectionReason::ValueKind,
109    SampleRejectionReason::HistogramShape,
110    SampleRejectionReason::UnregisteredDescriptor,
111    SampleRejectionReason::CardinalityLimit,
112];
113
114impl SampleRejectionReason {
115    /// 业务作用:返回拒绝原因在固定原子计数数组中的稳定位置。
116    ///
117    /// 参数说明: 无。
118    ///
119    /// 返回:与 [`SAMPLE_REJECTION_REASONS`] 顺序一致的数组下标。
120    const fn index(self) -> usize {
121        self as usize
122    }
123
124    /// 业务作用:返回可用于低基数指标 label 的稳定拒绝原因。
125    ///
126    /// 参数说明: 无。
127    ///
128    /// 返回:不包含动态输入或样本内容的固定原因文本。
129    const fn label(self) -> &'static str {
130        match self {
131            Self::UnknownFamily => "unknown_family",
132            Self::LabelShape => "label_shape",
133            Self::LabelValueTooLong => "label_value_too_long",
134            Self::ValueKind => "value_kind",
135            Self::HistogramShape => "histogram_shape",
136            Self::UnregisteredDescriptor => "unregistered_descriptor",
137            Self::CardinalityLimit => "cardinality_limit",
138        }
139    }
140}
141
142#[derive(Clone, Copy)]
143enum SampleRejectionSource {
144    Native,
145    Legacy,
146}
147
148impl SampleRejectionSource {
149    /// 业务作用:返回可用于低基数指标 label 的稳定样本来源。
150    ///
151    /// 参数说明: 无。
152    ///
153    /// 返回:`native` 表示直接记录入口,`legacy` 表示兼容源结构化快照。
154    const fn label(self) -> &'static str {
155        match self {
156            Self::Native => "native",
157            Self::Legacy => "legacy",
158        }
159    }
160}
161
162/// 业务作用:以固定来源和固定原因维度保存目录拒绝计数,使基数预算耗尽时仍能暴露拒绝事实。
163struct SampleRejectionCounters {
164    native: [AtomicU64; SAMPLE_REJECTION_REASONS.len()],
165    legacy: [AtomicU64; SAMPLE_REJECTION_REASONS.len()],
166}
167
168impl SampleRejectionCounters {
169    /// 业务作用:创建按固定来源和原因分组的拒绝计数器。
170    ///
171    /// 参数说明: 无。
172    ///
173    /// 返回:全部计数从零开始的无锁计数器集合。
174    fn new() -> Self {
175        Self {
176            native: std::array::from_fn(|_| AtomicU64::new(0)),
177            legacy: std::array::from_fn(|_| AtomicU64::new(0)),
178        }
179    }
180
181    /// 业务作用:累计一次被统一目录拒绝的样本检查事件。
182    ///
183    /// 参数说明:
184    /// - `source`: 样本来自直接记录入口还是兼容源快照。
185    /// - `reason`: 不包含动态内容的固定拒绝原因。
186    ///
187    /// 返回:无;对应来源与原因的累计值饱和前单调递增。
188    fn increment(&self, source: SampleRejectionSource, reason: SampleRejectionReason) {
189        let counters = match source {
190            SampleRejectionSource::Native => &self.native,
191            SampleRejectionSource::Legacy => &self.legacy,
192        };
193        let counter = &counters[reason.index()];
194        let _ = counter.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
195            Some(value.saturating_add(1))
196        });
197    }
198
199    /// 业务作用:把非零拒绝计数转换为统一目录自身的结构化指标样本。
200    ///
201    /// 参数说明: 无。
202    ///
203    /// 返回:按来源、原因稳定排序的累计 counter,不暴露被拒样本的 label 内容。
204    fn snapshot(&self) -> Vec<MetricSample> {
205        let mut samples = Vec::new();
206        for (source, counters) in [
207            (SampleRejectionSource::Native, &self.native),
208            (SampleRejectionSource::Legacy, &self.legacy),
209        ] {
210            for reason in SAMPLE_REJECTION_REASONS {
211                let value = counters[reason.index()].load(Ordering::Relaxed);
212                if value == 0 {
213                    continue;
214                }
215                samples.push(MetricSample {
216                    name: SAMPLE_REJECTIONS_TOTAL.name,
217                    labels: vec![
218                        ("source", source.label().to_owned()),
219                        ("reason", reason.label().to_owned()),
220                    ],
221                    value: MetricValue::Counter(value),
222                });
223            }
224        }
225        samples
226    }
227}
228
229impl MetricDescriptor {
230    /// 业务作用:比较两个同名指标描述的采集与导出语义。
231    ///
232    /// 参数说明:
233    /// - `other`:待比较的同名指标描述,名称由调用方另行匹配。
234    ///
235    /// 返回:kind、unit、help、有序 label_names 和 histogram_bounds 全部相等时返回 true;不在此比较名称。
236    fn semantically_eq(&self, other: &MetricDescriptor) -> bool {
237        self.kind == other.kind
238            && self.unit == other.unit
239            && self.help == other.help
240            && self.label_names == other.label_names
241            && self.histogram_bounds == other.histogram_bounds
242    }
243}
244
245/// 领域 crate 记录指标的入口。`napp` 持有唯一 `MetricHub` 实例并实现本 trait。
246pub trait MetricRecorder: Send + Sync {
247    /// 业务作用:按领域提供的描述和 label 值累加计数器。
248    ///
249    /// 参数说明:
250    /// - `descriptor`:决定 family、类型及有序 label 合同的静态描述。
251    /// - `delta`:本次非负增量。
252    /// - `labels`:与描述中 label_names 顺序对应的业务 label 值。
253    ///
254    /// 返回:无返回值;接纳、拒绝及诊断由记录器实现负责,调用不提供持久化或导出完成确认。
255    fn counter(&self, descriptor: &'static MetricDescriptor, delta: u64, labels: &[&str]);
256    /// 业务作用:按领域提供的描述和 label 值设置瞬时值。
257    ///
258    /// 参数说明:
259    /// - `descriptor`:决定 family、类型及有序 label 合同的静态描述。
260    /// - `value`:本次要记录的瞬时数值。
261    /// - `labels`:与描述中 label_names 顺序对应的业务 label 值。
262    ///
263    /// 返回:无返回值;接纳、拒绝及诊断由记录器实现负责,调用不提供持久化或导出完成确认。
264    fn gauge(&self, descriptor: &'static MetricDescriptor, value: f64, labels: &[&str]);
265    /// 业务作用:按领域提供的描述和 label 值记录一次分桶观测。
266    ///
267    /// 参数说明:
268    /// - `descriptor`:决定 family、类型及有序 label 合同的静态描述。
269    /// - `value`:本次待归入描述所声明桶的观测值。
270    /// - `labels`:与描述中 label_names 顺序对应的业务 label 值。
271    ///
272    /// 返回:无返回值;接纳、拒绝及诊断由记录器实现负责,调用不提供持久化或导出完成确认。
273    fn histogram(&self, descriptor: &'static MetricDescriptor, value: f64, labels: &[&str]);
274}
275
276/// descriptor 注册冲突。
277#[derive(Debug, Clone, PartialEq, Eq)]
278pub struct MetricConflict {
279    /// 冲突的 family 名称。
280    pub name: &'static str,
281}
282
283/// 指标源在启动期登记 descriptor 与最坏序列预算时的失败分类。
284#[derive(Debug, Clone, PartialEq, Eq)]
285pub enum MetricSourceRegistrationError {
286    /// 任一 family 与已有目录的静态语义冲突。
287    Conflict(MetricConflict),
288    /// 本源最坏序列数会越过进程硬上限。
289    SeriesBudgetExceeded,
290}
291
292impl From<MetricConflict> for MetricSourceRegistrationError {
293    /// 业务作用:把既有 descriptor 冲突纳入原子指标源登记的统一失败分类。
294    ///
295    /// 参数说明:
296    /// - `conflict`: 已包含稳定 family 名称的目录冲突。
297    ///
298    /// 返回:保持原始冲突事实的指标源登记错误。
299    fn from(conflict: MetricConflict) -> Self {
300        Self::Conflict(conflict)
301    }
302}
303
304impl fmt::Display for MetricSourceRegistrationError {
305    /// 业务作用:输出不携带动态 label 或指标样本内容的稳定登记失败分类。
306    ///
307    /// 参数说明:
308    /// - `formatter`: 接收稳定错误文本的格式化目标。
309    ///
310    /// 返回:错误文本写入成功时完成,否则透传格式化失败。
311    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
312        match self {
313            Self::Conflict(conflict) => {
314                write!(formatter, "metric descriptor `{}` conflicts", conflict.name)
315            }
316            Self::SeriesBudgetExceeded => formatter.write_str("metric series budget is exceeded"),
317        }
318    }
319}
320
321impl std::error::Error for MetricSourceRegistrationError {}
322
323/// 兼容期桥:旧指标源先实现本 trait,启动期用 `descriptors()` 做全局冲突审计,文本与非文本出口
324/// 优先读取 `snapshot()` 的同源结构化值;明确返回 `None` 的旧源仅在文本抓取时回落到
325/// `render_prometheus()`。迁移完成后弃用。
326pub trait LegacyMetricsSource: Send + Sync {
327    /// 业务作用:本源拥有的静态 descriptor,用于启动期冲突审计。
328    ///
329    /// 参数说明: 无。
330    ///
331    /// 返回:本源拥有且在启动期登记的全部 descriptor。
332    fn descriptors(&self) -> &'static [&'static MetricDescriptor];
333    /// 业务作用:导出与文本端点同源的结构化当前值,供 OTLP 等非文本后端复用。
334    ///
335    /// 参数说明: 无。
336    ///
337    /// 返回:`Some` 表示该源支持结构化快照,即使当前没有样本也返回 `Some(Vec::new())`;`None`
338    /// 表示旧源只支持 Prometheus 自渲染,不会进入非文本 exporter。
339    fn snapshot(&self) -> Option<Vec<MetricSample>> {
340        None
341    }
342    /// 业务作用:追加渲染本源的 Prometheus 文本(保持既有 family/HELP/TYPE/label 语义)。
343    ///
344    /// 参数说明:
345    /// - `output`: 接收本源文本的目标缓冲区。
346    ///
347    /// 返回:无;在现有缓冲区尾部追加,不清空已有内容。
348    fn render_prometheus(&self, output: &mut String);
349}
350
351/// 单个 (family, label 值) 组合的进程内值。
352enum Cell {
353    Counter(u64),
354    Gauge(f64),
355    Histogram {
356        /// 长度 = `bounds.len() + 1`,最后一个为 `+Inf` 桶;每个是"落入该桶"的观测数(非累积)。
357        buckets: Vec<u64>,
358        sum: f64,
359        count: u64,
360    },
361}
362
363#[derive(Clone)]
364struct RegisteredSource {
365    source: Arc<dyn LegacyMetricsSource>,
366    budget: Option<usize>,
367}
368
369/// 唯一进程级指标 backend:descriptor catalog(带冲突审计)+ 进程内记录 + 结构化/Prometheus 导出。
370pub struct MetricHub {
371    descriptors: RwLock<BTreeMap<&'static str, &'static MetricDescriptor>>,
372    /// (family 名, label 值序列) → 值。BTreeMap 使导出顺序稳定,便于 golden 对比。
373    cells: RwLock<BTreeMap<(&'static str, Vec<String>), Cell>>,
374    /// 兼容领域源(nafana/naweb 等)的 registry;其 descriptor 已并入 catalog,结构化快照由
375    /// hub 统一导出,只有明确不支持结构化快照的旧源才使用自身 Prometheus 文本入口。
376    sources: RwLock<Vec<RegisteredSource>>,
377    /// 原生 cell 展开为公开序列后的占用;写入与 cell 创建共用 cells 写锁。
378    native_series: AtomicUsize,
379    /// 启动期已由受管指标源原子提交的最坏导出序列数;与运行期原生 cell 共用进程硬上限。
380    reserved_series: Mutex<usize>,
381    /// 所有拒绝原因均为固定低基数 label;不保存被拒样本的动态内容。
382    rejections: SampleRejectionCounters,
383}
384
385impl MetricHub {
386    /// 业务作用:创建只预留统一目录拒绝指标、尚未登记业务指标源的 hub。
387    ///
388    /// 参数说明: 无。
389    ///
390    /// 返回:可执行 descriptor 冲突审计、记录和双出口快照的独立指标目录。
391    pub fn new() -> Self {
392        let mut descriptors = BTreeMap::new();
393        descriptors.insert(SAMPLE_REJECTIONS_TOTAL.name, &SAMPLE_REJECTIONS_TOTAL);
394        Self {
395            descriptors: RwLock::new(descriptors),
396            cells: RwLock::new(BTreeMap::new()),
397            sources: RwLock::new(Vec::new()),
398            native_series: AtomicUsize::new(0),
399            // 内部拒绝族必须在任何业务预留之前占位,保证目录满载时仍能解释后续拒绝。
400            reserved_series: Mutex::new(INTERNAL_METRIC_SERIES),
401            rejections: SampleRejectionCounters::new(),
402        }
403    }
404
405    /// 业务作用:注册一个静态 descriptor 并审计冲突。
406    ///
407    /// 参数说明:
408    /// - `descriptor`: 需要纳入进程唯一目录的静态指标语义。
409    ///
410    /// 返回:首次登记或同一业务 descriptor 幂等登记时成功;内部诊断 family 与业务 family
411    /// 语义冲突时失败,目录保持原状。
412    ///
413    /// # 错误
414    ///
415    /// 同名但语义不同(kind/unit/help/label_names/histogram_bounds 任一不同)时返回
416    /// [`MetricConflict`];同名且完全一致是幂等的(返回 `Ok`)。
417    pub fn register(&self, descriptor: &'static MetricDescriptor) -> Result<(), MetricConflict> {
418        validate_descriptor(descriptor)?;
419        if descriptor.name == SAMPLE_REJECTIONS_TOTAL.name
420            && !std::ptr::eq(descriptor, &SAMPLE_REJECTIONS_TOTAL)
421        {
422            return Err(MetricConflict {
423                name: descriptor.name,
424            });
425        }
426        let mut descriptors = self
427            .descriptors
428            .write()
429            .unwrap_or_else(std::sync::PoisonError::into_inner);
430        if let Some(existing) = descriptors.get(descriptor.name) {
431            if existing.semantically_eq(descriptor) {
432                return Ok(());
433            }
434            return Err(MetricConflict {
435                name: descriptor.name,
436            });
437        }
438        descriptors.insert(descriptor.name, descriptor);
439        Ok(())
440    }
441
442    /// 业务作用:审计一个 [`LegacyMetricsSource`] 的 descriptor 纳入统一 catalog,并保存该源以便导出。
443    ///
444    /// 审计通过后,`Some` 结构化快照同时进入 Prometheus 与非文本出口;明确返回 `None` 的旧源
445    /// 只进入 `render_prometheus` 回落路径。原生渲染循环跳过文本旧源声明的族名,避免重复
446    /// HELP/TYPE。
447    ///
448    /// 参数说明:
449    /// - `source`:为拥有独立 family 的兼容指标源。
450    ///
451    /// 返回:目录无冲突时登记;结构化快照只使用全进程预留之外的动态余量,超额样本在导出时拒绝。
452    ///
453    /// # 错误
454    ///
455    /// 任一 descriptor 与已注册项冲突时返回首个 [`MetricConflict`],此时源不会被保存。
456    pub fn register_legacy_source(
457        &self,
458        source: Arc<dyn LegacyMetricsSource>,
459    ) -> Result<(), MetricConflict> {
460        {
461            let sources = self
462                .sources
463                .read()
464                .unwrap_or_else(std::sync::PoisonError::into_inner);
465            if sources
466                .iter()
467                .any(|existing| Arc::ptr_eq(&existing.source, &source))
468            {
469                return Ok(());
470            }
471        }
472        let candidates = source.descriptors();
473        for descriptor in candidates {
474            validate_descriptor(descriptor)?;
475        }
476        let mut descriptors = self
477            .descriptors
478            .write()
479            .unwrap_or_else(std::sync::PoisonError::into_inner);
480        // 兼容源拥有它声明的 family;即使语义相同,也不能与原生/另一兼容源双重拥有并渲染。
481        if let Some(conflict) = candidates
482            .iter()
483            .find(|descriptor| descriptors.contains_key(descriptor.name))
484        {
485            return Err(MetricConflict {
486                name: conflict.name,
487            });
488        }
489        for descriptor in source.descriptors() {
490            descriptors.insert(descriptor.name, descriptor);
491        }
492        drop(descriptors);
493        self.sources
494            .write()
495            .unwrap_or_else(std::sync::PoisonError::into_inner)
496            .push(RegisteredSource {
497                source,
498                budget: None,
499            });
500        Ok(())
501    }
502
503    /// 业务作用:在一个临界区内校验并提交兼容指标源的 descriptor、所有权与最坏序列预算。
504    ///
505    /// 参数说明:
506    /// - `source`: 只产生 sealed label domain 的结构化指标源。
507    /// - `worst_case_series`: 该源全部 family 展开 label 与 histogram 后的最大公开序列数。
508    ///
509    /// 返回:目录无冲突且进程预留不超过 [`MAX_METRIC_SERIES`] 时原子提交;失败时 descriptor、source
510    /// 和预留计数均保持不变,不会留下半份公开指标源。
511    pub fn register_legacy_source_reserved(
512        &self,
513        source: Arc<dyn LegacyMetricsSource>,
514        worst_case_series: usize,
515    ) -> Result<(), MetricSourceRegistrationError> {
516        let candidates = source.descriptors();
517        for descriptor in candidates {
518            validate_descriptor(descriptor)?;
519        }
520        let mut descriptors = self
521            .descriptors
522            .write()
523            .unwrap_or_else(std::sync::PoisonError::into_inner);
524        let mut sources = self
525            .sources
526            .write()
527            .unwrap_or_else(std::sync::PoisonError::into_inner);
528        if sources
529            .iter()
530            .any(|existing| Arc::ptr_eq(&existing.source, &source))
531        {
532            return Ok(());
533        }
534        if let Some(conflict) = candidates
535            .iter()
536            .find(|descriptor| descriptors.contains_key(descriptor.name))
537        {
538            return Err(MetricConflict {
539                name: conflict.name,
540            }
541            .into());
542        }
543        let cells = self
544            .cells
545            .read()
546            .unwrap_or_else(std::sync::PoisonError::into_inner);
547        let mut reserved = self
548            .reserved_series
549            .lock()
550            .unwrap_or_else(std::sync::PoisonError::into_inner);
551        let next = reserved
552            .checked_add(worst_case_series)
553            .and_then(|total| {
554                total
555                    .checked_add(self.native_series.load(Ordering::Relaxed))
556                    .map(|used| (total, used))
557            })
558            .filter(|(_, used)| *used <= MAX_METRIC_SERIES)
559            .map(|(total, _)| total)
560            .ok_or(MetricSourceRegistrationError::SeriesBudgetExceeded)?;
561
562        // 三类状态只在全部门禁通过后一起发布;任何前置失败都不能占用预算或暴露部分 family。
563        for descriptor in candidates {
564            descriptors.insert(descriptor.name, descriptor);
565        }
566        sources.push(RegisteredSource {
567            source,
568            budget: Some(worst_case_series),
569        });
570        drop(cells);
571        *reserved = next;
572        Ok(())
573    }
574
575    /// 业务作用:读取启动期已提交的最坏公开序列预留,供 Ready 门禁与诊断核对全进程余量。
576    ///
577    /// 参数说明: 无。
578    ///
579    /// 返回:目录自身诊断族与显式登记源的预留之和;原生 cell 的实际展开占用另行参与同一总量门禁。
580    pub fn reserved_series(&self) -> usize {
581        *self
582            .reserved_series
583            .lock()
584            .unwrap_or_else(std::sync::PoisonError::into_inner)
585    }
586
587    /// 业务作用:为出口启动门禁读取已承诺的完整公开序列占用,包含已创建的原生指标。
588    ///
589    /// 参数说明: 无。
590    ///
591    /// 返回:内部诊断与显式源的最坏预留,加上原生 cell 的展开占用;histogram 包含全部桶、sum 和 count。
592    /// 无预留的兼容源与检查之后新增的原生 label 不在此值内,调用方仍需单独约束动态增长。
593    pub fn committed_series(&self) -> usize {
594        // 沿用创建 cell 和登记 source 的 cells → reserved 锁顺序,保证两个占用来自同一时刻,
595        // 不能让并发登记或原生首次写入在 Ready 核对时落入两个读数之间的空隙。
596        let _cells = self
597            .cells
598            .read()
599            .unwrap_or_else(std::sync::PoisonError::into_inner);
600        let reserved = self
601            .reserved_series
602            .lock()
603            .unwrap_or_else(std::sync::PoisonError::into_inner);
604        reserved.saturating_add(self.native_series.load(Ordering::Relaxed))
605    }
606
607    /// 业务作用:校验直接记录入口的 label 数量与单值内存上限。
608    ///
609    /// 参数说明:
610    /// - `descriptor`: 已声明 label 顺序的静态指标语义。
611    /// - `labels`: 调用方按 descriptor 顺序提交的 label 值。
612    ///
613    /// 返回:满足数量和单值上限时成功,否则返回稳定拒绝原因。
614    fn validate_labels(
615        descriptor: &MetricDescriptor,
616        labels: &[&str],
617    ) -> Result<(), SampleRejectionReason> {
618        if labels.len() != descriptor.label_names.len() {
619            return Err(SampleRejectionReason::LabelShape);
620        }
621        if labels
622            .iter()
623            .any(|value| value.len() > MAX_LABEL_VALUE_BYTES)
624        {
625            return Err(SampleRejectionReason::LabelValueTooLong);
626        }
627        Ok(())
628    }
629
630    /// 业务作用:确认调用方使用的是已登记且语义完全一致的 descriptor,防止同名漂移写入。
631    ///
632    /// 参数说明:
633    /// - `descriptor`: 本次记录入口携带的静态 descriptor。
634    ///
635    /// 返回:业务 descriptor 与目录语义一致时返回 `true`;内部拒绝指标只接受目录私有实例。
636    fn is_registered(&self, descriptor: &MetricDescriptor) -> bool {
637        if descriptor.name == SAMPLE_REJECTIONS_TOTAL.name {
638            return std::ptr::eq(descriptor, &SAMPLE_REJECTIONS_TOTAL);
639        }
640        self.descriptors
641            .read()
642            .unwrap_or_else(std::sync::PoisonError::into_inner)
643            .get(descriptor.name)
644            .is_some_and(|registered| registered.semantically_eq(descriptor))
645    }
646
647    /// 业务作用:在原生 cell 写锁保护下检查并预占新样本完整导出序列预算。
648    ///
649    /// 参数说明:
650    /// - `cells`:调用方已持写锁的当前原生样本表。
651    /// - `key`:本次 family 名称和有序 label 值组合。
652    /// - `descriptor`:决定新 cell 所需导出序列数的指标定义。
653    ///
654    /// 返回:已存在组合直接允许;新组合及预留总数不超过硬上限时先增加原生占用并返回 true。溢出或容量不足返回 false,不修改占用;实际 cell 插入由调用方在同一锁范围完成。
655    fn can_insert_cell(
656        &self,
657        cells: &BTreeMap<(&'static str, Vec<String>), Cell>,
658        key: &(&'static str, Vec<String>),
659        descriptor: &MetricDescriptor,
660    ) -> bool {
661        if cells.contains_key(key) {
662            return true;
663        }
664        let reserved = *self
665            .reserved_series
666            .lock()
667            .unwrap_or_else(std::sync::PoisonError::into_inner);
668        let used = self.native_series.load(Ordering::Relaxed);
669        let cost = descriptor_series(descriptor);
670        // 完整 histogram 在创建前一次性占位,避免桶、sum、count 越过进程硬限。
671        if used
672            .checked_add(cost)
673            .and_then(|total| total.checked_add(reserved))
674            .is_none_or(|total| total > MAX_METRIC_SERIES)
675        {
676            return false;
677        }
678        self.native_series.store(used + cost, Ordering::Relaxed);
679        true
680    }
681
682    /// 业务作用:将指标名称与借用的有序 label 值固化为样本表键。
683    ///
684    /// 参数说明:
685    /// - `descriptor`:提供静态 family 名称的指标定义。
686    /// - `labels`:与描述声明顺序一致的 label 值。
687    ///
688    /// 返回:返回静态名称和拥有内容的 label 值向量,不检查形状、长度或登记资格。
689    fn key(descriptor: &MetricDescriptor, labels: &[&str]) -> (&'static str, Vec<String>) {
690        (
691            descriptor.name,
692            labels.iter().map(|value| (*value).to_owned()).collect(),
693        )
694    }
695
696    /// 业务作用:导出全部原生与兼容源指标的结构化快照,family 与 label 组合按名称有序。
697    ///
698    /// 兼容源必须直接读取自己的原子 registry,不从 Prometheus 文本反解析。源返回的 family、label
699    /// 或 value kind 与启动期 descriptor 不一致时,该样本会被拒绝,避免非文本出口绕过 catalog。
700    ///
701    /// 参数说明: 无。
702    ///
703    /// 返回:按 family 与 label 有序且符合全局公开序列预算的当前快照;拒绝事实在同次快照中可见,
704    /// 读取不会清零计数或 histogram。
705    pub fn snapshot(&self) -> Vec<MetricSample> {
706        self.collect_snapshot().0
707    }
708
709    /// 业务作用:一次性收集原生与结构化兼容源样本,并识别只能自渲染文本的旧源。
710    ///
711    /// 参数说明: 无。
712    ///
713    /// 返回:第一项是经过 descriptor 校验的统一快照,第二项是明确返回 `None` 的文本旧源;结构化
714    /// 源即使当前为空或全部样本被拒绝也不会退回另一条数据路径。
715    fn collect_snapshot(&self) -> (Vec<MetricSample>, Vec<Arc<dyn LegacyMetricsSource>>) {
716        let mut out = Vec::new();
717        let mut text_only_sources = Vec::new();
718        let sources = self
719            .sources
720            .read()
721            .unwrap_or_else(std::sync::PoisonError::into_inner)
722            .clone();
723        let native = self.native_snapshot();
724        let native_count = native
725            .iter()
726            .filter(|sample| sample.name != SAMPLE_REJECTIONS_TOTAL.name)
727            .map(sample_series)
728            .sum::<usize>();
729        let reserved = sources
730            .iter()
731            .filter_map(|entry| entry.budget)
732            .sum::<usize>();
733        let mut remaining = MAX_METRIC_SERIES
734            .saturating_sub(INTERNAL_METRIC_SERIES)
735            .saturating_sub(native_count)
736            .saturating_sub(reserved);
737        for entry in sources {
738            let source = entry.source;
739            let Some(mut samples) = source.snapshot() else {
740                text_only_sources.push(source);
741                continue;
742            };
743            let owned: BTreeMap<&'static str, &'static MetricDescriptor> = source
744                .descriptors()
745                .iter()
746                .map(|descriptor| (descriptor.name, *descriptor))
747                .collect();
748            // 固定排序使容量拒绝不依赖兼容源的枚举顺序;受管源不能挤占其它源已承诺的预算。
749            samples.sort_by(|left, right| {
750                left.name
751                    .cmp(right.name)
752                    .then_with(|| left.labels.cmp(&right.labels))
753            });
754            let mut available = entry.budget.unwrap_or(remaining);
755            for sample in samples {
756                let Some(descriptor) = owned.get(sample.name).copied() else {
757                    self.rejections.increment(
758                        SampleRejectionSource::Legacy,
759                        SampleRejectionReason::UnknownFamily,
760                    );
761                    continue;
762                };
763                match validate_sample(&sample, descriptor) {
764                    Ok(()) => {
765                        let cost = sample_series(&sample);
766                        // 容量不足时拒绝整个样本,不能发布缺少部分桶或 sum/count 的 histogram。
767                        if cost > available {
768                            self.rejections.increment(
769                                SampleRejectionSource::Legacy,
770                                SampleRejectionReason::CardinalityLimit,
771                            );
772                            continue;
773                        }
774                        available -= cost;
775                        out.push(sample);
776                    }
777                    Err(reason) => self
778                        .rejections
779                        .increment(SampleRejectionSource::Legacy, reason),
780                }
781            }
782            if entry.budget.is_none() {
783                remaining = available;
784            }
785        }
786        out.extend(
787            native
788                .into_iter()
789                .filter(|sample| sample.name != SAMPLE_REJECTIONS_TOTAL.name),
790        );
791        // 拒绝发生后再读固定诊断,使本次导出本身就能解释容量损失。
792        out.extend(self.rejections.snapshot());
793        out.sort_by(|left, right| {
794            left.name
795                .cmp(right.name)
796                .then_with(|| left.labels.cmp(&right.labels))
797        });
798        (out, text_only_sources)
799    }
800
801    /// 业务作用:导出由 hub 直接记录的指标值,不触发兼容源的快照副作用。
802    ///
803    /// 参数说明: 无。
804    ///
805    /// 返回:按 hub 有序 cell 生成的当前值以及非零拒绝诊断;调用时不清零任何计数。
806    fn native_snapshot(&self) -> Vec<MetricSample> {
807        let descriptors = self
808            .descriptors
809            .read()
810            .unwrap_or_else(std::sync::PoisonError::into_inner);
811        let cells = self
812            .cells
813            .read()
814            .unwrap_or_else(std::sync::PoisonError::into_inner);
815        let mut out = Vec::with_capacity(cells.len());
816        for ((name, label_values), cell) in cells.iter() {
817            let Some(descriptor) = descriptors.get(name) else {
818                continue;
819            };
820            let labels: Vec<(&'static str, String)> = descriptor
821                .label_names
822                .iter()
823                .copied()
824                .zip(label_values.iter().cloned())
825                .collect();
826            let value = match cell {
827                Cell::Counter(v) => MetricValue::Counter(*v),
828                Cell::Gauge(v) => MetricValue::Gauge(*v),
829                Cell::Histogram {
830                    buckets,
831                    sum,
832                    count,
833                } => MetricValue::Histogram {
834                    bounds: descriptor.histogram_bounds,
835                    buckets: buckets.clone(),
836                    sum: *sum,
837                    count: *count,
838                },
839            };
840            out.push(MetricSample {
841                name,
842                labels,
843                value,
844            });
845        }
846        drop(cells);
847        drop(descriptors);
848        out.extend(self.rejections.snapshot());
849        out
850    }
851
852    /// 业务作用:把当前值按启动期 descriptor 聚合成可直接编码的指标 family 快照。
853    ///
854    /// 参数说明: 无。
855    ///
856    /// 返回:只包含当前至少有一个样本的 family;名称、说明、单位、类型与 histogram 边界均来自
857    /// 唯一 catalog,OTLP 与 Prometheus 不会各自维护第二份指标语义。
858    pub fn family_snapshot(&self) -> Vec<MetricFamilySnapshot> {
859        let samples = self.snapshot();
860        let descriptors = self
861            .descriptors
862            .read()
863            .unwrap_or_else(std::sync::PoisonError::into_inner);
864        let mut families: BTreeMap<&'static str, MetricFamilySnapshot> = BTreeMap::new();
865        for sample in samples {
866            let Some(descriptor) = descriptors.get(sample.name).copied() else {
867                continue;
868            };
869            families
870                .entry(descriptor.name)
871                .or_insert_with(|| MetricFamilySnapshot {
872                    name: descriptor.name,
873                    description: descriptor.help,
874                    unit: descriptor.unit,
875                    kind: descriptor.kind,
876                    histogram_bounds: descriptor.histogram_bounds,
877                    samples: Vec::new(),
878                })
879                .samples
880                .push(sample);
881        }
882        families.into_values().collect()
883    }
884
885    /// 业务作用:把 hub 拥有的全部指标渲染为 Prometheus 文本(HELP/TYPE + 样本),追加到 `output`。
886    ///
887    /// 渲染顺序:先按名称有序输出原生 family 和结构化兼容源,再按注册顺序处理文本旧源。返回
888    /// `Some(Vec::new())` 的结构化源只表示当前无样本,不会调用另一份自渲染入口。
889    /// 同一 family 始终只有一组 HELP/TYPE,结构化源与 OTLP 共用同一值和边界。
890    ///
891    /// 参数说明:
892    /// - `output`: 接收完整 Prometheus exposition 的目标缓冲区。
893    ///
894    /// 返回:无;在现有缓冲区尾部追加,不清空已有内容。
895    pub fn render_prometheus(&self, output: &mut String) {
896        use std::fmt::Write as _;
897        // 单次收集同时决定结构化与文本旧源,避免“结构化快照为空”在不同出口被解释成不同数据源。
898        let (samples, text_only_sources) = self.collect_snapshot();
899        let text_only_names: BTreeSet<&'static str> = text_only_sources
900            .iter()
901            .flat_map(|source| source.descriptors().iter().map(|d| d.name))
902            .collect();
903        let descriptors = self
904            .descriptors
905            .read()
906            .unwrap_or_else(std::sync::PoisonError::into_inner);
907        // 按 family 分组渲染原生族,每个 family 一组 HELP/TYPE。
908        for (name, descriptor) in descriptors.iter() {
909            if text_only_names.contains(name) {
910                continue;
911            }
912            if *name == SAMPLE_REJECTIONS_TOTAL.name
913                && !samples.iter().any(|sample| sample.name == *name)
914            {
915                continue;
916            }
917            let _ = writeln!(output, "# HELP {name} {}", descriptor.help);
918            let _ = writeln!(
919                output,
920                "# TYPE {name} {}",
921                descriptor.kind.prometheus_type()
922            );
923            for sample in samples.iter().filter(|s| s.name == *name) {
924                sample.render_prometheus(output);
925            }
926        }
927        drop(descriptors);
928        // 只有显式声明不支持结构化快照的旧源使用自身文本入口;结构化源的文本与 OTLP 始终共用上面的值。
929        for source in text_only_sources {
930            source.render_prometheus(output);
931        }
932    }
933}
934
935/// 业务作用:计算 descriptor 的一个 label 组合占用的公开序列数。
936///
937/// 参数说明:
938/// - `descriptor`:为已校验的静态指标语义。
939///
940/// 返回:普通样本占一条,histogram 包括所有有限桶、+Inf、sum 和 count。
941fn descriptor_series(descriptor: &MetricDescriptor) -> usize {
942    if descriptor.kind == MetricKind::Histogram {
943        descriptor.histogram_bounds.len() + 3
944    } else {
945        1
946    }
947}
948
949/// 业务作用:按实际样本结构核算出口容量。
950///
951/// 参数说明:
952/// - `sample`:为已经过 descriptor 校验的完整样本。
953///
954/// 返回:与 Prometheus 展开结果一致的序列数。
955fn sample_series(sample: &MetricSample) -> usize {
956    match &sample.value {
957        MetricValue::Histogram {
958            bounds,
959            ..
960        } => bounds.len() + 3,
961        _ => 1,
962    }
963}
964
965/// 业务作用:验证兼容源样本与启动期 descriptor 的名称、label 顺序、资源上限和 value kind 完全一致。
966///
967/// 参数说明:
968/// - `sample`: 兼容源从自身 registry 读取的当前值。
969/// - `descriptor`: 该源在注册时提交并通过冲突审计的静态语义。
970///
971/// 返回:样本可安全进入统一快照时成功;不符合合同则返回可观测的固定拒绝原因。
972fn validate_sample(
973    sample: &MetricSample,
974    descriptor: &MetricDescriptor,
975) -> Result<(), SampleRejectionReason> {
976    if sample.name != descriptor.name
977        || sample.labels.len() != descriptor.label_names.len()
978        || sample
979            .labels
980            .iter()
981            .zip(descriptor.label_names)
982            .any(|((actual, _), expected)| actual != expected)
983    {
984        return Err(SampleRejectionReason::LabelShape);
985    }
986    if sample
987        .labels
988        .iter()
989        .any(|(_, value)| value.len() > MAX_LABEL_VALUE_BYTES)
990    {
991        return Err(SampleRejectionReason::LabelValueTooLong);
992    }
993    match (&sample.value, descriptor.kind) {
994        (MetricValue::Counter(_), MetricKind::Counter)
995        | (MetricValue::Gauge(_), MetricKind::Gauge) => Ok(()),
996        (
997            MetricValue::Histogram {
998                bounds,
999                buckets,
1000                count,
1001                ..
1002            },
1003            MetricKind::Histogram,
1004        ) => {
1005            if *bounds == descriptor.histogram_bounds
1006                && buckets.len() == bounds.len() + 1
1007                && buckets.iter().copied().fold(0_u64, u64::saturating_add) == *count
1008            {
1009                Ok(())
1010            } else {
1011                Err(SampleRejectionReason::HistogramShape)
1012            }
1013        }
1014        _ => Err(SampleRejectionReason::ValueKind),
1015    }
1016}
1017
1018impl Default for MetricHub {
1019    /// 业务作用:构造预留内部拒绝指标的进程指标目录。
1020    ///
1021    /// 参数说明: 无。
1022    ///
1023    /// 返回:与 new 相同,返回含内部描述和预算预留、尚无业务源和原生样本的独立目录。
1024    fn default() -> Self {
1025        Self::new()
1026    }
1027}
1028
1029impl MetricRecorder for MetricHub {
1030    /// 业务作用:对已登记 counter 做饱和累加,并对不合规写入累计固定原因诊断。
1031    ///
1032    /// 参数说明:
1033    /// - `descriptor`: 启动期登记的静态 counter 语义。
1034    /// - `delta`: 本次需要累计的非负增量。
1035    /// - `labels`: 按 descriptor 顺序提供的低基数 label 值。
1036    ///
1037    /// 返回:无;合法写入饱和累加,非法 descriptor、label 或超基数写入不改变业务样本。
1038    fn counter(&self, descriptor: &'static MetricDescriptor, delta: u64, labels: &[&str]) {
1039        if let Err(reason) = Self::validate_labels(descriptor, labels) {
1040            self.rejections
1041                .increment(SampleRejectionSource::Native, reason);
1042            return;
1043        }
1044        if !self.is_registered(descriptor) {
1045            self.rejections.increment(
1046                SampleRejectionSource::Native,
1047                SampleRejectionReason::UnregisteredDescriptor,
1048            );
1049            return;
1050        }
1051        let mut cells = self
1052            .cells
1053            .write()
1054            .unwrap_or_else(std::sync::PoisonError::into_inner);
1055        let key = Self::key(descriptor, labels);
1056        if !self.can_insert_cell(&cells, &key, descriptor) {
1057            self.rejections.increment(
1058                SampleRejectionSource::Native,
1059                SampleRejectionReason::CardinalityLimit,
1060            );
1061            return;
1062        }
1063        match cells.entry(key).or_insert(Cell::Counter(0)) {
1064            Cell::Counter(v) => *v = v.saturating_add(delta),
1065            _ => debug_assert!(false, "metric `{}` kind mismatch", descriptor.name),
1066        }
1067    }
1068
1069    /// 业务作用:覆盖已登记 gauge 的当前值,并对不合规写入累计固定原因诊断。
1070    ///
1071    /// 参数说明:
1072    /// - `descriptor`: 启动期登记的静态 gauge 语义。
1073    /// - `value`: 需要发布的当前值。
1074    /// - `labels`: 按 descriptor 顺序提供的低基数 label 值。
1075    ///
1076    /// 返回:无;合法写入覆盖当前值,非法 descriptor、label 或超基数写入不改变业务样本。
1077    fn gauge(&self, descriptor: &'static MetricDescriptor, value: f64, labels: &[&str]) {
1078        if let Err(reason) = Self::validate_labels(descriptor, labels) {
1079            self.rejections
1080                .increment(SampleRejectionSource::Native, reason);
1081            return;
1082        }
1083        if !self.is_registered(descriptor) {
1084            self.rejections.increment(
1085                SampleRejectionSource::Native,
1086                SampleRejectionReason::UnregisteredDescriptor,
1087            );
1088            return;
1089        }
1090        let mut cells = self
1091            .cells
1092            .write()
1093            .unwrap_or_else(std::sync::PoisonError::into_inner);
1094        let key = Self::key(descriptor, labels);
1095        if !self.can_insert_cell(&cells, &key, descriptor) {
1096            self.rejections.increment(
1097                SampleRejectionSource::Native,
1098                SampleRejectionReason::CardinalityLimit,
1099            );
1100            return;
1101        }
1102        match cells.entry(key).or_insert(Cell::Gauge(0.0)) {
1103            Cell::Gauge(v) => *v = value,
1104            _ => debug_assert!(false, "metric `{}` kind mismatch", descriptor.name),
1105        }
1106    }
1107
1108    /// 业务作用:把观测值计入首个匹配边界或 `+Inf` 桶,并对不合规写入累计固定原因诊断。
1109    ///
1110    /// 参数说明:
1111    /// - `descriptor`: 启动期登记的静态 histogram 语义与边界。
1112    /// - `value`: 本次观测值。
1113    /// - `labels`: 按 descriptor 顺序提供的低基数 label 值。
1114    ///
1115    /// 返回:无;合法写入同步累计 bucket、sum、count,非法写入不改变业务样本。
1116    fn histogram(&self, descriptor: &'static MetricDescriptor, value: f64, labels: &[&str]) {
1117        if let Err(reason) = Self::validate_labels(descriptor, labels) {
1118            self.rejections
1119                .increment(SampleRejectionSource::Native, reason);
1120            return;
1121        }
1122        if !self.is_registered(descriptor) {
1123            self.rejections.increment(
1124                SampleRejectionSource::Native,
1125                SampleRejectionReason::UnregisteredDescriptor,
1126            );
1127            return;
1128        }
1129        let bounds = descriptor.histogram_bounds;
1130        let mut cells = self
1131            .cells
1132            .write()
1133            .unwrap_or_else(std::sync::PoisonError::into_inner);
1134        let key = Self::key(descriptor, labels);
1135        if !self.can_insert_cell(&cells, &key, descriptor) {
1136            self.rejections.increment(
1137                SampleRejectionSource::Native,
1138                SampleRejectionReason::CardinalityLimit,
1139            );
1140            return;
1141        }
1142        let cell = cells.entry(key).or_insert_with(|| Cell::Histogram {
1143            buckets: vec![0; bounds.len() + 1],
1144            sum: 0.0,
1145            count: 0,
1146        });
1147        if let Cell::Histogram {
1148            buckets,
1149            sum,
1150            count,
1151        } = cell
1152        {
1153            // 落入第一个 `value <= bound` 的桶;都不满足则落入 +Inf 桶(最后一个)。
1154            let index = bounds
1155                .iter()
1156                .position(|bound| value <= *bound)
1157                .unwrap_or(bounds.len());
1158            buckets[index] = buckets[index].saturating_add(1);
1159            *sum += value;
1160            *count = count.saturating_add(1);
1161        } else {
1162            debug_assert!(false, "metric `{}` kind mismatch", descriptor.name);
1163        }
1164    }
1165}
1166
1167/// 业务作用:在登记前检查指标名、label 定义与分桶边界的结构合法性。
1168///
1169/// 参数说明:
1170/// - `descriptor`:待登记的静态指标定义。
1171///
1172/// 返回:名称、单行非空说明、唯一合法 label 和与类型相符的桶定义有效时成功;非法时返回包含 family 名称的 MetricConflict,不修改目录。直方图边界须非空、有限且严格递增。
1173fn validate_descriptor(descriptor: &'static MetricDescriptor) -> Result<(), MetricConflict> {
1174    let valid_name = |name: &str| {
1175        let mut bytes = name.bytes();
1176        bytes
1177            .next()
1178            .is_some_and(|byte| byte.is_ascii_alphabetic() || matches!(byte, b'_' | b':'))
1179            && bytes.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b':'))
1180    };
1181    let valid_label = |name: &str| {
1182        let mut bytes = name.bytes();
1183        bytes
1184            .next()
1185            .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
1186            && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
1187    };
1188    let labels: BTreeSet<&str> = descriptor.label_names.iter().copied().collect();
1189    let invalid = !valid_name(descriptor.name)
1190        || descriptor.help.is_empty()
1191        || descriptor.help.contains(['\n', '\r'])
1192        || labels.len() != descriptor.label_names.len()
1193        || descriptor
1194            .label_names
1195            .iter()
1196            .any(|name| !valid_label(name) || *name == "le")
1197        || match descriptor.kind {
1198            MetricKind::Histogram => {
1199                descriptor.histogram_bounds.is_empty()
1200                    || descriptor
1201                        .histogram_bounds
1202                        .iter()
1203                        .any(|bound| !bound.is_finite())
1204                    || descriptor
1205                        .histogram_bounds
1206                        .windows(2)
1207                        .any(|pair| pair[0] >= pair[1])
1208            }
1209            MetricKind::Counter | MetricKind::Gauge => !descriptor.histogram_bounds.is_empty(),
1210        };
1211    if invalid {
1212        Err(MetricConflict {
1213            name: descriptor.name,
1214        })
1215    } else {
1216        Ok(())
1217    }
1218}
1219
1220/// 单个指标样本(family + label 组合 + 值)的结构化快照。
1221#[derive(Debug, Clone)]
1222pub struct MetricSample {
1223    /// family 名称。
1224    pub name: &'static str,
1225    /// (label 名, label 值) 有序对。
1226    pub labels: Vec<(&'static str, String)>,
1227    /// 样本值。
1228    pub value: MetricValue,
1229}
1230
1231/// 一个带唯一 descriptor 语义的指标 family 当前快照。
1232#[derive(Debug, Clone)]
1233pub struct MetricFamilySnapshot {
1234    /// family 名称。
1235    pub name: &'static str,
1236    /// 稳定业务说明。
1237    pub description: &'static str,
1238    /// UCUM 单位;无单位时为空串。
1239    pub unit: &'static str,
1240    /// counter、gauge 或 histogram 类型。
1241    pub kind: MetricKind,
1242    /// histogram 显式边界;其它类型为空切片。
1243    pub histogram_bounds: &'static [f64],
1244    /// 按 label 有序的当前数据点。
1245    pub samples: Vec<MetricSample>,
1246}
1247
1248impl MetricSample {
1249    /// 业务作用:将样本直接追加到 Prometheus 文本缓冲区,避免为每行标签建立临时字符串集合。
1250    ///
1251    /// 参数说明:
1252    /// - `output`: 接收不含 HELP/TYPE 的完整样本行,原有内容保留。
1253    ///
1254    /// 返回:追加标量或直方图累积桶、sum 和 count,不改变样本及标签顺序。
1255    fn render_prometheus(&self, output: &mut String) {
1256        use std::fmt::Write as _;
1257        match &self.value {
1258            MetricValue::Counter(v) => {
1259                output.push_str(self.name);
1260                self.render_labels(output, &[]);
1261                let _ = writeln!(output, " {v}");
1262            }
1263            MetricValue::Gauge(v) => {
1264                output.push_str(self.name);
1265                self.render_labels(output, &[]);
1266                let _ = writeln!(output, " {v}");
1267            }
1268            MetricValue::Histogram {
1269                bounds,
1270                buckets,
1271                sum,
1272                count,
1273            } => {
1274                // 累积 `le` 桶。
1275                let mut cumulative = 0u64;
1276                for (i, bound) in bounds.iter().enumerate() {
1277                    cumulative = cumulative.saturating_add(buckets[i]);
1278                    let le = format!("{bound}");
1279                    let _ = write!(output, "{}_bucket", self.name);
1280                    self.render_labels(output, &[("le", le.as_str())]);
1281                    let _ = writeln!(output, " {cumulative}");
1282                }
1283                cumulative = cumulative.saturating_add(buckets[bounds.len()]);
1284                let _ = write!(output, "{}_bucket", self.name);
1285                self.render_labels(output, &[("le", "+Inf")]);
1286                let _ = writeln!(output, " {cumulative}");
1287                let _ = write!(output, "{}_sum", self.name);
1288                self.render_labels(output, &[]);
1289                let _ = writeln!(output, " {sum}");
1290                let _ = write!(output, "{}_count", self.name);
1291                self.render_labels(output, &[]);
1292                let _ = writeln!(output, " {count}");
1293            }
1294        }
1295    }
1296
1297    /// 业务作用:按样本标签和附加标签的既定顺序编码集合,不分配逐标签中间结果。
1298    ///
1299    /// 参数说明:
1300    /// - `output`: 接收标签集合的文本缓冲区。
1301    /// - `extra`: 追加在样本标签之后的标签,如直方图的 `le`。
1302    ///
1303    /// 返回:有标签时追加花括号、逗号和已转义值;无标签时不写入内容。
1304    fn render_labels(&self, output: &mut String, extra: &[(&str, &str)]) {
1305        if self.labels.is_empty() && extra.is_empty() {
1306            return;
1307        }
1308        output.push('{');
1309        for (index, (key, value)) in self
1310            .labels
1311            .iter()
1312            .map(|(key, value)| (*key, value.as_str()))
1313            .chain(extra.iter().copied())
1314            .enumerate()
1315        {
1316            if index != 0 {
1317                output.push(',');
1318            }
1319            output.push_str(key);
1320            output.push_str("=\"");
1321            append_escaped_label(output, value);
1322            output.push('"');
1323        }
1324        output.push('}');
1325    }
1326}
1327
1328/// 业务作用:直接追加符合 Prometheus 文本协议的标签值,防止引号、反斜杠或换行改变样本结构。
1329///
1330/// 参数说明:
1331/// - `output`: 接收已转义标签值的文本缓冲区。
1332/// - `value`: 原始 UTF-8 标签值,不包含外围引号。
1333///
1334/// 返回:仅转义反斜杠、双引号和换行,其他 UTF-8 内容按原字节保留。
1335fn append_escaped_label(output: &mut String, value: &str) {
1336    let mut start = 0;
1337    for (index, byte) in value.bytes().enumerate() {
1338        let escaped = match byte {
1339            b'\\' => "\\\\",
1340            b'"' => "\\\"",
1341            b'\n' => "\\n",
1342            _ => continue,
1343        };
1344        // 只在单字节 ASCII 字符处切分,保持多字节 UTF-8 标签的边界完整。
1345        output.push_str(&value[start..index]);
1346        output.push_str(escaped);
1347        start = index + 1;
1348    }
1349    output.push_str(&value[start..]);
1350}
1351
1352/// 指标样本值。
1353#[derive(Debug, Clone)]
1354pub enum MetricValue {
1355    /// 计数器当前值。
1356    Counter(u64),
1357    /// gauge 当前值。
1358    Gauge(f64),
1359    /// histogram 分布。
1360    Histogram {
1361        /// `le` 上界(升序)。
1362        bounds: &'static [f64],
1363        /// 每桶观测数(非累积;长度 = `bounds.len() + 1`)。
1364        buckets: Vec<u64>,
1365        /// 观测值之和。
1366        sum: f64,
1367        /// 观测次数。
1368        count: u64,
1369    },
1370}