Skip to content

Commit

Permalink
rpc: add Client::wait_until_healthy method
Browse files Browse the repository at this point in the history
Adds a method which repeatedly polls the `/health` endpoint until it
returns a successful response or a specified timeout elapses.

This is useful when writing tests that need to wait for a node to boot
up (e.g. inside of a docker container).
  • Loading branch information
tony-iqlusion committed Apr 6, 2021
1 parent d1c8877 commit d107113
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions rpc/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,17 @@ pub use transport::websocket::{WebSocketClient, WebSocketClientDriver, WebSocket

use crate::endpoint::validators::DEFAULT_VALIDATORS_PER_PAGE;
use crate::endpoint::*;
use crate::error::Error;
use crate::paging::Paging;
use crate::query::Query;
use crate::{Order, Result, SimpleRequest};
use async_trait::async_trait;
use std::time::Duration;
use tendermint::abci::{self, Transaction};
use tendermint::block::Height;
use tendermint::evidence::Evidence;
use tendermint::Genesis;
use tokio::time;

/// Provides lightweight access to the Tendermint RPC. It gives access to all
/// endpoints with the exception of the event subscription-related ones.
Expand Down Expand Up @@ -221,6 +224,31 @@ pub trait Client {
.await
}

/// Poll the `/health` endpoint until it returns a successful result or
/// the given `timeout` has elapsed.
async fn wait_until_healthy<T>(&self, timeout: T) -> Result<()>
where
T: Into<Duration> + Send
{
let timeout = timeout.into();
let poll_interval = Duration::from_millis(200);
let mut attempts_remaining = timeout.as_millis() / poll_interval.as_millis();

while let Err(_) = self.health().await {
if attempts_remaining == 0 {
return Err(Error::client_internal_error(format!(
"timed out waiting for healthy response after {}ms",
timeout.as_millis()
)));
}

attempts_remaining -= 1;
time::sleep(poll_interval).await;
}

Ok(())
}

/// Perform a request against the RPC endpoint
async fn perform<R>(&self, request: R) -> Result<R::Response>
where
Expand Down

0 comments on commit d107113

Please sign in to comment.