lordgamez commented on code in PR #2268: URL: https://github.com/apache/nifi-minifi-cpp/pull/2268#discussion_r4640885181
########## extensions/opc/src/OPCCommon.cpp: ########## Review Comment: You are right, as I checked there were some additional leak issues too here, so I refactored the whole function in https://github.com/apache/nifi-minifi-cpp/pull/2268/commits/935d18a6a943281549fd665fd859ddbc87c74d0f ########## extensions/opc/src/OPCCommon.cpp: ########## @@ -666,4 +676,155 @@ std::expected<opc::NodeId, std::string> buildNodeId(opc::OPCNodeIDType id_type, } } +std::string buildEventFilterExpression(const EventFilter& options) { + if (!options.filter_expression.empty()) { + return options.filter_expression; + } + + // The browse paths of the select clauses are written with a leading '/', which is not required from the property. A field + // that is prefixed with the node id of an event type keeps its own prefix: such a path starts with the node id, not a '/'. + gsl_Expects(!options.select_fields.empty()); + std::string expression = "SELECT "; + for (const auto& select_field : options.select_fields) { + const bool is_full_path = select_field.starts_with('/') || select_field.contains('='); + expression += is_full_path ? select_field : "/" + select_field; + expression += ", "; + } + expression.erase(expression.size() - 2); + + std::vector<std::string> conditions; + if (!options.event_type_node_id.empty()) { + conditions.push_back("OFTYPE " + options.event_type_node_id); + } + if (options.minimum_severity) { + conditions.push_back("/Severity >= " + std::to_string(*options.minimum_severity)); + } + if (!conditions.empty()) { + expression += " WHERE " + utils::string::join(" AND ", conditions); + } + return expression; +} + +UA_StatusCode Client::subscribeToEvents(const UA_NodeId& node_id, const EventFilter& event_filter) { + if (subscription_) { + logger_->log_debug("Deleting the dead OPC UA event subscription {} before resubscribing", subscription_->id); + UA_Client_Subscriptions_deleteSingle(client_, subscription_->id); + subscription_.reset(); + } + + UA_CreateSubscriptionResponse response = UA_Client_Subscriptions_create(client_, UA_CreateSubscriptionRequest_default(), this, + &Client::subscriptionStatusChangeCallback, &Client::subscriptionDeleteCallback); + const auto response_guard = gsl::finally([&response]() { UA_CreateSubscriptionResponse_clear(&response); }); + if (response.responseHeader.serviceResult != UA_STATUSCODE_GOOD) { + return response.responseHeader.serviceResult; + } + const auto subscription_id = response.subscriptionId; + auto subscription_id_guard = gsl::finally([this, &subscription_id]() { + if (!subscription_ || subscription_->id != subscription_id) { + UA_Client_Subscriptions_deleteSingle(client_, subscription_id); + } + }); + + UA_MonitoredItemCreateRequest item; + UA_MonitoredItemCreateRequest_init(&item); + const auto item_guard = gsl::finally([&item]() { UA_MonitoredItemCreateRequest_clear(&item); }); + UA_NodeId_copy(&node_id, &item.itemToMonitor.nodeId); + item.itemToMonitor.attributeId = UA_ATTRIBUTEID_EVENTNOTIFIER; + item.monitoringMode = UA_MONITORINGMODE_REPORTING; + + const std::string event_filter_str = buildEventFilterExpression(event_filter); + logger_->log_debug("Subscribing with the event filter '{}'", event_filter_str); + + auto* filter = UA_EventFilter_new(); + if (filter == nullptr) { + return UA_STATUSCODE_BADOUTOFMEMORY; + } + if (auto sc = UA_EventFilter_parse(filter, UA_STRING(const_cast<char*>(event_filter_str.c_str())), nullptr); sc != UA_STATUSCODE_GOOD) { + logger_->log_error("Failed to parse the event filter '{}': {}", event_filter_str, UA_StatusCode_name(sc)); + UA_EventFilter_delete(filter); + return sc; + } + UA_ExtensionObject_setValue(&item.requestedParameters.filter, filter, &UA_TYPES[UA_TYPES_EVENTFILTER]); + + UA_MonitoredItemCreateResult result = UA_Client_MonitoredItems_createEvent(client_, subscription_id, UA_TIMESTAMPSTORETURN_BOTH, item, + this, eventNotificationCallback, nullptr); + const auto result_guard = gsl::finally([&result]() { UA_MonitoredItemCreateResult_clear(&result); }); + if (result.statusCode != UA_STATUSCODE_GOOD) { + return result.statusCode; + } + + subscription_ = EventSubscription{.id = subscription_id, .alive = true}; + return UA_STATUSCODE_GOOD; +} + +void Client::eventNotificationCallback(UA_Client* /*client*/, UA_UInt32 /*sub_id*/, void* /*sub_context*/, UA_UInt32 /*mon_id*/, void* mon_context, + const UA_KeyValueMap event_fields) { + auto* client = static_cast<Client*>(mon_context); + + Event event; + for (size_t i = 0; i < event_fields.mapSize; ++i) { + const UA_KeyValuePair& field = event_fields.map[i]; + std::string name{reinterpret_cast<const char*>(field.key.name.data), field.key.name.length}; + if (name.starts_with('/')) { + name.erase(0, 1); + } + if (UA_Variant_isEmpty(&field.value)) { + continue; + } + try { + event.fields[name] = variantToString(field.value, BinaryEncoding::Base64); + } catch (const OPCException& ex) { Review Comment: Good point, updated in https://github.com/apache/nifi-minifi-cpp/pull/2268/commits/935d18a6a943281549fd665fd859ddbc87c74d0f ########## extensions/opc/src/OPCCommon.cpp: ########## @@ -666,4 +676,155 @@ std::expected<opc::NodeId, std::string> buildNodeId(opc::OPCNodeIDType id_type, } } +std::string buildEventFilterExpression(const EventFilter& options) { Review Comment: It can still be possible to get an error due to the server rejecting the filter when subscribing, but you are right we can fail early for parse issues in onSchedule, so I moved it there in https://github.com/apache/nifi-minifi-cpp/pull/2268/commits/935d18a6a943281549fd665fd859ddbc87c74d0f -- 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]
