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
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
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! Credit 配额周期模型:`CreditCycle` 枚举,支持固定窗口(自然月)和滚动窗口两种周期模式。

use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize};

/// Credit 配额周期模式:决定 credit 计数何时重置为零。
///
/// `Fixed` 为每月固定日期 00:00 UTC 重置(`day_of_month` 范围 1..=28),`Rolling` 为
/// 首次消费起 N 天后重置。
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum CreditCycle {
    /// 固定窗口:每月 `day_of_month` 日 00:00 UTC 重置。
    ///
    /// `day_of_month` 范围 1..=28(避免 29/30/31 月问题)。
    Fixed {
        /// 重置日(1..=28)。
        day_of_month: u32,
    },
    /// 滚动窗口:首次消费起 `days` 天后重置。
    Rolling {
        /// 窗口天数。
        days: u32,
    },
}

impl CreditCycle {
    /// 计算当前周期的起始时间(Unix 时间戳);`window_start` 仅 `Rolling` 使用,
    /// `None` 表示尚未开始(首次消费),返回当前时间。
    pub fn cycle_start(&self, window_start: Option<i64>, now: NaiveDateTime) -> i64 {
        match self {
            CreditCycle::Fixed { day_of_month } => {
                let day = *day_of_month;
                let (year, month, current_day) = (now.year(), now.month(), now.day());
                if current_day >= day {
                    chrono::NaiveDate::from_ymd_opt(year, month, day)
                        .unwrap_or_else(|| {
                            // day > 当月天数时回退到当月最后一天
                            chrono::NaiveDate::from_ymd_opt(
                                year,
                                month,
                                last_day_of_month(year, month),
                            )
                            .unwrap()
                        })
                        .and_hms_opt(0, 0, 0)
                        .unwrap()
                        .and_utc()
                        .timestamp()
                } else {
                    let (prev_year, prev_month) = if month == 1 {
                        (year - 1, 12)
                    } else {
                        (year, month - 1)
                    };
                    chrono::NaiveDate::from_ymd_opt(prev_year, prev_month, day)
                        .unwrap_or_else(|| {
                            chrono::NaiveDate::from_ymd_opt(
                                prev_year,
                                prev_month,
                                last_day_of_month(prev_year, prev_month),
                            )
                            .unwrap()
                        })
                        .and_hms_opt(0, 0, 0)
                        .unwrap()
                        .and_utc()
                        .timestamp()
                }
            },
            CreditCycle::Rolling { .. } => {
                window_start.unwrap_or_else(|| now.and_utc().timestamp())
            },
        }
    }

    /// 计算当前周期的结束时间(Unix 时间戳)。
    pub fn cycle_end(&self, window_start: Option<i64>, now: NaiveDateTime) -> i64 {
        match self {
            CreditCycle::Fixed { day_of_month } => {
                let day = *day_of_month;
                let (year, month, current_day) = (now.year(), now.month(), now.day());
                if current_day >= day {
                    let (next_year, next_month) = if month == 12 {
                        (year + 1, 1)
                    } else {
                        (year, month + 1)
                    };
                    chrono::NaiveDate::from_ymd_opt(next_year, next_month, day)
                        .unwrap_or_else(|| {
                            chrono::NaiveDate::from_ymd_opt(
                                next_year,
                                next_month,
                                last_day_of_month(next_year, next_month),
                            )
                            .unwrap()
                        })
                        .and_hms_opt(0, 0, 0)
                        .unwrap()
                        .and_utc()
                        .timestamp()
                } else {
                    chrono::NaiveDate::from_ymd_opt(year, month, day)
                        .unwrap_or_else(|| {
                            chrono::NaiveDate::from_ymd_opt(
                                year,
                                month,
                                last_day_of_month(year, month),
                            )
                            .unwrap()
                        })
                        .and_hms_opt(0, 0, 0)
                        .unwrap()
                        .and_utc()
                        .timestamp()
                }
            },
            CreditCycle::Rolling { days } => {
                let start = window_start.unwrap_or_else(|| now.and_utc().timestamp());
                start + (*days as i64) * 86400
            },
        }
    }

