garrison 0.9.0

Garrison - 面向 Rust 生态的一站式身份认证鉴权框架
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
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! Credit 计量 Prometheus 指标。
//!
//! 启用 `metrics-prometheus` feature 时编译,提供 3 个指标覆盖 credit 消费/剩余/告警;
//! 未启用时 `CreditMetrics` 为 `()` 别名,调用方代码无需条件编译。
//!
//! # 指标清单
//!
//! | 指标名 | 类型 | 标签 | 说明 |
//! |--------|------|------|------|
//! | `garrison_credit_consumed_total` | Counter | `tenant_id`, `resource` | credit 消费总量 |
//! | `garrison_credit_remaining` | Gauge | `tenant_id` | 当前剩余 credit |
//! | `garrison_credit_alerts_total` | Counter | `tenant_id`, `threshold` | 告警触发次数 |
//!
//! # 集成点
//!
//! - `CreditMeter::consume_credit`:消费成功后调用 `record_consumed` + `set_remaining`,告警阈值触发时调用 `record_alert`
//!
//! # 标签基数(cardinality)
//!
//! `tenant_id` / `resource` 等标签值必须来自有限集合(数字 ID、内部资源白名单);Prometheus 标签基数无上界,直接拼接用户可控字符串(动态路径、请求参数)会导致内存膨胀。本模块不做白名单校验,契约见 `record_consumed` 文档。

// CreditMetrics:Credit 计量指标集合(feature = "metrics-prometheus")

/// Credit 计量 Prometheus 指标集合。
///
/// 模式与 `crate::account::metrics::AccountMetrics` 一致:3 个指标注册到指定 registry,
/// 通过 `CreditMeter` 内部持有 `Option<Arc<CreditMetrics>>` 注入。
///
/// # 构造语义(new 与 register_to 不可混用)
///
/// - [`Self::new`] / `Default`:绑定 **prometheus 默认 registry** 的进程级单例
///   (`OnceLock` 缓存)。所有后续 `new()` 调用返回同一实例,**忽略调用方期望的
///   registry**——不要在 `register_to(custom)` 之后调用 `new()` 并期望指标落在
///   custom registry 上。
/// - [`Self::register_to`]:注册到指定 registry(测试隔离 / 多 registry 场景)。
///   对同一 registry 重复调用返回 `AlreadyReg` 错误;对**不同** registry 各自
///   独立注册互不冲突。
/// - 两个构造器混用的后果:先 `register_to(custom)` 后 `new()` → 默认 registry
///   与 custom registry 各有一套同名指标(重复采集);先 `new()` 后
///   `register_to(default_registry)` → 后者返回 `AlreadyReg`。
///
/// # 使用示例
///
/// ```ignore
/// use garrison::credit::metrics::CreditMetrics;
/// use std::sync::Arc;
///
/// let metrics = Arc::new(CreditMetrics::new());
/// metrics.record_consumed("42", "login", 5);
/// metrics.set_remaining("42", 9995);
/// metrics.record_alert("42", 80);
/// ```
#[cfg(feature = "metrics-prometheus")]
#[derive(Clone)]
pub struct CreditMetrics {
    /// credit 消费总量 Counter(标签:tenant_id, resource)。
    consumed_total: prometheus::CounterVec,
    /// 当前剩余 credit Gauge(标签:tenant_id)。
    remaining: prometheus::GaugeVec,
    /// 告警触发次数 Counter(标签:tenant_id, threshold)。
    alerts_total: prometheus::CounterVec,
}

#[cfg(feature = "metrics-prometheus")]
impl CreditMetrics {
    /// 创建新的指标集合,注册到默认 registry(进程级单例,语义见类型文档)。
    ///
    /// **不会 panic**:若默认 registry 已存在同名指标(重复调用 `new` / 与
    /// `register_to(default_registry)` 混用),以 `tracing::warn` 记录后返回一个未注册的
    /// 本地实例(`record_*` / `gather()` 均可用,仅默认 registry 不再新增采集)。
    pub fn new() -> Self {
        use std::sync::OnceLock;
        static INSTANCE: OnceLock<CreditMetrics> = OnceLock::new();
        INSTANCE.get_or_init(Self::init_default).clone()
    }

