Skip to content

Commit

Permalink
feat(sozo): provider health check (#2745)
Browse files Browse the repository at this point in the history
* [ISSUES#] 2739 sozo health check.

* [ISSUES#] 2739 provider health check for sozo.

* [ISSUES#] 2739 provider health check for sozo.

* [ISSUES#] 2739 provider health check for sozo fmt.

* fix: new utils provider module and minor fixes

---------

Co-authored-by: glihm <[email protected]>
  • Loading branch information
847850277 and glihm authored Dec 9, 2024
1 parent bd04c6b commit 0d29ae3
Show file tree
Hide file tree
Showing 8 changed files with 55 additions and 29 deletions.
15 changes: 12 additions & 3 deletions bin/sozo/src/commands/migrate.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use anyhow::{Context, Result};
use std::sync::Arc;

use anyhow::{anyhow, Context, Result};
use clap::Args;
use colored::*;
use dojo_utils::{self, TxnConfig};
use dojo_utils::{self, provider as provider_utils, TxnConfig};
use dojo_world::contracts::WorldContract;
use dojo_world::services::IpfsService;
use scarb::core::{Config, Workspace};
Expand All @@ -12,13 +14,14 @@ use starknet::core::utils::parse_cairo_short_string;
use starknet::providers::Provider;
use tabled::settings::Style;
use tabled::{Table, Tabled};
use tracing::trace;
use tracing::{error, trace};

use super::options::account::AccountOptions;
use super::options::ipfs::IpfsOptions;
use super::options::starknet::StarknetOptions;
use super::options::transaction::TransactionOptions;
use super::options::world::WorldOptions;
use crate::commands::LOG_TARGET;
use crate::utils;

#[derive(Debug, Clone, Args)]
Expand Down Expand Up @@ -141,6 +144,12 @@ async fn print_banner(ws: &Workspace<'_>, starknet: &StarknetOptions) -> Result<
let profile_config = ws.load_profile_config()?;
let (provider, rpc_url) = starknet.provider(profile_config.env.as_ref())?;

let provider = Arc::new(provider);
if let Err(e) = provider_utils::health_check_provider(provider.clone()).await {
error!(target: LOG_TARGET,"Provider health check failed during sozo migrate.");
return Err(e);
}
let provider = Arc::try_unwrap(provider).map_err(|_| anyhow!("Failed to unwrap Arc"))?;
let chain_id = provider.chain_id().await?;
let chain_id =
parse_cairo_short_string(&chain_id).with_context(|| "Cannot parse chain_id as string")?;
Expand Down
2 changes: 2 additions & 0 deletions bin/sozo/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ use migrate::MigrateArgs;
use model::ModelArgs;
use test::TestArgs;

pub(crate) const LOG_TARGET: &str = "sozo::cli";

#[derive(Debug, Subcommand)]
pub enum Commands {
#[command(about = "Grant or revoke a contract permission to write to a resource")]
Expand Down
11 changes: 10 additions & 1 deletion bin/sozo/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use std::collections::HashMap;
use std::io::{self, Write};
use std::str::FromStr;
use std::sync::Arc;

use anyhow::{anyhow, Context, Result};
use camino::Utf8PathBuf;
use colored::*;
use dojo_utils::provider as provider_utils;
use dojo_world::config::ProfileConfig;
use dojo_world::contracts::ContractInfo;
use dojo_world::diff::WorldDiff;
Expand All @@ -19,11 +21,12 @@ use starknet::core::types::Felt;
use starknet::core::utils as snutils;
use starknet::providers::jsonrpc::HttpTransport;
use starknet::providers::{JsonRpcClient, Provider};
use tracing::trace;
use tracing::{error, trace};

use crate::commands::options::account::{AccountOptions, SozoAccount};
use crate::commands::options::starknet::StarknetOptions;
use crate::commands::options::world::WorldOptions;
use crate::commands::LOG_TARGET;

/// Computes the world address based on the provided options.
pub fn get_world_address(
Expand Down Expand Up @@ -113,6 +116,12 @@ pub async fn get_world_diff_and_provider(
let world_address = get_world_address(&profile_config, &world, &world_local)?;

let (provider, rpc_url) = starknet.provider(env)?;
let provider = Arc::new(provider);
if let Err(e) = provider_utils::health_check_provider(provider.clone()).await {
error!(target: LOG_TARGET,"Provider health check failed during sozo inspect.");
return Err(e);
}
let provider = Arc::try_unwrap(provider).map_err(|_| anyhow!("Failed to unwrap Arc"))?;
trace!(?provider, "Provider initialized.");

let spec_version = provider.spec_version().await?;
Expand Down
2 changes: 1 addition & 1 deletion crates/dojo/utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ pub use tx::*;

pub mod env;
pub mod keystore;

pub mod provider;
pub mod signal;
26 changes: 26 additions & 0 deletions crates/dojo/utils/src/provider.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
use starknet::core::types::{BlockId, BlockTag};
use starknet::providers::Provider;
use tracing::trace;

/// Check if the provider is healthy.
///
/// This function will check if the provider is healthy by getting the latest block,
/// and returns an error otherwise.
pub async fn health_check_provider<P: Provider + Sync + std::fmt::Debug + 'static>(
provider: P,
) -> anyhow::Result<(), anyhow::Error> {
match provider.get_block_with_tx_hashes(BlockId::Tag(BlockTag::Latest)).await {
Ok(block) => {
trace!(
latest_block = ?block,
"Provider health check."
);
Ok(())
}
Err(_) => {
let error_info =
format!("Unhealthy provider {:?}, please check your configuration.", provider);
Err(anyhow::anyhow!(error_info))
}
}
}
1 change: 1 addition & 0 deletions crates/torii/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ chrono.workspace = true
crypto-bigint.workspace = true
data-url.workspace = true
dojo-types.workspace = true
dojo-utils.workspace = true
dojo-world.workspace = true
futures-channel = "0.3.0"
futures-util.workspace = true
Expand Down
4 changes: 2 additions & 2 deletions crates/torii/core/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::time::Duration;

use anyhow::Result;
use bitflags::bitflags;
use dojo_utils::provider as provider_utils;
use dojo_world::contracts::world::WorldContractReader;
use futures_util::future::{join_all, try_join_all};
use hashlink::LinkedHashMap;
Expand Down Expand Up @@ -45,7 +46,6 @@ use crate::processors::{
};
use crate::sql::{Cursors, Sql};
use crate::types::{Contract, ContractType};
use crate::utils::health_check_provider;

type EventProcessorMap<P> = HashMap<Felt, Vec<Box<dyn EventProcessor<P>>>>;

Expand Down Expand Up @@ -253,7 +253,7 @@ impl<P: Provider + Send + Sync + std::fmt::Debug + 'static> Engine<P> {
}

pub async fn start(&mut self) -> Result<()> {
if let Err(e) = health_check_provider(self.provider.clone()).await {
if let Err(e) = provider_utils::health_check_provider(self.provider.clone()).await {
error!(target: LOG_TARGET,"Provider health check failed during engine start");
return Err(e);
}
Expand Down
23 changes: 1 addition & 22 deletions crates/torii/core/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@ use anyhow::Result;
use chrono::{DateTime, Utc};
use futures_util::TryStreamExt;
use ipfs_api_backend_hyper::{IpfsApi, IpfsClient, TryFromUri};
use starknet::core::types::{BlockId, BlockTag};
use starknet::providers::Provider;
use tokio_util::bytes::Bytes;
use tracing::{info, trace};
use tracing::info;

use crate::constants::{
IPFS_CLIENT_MAX_RETRY, IPFS_CLIENT_PASSWORD, IPFS_CLIENT_URL, IPFS_CLIENT_USERNAME,
Expand Down Expand Up @@ -48,25 +46,6 @@ pub async fn fetch_content_from_ipfs(cid: &str, mut retries: u8) -> Result<Bytes
)))
}

pub async fn health_check_provider<P: Provider + Sync + std::fmt::Debug + 'static>(
provider: P,
) -> Result<(), anyhow::Error> {
match provider.get_block_with_tx_hashes(BlockId::Tag(BlockTag::Latest)).await {
Ok(block) => {
trace!(
latest_block = ?block,
"Provider health check."
);
Ok(())
}
Err(_) => {
let error_info =
format!("Unhealthy provider {:?}, please check your configuration.", provider);
Err(anyhow::anyhow!(error_info))
}
}
}

// tests
#[cfg(test)]
mod tests {
Expand Down

0 comments on commit 0d29ae3

Please sign in to comment.