Skip to content

Commit 2c87f35

Browse files
committed
Initial Worker threads/context aware support
1 parent 4f6c9d8 commit 2c87f35

9 files changed

Lines changed: 199 additions & 112 deletions

File tree

‎build.c‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,8 @@ void prepare() {
5555

5656
/* Build for Unix systems */
5757
void build(char *compiler, char *cpp_compiler, char *cpp_linker, char *os, char *arch) {
58-
char *c_shared = "-DLIBUS_USE_LIBUV -flto -O3 -c -fPIC -I uWebSockets/uSockets/src uWebSockets/uSockets/src/*.c uWebSockets/uSockets/src/eventing/*.c";
59-
char *cpp_shared = "-DLIBUS_USE_LIBUV -flto -O3 -c -fPIC -std=c++17 -I uWebSockets/uSockets/src -I uWebSockets/src src/addon.cpp";
58+
char *c_shared = "-DLIBUS_USE_LIBUV -DLIBUS_USE_OPENSSL -flto -O3 -c -fPIC -I uWebSockets/uSockets/src uWebSockets/uSockets/src/*.c uWebSockets/uSockets/src/eventing/*.c uWebSockets/uSockets/src/crypto/*.c";
59+
char *cpp_shared = "-DLIBUS_USE_LIBUV -DLIBUS_USE_OPENSSL -flto -O3 -c -fPIC -std=c++17 -I uWebSockets/uSockets/src -I uWebSockets/src src/addon.cpp";
6060

6161
for (unsigned int i = 0; i < sizeof(versions) / sizeof(struct node_version); i++) {
6262
run("%s %s -I targets/node-%s/include/node", compiler, c_shared, versions[i].name);
@@ -77,8 +77,8 @@ void copy_files() {
7777
void build_windows(char *arch) {
7878
/* For all versions */
7979
for (unsigned int i = 0; i < sizeof(versions) / sizeof(struct node_version); i++) {
80-
run("cl /D \"LIBUS_USE_LIBUV\" /std:c++17 /I uWebSockets/uSockets/src uWebSockets/uSockets/src/*.c "
81-
"uWebSockets/uSockets/src/eventing/*.c /I targets/node-%s/include/node /I uWebSockets/src /EHsc "
80+
run("cl /D \"LIBUS_USE_LIBUV\" /D \"LIBUS_USE_OPENSSL\" /std:c++17 /I uWebSockets/uSockets/src uWebSockets/uSockets/src/*.c "
81+
"uWebSockets/uSockets/src/eventing/*.c uWebSockets/uSockets/src/crypto/*.c /I targets/node-%s/include/node /I uWebSockets/src /EHsc "
8282
"/Ox /LD /Fedist/uws_win32_%s_%s.node src/addon.cpp targets/node-%s/node.lib",
8383
versions[i].name, arch, versions[i].abi, versions[i].name);
8484
}

‎examples/WorkerThreads.js‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/* This example spawns two worker threads, each with their own
2+
* server listening to the same port (Linux feature). */
3+
4+
const uWS = require('../dist/uws.js');
5+
const port = 9001;
6+
const { Worker, isMainThread, threadId } = require('worker_threads');
7+
const os = require('os');
8+
9+
if (isMainThread) {
10+
/* Main thread loops over all CPUs */
11+
/* In this case we only spawn two (hardcoded) */
12+
/*os.cpus()*/[0, 1].forEach(() => {
13+
/* Spawn a new thread running this source file */
14+
new Worker(__filename);
15+
});
16+
17+
/* I guess main thread joins by default? */
18+
} else {
19+
/* Here we are inside a worker thread */
20+
const app = uWS./*SSL*/App({
21+
key_file_name: 'misc/key.pem',
22+
cert_file_name: 'misc/cert.pem',
23+
passphrase: '1234'
24+
}).get('/*', (res, req) => {
25+
res.end('Hello Worker!');
26+
}).listen(port, (token) => {
27+
if (token) {
28+
console.log('Listening to port ' + port + ' from thread ' + threadId);
29+
} else {
30+
console.log('Failed to listen to port ' + port + ' from thread ' + threadId);
31+
}
32+
});
33+
}

‎src/AppWrapper.h‎

Lines changed: 52 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,11 @@ using namespace v8;
66
/* uWS.App.ws('/pattern', behavior) */
77
template <typename APP>
88
void uWS_App_ws(const FunctionCallbackInfo<Value> &args) {
9+
10+
Isolate *isolate = args.GetIsolate();
11+
12+
PerContextData *perContextData = (PerContextData *) Local<External>::Cast(args.Data())->Value();
13+
914
APP *app = (APP *) args.Holder()->GetAlignedPointerFromInternalField(0);
1015
/* This one is default constructed with defaults */
1116
typename APP::WebSocketBehavior behavior = {};
@@ -63,15 +68,16 @@ void uWS_App_ws(const FunctionCallbackInfo<Value> &args) {
6368
}
6469

6570
/* Open handler is NOT optional for the wrapper */
66-
behavior.open = [openPf = std::move(openPf)](auto *ws, auto *req) {
71+
behavior.open = [openPf = std::move(openPf), perContextData](auto *ws, auto *req) {
72+
Isolate *isolate = perContextData->isolate;
6773
HandleScope hs(isolate);
6874

6975
/* Create a new websocket object */
70-
Local<Object> wsObject = WebSocketWrapper::getWsInstance<APP>();
76+
Local<Object> wsObject = perContextData->wsTemplate[getAppTypeIndex<APP>()].Get(isolate)->Clone();
7177
wsObject->SetAlignedPointerInInternalField(0, ws);
7278

7379
/* Create the HttpRequest wrapper */
74-
Local<Object> reqObject = HttpRequestWrapper::getReqInstance();
80+
Local<Object> reqObject = perContextData->reqTemplate.Get(isolate)->Clone();
7581
reqObject->SetAlignedPointerInInternalField(0, req);
7682

7783
/* Attach a new V8 object with pointer to us, to us */
@@ -88,7 +94,7 @@ void uWS_App_ws(const FunctionCallbackInfo<Value> &args) {
8894

8995
/* Message handler is always optional */
9096
if (messagePf != Undefined(isolate)) {
91-
behavior.message = [messagePf = std::move(messagePf)](auto *ws, std::string_view message, uWS::OpCode opCode) {
97+
behavior.message = [messagePf = std::move(messagePf), isolate](auto *ws, std::string_view message, uWS::OpCode opCode) {
9298
HandleScope hs(isolate);
9399

94100
Local<ArrayBuffer> messageArrayBuffer = ArrayBuffer::New(isolate, (void *) message.data(), message.length());
@@ -106,7 +112,7 @@ void uWS_App_ws(const FunctionCallbackInfo<Value> &args) {
106112

107113
/* Drain handler is always optional */
108114
if (drainPf != Undefined(isolate)) {
109-
behavior.drain = [drainPf = std::move(drainPf)](auto *ws) {
115+
behavior.drain = [drainPf = std::move(drainPf), isolate](auto *ws) {
110116
HandleScope hs(isolate);
111117

112118
PerSocketData *perSocketData = (PerSocketData *) ws->getUserData();
@@ -126,7 +132,7 @@ void uWS_App_ws(const FunctionCallbackInfo<Value> &args) {
126132
};
127133

128134
/* Close handler is NOT optional for the wrapper */
129-
behavior.close = [closePf = std::move(closePf)](auto *ws, int code, std::string_view message) {
135+
behavior.close = [closePf = std::move(closePf), isolate](auto *ws, int code, std::string_view message) {
130136
HandleScope hs(isolate);
131137

132138
Local<ArrayBuffer> messageArrayBuffer = ArrayBuffer::New(isolate, (void *) message.data(), message.length());
@@ -165,21 +171,22 @@ void uWS_App_get(F f, const FunctionCallbackInfo<Value> &args) {
165171
return;
166172
}
167173

168-
/* todo: make it UniquePersistent */
169-
std::shared_ptr<Persistent<Function>> pf(new Persistent<Function>);
170-
pf->Reset(args.GetIsolate(), Local<Function>::Cast(args[1]));
174+
/* This function requires perContextData */
175+
PerContextData *perContextData = (PerContextData *) Local<External>::Cast(args.Data())->Value();
176+
UniquePersistent<Function> cb(args.GetIsolate(), Local<Function>::Cast(args[1]));
171177

172-
(app->*f)(std::string(pattern.getString()), [pf](auto *res, auto *req) {
178+
(app->*f)(std::string(pattern.getString()), [cb = std::move(cb), perContextData](auto *res, auto *req) {
179+
Isolate *isolate = perContextData->isolate;
173180
HandleScope hs(isolate);
174181

175-
Local<Object> resObject = HttpResponseWrapper::getResInstance<APP>();
182+
Local<Object> resObject = perContextData->resTemplate[getAppTypeIndex<APP>()].Get(isolate)->Clone();
176183
resObject->SetAlignedPointerInInternalField(0, res);
177184

178-
Local<Object> reqObject = HttpRequestWrapper::getReqInstance();
185+
Local<Object> reqObject = perContextData->reqTemplate.Get(isolate)->Clone();
179186
reqObject->SetAlignedPointerInInternalField(0, req);
180187

181188
Local<Value> argv[] = {resObject, reqObject};
182-
Local<Function>::New(isolate, *pf)->Call(isolate->GetCurrentContext(), isolate->GetCurrentContext()->Global(), 2, argv).IsEmpty();
189+
cb.Get(isolate)->Call(isolate->GetCurrentContext(), isolate->GetCurrentContext()->Global(), 2, argv).IsEmpty();
183190

184191
/* Properly invalidate req */
185192
reqObject->SetAlignedPointerInInternalField(0, nullptr);
@@ -195,6 +202,8 @@ template <typename APP>
195202
void uWS_App_listen(const FunctionCallbackInfo<Value> &args) {
196203
APP *app = (APP *) args.Holder()->GetAlignedPointerFromInternalField(0);
197204

205+
Isolate *isolate = args.GetIsolate();
206+
198207
/* Require at least two arguments */
199208
if (args.Length() < 2) {
200209
/* Throw here */
@@ -203,7 +212,7 @@ void uWS_App_listen(const FunctionCallbackInfo<Value> &args) {
203212
}
204213

205214
/* Callback is last */
206-
auto cb = [&args](auto *token) {
215+
auto cb = [&args, isolate](auto *token) {
207216
/* Return a false boolean if listen failed */
208217
Local<Value> argv[] = {token ? Local<Value>::Cast(External::New(isolate, token)) : Local<Value>::Cast(Boolean::New(isolate, false))};
209218
Local<Function>::Cast(args[args.Length() - 1])->Call(isolate->GetCurrentContext(), isolate->GetCurrentContext()->Global(), 1, argv).IsEmpty();
@@ -236,29 +245,35 @@ template <typename APP>
236245
void uWS_App_publish(const FunctionCallbackInfo<Value> &args) {
237246
APP *app = (APP *) args.Holder()->GetAlignedPointerFromInternalField(0);
238247

248+
Isolate *isolate = args.GetIsolate();
249+
239250
NativeString topic(isolate, args[0]);
240251
NativeString message(isolate, args[1]);
241252
app->publish(topic.getString(), message.getString(), BooleanValue(isolate, args[2]) ? uWS::OpCode::BINARY : uWS::OpCode::TEXT, BooleanValue(isolate, args[3]));
242253
}
243254

244255
template <typename APP>
245256
void uWS_App(const FunctionCallbackInfo<Value> &args) {
257+
258+
Isolate *isolate = args.GetIsolate();
259+
246260
Local<FunctionTemplate> appTemplate = FunctionTemplate::New(isolate);
247261

248262
APP *app;
249263

264+
/* These won't outlive the function, uSockets will have to copy strings it wants to keep! */
265+
std::string keyFileName;
266+
std::string certFileName;
267+
std::string passphrase;
268+
std::string dhParamsFileName;
269+
250270
/* Name differs based on type */
251271
if (std::is_same<APP, uWS::SSLApp>::value) {
252272
appTemplate->SetClassName(String::NewFromUtf8(isolate, "uWS.SSLApp", NewStringType::kNormal).ToLocalChecked());
253273

254274
/* We fill these below */
255275
us_socket_context_options_t ssl_options = {};
256276

257-
static std::string keyFileName;
258-
static std::string certFileName;
259-
static std::string passphrase;
260-
static std::string dhParamsFileName;
261-
262277
/* Read the options object (SSL options) */
263278
if (args.Length() == 1) {
264279

@@ -308,6 +323,7 @@ void uWS_App(const FunctionCallbackInfo<Value> &args) {
308323
ssl_options.ssl_prefer_low_memory_usage = BooleanValue(isolate, optionsObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "ssl_prefer_low_memory_usage", NewStringType::kNormal).ToLocalChecked()).ToLocalChecked());
309324
}
310325

326+
/* uSockets should really copy strings it wants to keep */
311327
app = new APP(ssl_options);
312328
} else {
313329
appTemplate->SetClassName(String::NewFromUtf8(isolate, "uWS.App", NewStringType::kNormal).ToLocalChecked());
@@ -326,58 +342,60 @@ void uWS_App(const FunctionCallbackInfo<Value> &args) {
326342
/* All the http methods */
327343
appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "get", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, [](auto &args) {
328344
uWS_App_get<APP>(&APP::get, args);
329-
}));
345+
}, args.Data()));
330346

331347
appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "post", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, [](auto &args) {
332348
uWS_App_get<APP>(&APP::post, args);
333-
}));
349+
}, args.Data()));
334350

335351
appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "options", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, [](auto &args) {
336352
uWS_App_get<APP>(&APP::options, args);
337-
}));
353+
}, args.Data()));
338354

339355
appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "del", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, [](auto &args) {
340356
uWS_App_get<APP>(&APP::del, args);
341-
}));
357+
}, args.Data()));
342358

343359
appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "patch", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, [](auto &args) {
344360
uWS_App_get<APP>(&APP::patch, args);
345-
}));
361+
}, args.Data()));
346362

347363
appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "put", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, [](auto &args) {
348364
uWS_App_get<APP>(&APP::put, args);
349-
}));
365+
}, args.Data()));
350366

