Skip to content

Commit

Permalink
chore(infra_utils): add parse_numeric_metric
Browse files Browse the repository at this point in the history
commit-id:e1f0b265
  • Loading branch information
Itay-Tsabary-Starkware committed Dec 24, 2024
1 parent 701a020 commit a99ca46
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 0 deletions.
2 changes: 2 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
}

0 comments on commit a99ca46

Please sign in to comment.