limiteron 0.2.6

Unified flow control framework for 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
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! 事件类型定义
//!
//! 提供事件系统使用的类型、枚举和元数据结构。

use ahash::AHashMap as StdHashMap;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// 事件类型枚举
///
/// 定义了系统中所有可能触发的事件类型。
/// 每种事件类型携带不同的上下文数据。
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", content = "data")]
pub enum EventType {
    /// 限流触发事件
    ///
    /// 当请求被限流时触发此事件。
    RateLimitTriggered {
        /// 限流键(如 IP 地址、用户 ID 等)
        key: String,
        /// 触发限流的规则 ID
        rule_id: String,
        /// 限流决策(Allow、Deny、Fallback 等)
        decision: String,
    },

    /// 封禁应用事件
    ///
    /// 当目标被封禁时触发此事件。
    BanApplied {
        /// 封禁目标(如 IP、用户 ID 等)
        target: String,
        /// 封禁原因
        reason: String,
        /// 封禁时长(秒)
        duration: u64,
    },

    /// 封禁过期事件
    ///
    /// 当封禁自动过期时触发此事件。
    BanExpired {
        /// 封禁目标
        target: String,
    },

    /// 熔断器状态变更事件
    ///
    /// 当熔断器状态发生变化时触发此事件。
    CircuitStateChanged {
        /// 变更前状态
        from: String,
        /// 变更后状态
        to: String,
    },

    /// 配额告警事件
    ///
    /// 当配额使用率达到告警阈值时触发此事件。
    QuotaAlert {
        /// 用户 ID
        user_id: String,
        /// 资源类型
        resource: String,
        /// 使用率百分比(0-100)
        usage_percent: f64,
    },
}

impl EventType {
    /// 获取事件类型的名称
    pub fn name(&self) -> &'static str {
        match self {
            EventType::RateLimitTriggered { .. } => "rate_limit_triggered",
            EventType::BanApplied { .. } => "ban_applied",
            EventType::BanExpired { .. } => "ban_expired",
            EventType::CircuitStateChanged { .. } => "circuit_state_changed",
            EventType::QuotaAlert { .. } => "quota_alert",
        }
    }

    /// 获取事件的严重级别
    ///
    /// 返回 0-10 的数值,数值越高表示越严重。
    pub fn severity(&self) -> u8 {
        match self {
            EventType::RateLimitTriggered { decision, .. } => match decision.as_str() {
                "Deny" => 6,
                "Fallback" => 4,
                _ => 2,
            },
            EventType::BanApplied { .. } => 8,
            EventType::BanExpired { .. } => 1,
            EventType::CircuitStateChanged { to, .. } => match to.as_str() {
                "Open" => 9,
                "HalfOpen" => 5,
                "Closed" => 1,
                _ => 3,
            },
            EventType::QuotaAlert { usage_percent, .. } => {
                if *usage_percent >= 90.0 {
                    7
                } else if *usage_percent >= 75.0 {
                    5
                } else {
                    3
                }
            }
        }
    }
}

/// 事件结构体
///
/// 系统中所有事件的统一包装结构,包含事件类型、时间戳和扩展元数据。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Event {
    /// 事件类型
    pub event_type: EventType,

    /// 事件发生时间
    pub timestamp: DateTime<Utc>,

    /// 扩展元数据
    ///
    /// 允许携带任意额外的上下文信息。
    #[serde(default)]
    pub metadata: StdHashMap<String, serde_json::Value>,
}

impl Event {
    /// 创建新事件
    pub fn new(event_type: EventType) -> Self {
        Self {
            event_type,
            timestamp: Utc::now(),
            metadata: StdHashMap::new(),
        }
    }

    /// 创建新事件并附带元数据
    pub fn with_metadata(
        event_type: EventType,
        metadata: StdHashMap<String, serde_json::Value>,
    ) -> Self {
        Self {
            event_type,
            timestamp: Utc::now(),
            metadata,
        }
    }

    /// 添加元数据
    pub fn add_metadata(mut self, key: &str, value: serde_json::Value) -> Self {
        self.metadata.insert(key.to_string(), value);
        self
    }

    /// 获取事件名称
    pub fn name(&self) -> &'static str {
        self.event_type.name()
    }

    /// 获取事件严重级别
    pub fn severity(&self) -> u8 {
        self.event_type.severity()
    }
}

/// 事件处理器 trait
///
/// 实现此 trait 可以处理特定类型的事件。
#[async_trait::async_trait]
pub trait EventHandler: Send + Sync {
    /// 处理事件
    ///
    /// # 参数
    /// - `event`: 要处理的事件
    ///
    /// # 返回
    /// - `Ok(())`: 处理成功
    /// - `Err(Box<dyn std::error::Error>)`: 处理失败
    async fn handle(&self, event: &Event) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;

