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

chore(starknet_gateway): create bench file for benchmark test #2404

Merged
merged 2 commits into from
Dec 29, 2024
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.lock

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

6 changes: 6 additions & 0 deletions crates/starknet_gateway/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ validator.workspace = true
[dev-dependencies]
assert_matches.workspace = true
cairo-lang-sierra-to-casm.workspace = true
criterion.workspace = true
mockall.workspace = true
mockito.workspace = true
num-bigint.workspace = true
Expand All @@ -49,3 +50,8 @@ rstest.workspace = true
starknet_mempool.workspace = true
starknet_mempool_types = { workspace = true, features = ["testing"] }
tracing-test.workspace = true

[[bench]]
harness = false
name = "gateway_bench"
path = "bench/gateway_bench.rs"
19 changes: 19 additions & 0 deletions crates/starknet_gateway/bench/gateway_bench.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//! Benchmark module for the starknet gateway crate. It provides functionalities to benchmark
//! the performance of the gateway service, including declare, deploy account and invoke
//! transactions.
//!
//! There are four benchmark functions in this flow: `declare_benchmark`,
//! `deploy_account_benchmark`, `invoke_benchmark` and `gateway_benchmark` which combines all of the
//! types. Each of the functions measure the performance of the gateway handling randomly created
//! txs of the respective type.
//!
//! Run the benchmarks using `cargo bench --bench gateway_bench`.

use criterion::{criterion_group, criterion_main, Criterion};

fn invoke_benchmark(criterion: &mut Criterion) {
criterion.bench_function("invokes", |benchmark| benchmark.iter(|| {}));
}

criterion_group!(benches, invoke_benchmark);
criterion_main!(benches);
58 changes: 36 additions & 22 deletions crates/starknet_gateway/src/gateway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,25 +26,21 @@ use crate::utils::compile_contract_and_build_executable_tx;
#[path = "gateway_test.rs"]
pub mod gateway_test;

pub struct Gateway {
pub config: GatewayConfig,
struct GatewayBusinessLogic {
pub stateless_tx_validator: Arc<StatelessTransactionValidator>,
pub stateful_tx_validator: Arc<StatefulTransactionValidator>,
pub state_reader_factory: Arc<dyn StateReaderFactory>,
pub gateway_compiler: Arc<GatewayCompiler>,
pub mempool_client: SharedMempoolClient,
pub chain_info: ChainInfo,
}

impl Gateway {
impl GatewayBusinessLogic {
pub fn new(
config: GatewayConfig,
state_reader_factory: Arc<dyn StateReaderFactory>,
gateway_compiler: GatewayCompiler,
mempool_client: SharedMempoolClient,
) -> Self {
Self {
config: config.clone(),
stateless_tx_validator: Arc::new(StatelessTransactionValidator {
config: config.stateless_tx_validator_config.clone(),
}),
Expand All @@ -53,31 +49,49 @@ impl Gateway {
}),
state_reader_factory,
gateway_compiler: Arc::new(gateway_compiler),
mempool_client,
chain_info: config.chain_info.clone(),
}
}

pub async fn add_tx(&self, tx: RpcTransaction) -> GatewayResult<AddTransactionArgs> {
info!("Processing tx");
let blocking_task = ProcessTxBlockingTask::new(self, tx);
// Run the blocking task in the current span.
let curr_span = Span::current();
tokio::task::spawn_blocking(move || curr_span.in_scope(|| blocking_task.process_tx()))
.await
.map_err(|join_err| {
error!("Failed to process tx: {}", join_err);
GatewaySpecError::UnexpectedError { data: "Internal server error".to_owned() }
})?
}
}

pub struct Gateway {
pub mempool_client: SharedMempoolClient,
business_logic: GatewayBusinessLogic,
}

impl Gateway {
pub fn new(
config: GatewayConfig,
state_reader_factory: Arc<dyn StateReaderFactory>,
gateway_compiler: GatewayCompiler,
mempool_client: SharedMempoolClient,
) -> Self {
let business_logic =
GatewayBusinessLogic::new(config, state_reader_factory, gateway_compiler);
Self { business_logic, mempool_client }
}

#[instrument(skip(self), ret)]
pub async fn add_tx(
&self,
tx: RpcTransaction,
p2p_message_metadata: Option<BroadcastedMessageMetadata>,
) -> GatewayResult<TransactionHash> {
info!("Processing tx");
let blocking_task = ProcessTxBlockingTask::new(self, tx);
// Run the blocking task in the current span.
let curr_span = Span::current();
let add_tx_args =
tokio::task::spawn_blocking(move || curr_span.in_scope(|| blocking_task.process_tx()))
.await
.map_err(|join_err| {
error!("Failed to process tx: {}", join_err);
GatewaySpecError::UnexpectedError { data: "Internal server error".to_owned() }
})??;

let add_tx_args = self.business_logic.add_tx(tx).await?;
let tx_hash = add_tx_args.tx.tx_hash();

let add_tx_args = AddTransactionArgsWrapper { args: add_tx_args, p2p_message_metadata };
self.mempool_client.add_tx(add_tx_args).await.map_err(|e| {
error!("Failed to send tx to mempool: {}", e);
Expand All @@ -100,7 +114,7 @@ struct ProcessTxBlockingTask {
}

impl ProcessTxBlockingTask {
pub fn new(gateway: &Gateway, tx: RpcTransaction) -> Self {
pub fn new(gateway: &GatewayBusinessLogic, tx: RpcTransaction) -> Self {
Self {
stateless_tx_validator: gateway.stateless_tx_validator.clone(),
stateful_tx_validator: gateway.stateful_tx_validator.clone(),
Expand All @@ -123,7 +137,7 @@ impl ProcessTxBlockingTask {
&self.chain_info.chain_id,
)?;

// Perfom post compilation validations.
// Perform post compilation validations.
if let AccountTransaction::Declare(executable_declare_tx) = &executable_tx {
if !executable_declare_tx.validate_compiled_class_hash() {
return Err(GatewaySpecError::CompiledClassHashMismatch);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ fn test_instantiate_validator(stateful_validator: StatefulTransactionValidator)

let mut mock_state_reader_factory = MockStateReaderFactory::new();

// Make sure stateful_validator uses the latest block in the initiall call.
// Make sure stateful_validator uses the latest block in the initial call.
let latest_state_reader = state_reader_factory.get_state_reader_from_latest_block();
mock_state_reader_factory
.expect_get_state_reader_from_latest_block()
Expand Down
Loading