    /// new() 的单例初始化:注册默认 registry,冲突时 warn + 回退本地实例。
    fn init_default() -> Self {
        match Self::register_to(prometheus::default_registry()) {
            Ok(m) => m,
            Err(e) => {
                tracing::warn!(
                    error = %e,
                    "{}",
                    crate::i18n::translate_detail(
                        "logs-metrics-already-registered",
                        &[("arg0", "CreditMetrics")]
                    )
                );
                // build() 仅在指标名/帮助文本非法时失败——静态字面量下不可达
                Self::build().expect("CreditMetrics: static metric opts are valid (unreachable)")
            },
        }
    }

    /// 创建并注册到指定 registry(用于自定义 registry 场景,测试隔离);指标已注册返回 `Err(prometheus::Error::AlreadyReg)`。
    pub fn register_to(registry: &prometheus::Registry) -> Result<Self, prometheus::Error> {
        let metrics = Self::build()?;
        registry.register(Box::new(metrics.consumed_total.clone()))?;
        registry.register(Box::new(metrics.remaining.clone()))?;
        registry.register(Box::new(metrics.alerts_total.clone()))?;
        Ok(metrics)
    }

    /// 构建指标集合(不注册到任何 registry)。
    fn build() -> Result<Self, prometheus::Error> {
        let consumed_total = prometheus::CounterVec::new(
            prometheus::Opts::new(
                "garrison_credit_consumed_total",
                "Total credit consumed (tenant-level metering)",
            ),
            &["tenant_id", "resource"],
        )?;
        let remaining = prometheus::GaugeVec::new(
            prometheus::Opts::new(
                "garrison_credit_remaining",
                "Current remaining credit for tenant",
            ),
            &["tenant_id"],
        )?;
        let alerts_total = prometheus::CounterVec::new(
            prometheus::Opts::new(
                "garrison_credit_alerts_total",
                "Total credit alert threshold triggers",
            ),
            &["tenant_id", "threshold"],
        )?;

        Ok(Self {
            consumed_total,
            remaining,
            alerts_total,
        })
    }

    /// 记录一次 credit 消费。
    ///
    /// 标签基数契约:`tenant_id` 与 `resource` **必须来自有限集合**(数字 ID、内部资源
    /// 白名单)——Prometheus 标签基数无上界,将用户可控字符串(动态 API 路径、请求参数等)
    /// 直接作为标签值会撑爆 Prometheus;本方法不做白名单校验,责任在调用方。
    pub fn record_consumed(&self, tenant_id: &str, resource: &str, credits: u64) {
        self.consumed_total
            .with_label_values(&[tenant_id, resource])
            .inc_by(credits as f64);
    }

    /// 设置当前剩余 credit。
    pub fn set_remaining(&self, tenant_id: &str, remaining_credits: u64) {
        self.remaining
            .with_label_values(&[tenant_id])
            .set(remaining_credits as f64);
    }

    /// 记录一次告警阈值触发。
    pub fn record_alert(&self, tenant_id: &str, threshold: u8) {
        self.alerts_total
            .with_label_values(&[tenant_id, &threshold.to_string()])
            .inc();
    }

    /// 收集所有指标为 Prometheus 文本格式。
    ///
    /// 用于暴露给 `/metrics` 端点供 Prometheus 抓取。
    /// 不依赖外部 registry,直接从字段调用 `Collector::collect`。
    pub fn gather(&self) -> String {
        use prometheus::core::Collector;
        use prometheus::Encoder;
        let mut metric_families = Vec::new();
        metric_families.extend(self.consumed_total.collect());
        metric_families.extend(self.remaining.collect());
        metric_families.extend(self.alerts_total.collect());
        let mut buffer = Vec::new();
        let encoder = prometheus::TextEncoder::new();
        if let Err(e) = encoder.encode(&metric_families, &mut buffer) {
            tracing::warn!(error = %e, "CreditMetrics::gather prometheus encode failed");
        }
        String::from_utf8_lossy(&buffer).into_owned()
    }
}

#[cfg(feature = "metrics-prometheus")]
impl Default for CreditMetrics {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "metrics-prometheus")]
impl std::fmt::Debug for CreditMetrics {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CreditMetrics")
            .field("consumed_total", &"CounterVec")
            .field("remaining", &"GaugeVec")
            .field("alerts_total", &"CounterVec")
            .finish()
    }
}

// 公共 API(feature 未启用时提供 no-op 占位)

