-
Notifications
You must be signed in to change notification settings - Fork 11
/
module.cpp
426 lines (363 loc) · 12.9 KB
/
module.cpp
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
#include "js.h"
#include "redismodule.h"
#include <limits.h>
#include <vector>
#include <v8.h>
#include <math.h>
#include <fstream>
#include <streambuf>
#include <dlfcn.h>
#include <experimental/filesystem>
RedisModuleCtx *g_ctx = nullptr;
JSContext *g_jscontext = nullptr;
bool g_fInStartup = true;
class KeyDBContext
{
RedisModuleCtx *m_ctxSave;
public:
KeyDBContext(RedisModuleCtx *ctxSet)
{
m_ctxSave = g_ctx;
g_ctx = ctxSet;
}
~KeyDBContext()
{
g_ctx = m_ctxSave;
}
};
static void processResult(RedisModuleCtx *ctx, v8::Isolate *isolate, v8::Local<v8::Context> &v8ctx, v8::Local<v8::Value> &result)
{
if (result->IsArray())
{
v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(result);
RedisModule_ReplyWithArray(g_ctx, array->Length());
for (size_t ielem = 0; ielem < array->Length(); ++ielem)
{
auto maybe = array->Get(v8ctx, ielem);
v8::Local<v8::Value> val;
if (maybe.ToLocal(&val))
processResult(ctx, isolate, v8ctx, val);
else
RedisModule_ReplyWithNull(ctx);
}
}
else if (result->IsInt32())
{
v8::Local<v8::Int32> num = v8::Local<v8::Int32>::Cast(result);
int32_t val = num->Value();
RedisModule_ReplyWithLongLong(ctx, val);
}
else if (result->IsNumber())
{
v8::Local<v8::Number> num = v8::Local<v8::Number>::Cast(result);
double dv = num->Value();
RedisModule_ReplyWithDouble(ctx, dv);
}
else if (result->IsString())
{
v8::String::Utf8Value utf8(isolate, result);
RedisModule_ReplyWithCString(ctx, *utf8);
}
else
{
RedisModule_ReplyWithNull(ctx);
}
}
static void ProcessCallReply(v8::Local<v8::Value> &dst, v8::Isolate* isolate, RedisModuleCallReply *reply)
{
const char *rgchReply;
size_t cchReply;
switch (RedisModule_CallReplyType(reply))
{
case REDISMODULE_REPLY_STRING:
rgchReply = RedisModule_CallReplyStringPtr(reply, &cchReply);
dst = v8::String::NewFromUtf8(isolate, rgchReply, v8::NewStringType::kNormal, cchReply).ToLocalChecked();
break;
case REDISMODULE_REPLY_INTEGER:
{
long long val = RedisModule_CallReplyInteger(reply);
dst = v8::Number::New(isolate, (double)val);
break;
}
case REDISMODULE_REPLY_ARRAY:
{
size_t celem = RedisModule_CallReplyLength(reply);
auto array = v8::Array::New(isolate, celem);
for (size_t ielem = 0; ielem < celem; ++ielem)
{
RedisModuleCallReply *replyArray = RedisModule_CallReplyArrayElement(reply, ielem);
v8::Local<v8::Value> val;
ProcessCallReply(val, isolate, replyArray);
v8::Maybe<bool> result = array->Set(isolate->GetCurrentContext(), ielem, val);
bool fResult;
if (!result.To(&fResult) || !fResult)
{
RedisModule_Log(g_ctx, "warning", "Failed to process array result");
}
}
dst = array;
break;
}
default:
rgchReply = RedisModule_CallReplyProto(reply, &cchReply);
dst = v8::String::NewFromUtf8(isolate, rgchReply, v8::NewStringType::kNormal, cchReply).ToLocalChecked();
}
}
void KeyDBExecuteCallback(const v8::FunctionCallbackInfo<v8::Value>& args)
{
if (args.Length() < 1) return;
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Value> vfnName = args[0];
v8::String::Utf8Value fnName(isolate, vfnName);
std::vector<RedisModuleString*> vecstrs;
for (int iarg = 1; iarg < args.Length(); ++iarg)
{
v8::String::Utf8Value argument(isolate, args[iarg]);
vecstrs.push_back(RedisModule_CreateString(g_ctx, *argument, argument.length()));
}
RedisModuleCallReply *reply = RedisModule_Call(g_ctx, *fnName, "v", vecstrs.data(), vecstrs.size());
if (reply != nullptr)
{
v8::Local<v8::Value> result;
ProcessCallReply(result, isolate, reply);
args.GetReturnValue().Set(result);
RedisModule_FreeCallReply(reply);
}
else
{
isolate->ThrowException(v8::String::NewFromUtf8(isolate, "Invalid Command").ToLocalChecked());
}
for (auto str : vecstrs)
RedisModule_FreeString(g_ctx, str);
}
void LogCallback(const v8::FunctionCallbackInfo<v8::Value>& args)
{
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope scope(isolate);
if (args.Length() != 2)
{
isolate->ThrowException(v8::String::NewFromUtf8(isolate, "Log expects two parameters").ToLocalChecked());
return;
}
v8::String::Utf8Value level(isolate, args[0]);
v8::String::Utf8Value message(isolate, args[1]);
RedisModule_Log(g_ctx, *level, "%s", *message);
}
int js_command(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
{
KeyDBContext ctxsav(ctx);
v8::Locker locker(g_jscontext->getIsolate());
v8::HandleScope scope(g_jscontext->getIsolate());
if (argc < 1)
return REDISMODULE_ERR;
v8::Local<v8::Context> context = g_jscontext->getCurrentContext();
v8::Context::Scope context_scope(context);
try
{
size_t cchName;
const char *rgchName = RedisModule_StringPtrLen(argv[0], &cchName);
v8::Handle<v8::Object> global = context->Global();
v8::Isolate *isolate = g_jscontext->getIsolate();
auto strFn = v8::String::NewFromUtf8(isolate, rgchName, v8::NewStringType::kNormal, cchName).ToLocalChecked();
auto mvfnCall = global->Get(context, v8::Local<v8::Value>::Cast(strFn));
v8::Handle<v8::Value> vfnCall;
if (!mvfnCall.ToLocal(&vfnCall))
return REDISMODULE_ERR;
if (!vfnCall->IsFunction())
return REDISMODULE_ERR;
v8::Handle<v8::Function> fnCall = v8::Handle<v8::Function>::Cast(vfnCall);
std::vector<v8::Local<v8::Value>> vecargs;
vecargs.reserve(argc);
for (int iarg = 1; iarg < argc; ++iarg)
{
size_t cch;
const char *rgch = RedisModule_StringPtrLen(argv[iarg], &cch);
auto str = v8::String::NewFromUtf8(isolate, rgch, v8::NewStringType::kNormal, cch).ToLocalChecked();
vecargs.push_back(str);
}
auto maybeResult = fnCall->Call(context, global, (int)vecargs.size(), vecargs.data());
v8::Local<v8::Value> result;
if (!maybeResult.ToLocal(&result))
{
RedisModule_ReplyWithNull(ctx);
return REDISMODULE_OK;
}
processResult(ctx, g_jscontext->getIsolate(), context, result);
}
catch (std::string strerr)
{
RedisModule_ReplyWithError(ctx, strerr.c_str());
return REDISMODULE_ERR;
}
catch (std::nullptr_t)
{
RedisModule_ReplyWithError(ctx, "Unknown Error");
return REDISMODULE_ERR;
}
return REDISMODULE_OK;
}
void RegisterCommandCallback(const v8::FunctionCallbackInfo<v8::Value>& args)
{
if (args.Length() < 1) return;
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope scope(isolate);
if (!g_fInStartup)
{
isolate->ThrowException(v8::String::NewFromUtf8(isolate, "New commands may only be registered during startup").ToLocalChecked());
return;
}
v8::Local<v8::Value> vfn = args[0];
if (!vfn->IsFunction())
return;
v8::Local<v8::Function> fn = v8::Local<v8::Function>::Cast(vfn);
v8::Local<v8::Value> vfnName = fn->GetName();
v8::String::Utf8Value fnName(isolate, vfnName);
std::string flags = "write deny-oom random";
if (args.Length() >= 2)
{
// They passed in their own flags
v8::Local<v8::Value> vFlags = args[1];
if (vFlags->IsString())
{
auto utfFlags = v8::String::Utf8Value(isolate, vFlags);
flags = *utfFlags;
}
}
int keyFirst = 0;
int keyLast = 0;
int keyStep = 0;
if (args.Length() > 2)
{
if (args.Length() != 5)
{
isolate->ThrowException(v8::String::NewFromUtf8(isolate, "incorrect number of arguments to register()").ToLocalChecked());
return;
}
if (!args[2]->IsInt32() || !args[3]->IsInt32() || !args[4]->IsInt32())
{
isolate->ThrowException(v8::String::NewFromUtf8(isolate, "expected integer argument").ToLocalChecked());
return;
}
keyFirst = v8::Local<v8::Int32>::Cast(args[2])->Value();
keyLast = v8::Local<v8::Int32>::Cast(args[3])->Value();
keyStep = v8::Local<v8::Int32>::Cast(args[4])->Value();
}
if (RedisModule_CreateCommand(g_ctx, *fnName, js_command, flags.c_str(), keyFirst, keyLast, keyStep) == REDISMODULE_ERR) {
isolate->ThrowException(v8::String::NewFromUtf8(isolate, "failed to register command").ToLocalChecked());
}
RedisModule_Log(g_ctx, "verbose", "Function %s registered", *fnName);
}
int evaljs_command(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
{
KeyDBContext ctxsav(ctx);
if (argc != 2)
{
RedisModule_WrongArity(ctx);
return REDISMODULE_ERR;
}
if (g_jscontext == nullptr)
{
g_jscontext = new JSContext();
g_jscontext->initialize();
}
v8::Locker locker(g_jscontext->getIsolate());
size_t cch = 0;
const char *rgch = RedisModule_StringPtrLen(argv[1], &cch);
try
{
v8::HandleScope scope(g_jscontext->getIsolate());
v8::Local<v8::Value> result = g_jscontext->run(rgch, cch);
auto context = g_jscontext->getCurrentContext();
processResult(ctx, g_jscontext->getIsolate(), context, result);
}
catch (std::string strerr)
{
RedisModule_ReplyWithError(ctx, strerr.c_str());
return REDISMODULE_ERR;
}
catch (std::nullptr_t)
{
RedisModule_ReplyWithError(ctx, "Unknown Error");
return REDISMODULE_ERR;
}
return REDISMODULE_OK;
}
int run_startup_script(RedisModuleCtx *ctx, const char *szPath)
{
KeyDBContext ctxsav(ctx);
std::ifstream file(szPath, std::ios::binary | std::ios::ate);
std::streamsize size = file.tellg();
if (size == -1)
{
RedisModule_Log(ctx, "warning", "startup script does not exist");
return REDISMODULE_ERR; // Failed to read file
}
file.seekg(0, std::ios::beg);
std::vector<char> buffer(size);
if (!file.read(buffer.data(), size))
{
RedisModule_Log(ctx, "warning", "failed to read startup script");
return REDISMODULE_ERR; // Failed to read file
}
v8::HandleScope scope(g_jscontext->getIsolate());
try
{
g_jscontext->run(buffer.data(), buffer.size(), true /* don't cache */);
}
catch (std::string str)
{
RedisModule_Log(ctx, "warning", "%s", str.c_str());
return REDISMODULE_ERR;
}
return REDISMODULE_OK;
}
int ReplyWithCString(RedisModuleCtx *ctx, const char *sz)
{
return RedisModule_ReplyWithStringBuffer(ctx, sz, strlen(sz));
}
extern "C" int __attribute__((visibility("default"))) RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
{
if (RedisModule_Init(ctx,"modjs",1,REDISMODULE_APIVER_1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_ReplyWithCString == nullptr)
RedisModule_ReplyWithCString = ReplyWithCString;
if (RedisModule_CreateCommand(ctx,"evaljs", evaljs_command,"write deny-oom random",0,0,0) == REDISMODULE_ERR)
return REDISMODULE_ERR;
javascript_initialize();
g_jscontext = new JSContext();
g_jscontext->initialize();
RedisModule_Log(g_ctx, "warning", "Initialized ModJS v0.1.0");
// Run our bootstrap.js code
{
Dl_info dlInfo;
dladdr((const void*)RedisModule_OnLoad, &dlInfo);
if (dlInfo.dli_sname != NULL && dlInfo.dli_saddr != NULL)
{
std::experimental::filesystem::path path(dlInfo.dli_fname);
path.remove_filename();
path /= "bootstrap.js";
std::string strPath = path.string();
if (run_startup_script(ctx, strPath.c_str()) == REDISMODULE_ERR)
{
RedisModule_Log(ctx, "warning", "failed to run bootstrap.js, ensure this is located in the same location as the .so");
return REDISMODULE_ERR;
}
}
else
{
RedisModule_Log(ctx, "warning", "failed to locate bootstrap script");
return REDISMODULE_ERR;
}
}
for (int iarg = 0; iarg < argc; ++iarg)
{
// Process the startup script
size_t cchPath;
const char *rgchPath = RedisModule_StringPtrLen(argv[iarg], &cchPath);
if (run_startup_script(ctx, rgchPath) == REDISMODULE_ERR)
return REDISMODULE_ERR;
}
g_fInStartup = false;
return REDISMODULE_OK;
}