|
| 1 | +#include <node.h> |
| 2 | +#include <uv.h> |
| 3 | +#include <v8.h> |
| 4 | + |
| 5 | +using v8::Context; |
| 6 | +using v8::Function; |
| 7 | +using v8::FunctionCallbackInfo; |
| 8 | +using v8::Global; |
| 9 | +using v8::HandleScope; |
| 10 | +using v8::Isolate; |
| 11 | +using v8::Local; |
| 12 | +using v8::Object; |
| 13 | +using v8::Value; |
| 14 | + |
| 15 | +// Same order as the types in index.js. |
| 16 | +enum Type { kMakeCallback, kMakeCallbackEnv }; |
| 17 | + |
| 18 | +struct State { |
| 19 | + uv_timer_t timer; |
| 20 | + Isolate* isolate; |
| 21 | + node::Environment* env; |
| 22 | + int64_t n; |
| 23 | + Type type; |
| 24 | + Global<Function> fn; |
| 25 | + Global<Function> done; |
| 26 | +}; |
| 27 | + |
| 28 | +static void OnTimer(uv_timer_t* handle) { |
| 29 | + State* state = static_cast<State*>(handle->data); |
| 30 | + Isolate* isolate = state->isolate; |
| 31 | + HandleScope handle_scope(isolate); |
| 32 | + Local<Function> fn = state->fn.Get(isolate); |
| 33 | + Local<Context> context = fn->GetCreationContextChecked(isolate); |
| 34 | + Context::Scope context_scope(context); |
| 35 | + Local<Object> recv = context->Global(); |
| 36 | + for (int64_t i = 0; i < state->n; i++) { |
| 37 | + HandleScope inner_scope(isolate); |
| 38 | + if (state->type == kMakeCallbackEnv) { |
| 39 | + (void)node::MakeCallback(state->env, recv, fn, 0, nullptr, {0, 0}); |
| 40 | + } else { |
| 41 | + (void)node::MakeCallback(isolate, recv, fn, 0, nullptr, {0, 0}); |
| 42 | + } |
| 43 | + } |
| 44 | + Local<Function> done = state->done.Get(isolate); |
| 45 | + (void)node::MakeCallback(isolate, recv, done, 0, nullptr, {0, 0}); |
| 46 | + uv_close(reinterpret_cast<uv_handle_t*>(&state->timer), |
| 47 | + [](uv_handle_t* h) { delete static_cast<State*>(h->data); }); |
| 48 | +} |
| 49 | + |
| 50 | +// run(n, fn, done, type): calls fn n times from a timer, then calls done. |
| 51 | +static void Run(const FunctionCallbackInfo<Value>& args) { |
| 52 | + Isolate* isolate = args.GetIsolate(); |
| 53 | + Local<Context> context = isolate->GetCurrentContext(); |
| 54 | + State* state = new State; |
| 55 | + state->isolate = isolate; |
| 56 | + // Found once, the point of the MakeCallbackEnv type. |
| 57 | + state->env = node::GetCurrentEnvironment(context); |
| 58 | + state->n = args[0]->IntegerValue(context).FromJust(); |
| 59 | + state->fn.Reset(isolate, args[1].As<Function>()); |
| 60 | + state->done.Reset(isolate, args[2].As<Function>()); |
| 61 | + state->type = static_cast<Type>(args[3]->Int32Value(context).FromJust()); |
| 62 | + state->timer.data = state; |
| 63 | + uv_timer_init(node::GetCurrentEventLoop(isolate), &state->timer); |
| 64 | + uv_timer_start(&state->timer, OnTimer, 0, 0); |
| 65 | +} |
| 66 | + |
| 67 | +static void Initialize(Local<Object> target, Local<Value> module, void* data) { |
| 68 | + NODE_SET_METHOD(target, "run", Run); |
| 69 | +} |
| 70 | + |
| 71 | +NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize) |
0 commit comments