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_monitoring_endpoint): add metric test utils #2884

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.

4 changes: 3 additions & 1 deletion crates/starknet_monitoring_endpoint/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ repository.workspace = true
license-file.workspace = true

[features]
testing = ["tokio", "tower"]
testing = ["num-traits", "thiserror", "tokio", "tower"]

[lints]
workspace = true
Expand All @@ -16,9 +16,11 @@ axum.workspace = true
hyper = { workspace = true }
infra_utils.workspace = true
metrics-exporter-prometheus.workspace = true
num-traits = { workspace = true, optional = true }
papyrus_config.workspace = true
serde.workspace = true
starknet_sequencer_infra.workspace = true
thiserror = { workspace = true, optional = true }
tokio = { workspace = true, optional = true }
tower = { workspace = true, optional = true }
tracing.workspace = true
Expand Down
49 changes: 48 additions & 1 deletion crates/starknet_monitoring_endpoint/src/test_utils.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,31 @@
use std::net::{IpAddr, SocketAddr};
use std::str::FromStr;

use axum::body::Body;
use axum::http::Request;
use hyper::body::to_bytes;
use hyper::client::HttpConnector;
use hyper::Client;
use infra_utils::metrics::parse_numeric_metric;
use infra_utils::run_until::run_until;
use infra_utils::tracing::{CustomLogger, TraceLevel};
use num_traits::Num;
use thiserror::Error;
use tracing::info;

use crate::monitoring_endpoint::{ALIVE, MONITORING_PREFIX};
use crate::monitoring_endpoint::{ALIVE, METRICS, MONITORING_PREFIX};

// TODO(Tsabary): rename IsAliveClient to MonitoringClient.

#[derive(Clone, Debug, Error, PartialEq, Eq)]
pub enum MonitoringClientError {
#[error("Failed to connect, error details: {}", connection_error)]
ConnectionError { connection_error: String },
#[error("Erroneous status: {}", status)]
ResponseStatusError { status: String },
#[error("Missing metric name: {}", metric_name)]
MetricNotFound { metric_name: String },
}

/// Client for querying 'alive' status of an http server.
pub struct IsAliveClient {
Expand Down Expand Up @@ -46,8 +63,38 @@ impl IsAliveClient {
.ok_or(())
.map(|_| ())
}

pub async fn get_metric<T: Num + FromStr>(
&self,
metric_name: &str,
) -> Result<T, MonitoringClientError> {
// Query the server for metrics.
let response = self
.client
.request(build_request(&self.socket.ip(), self.socket.port(), METRICS))
.await
.map_err(|err| MonitoringClientError::ConnectionError {
connection_error: err.to_string(),
})?;

// Check response status.
if !response.status().is_success() {
return Err(MonitoringClientError::ResponseStatusError {
status: format!("{:?}", response.status()),
});
}

// Parse the response body.
let body_bytes = to_bytes(response.into_body()).await.unwrap();
let body_string = String::from_utf8(body_bytes.to_vec()).unwrap();

// Extract and return the metric value, or a suitable error.
parse_numeric_metric::<T>(&body_string, metric_name)
.ok_or(MonitoringClientError::MetricNotFound { metric_name: metric_name.to_string() })
}
}

// TODO(Tsabary): use socket instead of ip and port.
pub(crate) fn build_request(ip: &IpAddr, port: u16, method: &str) -> Request<Body> {
Request::builder()
.uri(format!("http://{ip}:{port}/{MONITORING_PREFIX}/{method}").as_str())
Expand Down
Loading