garrison 0.7.3

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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
//! Copyright (c) 2026 Kirky.X. All rights reserved.
//! See LICENSE for full license text.

//! `QuotaStorage` 适配器,用 `GarrisonDao::incr` 实现配额消费。
//!
//! `consume` 通过循环 `dao.incr` 实现:cost=1 时单次 incr(进程内原子),
//! cost>1 时多次 incr(非原子,中间可能被其他请求插入)。

use crate::dao::GarrisonDao;
use crate::error::GarrisonError;
use async_trait::async_trait;
use chrono::Utc;
use limiteron::error::{ConsumeResult, StorageError};
use limiteron::storage::{QuotaInfo, QuotaStorage};
use std::sync::Arc;
use std::time::Duration;

use super::errors::map_to_storage_err;

/// 配额 key 前缀。
const QUOTA_KEY_PREFIX: &str = "limiteron:quota";
/// 配额计数 key:`limiteron:quota:{user_id}:{resource}:count`,存储 u64 计数值。
fn quota_count_key(user_id: &str, resource: &str) -> String {
    format!("{}:{}:{}:count", QUOTA_KEY_PREFIX, user_id, resource)
}
/// 配额元数据 key:`limiteron:quota:{user_id}:{resource}:meta`,存储 `consumed|limit|window_start|window_end`。
fn quota_meta_key(user_id: &str, resource: &str) -> String {
    format!("{}:{}:{}:meta", QUOTA_KEY_PREFIX, user_id, resource)
}

/// `QuotaStorage` 适配器,用 `GarrisonDao::incr` 实现配额消费。
///
/// `consume` 通过循环 `dao.incr` 实现:cost=1 时单次 incr(进程内原子),
/// cost>1 时多次 incr(非原子,中间可能被其他请求插入)。
pub struct GarrisonDaoQuotaStorage {
    pub(super) dao: Arc<dyn GarrisonDao>,
}

impl GarrisonDaoQuotaStorage {
    /// 创建适配器实例。
    ///
    /// # 参数
    /// - `dao`: 内部 DAO 实现。
    pub fn new(dao: Arc<dyn GarrisonDao>) -> Self {
        Self { dao }
    }
}

#[async_trait]
impl QuotaStorage for GarrisonDaoQuotaStorage {
    async fn get_quota(
        &self,
        user_id: &str,
        resource: &str,
    ) -> Result<Option<QuotaInfo>, StorageError> {
        let meta_key = quota_meta_key(user_id, resource);
        let count_key = quota_count_key(user_id, resource);

        let meta = self.dao.get(&meta_key).await.map_err(map_to_storage_err)?;
        let count = self.dao.get(&count_key).await.map_err(map_to_storage_err)?;

        match (meta, count) {
            (Some(meta_str), Some(count_str)) => {
                // M-3: parse 失败显性化 — 脏数据返回 Err(fail-fast)
                let consumed: u64 = count_str.parse().map_err(|e| {
                    map_to_storage_err(GarrisonError::Dao(format!(
                        "limiteron-quota-count-parse-failed::{}::{}::{}",
                        count_key, count_str, e
                    )))
                })?;
                let parts: Vec<&str> = meta_str.split('|').collect();
                if parts.len() != 4 {
                    return Err(map_to_storage_err(GarrisonError::Dao(format!(
                        "limiteron-quota-meta-format-error::{}::{}::{}",
                        meta_key,
                        meta_str,
                        parts.len()
                    ))));
                }
                let limit: u64 = parts[1].parse().map_err(|e| {
                    map_to_storage_err(GarrisonError::Dao(format!(
                        "limiteron-quota-limit-parse-failed::{}::{}::{}",
                        meta_key, parts[1], e
                    )))
                })?;
                let window_start_ts: i64 = parts[2].parse().map_err(|e| {
                    map_to_storage_err(GarrisonError::Dao(format!(
                        "limiteron-quota-window-start-parse-failed::{}::{}::{}",
                        meta_key, parts[2], e
                    )))
                })?;
                let window_end_ts: i64 = parts[3].parse().map_err(|e| {
                    map_to_storage_err(GarrisonError::Dao(format!(
                        "limiteron-quota-window-end-parse-failed::{}::{}::{}",
                        meta_key, parts[3], e
                    )))
                })?;
                let window_start = chrono::DateTime::from_timestamp(window_start_ts, 0)
                    .ok_or_else(|| {
                        map_to_storage_err(GarrisonError::Dao(format!(
                            "limiteron-quota-window-start-datetime-failed::{}",
                            window_start_ts
                        )))
                    })?;
                let window_end =
                    chrono::DateTime::from_timestamp(window_end_ts, 0).ok_or_else(|| {
                        map_to_storage_err(GarrisonError::Dao(format!(
                            "limiteron-quota-window-end-datetime-failed::{}",
                            window_end_ts
                        )))
                    })?;
                Ok(Some(QuotaInfo {
                    consumed,
                    limit,
                    window_start,
                    window_end,
                }))
            },
            _ => Ok(None),
        }
    }

