use std::{sync::Arc, time::Duration};
use tokio::{sync::Notify, task::JoinHandle, time::sleep};
use tower::{BoxError, Service, ServiceExt};
use tracing::Instrument;
use zakura_node_services::task::spawn_erased;
use crate::components::mempool;
const RATE_LIMIT_DELAY: Duration = Duration::from_secs(5);
pub struct QueueChecker<Mempool> {
mempool: Mempool,
verification_finished: Arc<Notify>,
}
impl<Mempool> QueueChecker<Mempool>
where
Mempool:
Service<mempool::Request, Response = mempool::Response, Error = BoxError> + Send + 'static,
Mempool::Future: Send,
{
pub fn spawn(
mempool: Mempool,
verification_finished: Arc<Notify>,
) -> JoinHandle<Result<(), BoxError>> {
let queue_checker = QueueChecker {
mempool,
verification_finished,
};
spawn_erased(queue_checker.run().in_current_span())
}
pub async fn run(mut self) -> Result<(), BoxError> {
info!("initializing mempool queue checker task");
loop {
tokio::select! {
_ = self.verification_finished.notified() => {}
_ = sleep(RATE_LIMIT_DELAY) => {}
}
self.check_queue().await?;
}
}
async fn check_queue(&mut self) -> Result<(), BoxError> {
debug!("checking for newly verified mempool transactions");
let response = self
.mempool
.ready()
.await?
.call(mempool::Request::CheckForVerifiedTransactions)
.await?;
match response {
mempool::Response::CheckedForVerifiedTransactions => {}
_ => {
unreachable!("mempool did not respond with checked queue to mempool queue checker")
}
};
Ok(())
}
}
#[cfg(test)]
mod tests {
use zakura_test::mock_service::MockService;
use super::*;
#[tokio::test]
async fn verification_finished_starts_queue_check() {
let _init_guard = zakura_test::init();
let mut mempool = MockService::build().for_unit_tests();
let verification_finished = Arc::new(Notify::new());
let _queue_checker = QueueChecker::spawn(mempool.clone(), verification_finished.clone());
mempool.expect_no_requests().await;
verification_finished.notify_one();
mempool
.expect_request(mempool::Request::CheckForVerifiedTransactions)
.await
.respond(mempool::Response::CheckedForVerifiedTransactions);
}
}