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

feat(combinator): displayExpression with prefix notation #21

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
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
117 changes: 117 additions & 0 deletions src/combinator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
#include <fmt/format.h>

#include <numeric>
#include <stdexcept>
#include <unordered_set>

using Log = metricq::logger::nitro::Log;

Expand All @@ -49,6 +51,112 @@ Combinator::~Combinator()
{
}

std::string handleBasicExpression(const nlohmann::json& expression)
{
if (expression.is_number())
{
auto value = expression.get<double>();
return (value == static_cast<int>(value)) ? std::to_string(static_cast<int>(value)) :
std::to_string(value);
}

if (expression.is_string())
{
return expression.get<std::string>();
}

throw std::runtime_error("Expression is not a basic type (number or string)!");
}

std::string handleOperatorExpression(const std::string& operation, const std::string& leftStr,
const std::string& rightStr)
{
if (operation.size() > 1)
{
throw std::logic_error("Invalid operator length!");
}

switch (operation[0])
{
case '+':
case '-':
case '*':
case '/':
return "(" + leftStr + " " + operation + " " + rightStr + ")";
default:
throw std::runtime_error("Invalid operator: " + operation);
}
}

std::string handleCombinationExpression(const std::string& operation,
const std::vector<std::string>& inputs)
{
static const std::unordered_set<std::string> validAggregates = { "sum", "min", "max" };

if (validAggregates.find(operation) == validAggregates.end())
{
throw std::runtime_error("Invalid aggregate operation: " + operation);
}

if (inputs.empty())
{
throw std::logic_error("Aggregate operation missing inputs!");
}

auto input = std::accumulate(std::next(inputs.begin()), inputs.end(), inputs[0],
[](std::string a, const std::string& b) { return a + ", " + b; });

return operation + "[" + input + "]";
}

std::string Combinator::displayExpression(const nlohmann::json& expression)
{
if (expression.is_number() || expression.is_string())
{
return handleBasicExpression(expression);
}

if (!expression.is_object() || !expression.contains("operation"))
{
throw std::runtime_error("Unknown expression format!");
}

std::string operation = expression.value("operation", "");

if (operation == "throttle")
{
if (!expression.contains("input"))
{
throw std::logic_error("Throttle does not contain a input");
}
return handleBasicExpression(expression["input"]);
}

if (expression.contains("left") && expression.contains("right"))
{
std::string leftStr = displayExpression(expression["left"]);
std::string rightStr = displayExpression(expression["right"]);
return handleOperatorExpression(operation, leftStr, rightStr);
}

if (expression.contains("inputs"))
{
if (!expression["inputs"].is_array())
{
throw std::logic_error("Inputs must be an array!");
}

std::vector<std::string> inputStrings;
for (const auto& input : expression["inputs"])
{
inputStrings.push_back(displayExpression(input));
}
return handleCombinationExpression(operation, inputStrings);
}

throw std::runtime_error("Unsupported operation type: " + operation);
}

void Combinator::on_transformer_config(const metricq::json& config)
{
input_metrics.clear();
Expand Down Expand Up @@ -93,6 +201,15 @@ void Combinator::on_transformer_config(const metricq::json& config)
// Register the combined metric as a new source metric
auto& metric = (*this)[combined_name];

try
{
metric.metadata["displayExpression"] = displayExpression(combined_expression);
}
catch (std::runtime_error&)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
catch (std::runtime_error&)
catch (const std::runtime_error&)

{
Log::error("Failed to create the Display Expression");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add context to the error message.

  • what is the affected metric?
  • what is the error message of the runtime error?

}

if (combined_config.count("chunk_size"))
{
auto chunk_size = combined_config["chunk_size"].get<int>();
Expand Down
1 change: 1 addition & 0 deletions src/combinator.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ class Combinator : public metricq::Transformer
public:
Combinator(const std::string& manager_host, const std::string& token);
~Combinator();
static std::string displayExpression(const nlohmann::json& expression);

private:
void on_transformer_config(const metricq::json& config) override;
Expand Down
14 changes: 7 additions & 7 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
add_executable(metricq-combinator.test_single_derivation test_single_derivation.cpp)
add_test(metricq-combinator.test_single_derivation metricq-combinator.test_single_derivation)
macro(add_test_case test_name)
add_executable(${test_name} ${test_name}.cpp)
add_test(${test_name} ${test_name})
target_link_libraries(${test_name} PRIVATE metricq-combinator-lib)
endmacro()

target_link_libraries(
metricq-combinator.test_single_derivation
PRIVATE
metricq-combinator-lib
)
add_test_case(test_single_derivation)
add_test_case(test_display_expression)
71 changes: 71 additions & 0 deletions tests/test_display_expression.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
#include "../src/combinator.hpp"
#include <iostream>
#include <metricq/json.hpp>

struct TestDisplayExpression
{
nlohmann::json input;
std::string expected;
};

int main()
{
try
{
std::vector<TestDisplayExpression> testCases;

testCases.emplace_back(TestDisplayExpression{
{ { "expression",
{ { "operation", "*" },
{ "left", 5 },
{ "right", { { "operation", "-" }, { "left", 45 }, { "right", 3 } } } } } },
"(5 * (45 - 3))" });

testCases.emplace_back(TestDisplayExpression{
{ { "expression",
{ { "operation", "*" },
{ "left", { { "operation", "+" }, { "left", 1 }, { "right", 2 } } },
{ "right",
{ { "operation", "-" }, { "left", 10 }, { "right", "dummy.source" } } } } } },
"((1 + 2) * (10 - dummy.source))" });

testCases.emplace_back(TestDisplayExpression{
{ { "expression",
{ { "operation", "-" },
{ "left",
{ { "operation", "+" },
{ "left", 15.3 },
{ "right", { { "operation", "min" }, { "inputs", { 42, 24, 8, 12 } } } } } },
{ "right",
{ { "operation", "throttle" },
{ "cooldown_period", "42" },
{ "input", 8 } } } } } },
"((15.300000 + min[42, 24, 8, 12]) - 8)" });

// Test the cases
for (const auto& testCase : testCases)
{

auto expression = testCase.input["expression"];
std::string result = Combinator::displayExpression(expression);

// Compare with expected result
if (result != testCase.expected) // comparing with the expected output
{
std::cerr << "Test case " << testCase.input << " failed:\n";
std::cerr << "Expected: " << testCase.expected << "\n";
std::cerr << "Got: " << result << "\n";
return 1;
}
}

std::cout << "All test cases passed successfully!" << std::endl;
}
catch (const std::exception& e)
{
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}

return 0;
}
Loading