Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add graceful shutdown #25

Merged
merged 4 commits into from
Jul 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ prometheus = "0.13.3"
serde = { version = "1.0", features = ["derive"] }
ethers = { version = "2.0", features = ["ws"] }
tokio = { version = "1.28.0", features = ["rt-multi-thread", "rt", "macros"] }
tokio-util = { version = "0.7.8" }
thiserror = "1.0.40"
tracing = "0.1.37"
tracing-subscriber = "0.3.17"
Expand Down
4 changes: 2 additions & 2 deletions compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ services:
- URL=http://0.0.0.0:8545/

fuel_node:
build:
context: fuel_node
build:
context: fuel_node
args:
fuel_core_version: "v${FUEL_CORE_VERSION:-0.18.3}"
container_name: fuel-node
Expand Down
4 changes: 2 additions & 2 deletions run_tests.sh
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ done
cargo test --bin fuel-block-committer

docker compose up -d
trap 'docker compose down' EXIT
trap 'docker compose down > /dev/null 2>&1' EXIT

cargo test --test e2e -- --nocapture

if [[ $show_logs = "true" ]]; then
docker compose logs block_committer
docker compose logs -f block_committer &
fi
19 changes: 16 additions & 3 deletions src/adapters/ethereum_adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,31 @@ pub use websocket::EthereumWs;

use crate::{adapters::fuel_adapter::FuelBlock, errors::Result};

#[derive(Debug, Clone, Copy)]
pub struct FuelBlockCommitedOnEth {
#[derive(Clone, Copy)]
pub struct FuelBlockCommittedOnEth {
pub fuel_block_hash: [u8; 32],
pub commit_height: U256,
}

impl std::fmt::Debug for FuelBlockCommittedOnEth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let hash = self
.fuel_block_hash
.map(|byte| format!("{byte:02x?}"))
.join("");
f.debug_struct("FuelBlockCommittedOnEth")
.field("hash", &hash)
.field("commit_height", &self.commit_height)
.finish()
}
}

#[cfg_attr(test, mockall::automock)]
#[async_trait]
pub trait EventStreamer {
async fn establish_stream<'a>(
&'a self,
) -> Result<Pin<Box<dyn Stream<Item = Result<FuelBlockCommitedOnEth>> + 'a + Send>>>;
) -> Result<Pin<Box<dyn Stream<Item = Result<FuelBlockCommittedOnEth>> + 'a + Send>>>;
}

#[cfg_attr(test, mockall::automock)]
Expand Down
6 changes: 3 additions & 3 deletions src/adapters/ethereum_adapter/websocket/event_streamer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use futures::{stream::TryStreamExt, Stream};

use crate::{
adapters::ethereum_adapter::{
websocket::adapter::CommitSubmittedFilter, EventStreamer, FuelBlockCommitedOnEth,
websocket::adapter::CommitSubmittedFilter, EventStreamer, FuelBlockCommittedOnEth,
},
errors::{Error, Result},
};
Expand All @@ -28,7 +28,7 @@ pub struct EthEventStreamer {
impl EventStreamer for EthEventStreamer {
async fn establish_stream(
&self,
) -> Result<Pin<Box<dyn Stream<Item = Result<FuelBlockCommitedOnEth>> + '_ + Send>>> {
) -> Result<Pin<Box<dyn Stream<Item = Result<FuelBlockCommittedOnEth>> + '_ + Send>>> {
Ok(Box::pin(
self.events
.subscribe()
Expand All @@ -37,7 +37,7 @@ impl EventStreamer for EthEventStreamer {
.map_ok(|event| {
let fuel_block_hash = event.block_hash;
let commit_height = event.commit_height;
FuelBlockCommitedOnEth {
FuelBlockCommittedOnEth {
fuel_block_hash,
commit_height,
}
Expand Down
12 changes: 11 additions & 1 deletion src/adapters/fuel_adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,22 @@ use serde::{Deserialize, Serialize};

use crate::errors::Result;

#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
pub struct FuelBlock {
pub hash: [u8; 32],
pub height: u32,
}

impl std::fmt::Debug for FuelBlock {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let hash = self.hash.map(|byte| format!("{byte:02x?}")).join("");
f.debug_struct("FuelBlock")
.field("hash", &hash)
.field("height", &self.height)
.finish()
}
}

#[cfg_attr(test, mockall::automock)]
#[async_trait::async_trait]
pub trait FuelAdapter: Send + Sync {
Expand Down
54 changes: 34 additions & 20 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ use crate::{
errors::{Error, Result},
setup::config::Config,
};
const ETHEREUM_RPC: &str = "http://127.0.0.1:8545/";
const FUEL_GRAPHQL_ENDPOINT: &str = "https://127.0.0.1:4000";
const STATE_CONTRACT_ADDRESS: Address = Address::zero();

const ETHEREUM_RPC: &str = "ws://127.0.0.1:8545/";
const FUEL_GRAPHQL_ENDPOINT: &str = "http://127.0.0.1:4000";
const COMMIT_INTERVAL: u32 = 1;
const HOST: &str = "127.0.0.1";
const PORT: u16 = 8080;
Expand All @@ -34,27 +34,37 @@ struct Cli {
ethereum_wallet_key: String,

/// Ethereum RPC
#[arg(long,
env = "ETHEREUM_RPC",
default_value = ETHEREUM_RPC, value_name = "URL", help = "URL to a Ethereum RPC endpoint.")]
#[arg(
long,
env = "ETHEREUM_RPC",
default_value = ETHEREUM_RPC, value_name = "URL", help = "URL to a Ethereum RPC endpoint."
)]
ethereum_rpc: Url,

/// Fuel GraphQL endpoint
#[arg(long,
env = "FUEL_GRAPHQL_ENDPOINT",
default_value = FUEL_GRAPHQL_ENDPOINT, value_name = "URL", help = "URL to a fuel-core graphql endpoint.")]
#[arg(
long,
env = "FUEL_GRAPHQL_ENDPOINT",
default_value = FUEL_GRAPHQL_ENDPOINT, value_name = "URL", help = "URL to a fuel-core graphql endpoint."
)]
fuel_graphql_endpoint: Url,

