Copilot commented on code in PR #2289: URL: https://github.com/apache/nifi-minifi-cpp/pull/2289#discussion_r4513718169
########## extensions/opc/src/PutOPCFile.cpp: ########## @@ -0,0 +1,193 @@ +/** + * 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 "PutOPCFile.h" + +#include <expected> +#include <memory> +#include <optional> +#include <span> +#include <string> +#include <utility> +#include <vector> + +#include "OPCFileTransfer.h" +#include "core/Resource.h" +#include "minifi-cpp/core/ProcessContext.h" +#include "utils/ProcessorConfigUtils.h" + +namespace org::apache::nifi::minifi::processors { + +void PutOPCFile::initialize() { + setSupportedProperties(Properties); + setSupportedRelationships(Relationships); +} + +void PutOPCFile::onSchedule(core::ProcessContext& context, core::ProcessSessionFactory& factory) { + logger_->log_trace("PutOPCFile::onSchedule"); + + BaseOPCProcessor::onSchedule(context, factory); + + target_node_id_defined_ = context.hasNonEmptyProperty(TargetNodeID.name); + parent_node_defined_ = false; + if (const auto parent_node_id = utils::parseOptionalProperty(context, ParentNodeID); parent_node_id && !parent_node_id->empty()) { + node_id_ = *parent_node_id; + id_type_ = utils::parseEnumProperty<opc::OPCNodeIDType>(context, ParentNodeIDType); + namespace_idx_ = gsl::narrow<UA_UInt16>(utils::parseOptionalU64Property(context, ParentNameSpaceIndex).value_or(0)); + parseNode(context, PathReferenceTypes); + parent_node_defined_ = true; + } + if (!target_node_id_defined_ && !parent_node_defined_) { + throw Exception(PROCESS_SCHEDULE_EXCEPTION, "Either Target node ID or Parent node ID must be set"); + } + + write_mode_ = utils::parseEnumProperty<OPCFileWriteMode>(context, WriteMode); +} + +std::expected<opc::NodeId, std::string> PutOPCFile::findOrCreateFileInParent(core::ProcessContext& context, const core::FlowFile& flow_file) { + if (!parent_node_defined_) { + return std::unexpected{"target file node does not exist and no parent node is defined to create it in"}; + } + + const auto browse_name = context.getProperty(TargetNodeBrowseName, &flow_file).value_or(""); + if (browse_name.empty()) { + return std::unexpected{"target node browse name is required to look up or create the file in the parent node"}; + } + + if (auto resolved = resolvePathNode(); !resolved) { + return std::unexpected{fmt::format("failed to resolve the parent node: {}", resolved.error())}; + } + + // The node ID of a created file is assigned by the server, so a file created earlier is found by its browse name. + // FileDirectoryType nodes reference their files with Organizes references (OPC UA Part 20, 4.3.1). + if (auto file_node = connection_->findObjectChildByName(node_, browse_name, UA_NS0ID_ORGANIZES)) { + return std::move(*file_node); + } else if (file_node.error() != UA_STATUSCODE_BADNOMATCH) { + return std::unexpected{fmt::format("failed to browse parent node '{}': {}", node_id_, UA_StatusCode_name(file_node.error()))}; + } + + logger_->log_debug("File '{}' not found in parent node '{}', creating it", browse_name, node_id_); + auto created_file_node = opc::createFileInDirectory(*connection_, node_, browse_name); + if (!created_file_node) { + return std::unexpected{ + fmt::format("failed to create file '{}' in parent node '{}': {}", browse_name, node_id_, UA_StatusCode_name(created_file_node.error()))}; + } + return std::move(*created_file_node); +} + +std::expected<opc::NodeId, std::string> PutOPCFile::getTargetFileNode(core::ProcessContext& context, const core::FlowFile& flow_file) { + if (target_node_id_defined_) { + auto target_node = resolveTargetNode(context, flow_file, {TargetNodeIDType, TargetNodeID, TargetNodeNameSpaceIndex, TargetPathReferenceTypes}); + if (!target_node) { + return std::unexpected{target_node.error()}; + } + if (target_node->exists) { + return std::move(target_node->node_id); + } + logger_->log_debug("Target file node does not exist, looking it up in the parent node"); + } + return findOrCreateFileInParent(context, flow_file); +} + +void PutOPCFile::addFileNodeAttributes(const UA_NodeId& file_node_id, core::FlowFile& flow_file) const { + for (const auto& [key, value] : opc::nodeIdAttributes(file_node_id)) { + flow_file.setAttribute(key, value); + } + if (auto browse_name = connection_->readBrowseName(file_node_id)) { + flow_file.setAttribute(BrowsenameAttr.name, *browse_name); + } +} + +std::expected<void, std::string> PutOPCFile::writeFile(const UA_NodeId& file_node_id, core::ProcessSession& session, + const std::shared_ptr<core::FlowFile>& flow_file) const { + auto remote_file = opc::RemoteFile::create(*connection_, opc::NodeId::copyOf(file_node_id)); + if (!remote_file) { + return std::unexpected{ + fmt::format("target node is not a file node, failed to find its file methods: {}", UA_StatusCode_name(remote_file.error()))}; + } + + const UA_Byte mode = opc::FILE_MODE_WRITE | (write_mode_ == OPCFileWriteMode::Append ? opc::FILE_MODE_APPEND : opc::FILE_MODE_ERASE_EXISTING); + auto file_handle = remote_file->open(mode); + if (!file_handle) { + return std::unexpected{fmt::format("failed to open file for writing: {}", UA_StatusCode_name(file_handle.error()))}; + } + + std::expected<void, UA_StatusCode> write_status; + session.read(flow_file, [&](const std::shared_ptr<io::InputStream>& input_stream) -> io::IoResult { + std::vector<std::byte> buffer(std::min<uint64_t>(gsl::narrow<size_t>(remote_file->chunkSize()), flow_file->getSize())); + size_t total_size = 0; + while (true) { + const auto read = input_stream->read(buffer); + if (io::isError(read)) { + return io::IoResult::error(); + } + if (read == 0) { + return io::IoResult::from(total_size); + } + auto write_result = remote_file->write(*file_handle, std::span<const std::byte>(buffer.data(), read)); + if (!write_result) { + write_status = std::unexpected{write_result.error()}; + return io::IoResult::from(total_size); + } + total_size += read; + } + }); + + if (!write_status) { + return std::unexpected{fmt::format("failed to write file: {}", UA_StatusCode_name(write_status.error()))}; + } + // Servers may only persist the written content on close, so its result has to be checked + if (auto close_result = file_handle->close(); !close_result) { + return std::unexpected{fmt::format("failed to close file: {}", UA_StatusCode_name(close_result.error()))}; + } Review Comment: The `session.read(...)` I/O failure path (`io::isError(read)`) returns `IoResult::error()` but does not update `write_status`, and the return value of `session.read(...)` is ignored. This can cause `writeFile()` to report success even when reading the FlowFile content failed. Capture and check the `IoResult` from `session.read(...)` (or set `write_status` to an error on the `io::isError(read)` path) so read failures correctly route to failure. ########## extensions/opc/src/BaseOPCProcessor.cpp: ########## @@ -143,4 +145,74 @@ void BaseOPCProcessor::parseNode(core::ProcessContext& context, const core::Prop } } +std::expected<void, std::string> BaseOPCProcessor::resolvePathNode() { + if (id_type_ != opc::OPCNodeIDType::Path || path_node_id_resolved_) { + return {}; + } + auto node = resolveSingleNodePath(node_id_, namespace_idx_, path_reference_types_); + if (!node) { + return std::unexpected{node.error()}; + } + node_ = std::move(*node); + path_node_id_resolved_ = true; + return {}; +} + +std::expected<BaseOPCProcessor::TargetNode, std::string> BaseOPCProcessor::resolveTargetNode(core::ProcessContext& context, + const core::FlowFile& flow_file, const TargetNodeProperties& properties) const { + const auto namespace_idx_str = context.getProperty(properties.namespace_index, &flow_file).value_or(""); + UA_UInt16 namespace_idx = 0; + try { + namespace_idx = gsl::narrow<UA_UInt16>(std::stoul(namespace_idx_str)); + } catch (const std::exception&) { + return std::unexpected{fmt::format("invalid target node namespace index '{}'", namespace_idx_str)}; + } Review Comment: When the namespace-index property evaluates to an empty string (missing property or expression language resolving to empty), the current error becomes `invalid target node namespace index ''`, which is hard to interpret. Consider explicitly handling the empty-string case with a clearer message (e.g., “target node namespace index is empty” / “missing target node namespace index”) and reserving “invalid …” for non-empty parse failures. ########## extensions/opc/tests/features/resources/opcua-file-server/file_server.cpp: ########## @@ -19,16 +19,19 @@ * OPC UA test server exposing the files of a directory through the FileType and FileDirectoryType object types. * * The "Files" FileDirectoryType node (ns=1;s=Files) contains a FileType node (ns=1;s=<file name>) for every regular file - * found in the directory at startup. The files are read-only. - * The FileType methods only define an interface, so their behavior is implemented here. + * found in the directory at startup. Files created with the CreateFile method get a node id assigned by the server. + * The FileType and FileDirectoryType methods only define an interface, so their behavior is implemented here. */ #include <open62541/server.h> #include <open62541/server_config_default.h> +#include <unistd.h> Review Comment: `unistd.h` and `access()` make this test server implementation POSIX-specific and can break builds on non-POSIX platforms. If this test utility is expected to compile in cross-platform CI, consider replacing `access()` with a standard C++ alternative (e.g., checking `std::filesystem::status(...).permissions()`) or adding a platform-gated implementation (`#ifdef _WIN32` using `_access` from `<io.h>`, etc.). ########## extensions/opc/tests/features/resources/opcua-file-server/file_server.cpp: ########## @@ -92,17 +97,30 @@ OpenHandle* findHandle(FileContext& context, UA_UInt32 handle_id) { } UA_StatusCode openHandle(FileContext& context, UA_Byte mode, UA_UInt32& handle_id) { - if (mode & FILE_MODE_WRITE) { - return UA_STATUSCODE_BADNOTWRITABLE; - } - if (!(mode & FILE_MODE_READ)) { + if (!(mode & (FILE_MODE_READ | FILE_MODE_WRITE))) { return UA_STATUSCODE_BADINVALIDARGUMENT; } + std::ios::openmode open_mode = std::ios::binary; + if (mode & FILE_MODE_READ) { + open_mode |= std::ios::in; + } + if (mode & FILE_MODE_WRITE) { + if (access(context.path.c_str(), W_OK) != 0) { + return UA_STATUSCODE_BADNOTWRITABLE; + } Review Comment: `unistd.h` and `access()` make this test server implementation POSIX-specific and can break builds on non-POSIX platforms. If this test utility is expected to compile in cross-platform CI, consider replacing `access()` with a standard C++ alternative (e.g., checking `std::filesystem::status(...).permissions()`) or adding a platform-gated implementation (`#ifdef _WIN32` using `_access` from `<io.h>`, etc.). -- 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]