/// 指标集合的 feature-gated 别名。
///
/// - `metrics-prometheus` 启用:解析为 [`CreditMetrics`]
/// - 未启用:解析为 `()` unit type,`Option<Arc<CreditMetrics>>` 仍可编译
#[cfg(not(feature = "metrics-prometheus"))]
pub type CreditMetrics = ();

#[cfg(all(test, feature = "metrics-prometheus"))]
mod tests {
    use super::*;
    use serial_test::serial;

    /// CreditMetrics 注册到自定义 registry 成功,3 个指标名出现在 gather 输出中。
    #[test]
    #[serial]
    fn credit_metrics_register_to_custom_registry() {
        let registry = prometheus::Registry::new();
        let metrics = CreditMetrics::register_to(&registry).expect("注册到自定义 registry 失败");
        metrics.record_consumed("42", "login", 5);
        metrics.set_remaining("42", 9995);
        metrics.record_alert("42", 80);

        let gathered = prometheus::TextEncoder::new()
            .encode_to_string(&registry.gather())
            .expect("encode 失败");
        assert!(
            gathered.contains("garrison_credit_consumed_total"),
            "missing credit_consumed_total: {}",
            gathered
        );
        assert!(
            gathered.contains("garrison_credit_remaining"),
            "missing credit_remaining: {}",
            gathered
        );
        assert!(
            gathered.contains("garrison_credit_alerts_total"),
            "missing credit_alerts_total: {}",
            gathered
        );
    }

    /// record_consumed 记录 tenant_id + resource 标签。
    #[test]
    #[serial]
    fn credit_consumed_total_labels() {
        let registry = prometheus::Registry::new();
        let metrics = CreditMetrics::register_to(&registry).unwrap();
        metrics.record_consumed("42", "login", 1);
        metrics.record_consumed("42", "api_call", 5);
        metrics.record_consumed("99", "login", 1);

        let output = prometheus::TextEncoder::new()
            .encode_to_string(&registry.gather())
            .unwrap();
        assert!(
            output.contains("tenant_id=\"42\"") && output.contains("resource=\"login\""),
            "missing tenant 42 login: {}",
            output
        );
        assert!(
            output.contains("resource=\"api_call\""),
            "missing api_call: {}",
            output
        );
    }

    /// set_remaining 设置 Gauge 值。
    #[test]
    #[serial]
    fn credit_remaining_gauge() {
        let registry = prometheus::Registry::new();
        let metrics = CreditMetrics::register_to(&registry).unwrap();
        metrics.set_remaining("42", 5000);

        let output = prometheus::TextEncoder::new()
            .encode_to_string(&registry.gather())
            .unwrap();
        assert!(
            output.contains("garrison_credit_remaining{tenant_id=\"42\"} 5000"),
            "remaining should be 5000: {}",
            output
        );
    }

    /// record_alert 记录 threshold 标签。
    #[test]
    #[serial]
    fn credit_alerts_total_labels() {
        let registry = prometheus::Registry::new();
        let metrics = CreditMetrics::register_to(&registry).unwrap();
        metrics.record_alert("42", 80);
        metrics.record_alert("42", 80);
        metrics.record_alert("42", 90);

        let output = prometheus::TextEncoder::new()
            .encode_to_string(&registry.gather())
            .unwrap();
        assert!(
            output.contains("threshold=\"80\""),
            "missing threshold 80: {}",
            output
        );
        assert!(
            output.contains("threshold=\"90\""),
            "missing threshold 90: {}",
            output
        );
        assert!(
            output.contains("garrison_credit_alerts_total{tenant_id=\"42\",threshold=\"80\"} 2"),
            "threshold 80 count should be 2: {}",
            output
        );
    }

    /// 重复注册返回 AlreadyReg 错误。
    #[test]
    #[serial]
    fn duplicate_register_returns_error() {
        let registry = prometheus::Registry::new();
        let _m1 = CreditMetrics::register_to(&registry).expect("首次注册失败");
        let result = CreditMetrics::register_to(&registry);
        assert!(result.is_err(), "重复注册应返回错误");
        match result {
            Err(prometheus::Error::AlreadyReg) => {},
            Err(e) => panic!("期望 AlreadyReg 错误,实际: {:?}", e),
            Ok(_) => panic!("期望错误,实际成功"),
        }
    }

