use std::sync::{Arc, Mutex};
use std::time::Instant;
use super::mechanism::ThrottleMechanism;
#[derive(Clone)]
pub struct Throttle {
mechanism: Arc<Mutex<Box<dyn ThrottleMechanism>>>,
}
impl Throttle {
pub fn new<T: 'static + ThrottleMechanism>(mechanism: T) -> Self {
Self {
mechanism: Arc::new(Mutex::new(Box::new(mechanism))),
}
}
pub async fn throttle(&self) {
let delay = {
let mut mechanism = self
.mechanism
.lock()
.expect("Failed to lock the throttle mechanism");
let time = Instant::now();
mechanism.timeout_delay(time)
};
log::trace!("Throttle for {:?}.", delay);
tokio::time::sleep(delay).await;
}
}