|
| 1 | +// License: MIT |
| 2 | +// Copyright © 2025 Frequenz Energy-as-a-Service GmbH |
| 3 | + |
| 4 | +//! This module contains the methods for generating `COALESCE` formulas for |
| 5 | +//! measuring metrics from individual components, with fallback to other |
| 6 | +//! components. |
| 7 | +
|
| 8 | +use std::collections::BTreeSet; |
| 9 | + |
| 10 | +use crate::{graph::formulas::expr::Expr, ComponentGraph, Edge, Error, Node}; |
| 11 | + |
| 12 | +pub(crate) struct CoalesceFormulaBuilder { |
| 13 | + component_ids: BTreeSet<u64>, |
| 14 | +} |
| 15 | + |
| 16 | +impl CoalesceFormulaBuilder { |
| 17 | + pub fn try_new( |
| 18 | + graph: &ComponentGraph<impl Node, impl Edge>, |
| 19 | + component_ids: BTreeSet<u64>, |
| 20 | + ) -> Result<Self, Error> { |
| 21 | + if component_ids.is_empty() { |
| 22 | + return Err(Error::missing_parameters("No component IDs specified.")); |
| 23 | + } |
| 24 | + for component_id in &component_ids { |
| 25 | + if graph.component(*component_id).is_err() { |
| 26 | + return Err(Error::component_not_found(format!( |
| 27 | + "Component with ID {} not found in the graph.", |
| 28 | + component_id |
| 29 | + ))); |
| 30 | + } |
| 31 | + } |
| 32 | + Ok(Self { component_ids }) |
| 33 | + } |
| 34 | + |
| 35 | + /// Generates a formula that uses the `COALESCE` function to return the first |
| 36 | + /// non-null value from the provided component IDs. |
| 37 | + pub fn build(self) -> Result<String, Error> { |
| 38 | + let expr = Expr::coalesce( |
| 39 | + self.component_ids |
| 40 | + .into_iter() |
| 41 | + .map(|component_id| Expr::Component { component_id }) |
| 42 | + .collect(), |
| 43 | + ); |
| 44 | + Ok(expr.to_string()) |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +#[cfg(test)] |
| 49 | +mod tests { |
| 50 | + use super::*; |
| 51 | + use crate::graph::test_utils::ComponentGraphBuilder; |
| 52 | + |
| 53 | + #[test] |
| 54 | + fn test_coalesce_formula() -> Result<(), Error> { |
| 55 | + let mut builder = ComponentGraphBuilder::new(); |
| 56 | + let grid = builder.grid(); |
| 57 | + |
| 58 | + // Add a grid meter and a battery chain behind it. |
| 59 | + let grid_meter_1 = builder.meter(); |
| 60 | + builder.connect(grid, grid_meter_1); |
| 61 | + let grid_meter_2 = builder.meter(); |
| 62 | + builder.connect(grid, grid_meter_2); |
| 63 | + |
| 64 | + let graph = builder.build(None)?; |
| 65 | + let formula = graph.coalesce(BTreeSet::from([1, 2]))?; |
| 66 | + assert_eq!(formula, "COALESCE(#1, #2)"); |
| 67 | + let formula = graph.coalesce(BTreeSet::from([1]))?; |
| 68 | + assert_eq!(formula, "COALESCE(#1)"); |
| 69 | + let formula = graph.coalesce(BTreeSet::from([])); |
| 70 | + assert_eq!( |
| 71 | + formula, |
| 72 | + Err(Error::missing_parameters("No component IDs specified.")) |
| 73 | + ); |
| 74 | + |
| 75 | + Ok(()) |
| 76 | + } |
| 77 | +} |
0 commit comments