diff --git a/src/prom.rs b/src/prom.rs index 585fba8..c24549e 100644 --- a/src/prom.rs +++ b/src/prom.rs @@ -41,33 +41,44 @@ struct MatrixEntry { values: Vec<(f64, String)>, } -pub fn current_power(base: &str) -> Result<(f64, f64, f64)> { - let url = format!("{}{}", base, PROM_QUERY); +pub struct PromClient { + base: String, + power_query_url: String +} - let reply: PromReply = ureq::get(&url).call()?.into_json()?; - - 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"), - } +impl PromClient { + pub fn new(base: String) -> Self { + let power_query_url = format!("{}{}", &base, PROM_QUERY); + PromClient { base, power_query_url } } - 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"))?, - )) + pub fn current_power(&self) -> Result<(f64, f64, f64)> { + let reply: PromReply = ureq::get(&self.power_query_url).call()?.into_json()?; + + 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"))?, + )) +} + }