Refactor prom client

This commit is contained in:
Maxime Augier 2024-08-18 14:36:17 +02:00
parent 8e698e71c1
commit 769544b608

View File

@ -41,33 +41,44 @@ struct MatrixEntry {
values: Vec<(f64, String)>, values: Vec<(f64, String)>,
} }
pub fn current_power(base: &str) -> Result<(f64, f64, f64)> { pub struct PromClient {
let url = format!("{}{}", base, PROM_QUERY); base: String,
power_query_url: String
}
let reply: PromReply = ureq::get(&url).call()?.into_json()?; impl PromClient {
pub fn new(base: String) -> Self {
let PromReply::Success { let power_query_url = format!("{}{}", &base, PROM_QUERY);
data: PromData::Vector(v), PromClient { base, power_query_url }
} = reply
else {
bail!("Could not understand Prometheus reply: {:?}", reply)
};
let mut r = (None, None, None);
for entry in &v {
let val: f64 = entry.value.1.parse()?;
match entry.metric.get("phase").map(|s| &**s) {
Some("a") => r.0 = Some(val),
Some("b") => r.1 = Some(val),
Some("c") => r.2 = Some(val),
_ => warn!("Metric with unexpected phase"),
}
} }
Ok(( pub fn current_power(&self) -> Result<(f64, f64, f64)> {
r.0.ok_or_else(|| anyhow!("Missing phase a"))?, let reply: PromReply = ureq::get(&self.power_query_url).call()?.into_json()?;
r.1.ok_or_else(|| anyhow!("Missing phase b"))?,
r.2.ok_or_else(|| anyhow!("Missing phase c"))?, let PromReply::Success {
)) data: PromData::Vector(v),
} = reply
else {
bail!("Could not understand Prometheus reply: {:?}", reply)
};
let mut r = (None, None, None);
for entry in &v {
let val: f64 = entry.value.1.parse()?;
match entry.metric.get("phase").map(|s| &**s) {
Some("a") => r.0 = Some(val),
Some("b") => r.1 = Some(val),
Some("c") => r.2 = Some(val),
_ => warn!("Metric with unexpected phase"),
}
}
Ok((
r.0.ok_or_else(|| anyhow!("Missing phase a"))?,
r.1.ok_or_else(|| anyhow!("Missing phase b"))?,
r.2.ok_or_else(|| anyhow!("Missing phase c"))?,
))
}
} }