Skip to content

Commit

Permalink
[CLI] Restructure local testnet code
Browse files Browse the repository at this point in the history
  • Loading branch information
banool committed Sep 27, 2023
1 parent 41b3284 commit bb9963f
Show file tree
Hide file tree
Showing 10 changed files with 522 additions and 288 deletions.
7 changes: 4 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -485,7 +485,7 @@ dirs = "5.0.1"
ed25519-dalek = { version = "1.0.1", features = ["std", "serde"] }
ed25519-dalek-bip32 = "0.2.0"
either = "1.6.1"
enum_dispatch = "0.3.8"
enum_dispatch = "0.3.12"
env_logger = "0.10.0"
erased-serde = "0.3.13"
event-listener = "2.5.3"
Expand Down
1 change: 1 addition & 0 deletions crates/aptos/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ thiserror = { workspace = true }
tokio = { workspace = true }
toml = { workspace = true }
tonic = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
walkdir = { workspace = true }

Expand Down
86 changes: 86 additions & 0 deletions crates/aptos/src/node/local_testnet/faucet.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// Copyright © Aptos Foundation
// SPDX-License-Identifier: Apache-2.0

use super::{health_checker::HealthChecker, traits::ServiceManager, RunLocalTestnet};
use anyhow::Result;
use aptos_faucet_core::server::{FunderKeyEnum, RunConfig};
use async_trait::async_trait;
use clap::Parser;
use reqwest::Url;
use std::path::PathBuf;

/// Args related to running a faucet in the local testnet.
#[derive(Debug, Parser)]
pub struct FaucetArgs {
/// Do not run a faucet alongside the node.
///
/// Running a faucet alongside the node allows you to create and fund accounts
/// for testing.
#[clap(long)]
pub no_faucet: bool,

/// This does nothing, we already run a faucet by default. We only keep this here
/// for backwards compatibility with tests. We will remove this once the commit
/// that added --no-faucet makes its way to the testnet branch.
#[clap(long, hide = true)]
pub with_faucet: bool,

/// Port to run the faucet on.
///
/// When running, you'll be able to use the faucet at `http://127.0.0.1:<port>/mint` e.g.
/// `http//127.0.0.1:8081/mint`
#[clap(long, default_value_t = 8081)]
pub faucet_port: u16,

/// Disable the delegation of faucet minting to a dedicated account.
#[clap(long)]
pub do_not_delegate: bool,
}

#[derive(Clone, Debug)]
pub struct FaucetManager {
config: RunConfig,
prerequisite_health_checkers: Vec<HealthChecker>,
}

impl FaucetManager {
pub fn new(
args: &RunLocalTestnet,
prerequisite_health_checkers: Vec<HealthChecker>,
test_dir: PathBuf,
node_api_url: Url,
) -> Result<Self> {
Ok(Self {
config: RunConfig::build_for_cli(
node_api_url.clone(),
args.faucet_args.faucet_port,
FunderKeyEnum::KeyFile(test_dir.join("mint.key")),
args.faucet_args.do_not_delegate,
None,
),
prerequisite_health_checkers,
})
}
}

#[async_trait]
impl ServiceManager for FaucetManager {
fn get_name(&self) -> String {
"Faucet".to_string()
}

fn get_healthchecks(&self) -> Vec<HealthChecker> {
vec![HealthChecker::http_checker_from_port(
self.config.server_config.listen_port,
self.get_name(),
)]
}

fn get_prerequisite_health_checkers(&self) -> Vec<&HealthChecker> {
self.prerequisite_health_checkers.iter().collect()
}

async fn run_service(self: Box<Self>) -> Result<()> {
self.config.run().await
}
}
26 changes: 22 additions & 4 deletions crates/aptos/src/node/local_testnet/health_checker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const WAIT_INTERVAL_MS: u64 = 150;
#[derive(Clone, Debug, Serialize)]
pub enum HealthChecker {
/// Check that an HTTP API is up. The second param is the name of the HTTP service.
Http(Url, &'static str),
Http(Url, String),
/// Check that the node API is up. This is just a specific case of Http for extra
/// guarantees around liveliness.
NodeApi(Url),
Expand Down Expand Up @@ -100,6 +100,14 @@ impl HealthChecker {
HealthChecker::DataServiceGrpc(url) => url.as_str(),
}
}

/// Given a port, make an instance of HealthChecker::Http targeting 127.0.0.1.
pub fn http_checker_from_port(port: u16, name: String) -> Self {
Self::Http(
Url::parse(&format!("http://127.0.0.1:{}", port,)).unwrap(),
name,
)
}
}

impl std::fmt::Display for HealthChecker {
Expand All @@ -123,15 +131,25 @@ where
let start = Instant::now();
let mut started_successfully = false;

let mut last_error_message = None;
while start.elapsed() < max_wait {
if check_fn().await.is_ok() {
started_successfully = true;
break;
match check_fn().await {
Ok(_) => {
started_successfully = true;
break;
},
Err(err) => {
last_error_message = Some(format!("{:#}", err));
},
}
tokio::time::sleep(wait_interval).await
}

if !started_successfully {
let error_message = match last_error_message {
Some(last_error_message) => format!("{}: {}", error_message, last_error_message),
None => error_message,
};
return Err(CliError::UnexpectedError(error_message));
}

Expand Down
Loading

0 comments on commit bb9963f

Please sign in to comment.