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(infra_utils): add parse_numeric_metric #2881

Merged
merged 1 commit 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
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
}
Loading