use std::{
sync::{Arc, Mutex},
task::{Context, Poll},
time::Duration,
};
use futures::{future, future::BoxFuture, FutureExt};
use tokio::time::{sleep_until, Instant};
use tower::Service;
#[derive(Clone, Debug)]
pub struct RateLimitBySkipping<S> {
inner: S,
interval: Duration,
next_allowed: Arc<Mutex<Option<Instant>>>,
}
impl<S> RateLimitBySkipping<S> {
pub fn new(inner: S, interval: Duration) -> Self {
Self {
inner,
interval,
next_allowed: Arc::new(Mutex::new(Some(Instant::now()))),
}
}
}
impl<S, Request> Service<Request> for RateLimitBySkipping<S>
where
S: Service<Request>,
S::Response: Default + Send + 'static,
S::Future: Send + 'static,
S::Error: Send + 'static,
{
type Response = S::Response;
type Error = S::Error;
type Future = BoxFuture<'static, Result<S::Response, S::Error>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request) -> Self::Future {
{
let mut next_allowed = self
.next_allowed
.lock()
.expect("mutex should be unpoisoned");
match *next_allowed {
None => return future::ready(Ok(S::Response::default())).boxed(),
Some(allowed_at) if Instant::now() < allowed_at => {
return future::ready(Ok(S::Response::default())).boxed()
}
Some(_) => {}
}
*next_allowed = None;
}
let call = self.inner.call(request);
let next_allowed = self.next_allowed.clone();
let interval = self.interval;
async move {
let result = call.await;
*next_allowed.lock().expect("mutex should be unpoisoned") =
Some(Instant::now() + interval);
result
}
.boxed()
}
}
#[derive(Clone, Debug)]
pub struct RateLimitOnYield<S, Response> {
inner: S,
interval: Duration,
charges: fn(&Response) -> bool,
next_allowed: Arc<Mutex<Instant>>,
}
impl<S, Response> RateLimitOnYield<S, Response> {
pub fn new(inner: S, interval: Duration, charges: fn(&Response) -> bool) -> Self {
Self {
inner,
interval,
charges,
next_allowed: Arc::new(Mutex::new(Instant::now())),
}
}
}
impl<S, Request, Response> Service<Request> for RateLimitOnYield<S, Response>
where
S: Service<Request, Response = Response>,
S::Future: Send + 'static,
S::Error: Send + 'static,
Response: Send + 'static,
{
type Response = Response;
type Error = S::Error;
type Future = BoxFuture<'static, Result<Response, S::Error>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request) -> Self::Future {
let response = self.inner.call(request);
let charges = self.charges;
let interval = self.interval;
let next_allowed = self.next_allowed.clone();
async move {
let response = response.await?;
if charges(&response) {
let slot = {
let mut next_allowed = next_allowed.lock().expect("mutex should be unpoisoned");
let now = Instant::now();
let slot = if *next_allowed > now {
*next_allowed
} else {
now
};
*next_allowed = slot + interval;
slot
};
sleep_until(slot).await;
{
let mut next_allowed = next_allowed.lock().expect("mutex should be unpoisoned");
let recharge = Instant::now() + interval;
if recharge > *next_allowed {
*next_allowed = recharge;
}
}
}
Ok(response)
}
.boxed()
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use tower::{service_fn, ServiceExt};
use super::*;
const TEST_INTERVAL: Duration = Duration::from_secs(30);
#[tokio::test(start_paused = true)]
async fn long_call_skips_concurrent_calls() {
let _init_guard = zebra_test::init();
let calls = Arc::new(AtomicUsize::new(0));
let inner = {
let calls = calls.clone();
service_fn(move |()| {
let calls = calls.clone();
async move {
calls.fetch_add(1, Ordering::SeqCst);
tokio::time::sleep(TEST_INTERVAL * 4).await;
Ok::<bool, std::convert::Infallible>(true)
}
})
};
let service = RateLimitBySkipping::new(inner, TEST_INTERVAL);
let long_call = tokio::spawn(service.clone().oneshot(()));
tokio::task::yield_now().await;
tokio::time::sleep(TEST_INTERVAL * 2).await;
let skipped = service
.clone()
.oneshot(())
.await
.expect("skipped calls return the default response");
assert!(
!skipped,
"a call made while another is in flight must be skipped, \
even after the interval has elapsed",
);
assert_eq!(
calls.load(Ordering::SeqCst),
1,
"the inner service must only be called once while a call is in flight",
);
assert!(long_call.await.expect("call task should not panic").is_ok());
}
#[tokio::test(start_paused = true)]
async fn failed_call_recharges_the_rate_limit() {
let _init_guard = zebra_test::init();
let service = RateLimitBySkipping::new(
service_fn(|()| async { Err::<bool, &'static str>("inner service error") }),
TEST_INTERVAL,
);
service
.clone()
.oneshot(())
.await
.expect_err("the inner error should be returned");
tokio::time::sleep(TEST_INTERVAL * 2).await;
service
.clone()
.oneshot(())
.await
.expect_err("a later call should reach the inner service, not be skipped forever");
}
}