    /// 获取处理器名称(用于日志和调试)
    fn name(&self) -> &str;

    /// 是否处理指定类型的事件
    ///
    /// 默认实现:处理所有事件类型。
    fn accepts(&self, _event_type: &EventType) -> bool {
        true
    }
}

/// 事件系统配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventConfig {
    /// 是否启用事件系统
    pub enabled: bool,

    /// 广播通道容量(最大缓冲事件数)
    pub channel_capacity: usize,

    /// 是否启用 Webhook 推送
    pub webhook_enabled: bool,

    /// Webhook URL 列表
    pub webhook_urls: Vec<String>,

    /// 是否启用事件日志
    pub event_logging_enabled: bool,
}

impl Default for EventConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            channel_capacity: 1024,
            webhook_enabled: false,
            webhook_urls: Vec::new(),
            event_logging_enabled: true,
        }
    }
}

impl EventConfig {
    /// 创建启用的配置
    pub fn enabled() -> Self {
        Self {
            enabled: true,
            ..Default::default()
        }
    }

    /// 设置通道容量
    pub fn with_channel_capacity(mut self, capacity: usize) -> Self {
        self.channel_capacity = capacity;
        self
    }

    /// 启用 Webhook 推送
    pub fn with_webhook_urls(mut self, urls: Vec<String>) -> Self {
        self.webhook_enabled = !urls.is_empty();
        self.webhook_urls = urls;
        self
    }