    /// Clone 共享底层状态。
    #[test]
    #[serial]
    fn clone_shares_state() {
        let registry = prometheus::Registry::new();
        let m1 = CreditMetrics::register_to(&registry).unwrap();
        let m2 = m1.clone();
        m1.record_consumed("1", "login", 3);
        m2.record_consumed("1", "login", 7);

        let output = prometheus::TextEncoder::new()
            .encode_to_string(&registry.gather())
            .unwrap();
        assert!(
            output
                .contains("garrison_credit_consumed_total{resource=\"login\",tenant_id=\"1\"} 10"),
            "clones should share underlying Counter: {}",
            output
        );
    }

    /// gather() 返回非空字符串。
    #[test]
    #[serial]
    fn gather_non_empty() {
        let registry = prometheus::Registry::new();
        let metrics = CreditMetrics::register_to(&registry).unwrap();
        metrics.record_consumed("1", "login", 1);
        let output = metrics.gather();
        assert!(!output.is_empty(), "gather() 应返回非空字符串");
    }

    /// new() / Default 注册到默认 registry(OnceLock 单例,同进程仅注册一次,多次调用返回同一实例)且实例可用;Debug 输出包含类型名与字段类型名。
    #[test]
    #[serial]
    fn new_and_default_register_to_default_registry_once() {
        // 首次调用走 register_to(default_registry)(get_or_init),
        // 后续调用(含其他测试中的 new/default)直接命中 OnceLock 缓存
        let m1 = CreditMetrics::new();
        let m2 = CreditMetrics::default();
        m1.record_consumed("808", "api_call", 2);
        m2.set_remaining("808", 7);

        // gather() 从字段收集,不依赖 registry,包含刚记录的值
        let gathered = m1.gather();
        assert!(
            gathered.contains("garrison_credit_consumed_total"),
            "gather 应含 consumed_total: {}",
            gathered
        );
        assert!(
            gathered.contains("tenant_id=\"808\""),
            "gather 应含 tenant 808: {}",
            gathered
        );

        // Debug 手写实现:输出类型名与字段类型名
        let debug = format!("{:?}", m1);
        assert!(debug.contains("CreditMetrics"), "实际: {}", debug);
        assert!(debug.contains("CounterVec"), "实际: {}", debug);
        assert!(debug.contains("GaugeVec"), "实际: {}", debug);
    }

    /// new() 在默认 registry 已注册同名指标时不再 panic(旧实现 expect panic):warn 后
    /// 返回可用的本地实例(record/gather 正常)。
    ///
    /// 注:与本文件其他测试共享进程级默认 registry,执行顺序不定——register_to 可能成功
    /// 或返回 AlreadyReg,均可。
    #[test]
    #[serial]
    fn new_does_not_panic_when_already_registered_to_default_registry() {
        let _ = CreditMetrics::register_to(prometheus::default_registry());
        let m = CreditMetrics::new();
        m.record_consumed("909", "login", 3);
        assert!(
            m.gather().contains("tenant_id=\"909\""),
            "回退实例应可正常记录与收集"
        );
    }

    /// gather() 输出为合法 Prometheus 文本格式(含 HELP/TYPE 行)。
    ///
    /// 注:三个指标均需至少记录一次——prometheus 0.14 的 CounterVec/GaugeVec 在仅部分
    /// 指标有观测值时 collect() 可能返回空 family 集。
    #[test]
    #[serial]
    fn gather_contains_help_and_type_lines() {
        let registry = prometheus::Registry::new();
        let metrics = CreditMetrics::register_to(&registry).unwrap();
        metrics.record_alert("1", 90);
        metrics.record_consumed("1", "login", 1);
        metrics.set_remaining("1", 2);
        let output = metrics.gather();
        assert!(
            output.contains("# HELP garrison_credit_alerts_total"),
            "{}",
            output
        );
        assert!(
            output.contains("# TYPE garrison_credit_alerts_total counter"),
            "{}",
            output
        );
    }
}

/// 无 feature 时的编译验证测试。
#[cfg(all(test, not(feature = "metrics-prometheus")))]
mod tests_no_feature {
    use super::*;

    /// 未启用 metrics-prometheus 时 CreditMetrics 为 unit type 别名。
    #[test]
    fn no_feature_credit_metrics_is_unit() {
        let _: CreditMetrics = ();
    }
}