BewareMyPower commented on code in PR #445: URL: https://github.com/apache/pulsar-client-node/pull/445#discussion_r2629882820
########## src/CryptoKeyReader.h: ########## @@ -0,0 +1,39 @@ +/** + * 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. + */ + +#ifndef CRYPTO_KEY_READER_H +#define CRYPTO_KEY_READER_H + +#include <napi.h> +#include <pulsar/CryptoKeyReader.h> +#include <thread> Review Comment: ```suggestion ``` ########## src/CryptoKeyReader.cc: ########## @@ -0,0 +1,182 @@ +/** + * 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 "CryptoKeyReader.h" +#include <pulsar/Result.h> +#include <pulsar/EncryptionKeyInfo.h> +#include <thread> +#include <future> +#include <iostream> Review Comment: ```suggestion ``` ########## src/CryptoKeyReader.cc: ########## @@ -0,0 +1,182 @@ +/** + * 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 "CryptoKeyReader.h" +#include <pulsar/Result.h> +#include <pulsar/EncryptionKeyInfo.h> +#include <thread> +#include <future> +#include <iostream> + +class CryptoKeyReaderWrapper : public pulsar::CryptoKeyReader { + public: + CryptoKeyReaderWrapper(const Napi::Object& jsObject) : mainThreadId_(std::this_thread::get_id()) { + jsObject_.Reset(jsObject, 1); + tsfn_ = Napi::ThreadSafeFunction::New( + jsObject.Env(), Napi::Function::New(jsObject.Env(), [](const Napi::CallbackInfo& info) {}), jsObject, + "CryptoKeyReader", 0, 1); + } + + ~CryptoKeyReaderWrapper() { tsfn_.Release(); } + + pulsar::Result getPublicKey(const std::string& keyName, std::map<std::string, std::string>& metadata, + pulsar::EncryptionKeyInfo& encKeyInfo) const override { + return executeCallback("getPublicKey", keyName, metadata, encKeyInfo); + } + + pulsar::Result getPrivateKey(const std::string& keyName, std::map<std::string, std::string>& metadata, + pulsar::EncryptionKeyInfo& encKeyInfo) const override { + return executeCallback("getPrivateKey", keyName, metadata, encKeyInfo); + } + + private: + mutable Napi::ObjectReference jsObject_; + Napi::ThreadSafeFunction tsfn_; + std::thread::id mainThreadId_; + + struct CallbackData { + std::string method; + std::string keyName; + std::map<std::string, std::string> metadata; + std::shared_ptr<std::promise<pulsar::Result>> promise; + pulsar::EncryptionKeyInfo* encKeyInfo; + Napi::ObjectReference* jsObjectRef; + }; + + static void parseEncryptionKeyInfo(const Napi::Object& obj, pulsar::EncryptionKeyInfo& info) { + if (obj.Has("key") && obj.Get("key").IsBuffer()) { + Napi::Buffer<char> keyBuf = obj.Get("key").As<Napi::Buffer<char>>(); + info.setKey(std::string(keyBuf.Data(), keyBuf.Length())); + } + if (obj.Has("metadata") && obj.Get("metadata").IsObject()) { + std::map<std::string, std::string> metadata; + Napi::Object metaObj = obj.Get("metadata").As<Napi::Object>(); + Napi::Array keys = metaObj.GetPropertyNames(); + for (uint32_t i = 0; i < keys.Length(); i++) { + std::string k = keys.Get(i).ToString().Utf8Value(); + std::string v = metaObj.Get(k).ToString().Utf8Value(); + metadata[k] = v; + } + info.setMetadata(metadata); + } + } + + pulsar::Result executeCallback(const std::string& method, const std::string& keyName, + std::map<std::string, std::string>& metadata, + pulsar::EncryptionKeyInfo& encKeyInfo) const { + if (std::this_thread::get_id() == mainThreadId_) { + Napi::Env env = jsObject_.Env(); + Napi::HandleScope scope(env); + + if (jsObject_.IsEmpty()) { + return pulsar::Result::ResultCryptoError; + } + Napi::Object obj = jsObject_.Value(); + + if (!obj.Has(method)) { + return pulsar::Result::ResultCryptoError; + } + Napi::Value funcVal = obj.Get(method); + if (!funcVal.IsFunction()) { + return pulsar::Result::ResultCryptoError; + } + Napi::Function func = funcVal.As<Napi::Function>(); + + Napi::Object metadataObj = Napi::Object::New(env); + for (const auto& kv : metadata) { + metadataObj.Set(kv.first, kv.second); + } + + try { + Napi::Value result = func.Call(obj, {Napi::String::New(env, keyName), metadataObj}); + if (result.IsObject()) { + parseEncryptionKeyInfo(result.As<Napi::Object>(), encKeyInfo); + return pulsar::Result::ResultOk; + } + } catch (const Napi::Error& e) { + return pulsar::Result::ResultCryptoError; + } + return pulsar::Result::ResultCryptoError; + } else { + auto promise = std::make_shared<std::promise<pulsar::Result>>(); + auto future = promise->get_future(); + + auto* data = new CallbackData{method, keyName, metadata, promise, &encKeyInfo, &jsObject_}; Review Comment: Actually the pattern to new a struct as the context is not recommended because `future.wait()` is called to block the current thread. You can check the official example here: https://github.com/nodejs/node-addon-api/blob/main/doc/threadsafe_function.md#example, whose difference is that after passing `data` to `BlockingCall`, the `data`'s ownership is actually transferred to the callback, i.e. `data` is no longer accessed in the original caller. In your case here, the owner of `data` is still the caller, where the callback just accesses the reference of `data`. Since you call `future.wait` here, the lifetime of the callback could never exceed the caller (`executeCallback`). Hence, a better and simpler solution should be: ```java auto promise = std::make_shared<std::promise<pulsar::Result>>(); napi_status status = tsfn_.BlockingCall([this, promise, &method, &keyName, &metadata, &encKeyInfo]( Napi::Env env, Napi::Function jsCallback) { Napi::HandleScope scope(env); Napi::Object obj = jsObject_.Value(); pulsar::Result res = pulsar::Result::ResultCryptoError; if (obj.Has(method) && obj.Get(method).IsFunction()) { Napi::Function func = obj.Get(method).As<Napi::Function>(); Napi::Object metadataObj = Napi::Object::New(env); for (const auto& kv : metadata) { metadataObj.Set(kv.first, kv.second); } try { Napi::Value result = func.Call(obj, {Napi::String::New(env, keyName), metadataObj}); if (result.IsObject()) { parseEncryptionKeyInfo(result.As<Napi::Object>(), encKeyInfo); res = pulsar::Result::ResultOk; } } catch (...) { res = pulsar::Result::ResultCryptoError; } } promise->set_value(res); }); if (status != napi_ok) { return pulsar::Result::ResultCryptoError; } return promise->get_future().get(); ``` Compared to the existing approach, it does not copy any string like `keyName`, instead, it just captures the reference of them. And the manual fragile `delete` calls are eliminated so that we don't need to worry about memory leak. Furthermore, we can reduce the duplicated code by wrapping the logic before `promise->set_value` into a method. ########## src/CryptoKeyReader.cc: ########## @@ -0,0 +1,182 @@ +/** + * 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 "CryptoKeyReader.h" +#include <pulsar/Result.h> +#include <pulsar/EncryptionKeyInfo.h> +#include <thread> +#include <future> +#include <iostream> + +class CryptoKeyReaderWrapper : public pulsar::CryptoKeyReader { + public: + CryptoKeyReaderWrapper(const Napi::Object& jsObject) : mainThreadId_(std::this_thread::get_id()) { + jsObject_.Reset(jsObject, 1); + tsfn_ = Napi::ThreadSafeFunction::New( + jsObject.Env(), Napi::Function::New(jsObject.Env(), [](const Napi::CallbackInfo& info) {}), jsObject, + "CryptoKeyReader", 0, 1); + } + + ~CryptoKeyReaderWrapper() { tsfn_.Release(); } + + pulsar::Result getPublicKey(const std::string& keyName, std::map<std::string, std::string>& metadata, + pulsar::EncryptionKeyInfo& encKeyInfo) const override { + return executeCallback("getPublicKey", keyName, metadata, encKeyInfo); + } + + pulsar::Result getPrivateKey(const std::string& keyName, std::map<std::string, std::string>& metadata, + pulsar::EncryptionKeyInfo& encKeyInfo) const override { + return executeCallback("getPrivateKey", keyName, metadata, encKeyInfo); + } + + private: + mutable Napi::ObjectReference jsObject_; Review Comment: Instead of adding `mutable` here, it's better to change `CallbackData.jsObjectRef` to `const Napi::ObjectReference*` because only const methods are called on `jsObjectRef`. -- 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]