/// State contract address
#[arg(long,
env = "STATE_CONTRACT_ADDRESS",
default_value_t = STATE_CONTRACT_ADDRESS, value_name = "BYTES20", help = "Ethereum address of the fuel chain state contract.")]
#[arg(
long,
env = "STATE_CONTRACT_ADDRESS",
value_name = "Address",
help = "Ethereum address of the fuel chain state contract."
)]
state_contract_address: Address,

/// Commit interval
#[arg(long,
env = "COMMIT_INTERVAL",
default_value_t = COMMIT_INTERVAL, value_name = "U32", help = "The number of fuel blocks between ethereum commits. If set to 1, then every block should be pushed to Ethereum.")]
#[arg(
long,
env = "COMMIT_INTERVAL",
default_value_t = COMMIT_INTERVAL, value_name = "U32", help = "The number of fuel \\
blocks between ethereum commits. If set to 1, then every block should be pushed to Ethereum."
)]
commit_interval: u32,

/// Host of the started API server
Expand All @@ -68,15 +78,19 @@ struct Cli {
host: Ipv4Addr,

/// Port of the started API server
#[arg(long,
env = "PORT",
default_value_t = PORT, value_name = "U16", help = "Port on which to start the API server.")]
#[arg(
long,
env = "PORT",
default_value_t = PORT, value_name = "U16", help = "Port on which to start the API server."
)]
port: u16,

/// Ethereum chain id
#[arg(long,
#[arg(
long,
env = "ETHEREUM_CHAIN",
default_value_t = CHAIN_NAME, value_name = "ChainName", help = "Chain id of the ethereum network.")]
default_value_t = CHAIN_NAME, value_name = "ChainName", help = "Chain id of the ethereum network."
)]
ethereum_chain: Chain,

#[arg(
Expand Down
13 changes: 13 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use actix_web::ResponseError;
use ethers::signers::WalletError;
use tokio::task::JoinError;
use url::ParseError;

#[derive(thiserror::Error, Debug)]
Expand Down Expand Up @@ -36,6 +37,18 @@ impl From<ParseError> for Error {
}
}

impl From<std::io::Error> for Error {
fn from(error: std::io::Error) -> Self {
Self::Other(error.to_string())
}
}

impl From<JoinError> for Error {
fn from(error: JoinError) -> Self {
Self::Other(error.to_string())
}
}

impl ResponseError for Error {}

pub type Result<T> = std::result::Result<T, Error>;
22 changes: 17 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,45 +12,50 @@ use prometheus::Registry;
use setup::{
config::InternalConfig,
helpers::{
create_eth_adapter, setup_logger, setup_storage, spawn_block_watcher,
create_eth_adapter, setup_logger, setup_storage, shut_down, spawn_block_watcher,
spawn_eth_committer_and_listener, spawn_wallet_balance_tracker,
},
};
use tokio_util::sync::CancellationToken;

#[tokio::main]
async fn main() -> Result<()> {
setup_logger();

let config = cli::parse()?;
let internal_config = InternalConfig::default();
let cancel_token = CancellationToken::new();

let storage = setup_storage(&config).await?;

let metrics_registry = Registry::default();

let (rx_fuel_block, _block_watcher_handle, fuel_health_check) = spawn_block_watcher(
let (rx_fuel_block, block_watcher_handle, fuel_health_check) = spawn_block_watcher(
&config,
&internal_config,
storage.clone(),
&metrics_registry,
cancel_token.clone(),
);

let (ethereum_rpc, eth_health_check) =
create_eth_adapter(&config, &internal_config, &metrics_registry).await?;

let _wallet_balance_tracker_handle = spawn_wallet_balance_tracker(
let wallet_balance_tracker_handle = spawn_wallet_balance_tracker(
&config,
&internal_config,
&metrics_registry,
ethereum_rpc.clone(),
cancel_token.clone(),
)?;

let (_committer_handle, _listener_handle) = spawn_eth_committer_and_listener(
let (committer_handle, listener_handle) = spawn_eth_committer_and_listener(
&internal_config,
rx_fuel_block,
ethereum_rpc,
storage.clone(),
&metrics_registry,
cancel_token.clone(),
)?;

launch_api_server(
Expand All @@ -62,5 +67,12 @@ async fn main() -> Result<()> {
)
.await?;

Ok(())
shut_down(
cancel_token,
block_watcher_handle,
wallet_balance_tracker_handle,
committer_handle,
listener_handle,
)
.await
}
4 changes: 3 additions & 1 deletion src/services/block_committer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,12 @@ impl Runner for BlockCommitter {
if let Err(error) = self.submit_block(fuel_block).await {
error!("{error}");
} else {
info!("Submitted fuel block! ({fuel_block:?})",);
info!("submitted {fuel_block:?}!");
}
}

info!("Block Committer stopped");

Ok(())
}
}
Expand Down
Loading
Loading