diff --git a/acmed/src/endpoint.rs b/acmed/src/endpoint.rs index a4016c1..5279c7b 100644 --- a/acmed/src/endpoint.rs +++ b/acmed/src/endpoint.rs @@ -2,8 +2,8 @@ use crate::acme_proto::structs::Directory; use crate::duration::parse_duration; use acme_common::error::Error; use std::cmp; -use std::thread; use std::time::{Duration, Instant}; +use tokio::time::sleep; #[derive(Clone, Debug)] pub struct Endpoint { @@ -65,19 +65,19 @@ impl RateLimit { }) } - pub fn block_until_allowed(&mut self) { + pub async fn block_until_allowed(&mut self) { if self.limits.is_empty() { return; } - let sleep_duration = self.get_sleep_duration(); + let mut sleep_duration = self.get_sleep_duration(); loop { + sleep(sleep_duration).await; self.prune_log(); if self.request_allowed() { self.query_log.push(Instant::now()); return; } - // TODO: find a better sleep duration - thread::sleep(sleep_duration); + sleep_duration = self.get_sleep_duration(); } } diff --git a/acmed/src/http.rs b/acmed/src/http.rs index 39fc81d..8ac6d8a 100644 --- a/acmed/src/http.rs +++ b/acmed/src/http.rs @@ -107,7 +107,7 @@ fn is_nonce(data: &str) -> bool { } async fn new_nonce(endpoint: &mut Endpoint) -> Result<(), HttpError> { - rate_limit(endpoint); + rate_limit(endpoint).await; let url = endpoint.dir.new_nonce.clone(); let _ = get(endpoint, &url).await?; Ok(()) @@ -134,8 +134,8 @@ fn check_status(response: &Response) -> Result<(), Error> { Ok(()) } -fn rate_limit(endpoint: &mut Endpoint) { - endpoint.rl.block_until_allowed(); +async fn rate_limit(endpoint: &mut Endpoint) { + endpoint.rl.block_until_allowed().await; } fn header_to_string(header_value: &HeaderValue) -> Result { @@ -175,7 +175,7 @@ fn get_client(root_certs: &[String]) -> Result { pub async fn get(endpoint: &mut Endpoint, url: &str) -> Result { let client = get_client(&endpoint.root_certificates)?; - rate_limit(endpoint); + rate_limit(endpoint).await; let response = client .get(url) .header(header::ACCEPT, CONTENT_TYPE_JSON) @@ -208,7 +208,7 @@ where request = request.header(header::CONTENT_TYPE, content_type); let nonce = &endpoint.nonce.clone().unwrap_or_default(); let body = data_builder(nonce, url)?; - rate_limit(endpoint); + rate_limit(endpoint).await; log::trace!("POST request body: {body}"); let response = request.body(body).send().await?; update_nonce(endpoint, &response)?;