    async fn consume(
        &self,
        user_id: &str,
        resource: &str,
        cost: u64,
        limit: u64,
        window: Duration,
    ) -> Result<ConsumeResult, StorageError> {
        let count_key = quota_count_key(user_id, resource);
        let meta_key = quota_meta_key(user_id, resource);
        let ttl = window.as_secs();

        // 循环 incr cost 次(cost=1 时单次,进程内原子)
        let mut new_count = 0u64;
        for _ in 0..cost {
            new_count = self
                .dao
                .incr(&count_key, ttl)
                .await
                .map_err(map_to_storage_err)?;
        }

        // 初始化/更新元数据(首次消费时设置窗口)
        let now = Utc::now();
        let window_end = now
            + chrono::Duration::from_std(window)
                .unwrap_or_else(|_| chrono::Duration::seconds(window.as_secs() as i64));
        let meta_val = format!(
            "{}|{}|{}|{}",
            new_count,
            limit,
            now.timestamp(),
            window_end.timestamp()
        );
        // 用 set 覆盖元数据(保留 TTL 与窗口一致)
        self.dao
            .set(&meta_key, &meta_val, ttl)
            .await
            .map_err(map_to_storage_err)?;

        let allowed = new_count <= limit;
        let remaining = limit.saturating_sub(new_count);
        let usage_percent = if limit == 0 {
            100.0
        } else {
            (new_count as f64 / limit as f64) * 100.0
        };

        Ok(ConsumeResult {
            allowed,
            remaining,
            alert_triggered: usage_percent >= 80.0,
            usage_percent,
        })
    }