351367
appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "head", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, [](auto &args) {
352368
uWS_App_get<APP>(&APP::head, args);
353-
}));
369+
}, args.Data()));
354370

355371
appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "connect", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, [](auto &args) {
356372
uWS_App_get<APP>(&APP::connect, args);
357-
}));
373+
}, args.Data()));
358374

359375
appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "trace", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, [](auto &args) {
360376
uWS_App_get<APP>(&APP::trace, args);
361-
}));
377+
}, args.Data()));
362378

363379
/* Any http method */
364380
appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "any", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, [](auto &args) {
365381
uWS_App_get<APP>(&APP::any, args);
366-
}));
382+
}, args.Data()));
367383

368384
/* ws, listen */
369-
appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "ws", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_ws<APP>));
370-
appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "listen", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_listen<APP>));
371-
appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "publish", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_publish<APP>));
385+
appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "ws", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_ws<APP>, args.Data()));
386+
appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "listen", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_listen<APP>, args.Data()));
387+
appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "publish", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_publish<APP>, args.Data()));
372388

373389
Local<Object> localApp = appTemplate->GetFunction(isolate->GetCurrentContext()).ToLocalChecked()->NewInstance(isolate->GetCurrentContext()).ToLocalChecked();
374390
localApp->SetAlignedPointerInInternalField(0, app);
375391

