1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
|
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <thread>
#include "assert.h"
#include "napi.h"
using namespace Napi;
class TestWorkerWithUserDefRecv : public AsyncWorker {
public:
static void DoWork(const CallbackInfo& info) {
Object recv = info[0].As<Object>();
Function cb = info[1].As<Function>();
TestWorkerWithUserDefRecv* worker = new TestWorkerWithUserDefRecv(recv, cb);
worker->Queue();
}
static void DoWorkWithAsyncRes(const CallbackInfo& info) {
Object recv = info[0].As<Object>();
Function cb = info[1].As<Function>();
Value resource = info[2];
TestWorkerWithUserDefRecv* worker = nullptr;
if (resource == info.Env().Null()) {
worker = new TestWorkerWithUserDefRecv(recv, cb, "TestResource");
} else {
worker = new TestWorkerWithUserDefRecv(
recv, cb, "TestResource", resource.As<Object>());
}
worker->Queue();
}
protected:
void Execute() override {}
private:
TestWorkerWithUserDefRecv(const Object& recv, const Function& cb)
: AsyncWorker(recv, cb) {}
TestWorkerWithUserDefRecv(const Object& recv,
const Function& cb,
const char* resource_name)
: AsyncWorker(recv, cb, resource_name) {}
TestWorkerWithUserDefRecv(const Object& recv,
const Function& cb,
const char* resource_name,
const Object& resource)
: AsyncWorker(recv, cb, resource_name, resource) {}
};
// Using default std::allocator impl, but assuming user can define their own
// allocate/deallocate methods
class CustomAllocWorker : public AsyncWorker {
using Allocator = std::allocator<CustomAllocWorker>;
public:
CustomAllocWorker(Function& cb) : AsyncWorker(cb){};
static void DoWork(const CallbackInfo& info) {
Function cb = info[0].As<Function>();
Allocator allocator;
CustomAllocWorker* newWorker = allocator.allocate(1);
std::allocator_traits<Allocator>::construct(allocator, newWorker, cb);
newWorker->Queue();
}
protected:
void Execute() override {}
void Destroy() override {
assert(this->_secretVal == 24);
Allocator allocator;
std::allocator_traits<Allocator>::destroy(allocator, this);
allocator.deallocate(this, 1);
}
private:
int _secretVal = 24;
};
class TestWorker : public AsyncWorker {
public:
static void DoWork(const CallbackInfo& info) {
bool succeed = info[0].As<Boolean>();
Object resource = info[1].As<Object>();
Function cb = info[2].As<Function>();
Value data = info[3];
TestWorker* worker = nullptr;
if (resource == info.Env().Null()) {
worker = new TestWorker(cb, "TestResource");
} else {
worker = new TestWorker(cb, "TestResource", resource);
}
worker->Receiver().Set("data", data);
worker->_succeed = succeed;
worker->Queue();
}
protected:
void Execute() override {
if (!_succeed) {
SetError("test error");
}
}
private:
TestWorker(Function cb, const char* resource_name, const Object& resource)
: AsyncWorker(cb, resource_name, resource) {}
TestWorker(Function cb, const char* resource_name)
: AsyncWorker(cb, resource_name) {}
bool _succeed{};
};
class TestWorkerWithResult : public AsyncWorker {
public:
static void DoWork(const CallbackInfo& info) {
bool succeed = info[0].As<Boolean>();
Object resource = info[1].As<Object>();
Function cb = info[2].As<Function>();
Value data = info[3];
TestWorkerWithResult* worker =
new TestWorkerWithResult(cb, "TestResource", resource);
worker->Receiver().Set("data", data);
worker->_succeed = succeed;
worker->Queue();
}
protected:
void Execute() override {
if (!_succeed) {
SetError("test error");
}
}
std::vector<napi_value> GetResult(Napi::Env env) override {
return {Boolean::New(env, _succeed),
String::New(env, _succeed ? "ok" : "error")};
}
private:
TestWorkerWithResult(Function cb,
const char* resource_name,
const Object& resource)
: AsyncWorker(cb, resource_name, resource) {}
bool _succeed{};
};
class TestWorkerNoCallback : public AsyncWorker {
public:
static Value DoWork(const CallbackInfo& info) {
bool succeed = info[0].As<Boolean>();
TestWorkerNoCallback* worker = new TestWorkerNoCallback(info.Env());
worker->_succeed = succeed;
worker->Queue();
return worker->_deferred.Promise();
}
static Value DoWorkWithAsyncRes(const CallbackInfo& info) {
napi_env env = info.Env();
bool succeed = info[0].As<Boolean>();
Object resource = info[1].As<Object>();
TestWorkerNoCallback* worker = nullptr;
if (resource == info.Env().Null()) {
worker = new TestWorkerNoCallback(env, "TestResource");
} else {
worker = new TestWorkerNoCallback(env, "TestResource", resource);
}
worker->_succeed = succeed;
worker->Queue();
return worker->_deferred.Promise();
}
protected:
void Execute() override {}
virtual void OnOK() override { _deferred.Resolve(Env().Undefined()); }
virtual void OnError(const Napi::Error& /* e */) override {
_deferred.Reject(Env().Undefined());
}
private:
TestWorkerNoCallback(Napi::Env env)
: AsyncWorker(env), _deferred(Napi::Promise::Deferred::New(env)) {}
TestWorkerNoCallback(napi_env env, const char* resource_name)
: AsyncWorker(env, resource_name),
_deferred(Napi::Promise::Deferred::New(env)) {}
TestWorkerNoCallback(napi_env env,
const char* resource_name,
const Object& resource)
: AsyncWorker(env, resource_name, resource),
_deferred(Napi::Promise::Deferred::New(env)) {}
Promise::Deferred _deferred;
bool _succeed{};
};
class EchoWorker : public AsyncWorker {
public:
EchoWorker(Function& cb, std::string& echo) : AsyncWorker(cb), echo(echo) {}
~EchoWorker() {}
void Execute() override {
// Simulate cpu heavy task
std::this_thread::sleep_for(std::chrono::milliseconds(30));
}
void OnOK() override {
HandleScope scope(Env());
Callback().Call({Env().Null(), String::New(Env(), echo)});
}
private:
std::string echo;
};
class FailCancelWorker : public AsyncWorker {
private:
bool taskIsRunning = false;
std::mutex mu;
std::condition_variable taskStartingCv;
void NotifyJSThreadTaskHasStarted() {
{
std::lock_guard<std::mutex> lk(mu);
taskIsRunning = true;
taskStartingCv.notify_one();
}
}
public:
FailCancelWorker(Function& cb) : AsyncWorker(cb) {}
~FailCancelWorker() {}
void WaitForWorkerTaskToStart() {
std::unique_lock<std::mutex> lk(mu);
taskStartingCv.wait(lk, [this] { return taskIsRunning; });
taskIsRunning = false;
}
static void DoCancel(const CallbackInfo& info) {
Function cb = info[0].As<Function>();
FailCancelWorker* cancelWorker = new FailCancelWorker(cb);
cancelWorker->Queue();
cancelWorker->WaitForWorkerTaskToStart();
#ifdef NAPI_CPP_EXCEPTIONS
try {
cancelWorker->Cancel();
} catch (Napi::Error&) {
Napi::Error::New(info.Env(), "Unable to cancel async worker tasks")
.ThrowAsJavaScriptException();
}
#else
cancelWorker->Cancel();
#endif
}
void Execute() override {
NotifyJSThreadTaskHasStarted();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
void OnOK() override {}
void OnError(const Error&) override {}
};
class CancelWorker : public AsyncWorker {
public:
CancelWorker(Function& cb) : AsyncWorker(cb) {}
~CancelWorker() {}
static void DoWork(const CallbackInfo& info) {
Function cb = info[0].As<Function>();
std::string echo = info[1].As<String>();
int threadNum = info[2].As<Number>().Uint32Value();
for (int i = 0; i < threadNum; i++) {
AsyncWorker* worker = new EchoWorker(cb, echo);
worker->Queue();
assert(worker->Env() == info.Env());
}
AsyncWorker* cancelWorker = new CancelWorker(cb);
cancelWorker->Queue();
#ifdef NAPI_CPP_EXCEPTIONS
try {
cancelWorker->Cancel();
} catch (Napi::Error&) {
Napi::Error::New(info.Env(), "Unable to cancel async worker tasks")
.ThrowAsJavaScriptException();
}
#else
cancelWorker->Cancel();
#endif
}
void Execute() override {
// Simulate cpu heavy task
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
void OnOK() override {
Napi::Error::New(this->Env(),
"OnOk should not be invoked on successful cancellation")
.ThrowAsJavaScriptException();
}
void OnError(const Error&) override {
Napi::Error::New(this->Env(),
"OnError should not be invoked on successful cancellation")
.ThrowAsJavaScriptException();
}
};
Object InitAsyncWorker(Env env) {
Object exports = Object::New(env);
exports["doWorkRecv"] = Function::New(env, TestWorkerWithUserDefRecv::DoWork);
exports["doWithRecvAsyncRes"] =
Function::New(env, TestWorkerWithUserDefRecv::DoWorkWithAsyncRes);
exports["doWork"] = Function::New(env, TestWorker::DoWork);
exports["doWorkAsyncResNoCallback"] =
Function::New(env, TestWorkerNoCallback::DoWorkWithAsyncRes);
exports["doWorkNoCallback"] =
Function::New(env, TestWorkerNoCallback::DoWork);
exports["doWorkWithResult"] =
Function::New(env, TestWorkerWithResult::DoWork);
exports["tryCancelQueuedWork"] = Function::New(env, CancelWorker::DoWork);
exports["expectCancelToFail"] =
Function::New(env, FailCancelWorker::DoCancel);
exports["expectCustomAllocWorkerToDealloc"] =
Function::New(env, CustomAllocWorker::DoWork);
return exports;
}
|