    async fn reset(
        &self,
        user_id: &str,
        resource: &str,
        _limit: u64,
        _window: Duration,
    ) -> Result<(), StorageError> {
        let count_key = quota_count_key(user_id, resource);
        let meta_key = quota_meta_key(user_id, resource);
        self.dao
            .delete(&count_key)
            .await
            .map_err(map_to_storage_err)?;
        self.dao.delete(&meta_key).await.map_err(map_to_storage_err)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dao::tests::MockDao;

    fn make_dao() -> Arc<dyn GarrisonDao> {
        Arc::new(MockDao::new())
    }

    // --- GarrisonDaoQuotaStorage 测试 ---

    #[tokio::test]
    async fn quota_consume_within_limit() {
        let quota = GarrisonDaoQuotaStorage::new(make_dao());
        let result = quota
            .consume("user1", "sms", 1, 5, Duration::from_secs(3600))
            .await
            .unwrap();
        assert!(result.allowed);
        assert_eq!(result.remaining, 4);
    }

    #[tokio::test]
    async fn quota_consume_exceeds_limit() {
        let quota = GarrisonDaoQuotaStorage::new(make_dao());
        // 消费 5 次,第 6 次超限
        for _ in 0..5 {
            let r = quota
                .consume("user2", "sms", 1, 5, Duration::from_secs(3600))
                .await
                .unwrap();
            assert!(r.allowed);
        }
        let result = quota
            .consume("user2", "sms", 1, 5, Duration::from_secs(3600))
            .await
            .unwrap();
        assert!(!result.allowed);
        assert_eq!(result.remaining, 0);
    }

    #[tokio::test]
    async fn quota_reset_clears_counters() {
        let quota = GarrisonDaoQuotaStorage::new(make_dao());
        quota
            .consume("user3", "sms", 3, 10, Duration::from_secs(60))
            .await
            .unwrap();
        assert!(quota.get_quota("user3", "sms").await.unwrap().is_some());

        quota
            .reset("user3", "sms", 10, Duration::from_secs(60))
            .await
            .unwrap();
        assert!(quota.get_quota("user3", "sms").await.unwrap().is_none());
    }

    // --- M-3: unwrap_or(0) 静默吞错修复测试 ---

    /// M-3: QuotaStorage::get_quota 遇到脏 count 数据时返回错误(fail-fast)。
    #[tokio::test]
    async fn m3_quota_get_quota_dirty_count_returns_err() {
        let quota = GarrisonDaoQuotaStorage::new(make_dao());
        // 直接注入脏数据:count 是非数字字符串
        quota
            .dao
            .set("limiteron:quota:user1:res:count", "not-a-number", 0)
            .await
            .unwrap();
        quota
            .dao
            .set("limiteron:quota:user1:res:meta", "1|5|1000|2000", 0)
            .await
            .unwrap();
        let result = quota.get_quota("user1", "res").await;
        assert!(
            result.is_err(),
            "脏 count 数据应返回错误,实际: {:?}",
            result
        );
        let err_msg = format!("{}", result.unwrap_err());
        assert!(
            err_msg.contains("limiteron-quota-count-parse-failed"),
            "错误消息应包含 'limiteron-quota-count-parse-failed',实际: {}",
            err_msg
        );
    }

    /// M-3: QuotaStorage::get_quota 遇到脏 meta 数据时返回错误(fail-fast)。
    #[tokio::test]
    async fn m3_quota_get_quota_dirty_meta_returns_err() {
        let quota = GarrisonDaoQuotaStorage::new(make_dao());
        quota
            .dao
            .set("limiteron:quota:user2:res:count", "1", 0)
            .await
            .unwrap();
        // meta 中 limit 字段是非数字
        quota
            .dao
            .set(
                "limiteron:quota:user2:res:meta",
                "1|not-number|1000|2000",
                0,
            )
            .await
            .unwrap();
        let result = quota.get_quota("user2", "res").await;
        assert!(
            result.is_err(),
            "脏 meta 数据应返回错误,实际: {:?}",
            result
        );
        let err_msg = format!("{}", result.unwrap_err());
        assert!(
            err_msg.contains("limiteron-quota-limit-parse-failed"),
            "错误消息应包含 'limiteron-quota-limit-parse-failed',实际: {}",
            err_msg
        );
    }

    // --- 补充覆盖:quota 辅助函数与边界路径 ---

    /// quota_count_key 与 quota_meta_key 生成正确的 key 格式。
    #[test]
    fn quota_key_format_correct() {
        assert_eq!(
            quota_count_key("user1", "sms"),
            "limiteron:quota:user1:sms:count"
        );
        assert_eq!(
            quota_meta_key("user1", "sms"),
            "limiteron:quota:user1:sms:meta"
        );
        assert_eq!(quota_count_key("", ""), "limiteron:quota:::count");
    }

    /// get_quota 在 consume 后返回正确的 QuotaInfo(round-trip)。
    #[tokio::test]
    async fn quota_get_quota_after_consume_returns_valid_info() {
        let quota = GarrisonDaoQuotaStorage::new(make_dao());
        quota
            .consume("user_rt", "res", 1, 10, Duration::from_secs(3600))
            .await
            .unwrap();
        let info = quota.get_quota("user_rt", "res").await.unwrap();
        assert!(info.is_some(), "consume 后 get_quota 应返回 Some");
        let info = info.unwrap();
        assert_eq!(info.consumed, 1);
        assert_eq!(info.limit, 10);
    }

    /// consume cost > 1 时正确递增计数。
    #[tokio::test]
    async fn quota_consume_cost_greater_than_one() {
        let quota = GarrisonDaoQuotaStorage::new(make_dao());
        let result = quota
            .consume("user_cost", "res", 5, 10, Duration::from_secs(60))
            .await
            .unwrap();
        assert!(result.allowed, "5 <= 10 应允许");
        assert_eq!(result.remaining, 5, "remaining = 10 - 5 = 5");
        assert!(
            result.usage_percent >= 50.0,
            "usage_percent 应 >= 50%,实际: {}",
            result.usage_percent
        );
    }

    /// consume 在 limit=0 时 usage_percent 为 100%。
    #[tokio::test]
    async fn quota_consume_limit_zero_usage_100_percent() {
        let quota = GarrisonDaoQuotaStorage::new(make_dao());
        let result = quota
            .consume("user_zero", "res", 1, 0, Duration::from_secs(60))
            .await
            .unwrap();
        // limit=0, count=1 > 0 → 不允许
        assert!(!result.allowed, "count 1 > limit 0 应拒绝");
        assert_eq!(result.remaining, 0);
        assert_eq!(
            result.usage_percent, 100.0,
            "limit=0 时 usage_percent 应为 100%"
        );
    }

    /// consume 在使用率达到 80% 时触发 alert_triggered。
    #[tokio::test]
    async fn quota_consume_alert_triggered_at_80_percent() {
        let quota = GarrisonDaoQuotaStorage::new(make_dao());
        // 消费 8 次(limit=10),usage=80%,应触发 alert
        let result = quota
            .consume("user_alert", "res", 8, 10, Duration::from_secs(60))
            .await
            .unwrap();
        assert!(
            result.alert_triggered,
            "usage 80% 应触发 alert,实际 usage_percent: {}",
            result.usage_percent
        );
        assert!(result.usage_percent >= 80.0);
    }

    /// consume 在使用率低于 80% 时不触发 alert。
    #[tokio::test]
    async fn quota_consume_no_alert_below_80_percent() {
        let quota = GarrisonDaoQuotaStorage::new(make_dao());
        let result = quota
            .consume("user_noalert", "res", 7, 10, Duration::from_secs(60))
            .await
            .unwrap();
        assert!(
            !result.alert_triggered,
            "usage 70% 不应触发 alert,实际 usage_percent: {}",
            result.usage_percent
        );
    }

    /// get_quota meta 格式错误(段数不对)返回错误。
    #[tokio::test]
    async fn quota_get_quota_meta_wrong_parts_returns_err() {
        let quota = GarrisonDaoQuotaStorage::new(make_dao());
        // 注入 count 正确但 meta 段数不对的数据
        quota
            .dao
            .set("limiteron:quota:user_w:res:count", "1", 0)
            .await
            .unwrap();
        // meta 只有 2 段(应为 4 段)
        quota
            .dao
            .set("limiteron:quota:user_w:res:meta", "1|5", 0)
            .await
            .unwrap();
        let result = quota.get_quota("user_w", "res").await;
        assert!(result.is_err(), "meta 段数不对应返回错误");
        let err_msg = format!("{}", result.unwrap_err());
        assert!(
            err_msg.contains("limiteron-quota-meta-format-error"),
            "错误消息应包含 'limiteron-quota-meta-format-error',实际: {}",
            err_msg
        );
    }

    /// get_quota window_start_ts 无效时返回错误。
    #[tokio::test]
    async fn quota_get_quota_invalid_window_start_ts_returns_err() {
        let quota = GarrisonDaoQuotaStorage::new(make_dao());
        quota
            .dao
            .set("limiteron:quota:user_ts:res:count", "1", 0)
            .await
            .unwrap();
        // window_start_ts 不是数字
        quota
            .dao
            .set("limiteron:quota:user_ts:res:meta", "1|5|not_number|2000", 0)
            .await
            .unwrap();
        let result = quota.get_quota("user_ts", "res").await;
        assert!(result.is_err(), "无效 window_start_ts 应返回错误");
    }

    /// get_quota 仅 count 存在但 meta 缺失时返回 None。
    #[tokio::test]
    async fn quota_get_quota_count_without_meta_returns_none() {
        let quota = GarrisonDaoQuotaStorage::new(make_dao());
        // 只有 count 没有 meta
        quota
            .dao
            .set("limiteron:quota:user_nm:res:count", "5", 0)
            .await
            .unwrap();
        let result = quota.get_quota("user_nm", "res").await.unwrap();
        assert!(result.is_none(), "count 有但 meta 缺失时应返回 None");
    }
}