tangled
alpha
login
or
join now
ptr.pet
/
Allegedly
forked from
microcosm.blue/Allegedly
0
fork
atom
Server tools to backfill, tail, mirror, and verify PLC logs
0
fork
atom
overview
issues
pulls
pipelines
grossly manage maintenance task from middleware
bad-example.com
5 months ago
5adfa74c
05410baa
+32
-2
1 changed file
expand all
collapse all
unified
split
src
ratelimit.rs
+32
-2
src/ratelimit.rs
···
12
12
sync::{Arc, LazyLock},
13
13
time::Duration,
14
14
};
15
15
+
use tokio::sync::oneshot;
15
16
16
17
static CLOCK: LazyLock<DefaultClock> = LazyLock::new(DefaultClock::default);
17
18
···
70
71
/// Once the rate limit has been reached, the middleware will respond with
71
72
/// status code 429 (too many requests) and a `Retry-After` header with the amount
72
73
/// of time that needs to pass before another request will be allowed.
73
73
-
#[derive(Debug, Clone)]
74
74
+
#[derive(Debug)]
74
75
pub struct GovernorMiddleware {
76
76
+
#[allow(dead_code)]
77
77
+
stop_on_drop: oneshot::Sender<()>,
75
78
limiters: Arc<IpLimiters>,
76
79
}
77
80
78
81
impl GovernorMiddleware {
82
82
+
/// Limit request rates
83
83
+
///
84
84
+
/// a little gross but this spawns a tokio task for housekeeping:
85
85
+
/// https://docs.rs/governor/latest/governor/struct.RateLimiter.html#keyed-rate-limiters---housekeeping
79
86
pub fn new(quota: Quota) -> Self {
87
87
+
let limiters = Arc::new(IpLimiters::new(quota));
88
88
+
let (stop_on_drop, mut stopped) = oneshot::channel();
89
89
+
tokio::task::spawn({
90
90
+
let limiters = limiters.clone();
91
91
+
async move {
92
92
+
loop {
93
93
+
tokio::select! {
94
94
+
_ = &mut stopped => break,
95
95
+
_ = tokio::time::sleep(Duration::from_secs(60)) => {},
96
96
+
};
97
97
+
log::debug!(
98
98
+
"limiter sizes before housekeeping: {}/ip {}/v6_56 {}/v6_48",
99
99
+
limiters.per_ip.len(),
100
100
+
limiters.ip6_56.len(),
101
101
+
limiters.ip6_48.len(),
102
102
+
);
103
103
+
limiters.per_ip.retain_recent();
104
104
+
limiters.ip6_56.retain_recent();
105
105
+
limiters.ip6_48.retain_recent();
106
106
+
}
107
107
+
}
108
108
+
});
80
109
Self {
81
81
-
limiters: Arc::new(IpLimiters::new(quota)),
110
110
+
stop_on_drop,
111
111
+
limiters,
82
112
}
83
113
}
84
114
}