Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 60 additions & 39 deletions src/Authentication.cc
Original file line number Diff line number Diff line change
Expand Up @@ -26,59 +26,67 @@ static const std::string PARAM_TOKEN = "token";
static const std::string PARAM_USERNAME = "username";
static const std::string PARAM_PASSWORD = "password";

void FinalizeTokenSupplierCallback(Napi::Env env, TokenSupplierCallback *cb, void *) { delete cb; }

struct TokenSupplierProxyData {
std::function<void(void)> callback;
std::string token;

TokenSupplierProxyData(std::function<void(void)> callback) : callback(callback), token(std::string()) {}
struct TokenSupplierProxyData : std::enable_shared_from_this<TokenSupplierProxyData> {
std::promise<std::string> result;
bool completed = false;

// Completion and cancellation both run on the JS thread.
void Complete(std::string token) {
if (!completed) {
completed = true;
result.set_value(std::move(token));
}
}
};

void TokenSupplierProxy(Napi::Env env, Napi::Function jsCallback, TokenSupplierProxyData *data) {
auto request = data->shared_from_this();
Napi::Value ret = jsCallback.Call({});
if (ret.IsPromise()) {
Napi::Promise promise = ret.As<Napi::Promise>();
Napi::Value thenValue = promise.Get("then");
if (thenValue.IsFunction()) {
Napi::Function then = thenValue.As<Napi::Function>();
Napi::Function callback = Napi::Function::New(env, [data](const Napi::CallbackInfo &info) {
Napi::Function callback = Napi::Function::New(env, [request](const Napi::CallbackInfo &info) {
Napi::Value value = info[0];
if (value.IsString()) {
data->token = value.ToString().Utf8Value();
}
data->callback();
request->Complete(value.IsString() ? value.ToString().Utf8Value() : std::string());
});
then.Call(promise, {callback});
return;
}
}
if (ret.IsString()) {
data->token = ret.ToString().Utf8Value();
}
data->callback();
request->Complete(ret.IsString() ? ret.ToString().Utf8Value() : std::string());
}

char *TokenSupplier(void *ctx) {
TokenSupplierCallback *tokenSupplierCallback = (TokenSupplierCallback *)ctx;
if (tokenSupplierCallback->callback.Acquire() != napi_ok) {
char *empty = (char *)malloc(0);
return empty;
}

std::promise<void> promise;
std::future<void> future = promise.get_future();

std::unique_ptr<TokenSupplierProxyData> dataPtr(
new TokenSupplierProxyData([&promise]() { promise.set_value(); }));

tokenSupplierCallback->callback.BlockingCall(dataPtr.get(), TokenSupplierProxy);
tokenSupplierCallback->callback.Release();
auto tokenSupplierCallback = static_cast<TokenSupplierCallback *>(ctx)->shared_from_this();
auto request = std::make_shared<TokenSupplierProxyData>();
auto future = request->result.get_future();

{
std::lock_guard<std::mutex> lock(tokenSupplierCallback->mutex);
if (tokenSupplierCallback->finalized || tokenSupplierCallback->callback.Acquire() != napi_ok) {
return static_cast<char *>(calloc(1, 1));
}

future.wait();
tokenSupplierCallback->pending.insert(request);
napi_status status = tokenSupplierCallback->callback.BlockingCall(request.get(), TokenSupplierProxy);
if (status != napi_closing) {
tokenSupplierCallback->callback.Release();
}
if (status != napi_ok) {
tokenSupplierCallback->pending.erase(request);
return static_cast<char *>(calloc(1, 1));
}
}

char *token = (char *)malloc(dataPtr->token.size() + 1);
strcpy(token, dataPtr->token.c_str());
std::string value = future.get();
{
std::lock_guard<std::mutex> lock(tokenSupplierCallback->mutex);
tokenSupplierCallback->pending.erase(request);
}
char *token = (char *)malloc(value.size() + 1);
strcpy(token, value.c_str());
return token;
}

Expand Down Expand Up @@ -134,14 +142,24 @@ Authentication::Authentication(const Napi::CallbackInfo &info)
}

if (obj.Get(PARAM_TOKEN).IsFunction()) {
this->tokenSupplier = new TokenSupplierCallback();
Napi::ThreadSafeFunction callback = Napi::ThreadSafeFunction::New(
obj.Env(), obj.Get(PARAM_TOKEN).As<Napi::Function>(), "Token Supplier Callback", 1, 1,
(void *)NULL, FinalizeTokenSupplierCallback, this->tokenSupplier);
this->tokenSupplier = std::make_shared<TokenSupplierCallback>();
std::shared_ptr<TokenSupplierCallback> tokenSupplier = this->tokenSupplier;
// An unbounded queue keeps BlockingCall from waiting while the mutex is held.
Napi::ThreadSafeFunction callback =
Napi::ThreadSafeFunction::New(obj.Env(), obj.Get(PARAM_TOKEN).As<Napi::Function>(),
"Token Supplier Callback", 0, 1, [tokenSupplier](Napi::Env) {
std::lock_guard<std::mutex> lock(tokenSupplier->mutex);
tokenSupplier->finalized = true;
for (const auto &request : tokenSupplier->pending) {
request->Complete(std::string());
}
tokenSupplier->pending.clear();
});
this->tokenSupplier->callback = std::move(callback);
this->tokenSupplier->callback.Unref(env);

this->cAuthentication =
pulsar_authentication_token_create_with_supplier(&TokenSupplier, this->tokenSupplier);
pulsar_authentication_token_create_with_supplier(&TokenSupplier, this->tokenSupplier.get());
return;
}
}
Expand Down Expand Up @@ -179,7 +197,10 @@ Authentication::Authentication(const Napi::CallbackInfo &info)

Authentication::~Authentication() {
if (this->tokenSupplier != nullptr) {
this->tokenSupplier->callback.Release();
std::lock_guard<std::mutex> lock(this->tokenSupplier->mutex);
if (!this->tokenSupplier->finalized) {
this->tokenSupplier->callback.Release();
}
}
if (this->cAuthentication != nullptr) {
pulsar_authentication_free(this->cAuthentication);
Expand Down
3 changes: 2 additions & 1 deletion src/Authentication.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#ifndef AUTH_H
#define AUTH_H

#include <memory>
#include <napi.h>
#include <pulsar/c/authentication.h>
#include "TokenSupplier.h"
Expand All @@ -35,7 +36,7 @@ class Authentication : public Napi::ObjectWrap<Authentication> {
static Napi::FunctionReference constructor;
pulsar_authentication_t *cAuthentication;

TokenSupplierCallback *tokenSupplier;
std::shared_ptr<TokenSupplierCallback> tokenSupplier;
};

#endif
71 changes: 39 additions & 32 deletions src/Client.cc
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ static const std::string CFG_LOG_LEVEL = "logLevel";
static const std::string CFG_LISTENER_NAME = "listenerName";
static const std::string CFG_CONNECTION_TIMEOUT = "connectionTimeoutMs";

LogCallback *Client::logCallback = nullptr;
std::shared_ptr<LogCallback> Client::logCallback;
std::mutex Client::logMutex;

struct _pulsar_client_configuration {
pulsar::ClientConfiguration conf;
Expand Down Expand Up @@ -259,27 +260,34 @@ static std::unique_ptr<pulsar::ServiceInfoProvider> BuildServiceInfoProvider(
void Client::SetLogHandler(const Napi::CallbackInfo &info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
Napi::Value jsFunction = info[0];
ConfigureLogHandler(info[0]);
}

if (jsFunction.IsNull()) {
if (Client::logCallback != nullptr) {
Client::logCallback->callback.Release();
delete Client::logCallback;
Client::logCallback = nullptr;
}
} else if (jsFunction.IsFunction()) {
Napi::ThreadSafeFunction logFunction =
Napi::ThreadSafeFunction::New(env, jsFunction.As<Napi::Function>(), "Pulsar Logging", 0, 1);
logFunction.Unref(env);
if (Client::logCallback != nullptr) {
Client::logCallback->callback.Release();
} else {
Client::logCallback = new LogCallback();
}
Client::logCallback->callback = std::move(logFunction);
} else {
void Client::ConfigureLogHandler(Napi::Value jsFunction) {
Napi::Env env = jsFunction.Env();
if (!jsFunction.IsNull() && !jsFunction.IsFunction()) {
Napi::Error::New(env, "Client log handler must be a function or null").ThrowAsJavaScriptException();
return;
}

std::shared_ptr<LogCallback> next;
if (jsFunction.IsFunction()) {
next = std::make_shared<LogCallback>();
next->callback = Napi::ThreadSafeFunction::New(env, jsFunction.As<Napi::Function>(), "Pulsar Logging", 0,
1, [next](Napi::Env) {
std::lock_guard<std::mutex> lock(logMutex);
if (logCallback == next) {
logCallback.reset();
}
});
next->callback.Unref(env);
}

std::lock_guard<std::mutex> lock(logMutex);
if (logCallback != nullptr) {
logCallback->callback.Release();
}
logCallback = std::move(next);
}

Napi::FunctionReference Client::constructor;
Expand Down Expand Up @@ -352,16 +360,7 @@ Client::Client(const Napi::CallbackInfo &info) : Napi::ObjectWrap<Client>(info)

// log config option should be deprecated in favour of static setLogHandler method
if (clientConfig.Has(CFG_LOG) && clientConfig.Get(CFG_LOG).IsFunction()) {
Napi::ThreadSafeFunction logFunction = Napi::ThreadSafeFunction::New(
env, clientConfig.Get(CFG_LOG).As<Napi::Function>(), "Pulsar Logging", 0, 1);
logFunction.Unref(env);

if (Client::logCallback != nullptr) {
Client::logCallback->callback.Release();
} else {
Client::logCallback = new LogCallback();
}
Client::logCallback->callback = std::move(logFunction);
ConfigureLogHandler(clientConfig.Get(CFG_LOG));
}

if (clientConfig.Has(CFG_AUTH) && clientConfig.Get(CFG_AUTH).IsObject()) {
Expand Down Expand Up @@ -535,7 +534,10 @@ void LogMessageProxy(Napi::Env env, Napi::Function jsCallback, struct LogMessage

void Client::LogMessage(pulsar_logger_level_t level, const char *file, int line, const char *message,
void *ctx) {
LogCallback *logCallback = Client::logCallback;
// The logging TSFN uses maxQueueSize = 0, so BlockingCall does not wait
// for JS to drain the queue while logMutex is held.
std::lock_guard<std::mutex> lock(logMutex);
auto logCallback = Client::logCallback;

if (logCallback == nullptr) {
return;
Expand All @@ -547,8 +549,13 @@ void Client::LogMessage(pulsar_logger_level_t level, const char *file, int line,

struct LogMessage *logMessage = new struct LogMessage(level, std::string(file), line, std::string(message));

logCallback->callback.BlockingCall(logMessage, LogMessageProxy);
logCallback->callback.Release();
napi_status status = logCallback->callback.BlockingCall(logMessage, LogMessageProxy);
if (status != napi_ok) {
delete logMessage;
}
if (status != napi_closing) {
logCallback->callback.Release();
}
}

Napi::Value Client::Close(const Napi::CallbackInfo &info) {
Expand Down
6 changes: 5 additions & 1 deletion src/Client.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
#ifndef CLIENT_H
#define CLIENT_H

#include <memory>
#include <mutex>
#include <napi.h>
#include <pulsar/c/client.h>
#include <vector>
Expand Down Expand Up @@ -50,13 +52,15 @@ class Client : public Napi::ObjectWrap<Client> {
~Client();

private:
static LogCallback *logCallback;
static std::shared_ptr<LogCallback> logCallback;
static std::mutex logMutex;
static Napi::FunctionReference constructor;
std::shared_ptr<pulsar_client_t> cClient;
std::shared_ptr<pulsar_client_configuration_t> cClientConfig;
pulsar_logger_level_t logLevel = pulsar_logger_level_t::pulsar_INFO;
std::vector<Napi::ObjectReference> authRefs_;

static void ConfigureLogHandler(Napi::Value jsFunction);
Napi::Value CreateProducer(const Napi::CallbackInfo &info);
Napi::Value Subscribe(const Napi::CallbackInfo &info);
Napi::Value CreateReader(const Napi::CallbackInfo &info);
Expand Down
10 changes: 9 additions & 1 deletion src/TokenSupplier.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,18 @@
#ifndef PULSAR_CLIENT_NODE_TOKENSUPPLIER_H
#define PULSAR_CLIENT_NODE_TOKENSUPPLIER_H

#include <memory>
#include <mutex>
#include <napi.h>
#include <unordered_set>

struct TokenSupplierCallback {
struct TokenSupplierProxyData;

struct TokenSupplierCallback : std::enable_shared_from_this<TokenSupplierCallback> {
Napi::ThreadSafeFunction callback;
std::mutex mutex;
bool finalized = false;
std::unordered_set<std::shared_ptr<TokenSupplierProxyData>> pending;

TokenSupplierCallback() {}
};
Expand Down
Loading
Loading