    /// 检查当前周期是否已过期。
    pub fn is_expired(&self, window_start: Option<i64>, now: NaiveDateTime) -> bool {
        let end = self.cycle_end(window_start, now);
        now.and_utc().timestamp() >= end
    }

    /// 返回下次重置时间的 Unix 时间戳。
    pub fn next_reset_at(&self, window_start: Option<i64>, now: NaiveDateTime) -> i64 {
        self.cycle_end(window_start, now)
    }

    /// 返回周期类型的字符串标识(用于 meta 序列化)。
    pub fn type_tag(&self) -> &'static str {
        match self {
            CreditCycle::Fixed { .. } => "fixed",
            CreditCycle::Rolling { .. } => "rolling",
        }
    }

    /// 从 meta 中的 type tag + 参数重建 `CreditCycle`。
    ///
    /// 违反文档约定时返回 `None`(调用方如 [`crate::credit::storage`] 的 meta 反序列化
    /// 将其转为脏数据错误,fail-fast):`fixed` 要求 `day_of_month` ∈ 1..=28(0 会使
    /// `from_ymd_opt` 恒失败并静默回退月末,29/30/31 有月末漂移问题),`rolling`
    /// 要求 `days` >= 1(0 会产生立即过期的空窗口)。
    pub fn from_tag(type_tag: &str, param: u32) -> Option<Self> {
        match type_tag {
            "fixed" if (1..=28).contains(&param) => Some(CreditCycle::Fixed {
                day_of_month: param,
            }),
            "rolling" if param >= 1 => Some(CreditCycle::Rolling { days: param }),
            _ => None,
        }
    }

    /// 返回周期参数值(fixed → day_of_month,rolling → days)。
    pub fn param(&self) -> u32 {
        match self {
            CreditCycle::Fixed { day_of_month } => *day_of_month,
            CreditCycle::Rolling { days } => *days,
        }
    }
}

/// 计算指定年月的最后一天。
fn last_day_of_month(year: i32, month: u32) -> u32 {
    // 下月第 0 天 = 当月最后一天(chrono 不支持 day=0,用下月 1 日 - 1 天)
    let (next_year, next_month) = if month == 12 {
        (year + 1, 1)
    } else {
        (year, month + 1)
    };
    chrono::NaiveDate::from_ymd_opt(next_year, next_month, 1)
        .unwrap()
        .pred_opt()
        .unwrap()
        .day()
}

