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_http_server): add metrics for added txs #2915

Merged
merged 2 commits into from
Dec 24, 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
3 changes: 3 additions & 0 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions crates/infra_utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ description = "Infrastructure utility."
workspace = true

[dependencies]
num-traits.workspace = true
regex.workspace = true
tokio = { workspace = true, features = ["process", "time"] }
tracing.workspace = true

Expand Down
1 change: 1 addition & 0 deletions crates/infra_utils/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod command;
pub mod metrics;
pub mod path;
pub mod run_until;
pub mod tracing;
Expand Down
41 changes: 41 additions & 0 deletions crates/infra_utils/src/metrics.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use std::str::FromStr;

use num_traits::Num;
use regex::{escape, Regex};

/// Parses a specific numeric metric value from a metrics string.
///
/// # Arguments
///
/// - `metrics_as_string`: A string containing the renders metrics data.
/// - `metric_name`: The name of the metric to search for.
///
/// # Type Parameters
///
/// - `T`: The numeric type to which the metric value will be parsed. The type must implement the
/// `Num` and `FromStr` traits, allowing it to represent numeric values and be parsed from a
/// string. Common types include `i32`, `u64`, and `f64`.
///
/// # Returns
///
/// - `Option<T>`: Returns `Some(T)` if the metric is found and successfully parsed into the
/// specified numeric type `T`. Returns `None` if the metric is not found or if parsing fails.
pub fn parse_numeric_metric<T: Num + FromStr>(
metrics_as_string: &str,
metric_name: &str,
) -> Option<T> {
// Create a regex to match "metric_name <number>".
let pattern = format!(r"{}\s+(\d+)", escape(metric_name));
let re = Regex::new(&pattern).expect("Invalid regex");

// Search for the pattern in the output.
if let Some(captures) = re.captures(metrics_as_string) {
// Extract the numeric value.
if let Some(value) = captures.get(1) {
// Parse the string into a number.
return value.as_str().parse().ok();
}
}
// If no match is found, return None.
None
}
1 change: 1 addition & 0 deletions crates/starknet_http_server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ workspace = true
axum.workspace = true
hyper.workspace = true
infra_utils.workspace = true
metrics.workspace = true
papyrus_config.workspace = true
reqwest = { workspace = true, optional = true }
serde.workspace = true
Expand Down
8 changes: 7 additions & 1 deletion crates/starknet_http_server/src/http_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use tracing::{error, info, instrument};

use crate::config::HttpServerConfig;
use crate::errors::HttpServerRunError;
use crate::metrics::{init_metrics, record_added_transaction, record_added_transaction_status};

#[cfg(test)]
#[path = "http_server_test.rs"]
Expand All @@ -36,6 +37,7 @@ pub struct AppState {
impl HttpServer {
pub fn new(config: HttpServerConfig, gateway_client: SharedGatewayClient) -> Self {
let app_state = AppState { gateway_client };
init_metrics();
HttpServer { config, app_state }
}

Expand All @@ -55,19 +57,23 @@ impl HttpServer {
}
}

// TODO(Tsabary): add a test for the module metrics.

// HttpServer handlers.

#[instrument(skip(app_state))]
async fn add_tx(
State(app_state): State<AppState>,
Json(tx): Json<RpcTransaction>,
) -> HttpServerResult<Json<TransactionHash>> {
let gateway_input: GatewayInput = GatewayInput { rpc_tx: tx.clone(), message_metadata: None };
record_added_transaction();
let gateway_input: GatewayInput = GatewayInput { rpc_tx: tx, message_metadata: None };

let add_tx_result = app_state.gateway_client.add_tx(gateway_input).await.map_err(|join_err| {
error!("Failed to process tx: {}", join_err);
GatewaySpecError::UnexpectedError { data: "Internal server error".to_owned() }
});
record_added_transaction_status(add_tx_result.is_ok());

add_tx_result_as_json(add_tx_result)
}
Expand Down
1 change: 1 addition & 0 deletions crates/starknet_http_server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@ pub mod communication;
pub mod config;
pub mod errors;
pub mod http_server;
mod metrics;
#[cfg(feature = "testing")]
pub mod test_utils;
36 changes: 36 additions & 0 deletions crates/starknet_http_server/src/metrics.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
use metrics::{absolute_counter, describe_counter, register_counter};
use tracing::info;

const ADDED_TRANSACTIONS_TOTAL: (&str, &str, u64) =
("ADDED_TRANSACTIONS_TOTAL", "Total number of transactions added", 0);
const ADDED_TRANSACTIONS_SUCCESS: (&str, &str, u64) =
("ADDED_TRANSACTIONS_SUCCESS", "Number of successfully added transactions", 0);
const ADDED_TRANSACTIONS_FAILURE: (&str, &str, u64) =
("ADDED_TRANSACTIONS_FAILURE", "Number of faulty added transactions", 0);

pub(crate) fn init_metrics() {
info!("Initializing HTTP Server metrics");
register_counter!(ADDED_TRANSACTIONS_TOTAL.0);
describe_counter!(ADDED_TRANSACTIONS_TOTAL.0, ADDED_TRANSACTIONS_TOTAL.1);
absolute_counter!(ADDED_TRANSACTIONS_TOTAL.0, ADDED_TRANSACTIONS_TOTAL.2);

register_counter!(ADDED_TRANSACTIONS_SUCCESS.0);
describe_counter!(ADDED_TRANSACTIONS_SUCCESS.0, ADDED_TRANSACTIONS_SUCCESS.1);
absolute_counter!(ADDED_TRANSACTIONS_SUCCESS.0, ADDED_TRANSACTIONS_SUCCESS.2);

register_counter!(ADDED_TRANSACTIONS_FAILURE.0);
describe_counter!(ADDED_TRANSACTIONS_FAILURE.0, ADDED_TRANSACTIONS_FAILURE.1);
absolute_counter!(ADDED_TRANSACTIONS_FAILURE.0, ADDED_TRANSACTIONS_FAILURE.2);
}

pub(crate) fn record_added_transaction() {
metrics::increment_counter!(ADDED_TRANSACTIONS_TOTAL.0);
}

pub(crate) fn record_added_transaction_status(add_tx_success: bool) {
if add_tx_success {
metrics::increment_counter!(ADDED_TRANSACTIONS_SUCCESS.0);
} else {
metrics::increment_counter!(ADDED_TRANSACTIONS_FAILURE.0);
}
}
Loading