-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnode-async.h
407 lines (335 loc) · 11.4 KB
/
node-async.h
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// Licensed 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
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
#pragma once
#include <v8.h>
#include <TlHelp32.h>
#include <functional>
#include <memory>
#include <vector>
namespace NodeUtils
{
using namespace v8;
typedef std::function<void (int, Handle<Value>*)> InvokeCallbackDelegate;
class Async
{
public:
template<typename TInput, typename TResult>
struct Baton
{
int error_code;
std::string error_message;
// Custom data
std::shared_ptr<TInput> data;
std::shared_ptr<TResult> result;
std::vector<Persistent<Value>> callback_args;
void setCallbackArgs(Handle<Value>* argv, int argc)
{
for (int i=0; i<argc; i++)
{
callback_args.push_back(Persistent<Value>::New(argv[i]));
}
}
virtual ~Baton()
{
for (std::vector<Persistent<Value>>::iterator it = callback_args.begin(); it != callback_args.end(); it++)
{
it->Dispose();
}
}
private:
uv_work_t request;
std::function<void (Baton*)> doWork;
std::function<void (Baton*)> afterWork;
Persistent<Object> callbackData;
friend Async;
};
private:
class TokenData
{
public:
static uv_async_t* NewAsyncToken()
{
uv_async_t* asyncHandle = new uv_async_t;
uv_async_init(uv_default_loop(), asyncHandle, AsyncCb);
SetHandleData(asyncHandle->data);
return asyncHandle;
}
static uv_async_t* NewAsyncToken(
Handle<Function> callback,
Handle<Value> receiver)
{
uv_async_t* asyncHandle = NewAsyncToken();
SetHandleCallbackData(asyncHandle->data, callback, receiver);
return asyncHandle;
}
static uv_idle_t* NewIdleToken()
{
uv_idle_t* idleHandle = new uv_idle_t;
uv_idle_init(uv_default_loop(), idleHandle);
SetHandleData(idleHandle->data);
return idleHandle;
}
static uv_idle_t* NewIdleToken(
Handle<Function> callback,
Handle<Value> receiver)
{
uv_idle_t* idleHandle = NewIdleToken();
SetHandleCallbackData(idleHandle->data, callback, receiver);
return idleHandle;
}
virtual ~TokenData()
{
callbackData.Dispose();
}
private:
static void SetHandleData(void*& handleData)
{
handleData = new TokenData();
}
static void SetHandleCallbackData(
void* handleData,
Handle<Function> callback,
Handle<Value> receiver)
{
TokenData* Token = static_cast<TokenData*>(handleData);
Token->callbackData = Persistent<Object>::New(CreateCallbackData(callback, receiver));
}
TokenData() {}
Persistent<Object> callbackData;
std::function<void ()> func;
friend Async;
};
public:
template<typename TInput, typename TResult>
static void __cdecl Run(
std::shared_ptr<TInput> input,
std::function<void (Baton<TInput, TResult>*)> doWork,
std::function<void (Baton<TInput, TResult>*)> afterWork,
Handle<Function> callback,
Handle<Value> receiver = Handle<Value>())
{
HandleScope scope;
Handle<Object> callbackData = CreateCallbackData(callback, receiver);
Baton<TInput, TResult>* baton = new Baton<TInput, TResult>();
baton->request.data = baton;
baton->callbackData = Persistent<Object>::New(callbackData);
baton->error_code = 0;
baton->data = input;
baton->doWork = doWork;
baton->afterWork = afterWork;
uv_queue_work(uv_default_loop(), &baton->request, AsyncWork<TInput, TResult>, AsyncAfter<TInput, TResult>);
}
static uv_async_t* __cdecl GetAsyncToken()
{
return TokenData::NewAsyncToken();
}
static uv_async_t* __cdecl GetAsyncToken(
Handle<Function> callback,
Handle<Value> receiver = Handle<Value>())
{
return TokenData::NewAsyncToken(callback, receiver);
}
static uv_idle_t* __cdecl GetIdleToken()
{
return TokenData::NewIdleToken();
}
static uv_idle_t* __cdecl GetIdleToken(
Handle<Function> callback,
Handle<Value> receiver = Handle<Value>())
{
return TokenData::NewIdleToken(callback, receiver);
}
static void __cdecl RunOnMain(uv_async_t* async, std::function<void ()> func)
{
TokenData* Token = static_cast<TokenData*>(async->data);
Token->func = func;
uv_async_send(async);
}
static void __cdecl RunOnMain(std::function<void ()> func)
{
static unsigned int uvMainThreadId = GetMainThreadId();
if (uvMainThreadId == uv_thread_self())
{
func();
}
else
{
uv_async_t *async = GetAsyncToken();
RunOnMain(async, func);
}
}
static void __cdecl RunCallbackOnMain(
uv_async_t* async,
std::function<void (InvokeCallbackDelegate invokeCallback)> func)
{
TokenData* Token = static_cast<TokenData*>(async->data);
InvokeCallbackDelegate invokeCallback = [Token](int argc, Handle<Value>* argv)
{
if (!Token->callbackData.IsEmpty())
{
node::MakeCallback(Token->callbackData, String::NewSymbol("callback"), argc, argv);
}
};
std::function<void ()> wrapper = [func, invokeCallback]()
{
HandleScope scope;
func(invokeCallback);
};
RunOnMain(async, wrapper);
}
// defers execution of the provided function by creating an idler
// that means, the function will be invoked once the event loop has delivered
// all pending events.
static void __cdecl NextTick(std::function<void ()> func)
{
uv_idle_t *idler = GetIdleToken();
NextTick(idler, func);
}
static void __cdecl NextTick(uv_idle_t *idler, std::function<void ()> func)
{
TokenData* Token = static_cast<TokenData*>(idler->data);
Token->func = func;
uv_idle_start(idler, onNextTick);
}
static void __cdecl RunCallbackOnNextTick(
uv_idle_t* idler,
std::function<void (InvokeCallbackDelegate invokeCallback)> func)
{
TokenData* Token = static_cast<TokenData*>(idler->data);
InvokeCallbackDelegate invokeCallback = [Token](int argc, Handle<Value>* argv)
{
if (!Token->callbackData.IsEmpty())
{
node::MakeCallback(Token->callbackData, String::NewSymbol("callback"), argc, argv);
}
};
std::function<void ()> wrapper = [func, invokeCallback]()
{
HandleScope scope;
func(invokeCallback);
};
NextTick(idler, wrapper);
}
private:
static Handle<Object> CreateCallbackData(Handle<Function> callback, Handle<Value> receiver)
{
HandleScope scope;
Handle<Object> callbackData;
if (!callback.IsEmpty() && !callback->Equals(Undefined()))
{
callbackData = Object::New();
if (!receiver.IsEmpty())
{
callbackData->SetPrototype(receiver);
}
callbackData->Set(String::NewSymbol("callback"), callback);
// get the current domain:
Handle<Value> currentDomain = Undefined();
Handle<Object> process = v8::Context::GetCurrent()->Global()->Get(String::NewSymbol("process")).As<Object>();
if (!process->Equals(Undefined()))
{
currentDomain = process->Get(String::NewSymbol("domain")) ;
}
callbackData->Set(String::NewSymbol("domain"), currentDomain);
}
return scope.Close(callbackData);
};
template<typename TInput, typename TResult>
static void __cdecl AsyncWork(uv_work_t* req)
{
// No HandleScope!
Baton<TInput, TResult>* baton = static_cast<Baton<TInput, TResult>*>(req->data);
// Do work in threadpool here.
// Set baton->error_code/message on failures.
// Set baton->result with a final result object
baton->doWork(baton);
}
template<typename TInput, typename TResult>
static void __cdecl AsyncAfter(uv_work_t* req, int status)
{
HandleScope scope;
Baton<TInput, TResult>* baton = static_cast<Baton<TInput, TResult>*>(req->data);
// typical AfterWorkFunc implementation
//if (baton->error)
//{
// Handle<Value> err = Exception::Error(...);
// Handle<Value> argv[] = { err };
// baton->setCallbackArgs(argv, _countof(argv));
//}
//else
//{
// Handle<Value> argv[] = { Undefined(), ... };
// baton->setCallbackArgs(argv, _countof(argv));
//}
baton->afterWork(baton);
if (!baton->callbackData.IsEmpty() || !baton->callbackData->Equals(Undefined()))
{
// call the callback, using domains and all
int argc = static_cast<int>(baton->callback_args.size());
std::unique_ptr<Handle<Value>> handlesArr(new Handle<Value>[argc]);
for (int i=0; i < argc; i++)
{
handlesArr.get()[i] = baton->callback_args[i];
}
node::MakeCallback(baton->callbackData, String::NewSymbol("callback"), argc, handlesArr.get());
}
baton->callbackData.Dispose();
delete baton;
}
// called after the async handle is closed in order to free it's memory
static void __cdecl AyncCloseCb(uv_handle_t* handle)
{
if (handle != nullptr)
{
uv_async_t* async = reinterpret_cast<uv_async_t*>(handle);
delete async;
}
}
// Called by run on main in case we are not running on the main thread
static void __cdecl AsyncCb(uv_async_t *handle, int status)
{
auto Token = static_cast<TokenData*>(handle->data);
Token->func();
uv_close((uv_handle_t*)handle, AyncCloseCb);
delete Token;
}
// Attributes goes to http://stackoverflow.com/a/1982200/1060807 (etan)
static unsigned int __cdecl GetMainThreadId()
{
const std::shared_ptr<void> hThreadSnapshot(
CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0), CloseHandle);
if (hThreadSnapshot.get() == INVALID_HANDLE_VALUE)
{
return 0;
}
THREADENTRY32 tEntry;
tEntry.dwSize = sizeof(THREADENTRY32);
DWORD result = 0;
DWORD currentPID = GetCurrentProcessId();
for (BOOL success = Thread32First(hThreadSnapshot.get(), &tEntry);
!result && success && GetLastError() != ERROR_NO_MORE_FILES;
success = Thread32Next(hThreadSnapshot.get(), &tEntry))
{
if (tEntry.th32OwnerProcessID == currentPID)
{
result = tEntry.th32ThreadID;
}
}
return result;
}
static void __cdecl onNextTick(uv_idle_t *handle, int status)
{
std::function<void ()> *func = static_cast<std::function<void ()> *>(handle->data);
(*func)();
delete func;
uv_idle_stop(handle);
delete handle;
}
};
}