use chrono::Datelike;

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

    /// Fixed 模式:当前日 >= day_of_month 时,周期起始为本月 day 日。
    #[test]
    fn test_fixed_cycle_start_end() {
        let cycle = CreditCycle::Fixed { day_of_month: 15 };
        // 2026-08-20 >= 15 → 周期起始 = 2026-08-15 00:00 UTC
        let now = chrono::NaiveDate::from_ymd_opt(2026, 8, 20)
            .unwrap()
            .and_hms_opt(12, 0, 0)
            .unwrap();
        let start = cycle.cycle_start(None, now);
        let expected_start = chrono::NaiveDate::from_ymd_opt(2026, 8, 15)
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap()
            .and_utc()
            .timestamp();
        assert_eq!(start, expected_start);

        let end = cycle.cycle_end(None, now);
        let expected_end = chrono::NaiveDate::from_ymd_opt(2026, 9, 15)
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap()
            .and_utc()
            .timestamp();
        assert_eq!(end, expected_end);
    }

    /// Fixed 模式:当前日 < day_of_month 时,周期起始为上月 day 日。
    #[test]
    fn test_fixed_cycle_start_before_day() {
        let cycle = CreditCycle::Fixed { day_of_month: 15 };
        // 2026-08-10 < 15 → 周期起始 = 2026-07-15 00:00 UTC
        let now = chrono::NaiveDate::from_ymd_opt(2026, 8, 10)
            .unwrap()
            .and_hms_opt(12, 0, 0)
            .unwrap();
        let start = cycle.cycle_start(None, now);
        let expected_start = chrono::NaiveDate::from_ymd_opt(2026, 7, 15)
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap()
            .and_utc()
            .timestamp();
        assert_eq!(start, expected_start);
    }

    /// Rolling 模式:周期起始为 window_start,结束为 window_start + days * 86400。
    #[test]
    fn test_rolling_cycle_start_end() {
        let cycle = CreditCycle::Rolling { days: 30 };
        let window_start_ts = 1_700_000_000i64;
        let now = chrono::NaiveDate::from_ymd_opt(2026, 8, 20)
            .unwrap()
            .and_hms_opt(12, 0, 0)
            .unwrap();
        let start = cycle.cycle_start(Some(window_start_ts), now);
        assert_eq!(start, window_start_ts);

        let end = cycle.cycle_end(Some(window_start_ts), now);
        assert_eq!(end, window_start_ts + 30 * 86400);
    }

    /// Fixed 模式:is_expired 在 window_start=None 时始终返回 false(Fixed 的 cycle_end
    /// 总是返回未来的下一个重置日,无 window_start 无法确定当前周期起始故无法判定过期;
    /// 实际使用中 meter 先 check_and_reset_cycle 再调用 is_expired)。
    #[test]
    fn test_fixed_cycle_is_expired_without_window_start() {
        let cycle = CreditCycle::Fixed { day_of_month: 15 };
        // cycle_end(None, 2026-09-16) = 2026-10-15(下月重置日)
        // 2026-09-16 < 2026-10-15 → not expired
        let now = chrono::NaiveDate::from_ymd_opt(2026, 9, 16)
            .unwrap()
            .and_hms_opt(0, 0, 1)
            .unwrap();
        assert!(!cycle.is_expired(None, now));

        // cycle_end(None, 2026-09-14) = 2026-09-15(本月重置日)
        // 2026-09-14 < 2026-09-15 → not expired
        let now2 = chrono::NaiveDate::from_ymd_opt(2026, 9, 14)
            .unwrap()
            .and_hms_opt(12, 0, 0)
            .unwrap();
        assert!(!cycle.is_expired(None, now2));
    }

    /// Rolling 模式:is_expired 在当前时间超过 window_start + days 时返回 true。
    #[test]
    fn test_rolling_cycle_is_expired() {
        let cycle = CreditCycle::Rolling { days: 30 };
        let window_start_ts = 1_700_000_000i64;
        // now > window_start + 30 * 86400 → expired
        let expired_now = chrono::DateTime::from_timestamp(window_start_ts + 31 * 86400, 0)
            .unwrap()
            .naive_utc();
        assert!(cycle.is_expired(Some(window_start_ts), expired_now));

        // now < window_start + 30 * 86400 → not expired
        let active_now = chrono::DateTime::from_timestamp(window_start_ts + 15 * 86400, 0)
            .unwrap()
            .naive_utc();
        assert!(!cycle.is_expired(Some(window_start_ts), active_now));
    }

    /// Fixed 模式:day_of_month = 28 在 28 天月(二月平年)边界正确。
    #[test]
    fn test_fixed_day_of_month_boundary() {
        let cycle = CreditCycle::Fixed { day_of_month: 28 };
        // 2026-02-28(平年二月最后一天)
        let now = chrono::NaiveDate::from_ymd_opt(2026, 2, 28)
            .unwrap()
            .and_hms_opt(12, 0, 0)
            .unwrap();
        let start = cycle.cycle_start(None, now);
        let expected = chrono::NaiveDate::from_ymd_opt(2026, 2, 28)
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap()
            .and_utc()
            .timestamp();
        assert_eq!(start, expected);
    }

    /// type_tag + from_tag 往返一致。
    #[test]
    fn test_type_tag_roundtrip() {
        let fixed = CreditCycle::Fixed { day_of_month: 15 };
        assert_eq!(fixed.type_tag(), "fixed");
        assert_eq!(fixed.param(), 15);
        let rebuilt = CreditCycle::from_tag("fixed", 15).unwrap();
        assert_eq!(rebuilt, fixed);

        let rolling = CreditCycle::Rolling { days: 30 };
        assert_eq!(rolling.type_tag(), "rolling");
        assert_eq!(rolling.param(), 30);
        let rebuilt = CreditCycle::from_tag("rolling", 30).unwrap();
        assert_eq!(rebuilt, rolling);
    }

    /// from_tag 对未知 tag 返回 None。
    #[test]
    fn test_from_tag_unknown() {
        assert!(CreditCycle::from_tag("unknown", 0).is_none());
    }

    /// from_tag 参数校验:fixed 拒绝 0 与 >28,rolling 拒绝 0(返回 None,
    /// 调用方转为脏数据错误 fail-fast)。
    #[test]
    fn test_from_tag_validates_param() {
        // fixed:day_of_month 必须在 1..=28
        assert!(
            CreditCycle::from_tag("fixed", 0).is_none(),
            "day=0 应被拒绝"
        );
        assert!(
            CreditCycle::from_tag("fixed", 29).is_none(),
            "day=29 应被拒绝"
        );
        assert!(
            CreditCycle::from_tag("fixed", 31).is_none(),
            "day=31 应被拒绝"
        );
        assert!(CreditCycle::from_tag("fixed", u32::MAX).is_none());
        assert!(CreditCycle::from_tag("fixed", 1).is_some());
        assert!(CreditCycle::from_tag("fixed", 28).is_some());
        // rolling:days 必须 >= 1(0 会产生立即过期的空窗口)
        assert!(
            CreditCycle::from_tag("rolling", 0).is_none(),
            "days=0 应被拒绝"
        );
        assert!(CreditCycle::from_tag("rolling", 1).is_some());
    }

    /// Fixed cycle_start 合法边界:day=30 在 31 天月(1 月)无需回退。
    ///
    /// from_tag 已拒绝 day > 28,此处直接构造以覆盖回退逻辑的边界行为
    /// (meta 脏数据 / 手工构造的越界值在含 30 日的月份中应直接取本月 day 日)。
    #[test]
    fn test_fixed_cycle_start_day30_in_31_day_month() {
        let cycle = CreditCycle::Fixed { day_of_month: 30 };
        // 2026-01-31:current_day(31) >= 30 → 周期起始 = 2026-01-30
        let now = chrono::NaiveDate::from_ymd_opt(2026, 1, 31)
            .unwrap()
            .and_hms_opt(12, 0, 0)
            .unwrap();
        let start = cycle.cycle_start(None, now);
        let expected = chrono::NaiveDate::from_ymd_opt(2026, 1, 30)
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap()
            .and_utc()
            .timestamp();
        assert_eq!(start, expected);
    }

    /// Fixed cycle_start 当月分支回退:day 超出当月天数(2 月无 30/31 日)。
    #[test]
    fn test_fixed_cycle_start_current_month_fallback_feb() {
        // day=0,now = 2026-02-10(10 >= 0 成立 → 当月分支)
        // from_tag 已拒绝 day=0,此处直接构造越界值验证回退行为
        let cycle = CreditCycle::Fixed { day_of_month: 0 };
        let now = chrono::NaiveDate::from_ymd_opt(2026, 2, 10)
            .unwrap()
            .and_hms_opt(12, 0, 0)
            .unwrap();
        let start = cycle.cycle_start(None, now);
        // day=0 非法 → 回退为当月最后一天 2026-02-28
        let expected = chrono::NaiveDate::from_ymd_opt(2026, 2, 28)
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap()
            .and_utc()
            .timestamp();
        assert_eq!(start, expected, "day=0 应回退为当月最后一天");
    }

    /// Fixed cycle_start 上月分支回退:上月无 day 日(3 月回看 2 月 day=30)。
    #[test]
    fn test_fixed_cycle_start_prev_month_fallback() {
        let cycle = CreditCycle::Fixed { day_of_month: 30 };
        // 2026-03-10 < 30 → 上月(2 月)无 30 日 → 回退 2026-02-28
        let now = chrono::NaiveDate::from_ymd_opt(2026, 3, 10)
            .unwrap()
            .and_hms_opt(12, 0, 0)
            .unwrap();
        let start = cycle.cycle_start(None, now);
        let expected = chrono::NaiveDate::from_ymd_opt(2026, 2, 28)
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap()
            .and_utc()
            .timestamp();
        assert_eq!(start, expected);
    }

    /// Fixed cycle_start 上月分支跨年:1 月回看上年 12 月。
    #[test]
    fn test_fixed_cycle_start_prev_month_crosses_year() {
        let cycle = CreditCycle::Fixed { day_of_month: 15 };
        // 2027-01-10 < 15 → 上月 = 2026-12-15
        let now = chrono::NaiveDate::from_ymd_opt(2027, 1, 10)
            .unwrap()
            .and_hms_opt(12, 0, 0)
            .unwrap();
        let start = cycle.cycle_start(None, now);
        let expected = chrono::NaiveDate::from_ymd_opt(2026, 12, 15)
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap()
            .and_utc()
            .timestamp();
        assert_eq!(start, expected);
    }

    /// Fixed cycle_end 下月分支回退:下月无 day 日(1 月 31 日看 2 月)。
    #[test]
    fn test_fixed_cycle_end_next_month_fallback() {
        let cycle = CreditCycle::Fixed { day_of_month: 31 };
        // 2026-01-31:current_day(31) >= 31 → 下月 2 月无 31 日 → 回退 2026-02-28
        let now = chrono::NaiveDate::from_ymd_opt(2026, 1, 31)
            .unwrap()
            .and_hms_opt(12, 0, 0)
            .unwrap();
        let end = cycle.cycle_end(None, now);
        let expected = chrono::NaiveDate::from_ymd_opt(2026, 2, 28)
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap()
            .and_utc()
            .timestamp();
        assert_eq!(end, expected);
    }

    /// Fixed cycle_end 当月分支回退:当月无 day 日(2 月 day=31)。
    #[test]
    fn test_fixed_cycle_end_current_month_fallback() {
        let cycle = CreditCycle::Fixed { day_of_month: 31 };
        // 2026-02-10 < 31 → 周期结束 = 本月 day 日 → 2 月无 31 日 → 回退 02-28
        let now = chrono::NaiveDate::from_ymd_opt(2026, 2, 10)
            .unwrap()
            .and_hms_opt(12, 0, 0)
            .unwrap();
        let end = cycle.cycle_end(None, now);
        let expected = chrono::NaiveDate::from_ymd_opt(2026, 2, 28)
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap()
            .and_utc()
            .timestamp();
        assert_eq!(end, expected);
    }

    /// Fixed cycle_end 跨年:12 月的下一周期为次年 1 月。
    #[test]
    fn test_fixed_cycle_end_crosses_year() {
        let cycle = CreditCycle::Fixed { day_of_month: 15 };
        // 2026-12-20 >= 15 → 下月 = 次年 1 月 15 日
        let now = chrono::NaiveDate::from_ymd_opt(2026, 12, 20)
            .unwrap()
            .and_hms_opt(12, 0, 0)
            .unwrap();
        let end = cycle.cycle_end(None, now);
        let expected = chrono::NaiveDate::from_ymd_opt(2027, 1, 15)
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap()
            .and_utc()
            .timestamp();
        assert_eq!(end, expected);
    }

    /// last_day_of_month 十二月分支:12 月回退取 12-31(经 cycle_end 触发,
    /// day 超出 12 月天数即 > 31,直接构造越界值)。
    #[test]
    fn test_fixed_cycle_end_december_fallback_last_day() {
        let cycle = CreditCycle::Fixed { day_of_month: 32 };
        // 2026-12-05 < 32 → 周期结束 = 本月 day 日 → 12 月无 32 日 → 回退 12-31
        let now = chrono::NaiveDate::from_ymd_opt(2026, 12, 5)
            .unwrap()
            .and_hms_opt(12, 0, 0)
            .unwrap();
        let end = cycle.cycle_end(None, now);
        let expected = chrono::NaiveDate::from_ymd_opt(2026, 12, 31)
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap()
            .and_utc()
            .timestamp();
        assert_eq!(end, expected);
    }

    /// Rolling cycle_start 在 window_start=None 时回退为当前时间。
    #[test]
    fn test_rolling_cycle_start_none_falls_back_to_now() {
        let cycle = CreditCycle::Rolling { days: 7 };
        let now = chrono::NaiveDate::from_ymd_opt(2026, 8, 20)
            .unwrap()
            .and_hms_opt(12, 0, 0)
            .unwrap();
        assert_eq!(
            cycle.cycle_start(None, now),
            now.and_utc().timestamp(),
            "window_start=None 应回退为当前时间戳"
        );
    }

    /// Rolling is_expired 边界:now == window_start + days 时恰好过期(>= 语义)。
    #[test]
    fn test_rolling_is_expired_exact_boundary() {
        let cycle = CreditCycle::Rolling { days: 30 };
        let window_start_ts = 1_700_000_000i64;
        let exact_end = chrono::DateTime::from_timestamp(window_start_ts + 30 * 86400, 0)
            .unwrap()
            .naive_utc();
        assert!(
            cycle.is_expired(Some(window_start_ts), exact_end),
            "now == 周期结束点应判定过期"
        );
    }

    /// Rolling next_reset_at = window_start + days * 86400。
    #[test]
    fn test_rolling_next_reset_at() {
        let cycle = CreditCycle::Rolling { days: 14 };
        let window_start_ts = 1_700_000_000i64;
        let now = chrono::NaiveDate::from_ymd_opt(2026, 8, 20)
            .unwrap()
            .and_hms_opt(12, 0, 0)
            .unwrap();
        assert_eq!(
            cycle.next_reset_at(Some(window_start_ts), now),
            window_start_ts + 14 * 86400
        );
    }

    /// Fixed next_reset_at 与 cycle_end 一致(下个重置日)。
    #[test]
    fn test_fixed_next_reset_at() {
        let cycle = CreditCycle::Fixed { day_of_month: 15 };
        let now = chrono::NaiveDate::from_ymd_opt(2026, 8, 20)
            .unwrap()
            .and_hms_opt(12, 0, 0)
            .unwrap();
        assert_eq!(cycle.next_reset_at(None, now), cycle.cycle_end(None, now));
    }

    /// Fixed is_expired 恒为 false:cycle_end 总是返回未来重置日(含重置日当天 00:00)。
    #[test]
    fn test_fixed_is_expired_always_false() {
        let cycle = CreditCycle::Fixed { day_of_month: 15 };
        // 重置日当天 00:00 整点:end 指向下月 15 日,仍未来
        let now = chrono::NaiveDate::from_ymd_opt(2026, 9, 15)
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap();
        assert!(!cycle.is_expired(None, now));
    }

    /// CreditCycle serde 往返(JSON)保持变体与参数一致。
    #[test]
    fn test_cycle_serde_roundtrip() {
        let fixed = CreditCycle::Fixed { day_of_month: 28 };
        let json = serde_json::to_string(&fixed).unwrap();
        assert_eq!(serde_json::from_str::<CreditCycle>(&json).unwrap(), fixed);

        let rolling = CreditCycle::Rolling { days: 90 };
        let json = serde_json::to_string(&rolling).unwrap();
        assert_eq!(serde_json::from_str::<CreditCycle>(&json).unwrap(), rolling);
    }

    /// Clone 语义:克隆体与原值相等且修改不影响原值(值语义枚举)。
    #[test]
    fn test_cycle_clone_eq() {
        let cycle = CreditCycle::Fixed { day_of_month: 1 };
        let cloned = cycle.clone();
        assert_eq!(cycle, cloned);
        assert_eq!(cloned.param(), 1);
    }
}