    /// 禁用事件日志
    pub fn without_logging(mut self) -> Self {
        self.event_logging_enabled = false;
        self
    }
}

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

    #[test]
    fn test_event_type_name() {
        let rate_limit = EventType::RateLimitTriggered {
            key: "192.168.1.1".to_string(),
            rule_id: "rule_1".to_string(),
            decision: "Deny".to_string(),
        };
        assert_eq!(rate_limit.name(), "rate_limit_triggered");

        let ban_applied = EventType::BanApplied {
            target: "192.168.1.1".to_string(),
            reason: "Excessive requests".to_string(),
            duration: 3600,
        };
        assert_eq!(ban_applied.name(), "ban_applied");
    }

    #[test]
    fn test_event_type_severity() {
        let deny = EventType::RateLimitTriggered {
            key: "key".to_string(),
            rule_id: "rule".to_string(),
            decision: "Deny".to_string(),
        };
        assert_eq!(deny.severity(), 6);

        let circuit_open = EventType::CircuitStateChanged {
            from: "Closed".to_string(),
            to: "Open".to_string(),
        };
        assert_eq!(circuit_open.severity(), 9);

        let quota_high = EventType::QuotaAlert {
            user_id: "user1".to_string(),
            resource: "api_calls".to_string(),
            usage_percent: 95.0,
        };
        assert_eq!(quota_high.severity(), 7);
    }

    #[test]
    fn test_event_type_name_all_variants() {
        assert_eq!(
            EventType::RateLimitTriggered {
                key: "k".to_string(),
                rule_id: "r".to_string(),
                decision: "Deny".to_string(),
            }
            .name(),
            "rate_limit_triggered"
        );
        assert_eq!(
            EventType::BanApplied {
                target: "t".to_string(),
                reason: "r".to_string(),
                duration: 1,
            }
            .name(),
            "ban_applied"
        );
        assert_eq!(
            EventType::BanExpired {
                target: "t".to_string(),
            }
            .name(),
            "ban_expired"
        );
        assert_eq!(
            EventType::CircuitStateChanged {
                from: "Closed".to_string(),
                to: "Open".to_string(),
            }
            .name(),
            "circuit_state_changed"
        );
        assert_eq!(
            EventType::QuotaAlert {
                user_id: "u".to_string(),
                resource: "r".to_string(),
                usage_percent: 50.0,
            }
            .name(),
            "quota_alert"
        );
    }

    #[test]
    fn test_event_type_severity_all_branches() {
        // RateLimitTriggered decision branches
        assert_eq!(
            EventType::RateLimitTriggered {
                key: "k".to_string(),
                rule_id: "r".to_string(),
                decision: "Deny".to_string(),
            }
            .severity(),
            6
        );
        assert_eq!(
            EventType::RateLimitTriggered {
                key: "k".to_string(),
                rule_id: "r".to_string(),
                decision: "Fallback".to_string(),
            }
            .severity(),
            4
        );
        assert_eq!(
            EventType::RateLimitTriggered {
                key: "k".to_string(),
                rule_id: "r".to_string(),
                decision: "Allow".to_string(),
            }
            .severity(),
            2
        );

        // BanApplied
        assert_eq!(
            EventType::BanApplied {
                target: "t".to_string(),
                reason: "r".to_string(),
                duration: 60,
            }
            .severity(),
            8
        );

        // BanExpired
        assert_eq!(
            EventType::BanExpired {
                target: "t".to_string(),
            }
            .severity(),
            1
        );

        // CircuitStateChanged to branches
        assert_eq!(
            EventType::CircuitStateChanged {
                from: "Closed".to_string(),
                to: "Open".to_string(),
            }
            .severity(),
            9
        );
        assert_eq!(
            EventType::CircuitStateChanged {
                from: "Open".to_string(),
                to: "HalfOpen".to_string(),
            }
            .severity(),
            5
        );
        assert_eq!(
            EventType::CircuitStateChanged {
                from: "HalfOpen".to_string(),
                to: "Closed".to_string(),
            }
            .severity(),
            1
        );
        assert_eq!(
            EventType::CircuitStateChanged {
                from: "X".to_string(),
                to: "Unknown".to_string(),
            }
            .severity(),
            3
        );

        // QuotaAlert usage_percent branches
        assert_eq!(
            EventType::QuotaAlert {
                user_id: "u".to_string(),
                resource: "r".to_string(),
                usage_percent: 95.0,
            }
            .severity(),
            7
        );
        assert_eq!(
            EventType::QuotaAlert {
                user_id: "u".to_string(),
                resource: "r".to_string(),
                usage_percent: 80.0,
            }
            .severity(),
            5
        );
        assert_eq!(
            EventType::QuotaAlert {
                user_id: "u".to_string(),
                resource: "r".to_string(),
                usage_percent: 50.0,
            }
            .severity(),
            3
        );
    }

    #[test]
    fn test_event_creation() {
        let event_type = EventType::BanApplied {
            target: "user123".to_string(),
            reason: "Test".to_string(),
            duration: 60,
        };

        let event = Event::new(event_type.clone());
        assert!(event.timestamp <= Utc::now());
        assert!(event.metadata.is_empty());
        assert_eq!(event.name(), "ban_applied");
    }

    #[test]
    fn test_event_with_metadata() {
        let event_type = EventType::RateLimitTriggered {
            key: "key".to_string(),
            rule_id: "rule".to_string(),
            decision: "Deny".to_string(),
        };

        let mut metadata = StdHashMap::new();
        metadata.insert("request_id".to_string(), serde_json::json!("req_123"));

        let event = Event::with_metadata(event_type, metadata.clone());
        assert_eq!(event.metadata.len(), 1);
        assert_eq!(
            event.metadata.get("request_id"),
            Some(&serde_json::json!("req_123"))
        );
    }

    #[test]
    fn test_event_add_metadata() {
        let event_type = EventType::BanExpired {
            target: "user123".to_string(),
        };

        let event = Event::new(event_type)
            .add_metadata("cleanup_reason", serde_json::json!("auto_cleanup"));

        assert_eq!(event.metadata.len(), 1);
    }

    #[test]
    fn test_event_config_default() {
        let config = EventConfig::default();
        assert!(config.enabled);
        assert_eq!(config.channel_capacity, 1024);
        assert!(!config.webhook_enabled);
        assert!(config.webhook_urls.is_empty());
        assert!(config.event_logging_enabled);
    }

    #[test]
    fn test_event_config_builder() {
        let config = EventConfig::enabled()
            .with_channel_capacity(2048)
            .with_webhook_urls(vec!["http://example.com/hook".to_string()])
            .without_logging();

        assert!(config.enabled);
        assert_eq!(config.channel_capacity, 2048);
        assert!(config.webhook_enabled);
        assert_eq!(config.webhook_urls.len(), 1);
        assert!(!config.event_logging_enabled);
    }

    #[test]
    fn test_event_serialization() {
        let event_type = EventType::CircuitStateChanged {
            from: "Closed".to_string(),
            to: "Open".to_string(),
        };

        let event = Event::new(event_type);
        let json = serde_json::to_string(&event).unwrap();
        let deserialized: Event = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.name(), event.name());
    }

    /// 测试 EventHandler trait 的 accepts 默认实现
    /// 默认实现应返回 true(处理所有事件类型)
    #[test]
    fn test_event_handler_accepts_default() {
        struct DummyHandler;

        #[async_trait::async_trait]
        impl EventHandler for DummyHandler {
            async fn handle(
                &self,
                _event: &Event,
            ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                Ok(())
            }

            fn name(&self) -> &str {
                "dummy"
            }
        }

        let handler = DummyHandler;
        let event_type = EventType::RateLimitTriggered {
            key: "k".to_string(),
            rule_id: "r".to_string(),
            decision: "Deny".to_string(),
        };
        // 默认 accepts 应返回 true
        assert!(handler.accepts(&event_type));

        let ban_event = EventType::BanApplied {
            target: "t".to_string(),
            reason: "r".to_string(),
            duration: 60,
        };
        assert!(handler.accepts(&ban_event));
    }
}