security_rust/throttle/
mod.rs1use std::fmt;
4
5pub mod guard;
6pub mod store;
7
8pub use crate::session::StoreError;
10
11pub use guard::Throttle;
12pub use store::{MemoryThrottleStore, ThrottleStore};
13
14#[derive(Debug, Clone)]
16pub struct ThrottleConfig {
17 pub threshold: u32,
19 pub window_secs: u64,
21 pub ban_secs: u64,
23}
24
25impl Default for ThrottleConfig {
26 fn default() -> Self {
27 Self {
28 threshold: 5,
29 window_secs: 60,
30 ban_secs: 900,
31 }
32 }
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum ThrottleDecision {
37 Allow { remaining: u32 },
44 Banned { until: u64 },
46 Unavailable,
60}
61
62impl fmt::Display for ThrottleDecision {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 match self {
66 ThrottleDecision::Allow { .. } => write!(f, "ALLOW"),
67 ThrottleDecision::Banned { .. } => write!(f, "BANNED"),
68 ThrottleDecision::Unavailable => write!(f, "UNAVAILABLE"),
69 }
70 }
71}
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum ThrottleOutcome {
77 Allow { remaining: u32 },
79 Banned { until: u64 },
81}
82
83impl fmt::Display for ThrottleOutcome {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 match self {
86 ThrottleOutcome::Allow { .. } => write!(f, "ALLOW"),
87 ThrottleOutcome::Banned { .. } => write!(f, "BANNED"),
88 }
89 }
90}
91
92#[cfg(test)]
93mod tests {
94 use super::*;
95
96 #[test]
97 fn config_defaults_match_spec() {
98 let c = ThrottleConfig::default();
99 assert_eq!(c.threshold, 5, "got {:?}", c);
100 assert_eq!(c.window_secs, 60, "got {:?}", c);
101 assert_eq!(c.ban_secs, 900, "got {:?}", c);
102 }
103
104 #[test]
105 fn decision_and_outcome_display_uppercase() {
106 assert_eq!(
107 ThrottleDecision::Allow { remaining: 3 }.to_string(),
108 "ALLOW"
109 );
110 assert_eq!(ThrottleDecision::Banned { until: 7 }.to_string(), "BANNED");
111 assert_eq!(ThrottleDecision::Unavailable.to_string(), "UNAVAILABLE");
112 assert_eq!(ThrottleOutcome::Allow { remaining: 3 }.to_string(), "ALLOW");
113 assert_eq!(ThrottleOutcome::Banned { until: 7 }.to_string(), "BANNED");
114 }
115}