392+
PerContextData *perContextData = (PerContextData *) Local<External>::Cast(args.Data())->Value();
393+
376394
/* Add this to our delete list */
377395
if constexpr (std::is_same<APP, uWS::SSLApp>::value) {
378-
sslApps.emplace_back(app);
396+
perContextData->sslApps.emplace_back(app);
379397
} else {
380-
apps.emplace_back(app);
398+
perContextData->apps.emplace_back(app);
381399
}
382400

383401
args.GetReturnValue().Set(localApp);

‎src/HttpRequestWrapper.h‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
#include "App.h"
2-
#include <v8.h>
32
#include "Utilities.h"
3+
4+
#include <v8.h>
45
using namespace v8;
56

67
/* This one is the same for SSL and non-SSL */
78
struct HttpRequestWrapper {
8-
static Persistent<Object> reqTemplate;
99

10+
/* Unwraps the HttpRequest from V8 object */
1011
static inline uWS::HttpRequest *getHttpRequest(const FunctionCallbackInfo<Value> &args) {
12+
Isolate *isolate = args.GetIsolate();
1113
/* Thow on deleted request */
1214
auto *req = (uWS::HttpRequest *) args.Holder()->GetAlignedPointerFromInternalField(0);
1315
if (!req) {
@@ -18,6 +20,7 @@ struct HttpRequestWrapper {
1820

1921
/* Takes function of string, string. Returns this (doesn't really but should) */
2022
static void req_forEach(const FunctionCallbackInfo<Value> &args) {
23+
Isolate *isolate = args.GetIsolate();
2124
auto *req = getHttpRequest(args);
2225
if (req) {
2326
Local<Function> cb = Local<Function>::Cast(args[0]);
@@ -32,6 +35,7 @@ struct HttpRequestWrapper {
3235

3336
/* Takes int, returns string (must be in bounds) */
3437
static void req_getParameter(const FunctionCallbackInfo<Value> &args) {
38+
Isolate *isolate = args.GetIsolate();
3539
auto *req = getHttpRequest(args);
3640
if (req) {
3741
int index = args[0]->Uint32Value(isolate->GetCurrentContext()).ToChecked();
@@ -43,6 +47,7 @@ struct HttpRequestWrapper {
4347

4448
/* Takes nothing, returns string */
4549
static void req_getUrl(const FunctionCallbackInfo<Value> &args) {
50+
Isolate *isolate = args.GetIsolate();
4651
auto *req = getHttpRequest(args);
4752
if (req) {
4853
std::string_view url = req->getUrl();
@@ -53,6 +58,7 @@ struct HttpRequestWrapper {
5358

5459
/* Takes String, returns String */
5560
static void req_getHeader(const FunctionCallbackInfo<Value> &args) {
61+
Isolate *isolate = args.GetIsolate();
5662
auto *req = getHttpRequest(args);
5763
if (req) {
5864
NativeString data(args.GetIsolate(), args[0]);
@@ -68,6 +74,7 @@ struct HttpRequestWrapper {
6874

6975
/* Takes nothing, returns string */
7076
static void req_getMethod(const FunctionCallbackInfo<Value> &args) {
77+
Isolate *isolate = args.GetIsolate();
7178
auto *req = getHttpRequest(args);
7279
if (req) {
7380
std::string_view method = req->getMethod();
@@ -77,6 +84,7 @@ struct HttpRequestWrapper {
7784
}
7885

7986
static void req_getQuery(const FunctionCallbackInfo<Value> &args) {
87+
Isolate *isolate = args.GetIsolate();
8088
auto *req = getHttpRequest(args);
8189
if (req) {
8290
std::string_view query = req->getQuery();
@@ -85,7 +93,8 @@ struct HttpRequestWrapper {
8593
}
8694
}
8795

88-
static void initReqTemplate() {
96+
/* Returns a clonable object wrapping an HttpRequest */
97+
static Local<Object> init(Isolate *isolate) {
8998
/* We do clone every request object, we could share them, they are illegal to use outside the function anyways */
9099
Local<FunctionTemplate> reqTemplateLocal = FunctionTemplate::New(isolate);
91100
reqTemplateLocal->SetClassName(String::NewFromUtf8(isolate, "uWS.HttpRequest", NewStringType::kNormal).ToLocalChecked());
@@ -101,12 +110,7 @@ struct HttpRequestWrapper {
101110

102111
/* Create the template */
103112
Local<Object> reqObjectLocal = reqTemplateLocal->GetFunction(isolate->GetCurrentContext()).ToLocalChecked()->NewInstance(isolate->GetCurrentContext()).ToLocalChecked();
104-
reqTemplate.Reset(isolate, reqObjectLocal);
105-
}
106113

107-
static Local<Object> getReqInstance() {
108-
return Local<Object>::New(isolate, reqTemplate)->Clone();
114+
return reqObjectLocal;
109115
}
110116
};
111-
112-
Persistent<Object> HttpRequestWrapper::reqTemplate;

0 commit comments

Comments
 (0)