szaszm commented on code in PR #1703:
URL: https://github.com/apache/nifi-minifi-cpp/pull/1703#discussion_r1414719168


##########
extensions/standard-processors/processors/AttributeRollingWindow.cpp:
##########
@@ -0,0 +1,122 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "AttributeRollingWindow.h"
+#include <algorithm>
+#include <numeric>
+#include "fmt/format.h"
+#include "core/ProcessContext.h"
+#include "core/ProcessSession.h"
+#include "core/Resource.h"
+#include "utils/expected.h"
+#include "utils/OptionalUtils.h"
+
+namespace org::apache::nifi::minifi::processors {
+
+void AttributeRollingWindow::onSchedule(core::ProcessContext* context, 
core::ProcessSessionFactory*) {
+  gsl_Expects(context);
+  time_window_ = context->getProperty<core::TimePeriodValue>(TimeWindow)
+      | utils::transform(&core::TimePeriodValue::getMilliseconds);
+  window_length_ = context->getProperty<uint64_t>(WindowLength)
+      | utils::filter([](uint64_t value) { return value > 0; })
+      | utils::transform([](uint64_t value) { return size_t{value}; });
+  if (!time_window_ && !window_length_) {
+    throw minifi::Exception{ExceptionType::PROCESS_SCHEDULE_EXCEPTION, "Either 
'Time window' or 'Window length' must be set"};
+  }
+  attribute_name_prefix_ = (context->getProperty(AttributeNamePrefix)
+      | utils::orElse([] {
+        throw minifi::Exception{ExceptionType::PROCESS_SCHEDULE_EXCEPTION, 
"'Attribute name prefix' must be set"};
+      })).value();
+  gsl_Ensures(runningInvariant());
+}
+
+void AttributeRollingWindow::onTrigger(core::ProcessContext* context, 
core::ProcessSession* session) {
+  gsl_Expects(context && session && runningInvariant());
+  const auto flow_file = session->get();
+  if (!flow_file) { yield(); return; }
+  gsl_Assert(flow_file);
+  const auto current_value_opt = context->getProperty(ValueToTrack, flow_file);
+  if (!current_value_opt) {
+    logger_->log_warn("Missing value to track, flow file uuid: {}", 
flow_file->getUUIDStr());
+    session->transfer(flow_file, Failure);
+    return;
+  }
+  const auto current_value = [&current_value_opt] {
+    try {
+      return std::stod(*current_value_opt);
+    } catch (const std::exception& ex) {
+      throw minifi::Exception{ExceptionType::PROCESSOR_EXCEPTION,
+          fmt::format("Failed to convert 'Value to track' of '{}' to double", 
*current_value_opt)};
+    }
+  }();
+  // copy: so we can release the lock sooner
+  const auto state_copy = [&, now = std::chrono::system_clock::now()] {
+    const std::lock_guard lg{state_mutex_};
+    state_.add(now, current_value);
+    if (window_length_) {
+      state_.shrinkToSize(*window_length_);
+    } else {
+      gsl_Assert(time_window_);
+      state_.removeOlderThan(now - *time_window_);
+    }
+    return state_.getEntries();
+  }();
+  const auto sorted_values = [&state_copy] {
+    auto values = state_copy | 
ranges::views::transform(&decltype(state_)::Entry::value) | 
ranges::to<std::vector>;
+    std::sort(std::begin(values), std::end(values));
+    return values;
+  }();
+  calculateAndSetAttributes(*flow_file, sorted_values);
+  session->transfer(flow_file, Success);
+}
+
+/**
+ * Calculate statistical properties of the values in the rolling window and 
set them as attributes on the flow file.
+ * Properties: count, value (sum), mean (average), median, variance, stddev
+ */
+void AttributeRollingWindow::calculateAndSetAttributes(core::FlowFile 
&flow_file,
+    std::span<const double> sorted_values) const {
+  const auto attribute_name = [this](std::string_view suffix) {
+    return utils::string::join_pack(attribute_name_prefix_, suffix);
+  };
+  const auto set_aggregate = [&flow_file, attribute_name](std::string_view 
name, double value) {
+    flow_file.setAttribute(attribute_name(name), std::to_string(value));
+  };
+  set_aggregate("count", sorted_values.size());
+  const auto sum = std::accumulate(std::begin(sorted_values), 
std::end(sorted_values), 0.0);
+  set_aggregate("value", sum);
+  const auto mean = sum / gsl::narrow_cast<double>(sorted_values.size());
+  set_aggregate("mean", mean);
+  set_aggregate("median", [&] {
+    const auto mid = sorted_values.size() / 2;
+    return sorted_values.size() % 2 == 0
+        ? std::midpoint(sorted_values[mid], sorted_values[mid - 1])  // even 
number of values: average the two middle values

Review Comment:
   fixed in 
[bdf1cd3](https://github.com/apache/nifi-minifi-cpp/pull/1703/commits/bdf1cd3b5f27b9c4d759ebc23b1a05c259905ef9)
 with gsl_Expects



##########
extensions/standard-processors/tests/unit/AttributeRollingWindowTests.cpp:
##########
@@ -0,0 +1,101 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <memory>
+#include <string_view>
+#include "Catch.h"
+#include "AttributeRollingWindow.h"
+#include "SingleProcessorTestController.h"
+
+namespace org::apache::nifi::minifi::test {
+using AttributeRollingWindow = processors::AttributeRollingWindow;
+
+bool checkAttributes(const std::map<std::string, std::string>& expected, const 
std::map<std::string, std::string>& actual) {
+  // expected may be incomplete, but if something is specified in expected, 
they also need to be in the actual
+  // set of attributes
+  return std::all_of(std::begin(expected), std::end(expected), [&actual](const 
auto& kvpair) {
+    const auto& key = kvpair.first;
+    const auto& value = kvpair.second;
+    return actual.at(key) == value;

Review Comment:
   fixed in 
[bdf1cd3](https://github.com/apache/nifi-minifi-cpp/pull/1703/commits/bdf1cd3b5f27b9c4d759ebc23b1a05c259905ef9)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to