fgerlits commented on code in PR #2221: URL: https://github.com/apache/nifi-minifi-cpp/pull/2221#discussion_r3959557667
########## extensions/standard-processors/processors/JoinEnrichmentAttributes.h: ########## @@ -0,0 +1,147 @@ +/** + * 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. + */ + +#pragma once + +#include <array> +#include <chrono> +#include <deque> +#include <functional> +#include <memory> +#include <optional> +#include <string> +#include <unordered_map> +#include <utility> +#include <vector> + +#include "core/FlowFileStore.h" +#include "core/ProcessorImpl.h" +#include "core/PropertyDefinitionBuilder.h" +#include "minifi-cpp/core/PropertyDefinition.h" +#include "utils/Enum.h" +#include "utils/RegexUtils.h" + +namespace org::apache::nifi::minifi::standard { + +namespace join_enrichment_attributes { +class TimeOutTracker { + public: + explicit TimeOutTracker(std::chrono::steady_clock::duration timeout) : time_out_(timeout) { + } + TimeOutTracker(const TimeOutTracker&) = delete; + TimeOutTracker& operator=(const TimeOutTracker&) = delete; + TimeOutTracker(TimeOutTracker&&) = delete; + TimeOutTracker& operator=(TimeOutTracker&&) = delete; + ~TimeOutTracker() = default; + + void track(std::string id, std::chrono::steady_clock::time_point timestamp) { + queue_.emplace_back(timestamp, std::move(id)); + } + + std::vector<std::string> getTimedOutFlowFiles(std::chrono::steady_clock::time_point current_time) { + std::vector<std::string> result; + // Even with 0 time_out_, we won't return just added FlowFiles + while (!queue_.empty() && queue_.front().timestamp + time_out_ < current_time) { + result.push_back(std::move(queue_.front().group_name)); + queue_.pop_front(); + } + return result; + } + + private: + struct TimeStampedGroup { + std::chrono::steady_clock::time_point timestamp; + std::string group_name; + }; + + std::chrono::steady_clock::duration time_out_; + std::deque<TimeStampedGroup> queue_; +}; +} // namespace join_enrichment_attributes + +using StoredFlowFileMap = std::unordered_map<std::string, std::shared_ptr<core::FlowFile>, utils::string::transparent_string_hash, std::equal_to<>>; + +class JoinEnrichmentAttributes : public core::ProcessorImpl { + public: + using ProcessorImpl::ProcessorImpl; + + EXTENSIONAPI static constexpr const char* Description = + "Rejoins the forked FlowFiles coming from ForkEnrichment processor, the resulting FlowFile will have the Original's content and all attributes " + "from both of them (prioritizing Enrichment's)."; + + EXTENSIONAPI static constexpr auto Invalid = core::RelationshipDefinition{"invalid", + "Any FlowFiles without the requisite attributes will be routed here"}; + EXTENSIONAPI static constexpr auto Joined = core::RelationshipDefinition{"joined", + "The resultant FlowFile with Records joined together from both the original and enrichment FlowFiles will be routed to this relationship"}; Review Comment: attributes, not records ########## extensions/standard-processors/processors/ForkEnrichment.cpp: ########## @@ -0,0 +1,61 @@ +/** + * 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 "ForkEnrichment.h" + +#include "core/Resource.h" +#include "minifi-cpp/core/ProcessSession.h" +#include "utils/ProcessorConfigUtils.h" + +namespace org::apache::nifi::minifi::standard { +void ForkEnrichment::initialize() { + setSupportedProperties(Properties); + setSupportedRelationships(Relationships); + ProcessorImpl::initialize(); +} + +void ForkEnrichment::onSchedule(core::ProcessContext& context, core::ProcessSessionFactory& session_factory) { + max_batch_size_ = utils::parseOptionalU64Property(context, MaxBatchSize); + if (max_batch_size_ && *max_batch_size_ == 0) { + throw Exception(PROCESSOR_EXCEPTION, "Max Batch Size property is invalid"); + } + + ProcessorImpl::onSchedule(context, session_factory); +} + +void ForkEnrichment::onTrigger(core::ProcessContext&, core::ProcessSession& session) { + uint64_t processed = 0; + while (const auto original = session.get()) { + const auto enrichment = session.clone(*original); + + original->setAttribute(ENRICHMENT_ROLE, "ORIGINAL"); + enrichment->setAttribute(ENRICHMENT_ROLE, "ENRICHMENT"); Review Comment: I would move the `EnrichmentRole` enum from `JoinEnrichmentAttributes` to somewhere which is visible from here, and use that instead of the "ORIGINAL" and "ENRICHMENT" strings. ########## extensions/standard-processors/processors/JoinEnrichmentAttributes.h: ########## @@ -0,0 +1,147 @@ +/** + * 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. + */ + +#pragma once + +#include <array> +#include <chrono> +#include <deque> +#include <functional> +#include <memory> +#include <optional> +#include <string> +#include <unordered_map> +#include <utility> +#include <vector> + +#include "core/FlowFileStore.h" +#include "core/ProcessorImpl.h" +#include "core/PropertyDefinitionBuilder.h" +#include "minifi-cpp/core/PropertyDefinition.h" +#include "utils/Enum.h" +#include "utils/RegexUtils.h" + +namespace org::apache::nifi::minifi::standard { + +namespace join_enrichment_attributes { +class TimeOutTracker { + public: + explicit TimeOutTracker(std::chrono::steady_clock::duration timeout) : time_out_(timeout) { + } + TimeOutTracker(const TimeOutTracker&) = delete; + TimeOutTracker& operator=(const TimeOutTracker&) = delete; + TimeOutTracker(TimeOutTracker&&) = delete; + TimeOutTracker& operator=(TimeOutTracker&&) = delete; + ~TimeOutTracker() = default; + + void track(std::string id, std::chrono::steady_clock::time_point timestamp) { + queue_.emplace_back(timestamp, std::move(id)); + } + + std::vector<std::string> getTimedOutFlowFiles(std::chrono::steady_clock::time_point current_time) { + std::vector<std::string> result; + // Even with 0 time_out_, we won't return just added FlowFiles + while (!queue_.empty() && queue_.front().timestamp + time_out_ < current_time) { + result.push_back(std::move(queue_.front().group_name)); + queue_.pop_front(); + } + return result; + } + + private: + struct TimeStampedGroup { + std::chrono::steady_clock::time_point timestamp; + std::string group_name; + }; + + std::chrono::steady_clock::duration time_out_; + std::deque<TimeStampedGroup> queue_; +}; +} // namespace join_enrichment_attributes + +using StoredFlowFileMap = std::unordered_map<std::string, std::shared_ptr<core::FlowFile>, utils::string::transparent_string_hash, std::equal_to<>>; + +class JoinEnrichmentAttributes : public core::ProcessorImpl { + public: + using ProcessorImpl::ProcessorImpl; + + EXTENSIONAPI static constexpr const char* Description = + "Rejoins the forked FlowFiles coming from ForkEnrichment processor, the resulting FlowFile will have the Original's content and all attributes " + "from both of them (prioritizing Enrichment's)."; + + EXTENSIONAPI static constexpr auto Invalid = core::RelationshipDefinition{"invalid", + "Any FlowFiles without the requisite attributes will be routed here"}; + EXTENSIONAPI static constexpr auto Joined = core::RelationshipDefinition{"joined", + "The resultant FlowFile with Records joined together from both the original and enrichment FlowFiles will be routed to this relationship"}; + EXTENSIONAPI static constexpr auto Original = core::RelationshipDefinition{"original", + "Both of the incoming FlowFiles ('original' and 'enrichment') will be routed to this Relationship. I.e., this is the 'original' version of " + "both of these FlowFiles."}; + EXTENSIONAPI static constexpr auto TimeoutRelationship = core::RelationshipDefinition{"timeout", + "If one of the incoming FlowFiles (i.e., the 'original' FlowFile or the 'enrichment' FlowFile) arrives to this Processor but the other does " + "not arrive within the configured Timeout period, the FlowFile that did arrive is routed to this relationship."}; + + EXTENSIONAPI static constexpr auto MaxBatchSize = + core::PropertyDefinitionBuilder<>::createProperty("Max Batch Size") + .withDescription("The maximum number of flow files to process at a time. If unset, all FlowFiles will be processed at once.") + .withValidator(core::StandardPropertyValidators::UNSIGNED_INTEGER_VALIDATOR) + .build(); + + EXTENSIONAPI static constexpr auto TimeoutProperty = + core::PropertyDefinitionBuilder<>::createProperty("Timeout") + .withDescription( + "Specifies the maximum amount of time to wait for the second FlowFile once the first arrives at the processor, after which point the " + "first FlowFile will be routed to the 'timeout' relationship.") + .withValidator(core::StandardPropertyValidators::TIME_PERIOD_VALIDATOR) + .isRequired(false) + .build(); + + EXTENSIONAPI static constexpr auto Properties = std::array<core::PropertyReference, 2>{TimeoutProperty, MaxBatchSize}; + EXTENSIONAPI static constexpr auto Relationships = std::array{Invalid, Joined, Original, TimeoutRelationship}; + + EXTENSIONAPI static constexpr bool SupportsDynamicProperties = false; + EXTENSIONAPI static constexpr bool SupportsDynamicRelationships = false; + EXTENSIONAPI static constexpr auto InputRequirement = core::annotation::Input::INPUT_REQUIRED; + EXTENSIONAPI static constexpr bool IsSingleThreaded = true; + + ADD_COMMON_VIRTUAL_FUNCTIONS_FOR_PROCESSORS + + EXTENSIONAPI static const core::Relationship Self; + + void initialize() override; + void onSchedule(core::ProcessContext& context, core::ProcessSessionFactory& session_factory) override; + void onTrigger(core::ProcessContext& context, core::ProcessSession& session) override; + void restore(const std::shared_ptr<core::FlowFile>& flowFile) override; + + private: + enum class EnrichmentRole { + ORIGINAL, + ENRICHMENT, + }; + + void handleFlowFile(std::shared_ptr<core::FlowFile> flow_file, core::ProcessSession& session, std::chrono::steady_clock::time_point current_time); + void join(const std::shared_ptr<core::FlowFile>& original, const std::shared_ptr<core::FlowFile>& enrichment, core::ProcessSession& session) const; + + core::FlowFileStore flow_file_store_; Review Comment: This is old code, but `FlowFileStore` assumes that after we move from `incoming_files_`, it will be empty. This is probably true in practice, but it isn't guaranteed. We should do a `clear` to be safe. ########## extensions/standard-processors/processors/JoinEnrichmentAttributes.cpp: ########## @@ -0,0 +1,160 @@ +/** + * 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 "JoinEnrichmentAttributes.h" + +#include "core/Resource.h" +#include "minifi-cpp/core/ProcessSession.h" +#include "utils/AttributeErrors.h" +#include "utils/EnrichmentUtils.h" +#include "utils/ProcessorConfigUtils.h" + +namespace org::apache::nifi::minifi::standard { +const core::Relationship JoinEnrichmentAttributes::Self("__self__", "Marks the FlowFile to be owned by this processor"); + +void JoinEnrichmentAttributes::initialize() { + setSupportedProperties(Properties); + setSupportedRelationships(Relationships); + ProcessorImpl::initialize(); +} + +void JoinEnrichmentAttributes::onSchedule(core::ProcessContext& context, core::ProcessSessionFactory& session_factory) { + using namespace std::literals::chrono_literals; + if (const auto timeout = utils::parseOptionalDurationProperty(context, TimeoutProperty); timeout && *timeout > 0ms) { + time_out_tracker_.emplace(*timeout); + } + max_batch_size_ = utils::parseOptionalU64Property(context, MaxBatchSize); + if (max_batch_size_ && *max_batch_size_ == 0) { + throw Exception(PROCESSOR_EXCEPTION, "Max Batch Size property is invalid"); + } + ProcessorImpl::onSchedule(context, session_factory); +} + +namespace { +bool checkRequiredAttributes(const core::FlowFile& flow_file) { + return flow_file.getAttribute(ENRICHMENT_ROLE).has_value() && flow_file.getAttribute(ENRICHMENT_GROUP_ID).has_value(); +} +} // namespace + +void JoinEnrichmentAttributes::join(const std::shared_ptr<core::FlowFile>& original, const std::shared_ptr<core::FlowFile>& enrichment, + core::ProcessSession& session) const { + const auto cloned = session.clone(*original); + for (const auto& [k, v] : enrichment->getAttributes()) { + if (k != ENRICHMENT_ROLE) { + cloned->setAttribute(k, v); + } + } + cloned->setAttribute(ENRICHMENT_ROLE, "JOINED"); + if (!std::ranges::contains(session_flow_files_, original->getUUID())) { + session.add(original); + } + if (!std::ranges::contains(session_flow_files_, enrichment->getUUID())) { + session.add(enrichment); + } + session.transfer(original, Original); + session.transfer(enrichment, Original); + session.transfer(cloned, Joined); +} + +void JoinEnrichmentAttributes::handleFlowFile(std::shared_ptr<core::FlowFile> flow_file, core::ProcessSession& session, + const std::chrono::steady_clock::time_point current_time) { + if (!checkRequiredAttributes(*flow_file)) { + logger_->log_warn("{} is missing enrichment.group.id and/or enrichment.role, routing it to Invalid", flow_file->getId()); + session.transfer(flow_file, Invalid); + return; + } + + const auto role = flow_file->getAttribute(ENRICHMENT_ROLE) | utils::toExpected(make_error_code(core::AttributeErrorCode::MissingAttribute)) | + utils::andThen(parsing::parseEnum<EnrichmentRole>); + if (!role) { + logger_->log_warn("{} has invalid role due to {}", flow_file->getId(), role.error()); + session.transfer(flow_file, Invalid); + return; + } + + std::string group_id = *(flow_file->getAttribute(ENRICHMENT_GROUP_ID)); + + auto& my_map = role == EnrichmentRole::ENRICHMENT ? enrichments_ : originals_; + auto& pair_map = role == EnrichmentRole::ENRICHMENT ? originals_ : enrichments_; + + if (const auto previous_node = my_map.extract(group_id)) { + logger_->log_warn("Encountered duplicate {} for {}, routing both to Invalid", magic_enum::enum_name(*role), group_id); + session.transfer(flow_file, Invalid); + session.transfer(previous_node.mapped(), Invalid); + if (!std::ranges::contains(session_flow_files_, previous_node.mapped()->getUUID())) { + session.add(previous_node.mapped()); + } Review Comment: Does this work? I would expect that we need to add the flow file first before we can transfer it. If this is the correct order, then please add a comment explaining why. ########## extensions/standard-processors/tests/unit/JoinEnrichmentAttributesTests.cpp: ########## @@ -0,0 +1,139 @@ +/** + * + * 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 <thread> + +#include "JoinEnrichmentAttributes.h" +#include "unit/Catch.h" +#include "unit/ProcessorUtils.h" +#include "unit/SingleProcessorTestController.h" +#include "utils/EnrichmentUtils.h" + +namespace org::apache::nifi::minifi::standard::test { +TEST_CASE("JoinEnrichmentAttributes input without appropriate attributes") { + minifi::test::SingleProcessorTestController + test_controller(minifi::test::utils::make_processor<JoinEnrichmentAttributes>("JoinEnrichmentAttributes")); + const auto trigger_result = test_controller.trigger("test_content"); + CHECK(trigger_result.at(JoinEnrichmentAttributes::Invalid).size() == 1); + CHECK(trigger_result.at(JoinEnrichmentAttributes::Original).empty()); + CHECK(trigger_result.at(JoinEnrichmentAttributes::TimeoutRelationship).empty()); + CHECK(trigger_result.at(JoinEnrichmentAttributes::Joined).empty()); +} + +TEST_CASE("JoinEnrichmentAttributes invalid role") { + minifi::test::SingleProcessorTestController + test_controller(minifi::test::utils::make_processor<JoinEnrichmentAttributes>("JoinEnrichmentAttributes")); + const auto trigger_result = test_controller.trigger(minifi::test::InputFlowFileData{.content = "first", + .attributes = {{std::string{ENRICHMENT_GROUP_ID}, "foo"}, {std::string{ENRICHMENT_ROLE}, "FIREBIRD"}}}); + CHECK(trigger_result.at(JoinEnrichmentAttributes::Invalid).size() == 1); + CHECK(trigger_result.at(JoinEnrichmentAttributes::Original).empty()); + CHECK(trigger_result.at(JoinEnrichmentAttributes::TimeoutRelationship).empty()); + CHECK(trigger_result.at(JoinEnrichmentAttributes::Joined).empty()); +} + +TEST_CASE("JoinEnrichmentAttributes same id same role same session") { + minifi::test::SingleProcessorTestController + test_controller(minifi::test::utils::make_processor<JoinEnrichmentAttributes>("JoinEnrichmentAttributes")); + const auto trigger = test_controller.trigger( + {minifi::test::InputFlowFileData{.content = "first", + .attributes = {{std::string{ENRICHMENT_GROUP_ID}, "foo"}, {std::string{ENRICHMENT_ROLE}, "ORIGINAL"}}}, + minifi::test::InputFlowFileData{.content = "second", + .attributes = {{std::string{ENRICHMENT_GROUP_ID}, "foo"}, {std::string{ENRICHMENT_ROLE}, "ORIGINAL"}}}}); + CHECK(trigger.at(JoinEnrichmentAttributes::Invalid).size() == 2); + CHECK(trigger.at(JoinEnrichmentAttributes::Original).empty()); + CHECK(trigger.at(JoinEnrichmentAttributes::TimeoutRelationship).empty()); + CHECK(trigger.at(JoinEnrichmentAttributes::Joined).empty()); +} + +TEST_CASE("JoinEnrichmentAttributes same id same role different session") { + minifi::test::SingleProcessorTestController + test_controller(minifi::test::utils::make_processor<JoinEnrichmentAttributes>("JoinEnrichmentAttributes")); + const auto first_trigger = test_controller.trigger(minifi::test::InputFlowFileData{.content = "first", + .attributes = {{std::string{ENRICHMENT_GROUP_ID}, "foo"}, {std::string{ENRICHMENT_ROLE}, "ORIGINAL"}}}); + // First trigger no output (it holds the original waiting for its pair) + CHECK(std::ranges::all_of(first_trigger, [](const auto& res) -> bool { return res.second.empty(); })); + + const auto second_trigger = test_controller.trigger(minifi::test::InputFlowFileData{.content = "second", + .attributes = {{std::string{ENRICHMENT_GROUP_ID}, "foo"}, {std::string{ENRICHMENT_ROLE}, "ORIGINAL"}}}); + CHECK(second_trigger.at(JoinEnrichmentAttributes::Invalid).size() == 2); + CHECK(second_trigger.at(JoinEnrichmentAttributes::Original).empty()); + CHECK(second_trigger.at(JoinEnrichmentAttributes::TimeoutRelationship).empty()); + CHECK(second_trigger.at(JoinEnrichmentAttributes::Joined).empty()); +} + +TEST_CASE("JoinEnrichmentAttributes same id diff role different session") { + minifi::test::SingleProcessorTestController + test_controller(minifi::test::utils::make_processor<JoinEnrichmentAttributes>("JoinEnrichmentAttributes")); + const auto first_trigger = test_controller.trigger(minifi::test::InputFlowFileData{.content = "first", + .attributes = {{std::string{ENRICHMENT_GROUP_ID}, "foo"}, {std::string{ENRICHMENT_ROLE}, "ORIGINAL"}, {"first_attr", "1"}}}); + // First trigger no output (it holds the original waiting for its pair) + CHECK(std::ranges::all_of(first_trigger, [](const auto& res) -> bool { return res.second.empty(); })); + + const auto second_trigger = test_controller.trigger(minifi::test::InputFlowFileData{.content = "second", + .attributes = {{std::string{ENRICHMENT_GROUP_ID}, "foo"}, {std::string{ENRICHMENT_ROLE}, "ENRICHMENT"}, {"second_attr", "2"}}}); + CHECK(second_trigger.at(JoinEnrichmentAttributes::Original).size() == 2); + CHECK(second_trigger.at(JoinEnrichmentAttributes::Invalid).empty()); + CHECK(second_trigger.at(JoinEnrichmentAttributes::TimeoutRelationship).empty()); + REQUIRE(second_trigger.at(JoinEnrichmentAttributes::Joined).size() == 1); + + const auto joined_content = test_controller.plan->getContent(second_trigger.at(JoinEnrichmentAttributes::Joined).at(0)); + const auto joined_attrs = second_trigger.at(JoinEnrichmentAttributes::Joined).at(0)->getAttributes(); + + CHECK(joined_content == "first"); + CHECK(joined_attrs.at(std::string{ENRICHMENT_GROUP_ID}) == "foo"); + CHECK(joined_attrs.at(std::string{ENRICHMENT_ROLE}) == "JOINED"); + CHECK(joined_attrs.at("first_attr") == "1"); + CHECK(joined_attrs.at("second_attr") == "2"); +} + +TEST_CASE("JoinEnrichmentAttributes test timeout") { + minifi::test::SingleProcessorTestController + test_controller(minifi::test::utils::make_processor<JoinEnrichmentAttributes>("JoinEnrichmentAttributes")); + const auto proc = test_controller.getProcessor(); + CHECK(test_controller.plan->setProperty(proc, JoinEnrichmentAttributes::TimeoutProperty.name, "1 ms")); + + const auto first_trigger = test_controller.trigger(minifi::test::InputFlowFileData{.content = "first", + .attributes = {{std::string{ENRICHMENT_GROUP_ID}, "foo"}, {std::string{ENRICHMENT_ROLE}, "ORIGINAL"}, {"first_attr", "1"}}}); + // First trigger no output (it holds the original waiting for its pair) + CHECK(std::ranges::all_of(first_trigger, [](const auto& res) -> bool { return res.second.empty(); })); + + std::this_thread::sleep_for(1ms); Review Comment: are you sure this is not going to be flaky? maybe we could sleep for 2 ms, to make flakiness less likely ########## extensions/standard-processors/processors/JoinEnrichmentAttributes.cpp: ########## @@ -0,0 +1,160 @@ +/** + * 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 "JoinEnrichmentAttributes.h" + +#include "core/Resource.h" +#include "minifi-cpp/core/ProcessSession.h" +#include "utils/AttributeErrors.h" +#include "utils/EnrichmentUtils.h" +#include "utils/ProcessorConfigUtils.h" + +namespace org::apache::nifi::minifi::standard { +const core::Relationship JoinEnrichmentAttributes::Self("__self__", "Marks the FlowFile to be owned by this processor"); + +void JoinEnrichmentAttributes::initialize() { + setSupportedProperties(Properties); + setSupportedRelationships(Relationships); + ProcessorImpl::initialize(); +} + +void JoinEnrichmentAttributes::onSchedule(core::ProcessContext& context, core::ProcessSessionFactory& session_factory) { + using namespace std::literals::chrono_literals; + if (const auto timeout = utils::parseOptionalDurationProperty(context, TimeoutProperty); timeout && *timeout > 0ms) { + time_out_tracker_.emplace(*timeout); + } + max_batch_size_ = utils::parseOptionalU64Property(context, MaxBatchSize); + if (max_batch_size_ && *max_batch_size_ == 0) { + throw Exception(PROCESSOR_EXCEPTION, "Max Batch Size property is invalid"); + } + ProcessorImpl::onSchedule(context, session_factory); +} + +namespace { +bool checkRequiredAttributes(const core::FlowFile& flow_file) { + return flow_file.getAttribute(ENRICHMENT_ROLE).has_value() && flow_file.getAttribute(ENRICHMENT_GROUP_ID).has_value(); +} +} // namespace + +void JoinEnrichmentAttributes::join(const std::shared_ptr<core::FlowFile>& original, const std::shared_ptr<core::FlowFile>& enrichment, + core::ProcessSession& session) const { + const auto cloned = session.clone(*original); + for (const auto& [k, v] : enrichment->getAttributes()) { + if (k != ENRICHMENT_ROLE) { + cloned->setAttribute(k, v); + } + } + cloned->setAttribute(ENRICHMENT_ROLE, "JOINED"); + if (!std::ranges::contains(session_flow_files_, original->getUUID())) { + session.add(original); + } + if (!std::ranges::contains(session_flow_files_, enrichment->getUUID())) { + session.add(enrichment); + } + session.transfer(original, Original); + session.transfer(enrichment, Original); + session.transfer(cloned, Joined); +} + +void JoinEnrichmentAttributes::handleFlowFile(std::shared_ptr<core::FlowFile> flow_file, core::ProcessSession& session, + const std::chrono::steady_clock::time_point current_time) { + if (!checkRequiredAttributes(*flow_file)) { + logger_->log_warn("{} is missing enrichment.group.id and/or enrichment.role, routing it to Invalid", flow_file->getId()); + session.transfer(flow_file, Invalid); + return; + } + + const auto role = flow_file->getAttribute(ENRICHMENT_ROLE) | utils::toExpected(make_error_code(core::AttributeErrorCode::MissingAttribute)) | + utils::andThen(parsing::parseEnum<EnrichmentRole>); + if (!role) { + logger_->log_warn("{} has invalid role due to {}", flow_file->getId(), role.error()); + session.transfer(flow_file, Invalid); + return; + } + + std::string group_id = *(flow_file->getAttribute(ENRICHMENT_GROUP_ID)); Review Comment: we should check or assert that the attribute exists before dereferencing it ########## extensions/standard-processors/tests/features/enrichment.feature: ########## Review Comment: Can you add a couple more attributes to the original flow file, please? One which is not touched by the enrichment branch, and one which is overwritten by it. At the end, both (together with the existing one, all three) should show up in the log with the correct value. -- 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]
