forked from starkdg/Redis-ImageScout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
module.cpp
543 lines (432 loc) · 16.8 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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
#include <cstdlib>
#include <string>
#include <ctime>
#include <chrono>
#include <list>
#include "redismodule.h"
#include "mvptree.hpp"
#define MVPTREE_ENCODING_VERSION 0
using namespace std;
static RedisModuleType *MVPTreeType;
static const char *descr_field = "descr";
/* =================== dyn mem management ==========================*/
void* operator new(size_t sz){
void *ptr = RedisModule_Alloc(sz);
return ptr;
}
void operator delete(void *ptr){
RedisModule_Free(ptr);
}
/* ================= aux. functions ==================================*/
int get_next_id(RedisModuleCtx *ctx, RedisModuleString *keystr, long long &id){
id = RedisModule_Milliseconds() << 32;
id |= (int64_t)(rand() & 0xffff0000);
string key = RedisModule_StringPtrLen(keystr, NULL);
key += ":counter";
RedisModuleCallReply *reply = RedisModule_Call(ctx, "INCRBY", "cl", key.c_str(), 1);
if (RedisModule_CallReplyType(reply) != REDISMODULE_REPLY_INTEGER){
return REDISMODULE_ERR;
}
id |= (0x0000ffffULL & RedisModule_CallReplyInteger(reply));
RedisModule_FreeCallReply(reply);
return REDISMODULE_OK;
}
/* retrieve a descr field stored in keystr+id hash redis datatype */
RedisModuleString* GetDescriptionField(RedisModuleCtx *ctx, RedisModuleString *keystr, long long id){
string idstr = RedisModule_StringPtrLen(keystr, NULL);
idstr += ":" + to_string(id);
RedisModuleString *keyidstr = RedisModule_CreateString(ctx, idstr.c_str(), idstr.length());
RedisModuleKey *key = (RedisModuleKey*)RedisModule_OpenKey(ctx, keyidstr, REDISMODULE_READ);
if (RedisModule_KeyType(key) != REDISMODULE_KEYTYPE_HASH){
RedisModule_CloseKey(key);
return NULL;
}
RedisModuleString *descr = NULL;
RedisModule_HashGet(key, REDISMODULE_HASH_CFIELDS, descr_field, &descr, NULL);
RedisModule_CloseKey(key);
return descr;
}
/* set a descr field for a keystr+id redis hash data type */
void SetDescriptionField(RedisModuleCtx *ctx, RedisModuleString *keystr, long long id, RedisModuleString *descr){
string idstr = RedisModule_StringPtrLen(keystr, NULL);
idstr += ":" + to_string(id);
RedisModuleString *keyidstr = RedisModule_CreateString(ctx, idstr.c_str(), idstr.length());
RedisModuleKey *key = (RedisModuleKey*)RedisModule_OpenKey(ctx, keyidstr, REDISMODULE_WRITE);
if (RedisModule_KeyType(key) != REDISMODULE_KEYTYPE_EMPTY){
RedisModule_CloseKey(key);
return;
}
RedisModule_HashSet(key, REDISMODULE_HASH_CFIELDS|REDISMODULE_HASH_NX, descr_field, descr, NULL);
RedisModule_CloseKey(key);
}
void DeleteDescriptionField(RedisModuleCtx *ctx, RedisModuleString *keystr, long long id){
string idstr = RedisModule_StringPtrLen(keystr, NULL);
idstr += ":" + to_string(id);
RedisModuleString *keyidstr = RedisModule_CreateString(ctx, idstr.c_str(), idstr.length());
RedisModuleKey *key = (RedisModuleKey*)RedisModule_OpenKey(ctx, keyidstr, REDISMODULE_WRITE);
if (RedisModule_KeyType(key) != REDISMODULE_KEYTYPE_HASH){
RedisModule_CloseKey(key);
return;
}
RedisModule_HashSet(key, REDISMODULE_HASH_CFIELDS, descr_field, REDISMODULE_HASH_DELETE, NULL);
RedisModule_CloseKey(key);
}
void DeleteDescriptionKey(RedisModuleCtx *ctx, RedisModuleString *keystr, long long id){
string idstr = RedisModule_StringPtrLen(keystr, NULL);
idstr += ":" + to_string(id);
RedisModuleString *keyidstr = RedisModule_CreateString(ctx, idstr.c_str(), idstr.length());
RedisModuleKey *key = (RedisModuleKey*)RedisModule_OpenKey(ctx, keyidstr, REDISMODULE_WRITE);
if (RedisModule_KeyType(key) != REDISMODULE_KEYTYPE_HASH){
RedisModule_CloseKey(key);
return;
}
RedisModule_DeleteKey(key);
RedisModule_CloseKey(key);
}
void DeleteCounterKey(RedisModuleCtx *ctx, RedisModuleString *keystr){
string counterstr = RedisModule_StringPtrLen(keystr, NULL);
counterstr += ":counter";
RedisModuleString *keycounterstr = RedisModule_CreateString(ctx, counterstr.c_str(), counterstr.length());
RedisModuleKey *key = (RedisModuleKey*)RedisModule_OpenKey(ctx, keycounterstr, REDISMODULE_WRITE);
RedisModule_DeleteKey(key);
RedisModule_CloseKey(key);
return;
}
void DeleteKey(RedisModuleCtx *ctx, RedisModuleString *keystr){
RedisModuleKey *key = (RedisModuleKey*)RedisModule_OpenKey(ctx, keystr, REDISMODULE_WRITE);
RedisModule_DeleteKey(key);
RedisModule_CloseKey(key);
return;
}
unsigned long long RMStringToUnsignedLongLong(const RedisModuleString *str){
return strtoull(RedisModule_StringPtrLen(str, NULL), NULL, 10);
}
/* ============== Get MVPTree =======================================*/
MVPTree* GetMVPTree(RedisModuleCtx *ctx, RedisModuleString *keystr){
RedisModuleKey *key = (RedisModuleKey*)RedisModule_OpenKey(ctx, keystr, REDISMODULE_READ);
int keytype = RedisModule_KeyType(key);
if (keytype == REDISMODULE_KEYTYPE_EMPTY){
RedisModule_CloseKey(key);
return NULL;
}
if (RedisModule_ModuleTypeGetType(key) != MVPTreeType){
RedisModule_CloseKey(key);
throw -1;
}
MVPTree *tree = (MVPTree*)RedisModule_ModuleTypeGetValue(key);
RedisModule_CloseKey(key);
return tree;
}
/* Create a new data type, throw -1 exception if already exists for a different type */
MVPTree* CreateMVPTree(RedisModuleCtx *ctx, RedisModuleString *keystr){
RedisModuleKey *key = (RedisModuleKey*)RedisModule_OpenKey(ctx, keystr, REDISMODULE_WRITE);
int keytype = RedisModule_KeyType(key);
if (keytype != REDISMODULE_KEYTYPE_EMPTY && RedisModule_ModuleTypeGetType(key) != MVPTreeType){
RedisModule_CloseKey(key);
throw -1;
}
MVPTree *tree = NULL;
if (keytype == REDISMODULE_KEYTYPE_EMPTY){
tree = (MVPTree*)new MVPTree();
RedisModule_ModuleTypeSetValue(key, MVPTreeType, tree);
} else {
tree = (MVPTree*)RedisModule_ModuleTypeGetValue(key);
}
RedisModule_CloseKey(key);
return tree;
}
/* ============== MVPTree type methods ==============================*/
extern "C" void* MVPTreeTypeRdbLoad(RedisModuleIO *rdb, int encver){
if (encver != MVPTREE_ENCODING_VERSION){
RedisModule_LogIOError(rdb, "warning", "rdbload unable to encode for encver %d", encver);
return NULL;
}
MVPTree *tree = (MVPTree*)new MVPTree();
unsigned long long n_points = RedisModule_LoadUnsigned(rdb);
for (unsigned long long i=0;i<n_points;i++){
DataPoint *dp = new DataPoint();
dp->id = RedisModule_LoadSigned(rdb);
dp->value = RedisModule_LoadUnsigned(rdb);
tree->Add(dp);
}
tree->Sync();
return (void*)tree;
}
extern "C" void MVPTreeTypeRdbSave(RedisModuleIO *rdb, void *value){
MVPTree *tree = (MVPTree*)value;
const map<long long, DataPoint*> ids = tree->GetMap();
RedisModule_SaveUnsigned(rdb, ids.size());
for (auto iter=ids.begin();iter!=ids.end();iter++){
RedisModule_SaveSigned(rdb, iter->second->id);
RedisModule_SaveUnsigned(rdb, iter->second->value);
}
}
extern "C" void MVPTreeTypeAofRewrite(RedisModuleIO *aof, RedisModuleString *key, void *value){
MVPTree *tree = (MVPTree*)value;
const map<long long, DataPoint*> ids = tree->GetMap();
for (auto iter=ids.begin();iter!=ids.end();iter++){
RedisModule_EmitAOF(aof, "imgscout.addrepl", "sll", key, iter->second->value, iter->first);
}
}
extern "C" void MVPTreeTypeFree(void *value){
MVPTree *tree = (MVPTree*)value;
tree->Clear();
}
extern "C" size_t MVPTreeTypeMemUsage(const void *value){
MVPTree *tree = (MVPTree*)value;
size_t n_bytes = tree->MemoryUsage();
return n_bytes;
}
extern "C" void MVPTreeTypeDigest(RedisModuleDigest *digest, void *value){
REDISMODULE_NOT_USED(digest);
REDISMODULE_NOT_USED(value);
}
/* ============== Redis Command functions ===========================*/
/* args: key hashvalue id */
extern "C" int MVPTreeAddRepl_RedisCmd(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){
if (argc < 4) return RedisModule_WrongArity(ctx);
RedisModule_AutoMemory(ctx);
MVPTree *tree = NULL;
try {
tree = GetMVPTree(ctx, argv[1]);
if (tree == NULL) tree = CreateMVPTree(ctx, argv[1]);
} catch (int &e){
RedisModule_ReplyWithError(ctx, "ERR - key exists for different type. Delete first.");
return REDISMODULE_ERR;
}
long long id;
if (RedisModule_StringToLongLong(argv[3], &id) == REDISMODULE_ERR){
RedisModule_ReplyWithError(ctx, "ERR - unable to parse id value");
return REDISMODULE_ERR;
}
unsigned long long hashvalue = RMStringToUnsignedLongLong(argv[2]);
DataPoint *dp = new DataPoint();
dp->id = id;
dp->value = hashvalue;
tree->Add(dp);
RedisModule_ReplyWithLongLong(ctx, id);
return REDISMODULE_OK;
}
/*args: key hashvalue descr [id] */
extern "C" int MVPTreeAdd_RedisCmd(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){
if (argc < 4) return RedisModule_WrongArity(ctx);
RedisModule_AutoMemory(ctx);
MVPTree *tree = NULL;
try {
tree = GetMVPTree(ctx, argv[1]);
if (tree == NULL) tree = CreateMVPTree(ctx, argv[1]);
} catch (int &e){
RedisModule_ReplyWithError(ctx, "ERR - key exists for different type. Delete first.");
return REDISMODULE_ERR;
}
long long id;
if (argc == 5){
if (RedisModule_StringToLongLong(argv[4], &id) == REDISMODULE_ERR){
RedisModule_ReplyWithError(ctx, "ERR - unable to parse id value");
return REDISMODULE_ERR;
}
} else {
if (get_next_id(ctx, argv[1], id) == REDISMODULE_ERR){
RedisModule_ReplyWithError(ctx, "ERR - unable to get next id value");
return REDISMODULE_ERR;
}
}
unsigned long long hash_value = RMStringToUnsignedLongLong(argv[2]);
DataPoint *dp = new DataPoint();
dp->id = id;
dp->value = hash_value;
try {
tree->Add(dp);
} catch (exception &ex){
RedisModule_ReplyWithError(ctx, "ERR - unable to add element");
return REDISMODULE_ERR;
}
SetDescriptionField(ctx, argv[1], id, argv[3]);
RedisModule_ReplyWithLongLong(ctx, id);
if (RedisModule_Replicate(ctx, "imgscout.add", "sssl", argv[1], argv[2], argv[3], id) == REDISMODULE_ERR){
RedisModule_Log(ctx, "warning", "unable to replicate add command for id = %lld", id);
}
return REDISMODULE_OK;
}
/* args: key */
extern "C" int MVPTreeSync_RedisCmd(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){
if (argc != 2) return RedisModule_WrongArity(ctx);
RedisModule_AutoMemory(ctx);
chrono::time_point<chrono::high_resolution_clock> start = chrono::high_resolution_clock::now();
MVPTree *tree = NULL;
try {
tree = GetMVPTree(ctx, argv[1]);
if (tree == NULL){
RedisModule_ReplyWithError(ctx, "ERR - no such key");
return REDISMODULE_ERR;
}
} catch (int &e){
RedisModule_ReplyWithError(ctx, "ERR - key exists for different type. Delete first.");
return REDISMODULE_ERR;
}
try {
tree->Sync();
} catch (exception &ex){
RedisModule_ReplyWithError(ctx, "ERR - unable to sync");
return REDISMODULE_ERR;
}
int n_points = tree->Size();
RedisModule_ReplyWithSimpleString(ctx, "OK");
RedisModule_ReplicateVerbatim(ctx);
chrono::time_point<chrono::high_resolution_clock> end = chrono::high_resolution_clock::now();
auto elapsed = chrono::duration_cast<chrono::microseconds>(end - start).count();
RedisModule_Log(ctx, "debug", "%llu points synced in %u microseconds", n_points, elapsed);
return REDISMODULE_OK;
}
/* args: key hashtarget radius */
extern "C" int MVPTreeQuery_RedisCmd(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){
if (argc != 4) return RedisModule_WrongArity(ctx);
RedisModule_AutoMemory(ctx);
chrono::time_point<chrono::high_resolution_clock> start = chrono::high_resolution_clock::now();
MVPTree *tree = NULL;
try {
tree = GetMVPTree(ctx, argv[1]);
if (tree == NULL){
RedisModule_ReplyWithError(ctx, "ERR - no such key");
return REDISMODULE_ERR;
}
} catch (int &e){
RedisModule_ReplyWithError(ctx, "ERR - key exists for different type. Delete first.");
return REDISMODULE_ERR;
}
unsigned long long hash_value = RMStringToUnsignedLongLong(argv[2]);
double radius;
if (RedisModule_StringToDouble(argv[3], &radius) == REDISMODULE_ERR){
RedisModule_ReplyWithError(ctx, "unable to parse radius value");
return REDISMODULE_ERR;
}
DataPoint target;
target.value = hash_value;
list<QueryResult> results;
try {
results = tree->Query(target, radius);
} catch (exception &ex){
RedisModule_ReplyWithError(ctx, "ERR - unable to complete query");
return REDISMODULE_ERR;
}
RedisModule_ReplyWithArray(ctx, results.size());
for (QueryResult &r: results){
RedisModuleString *reply_descr = GetDescriptionField(ctx, argv[1], r.dp->id);
RedisModule_ReplyWithArray(ctx, 3);
RedisModule_ReplyWithString(ctx, reply_descr);
RedisModule_ReplyWithLongLong(ctx, r.dp->id);
RedisModule_ReplyWithDouble(ctx, r.distance);
}
// calculate pct of distance operations
double pct_opers = (double)MVPTree::n_ops/(double)tree->Size();
chrono::time_point<chrono::high_resolution_clock> end = chrono::high_resolution_clock::now();
auto elapsed = chrono::duration_cast<chrono::microseconds>(end - start).count();
RedisModule_Log(ctx, "debug", "query in %llu microseconds (%f ops)", elapsed, pct_opers);
return REDISMODULE_OK;
}
/* args: key id */
extern "C" int MVPTreeLookup_RedisCmd(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){
if (argc != 3) return RedisModule_WrongArity(ctx);
RedisModule_AutoMemory(ctx);
long long id;
if (RedisModule_StringToLongLong(argv[2], &id) == REDISMODULE_ERR){
RedisModule_ReplyWithError(ctx, "Error - unable to parse id");
return REDISMODULE_ERR;
}
RedisModuleString *descr = GetDescriptionField(ctx, argv[1], id);
RedisModule_ReplyWithString(ctx, descr);
return REDISMODULE_OK;
}
/* args: key */
extern "C" int MVPTreeSize_RedisCmd(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){
if (argc != 2) return RedisModule_WrongArity(ctx);
RedisModule_AutoMemory(ctx);
MVPTree *tree = NULL;
try {
tree = GetMVPTree(ctx, argv[1]);
if (tree == NULL){
RedisModule_ReplyWithError(ctx, "ERR - no such key");
return REDISMODULE_ERR;
}
} catch (int &e){
RedisModule_ReplyWithError(ctx, "ERR - key exists for different type. Delete first.");
return REDISMODULE_ERR;
}
long long n_points;
try {
n_points = tree->Size();
} catch (exception &ex){
RedisModule_ReplyWithError(ctx, "ERR - unable to get size");
return REDISMODULE_ERR;
}
RedisModule_ReplyWithLongLong(ctx, n_points);
return REDISMODULE_OK;
}
/* args: key id */
extern "C" int MVPTreeDelete_RedisCmd(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){
if (argc != 3) return RedisModule_WrongArity(ctx);
RedisModule_AutoMemory(ctx);
MVPTree *tree = NULL;
try {
tree = GetMVPTree(ctx, argv[1]);
if (tree == NULL){
RedisModule_ReplyWithError(ctx, "ERR - no such key");
return REDISMODULE_ERR;
}
} catch (int &e){
RedisModule_ReplyWithError(ctx, "ERR - key exists for different type. Delete first.");
return REDISMODULE_ERR;
}
long long id;
if (RedisModule_StringToLongLong(argv[2], &id) == REDISMODULE_ERR){
RedisModule_ReplyWithError(ctx, "ERR - unable to parse id");
return REDISMODULE_ERR;
}
try {
tree->Delete(id);
} catch (exception &ex){
RedisModule_ReplyWithError(ctx, "ERR - unable to delete id");
return REDISMODULE_ERR;
}
DeleteDescriptionField(ctx, argv[1], id);
RedisModule_ReplyWithSimpleString(ctx, "OK");
RedisModule_ReplicateVerbatim(ctx);
return REDISMODULE_OK;
}
/* ============== Onload Init Function ==============================*/
extern "C" int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){
int rc = REDISMODULE_OK;
if (RedisModule_Init(ctx, "imgscout", 1, REDISMODULE_APIVER_1) == REDISMODULE_ERR)
rc = REDISMODULE_ERR;
RedisModuleTypeMethods tm = {.version = REDISMODULE_TYPE_METHOD_VERSION,
.rdb_load = MVPTreeTypeRdbLoad,
.rdb_save = MVPTreeTypeRdbSave,
.aof_rewrite = MVPTreeTypeAofRewrite,
.mem_usage = MVPTreeTypeMemUsage,
.digest = MVPTreeTypeDigest,
.free = MVPTreeTypeFree};
MVPTreeType = RedisModule_CreateDataType(ctx, "MVPTreeDS", MVPTREE_ENCODING_VERSION, &tm);
if (MVPTreeType == NULL) rc = REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx, "imgscout.add", MVPTreeAdd_RedisCmd,
"write deny-oom", 1, -1, 1) == REDISMODULE_ERR)
rc = REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx, "imgscout.addrepl", MVPTreeAddRepl_RedisCmd,
"write deny-oom", 1, -1, 1) == REDISMODULE_ERR)
rc = REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx, "imgscout.sync", MVPTreeSync_RedisCmd,
"write deny-oom", 1, -1, 1) == REDISMODULE_ERR)
rc = REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx, "imgscout.query", MVPTreeQuery_RedisCmd,
"readonly", 1, -1, 1) == REDISMODULE_ERR)
rc = REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx, "imgscout.lookup", MVPTreeLookup_RedisCmd,
"readonly fast", 1, -1, 1) == REDISMODULE_ERR)
rc = REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx, "imgscout.size", MVPTreeSize_RedisCmd,
"readonly fast", 1, -1, 1) == REDISMODULE_ERR)
rc = REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx, "imgscout.del", MVPTreeDelete_RedisCmd,
"write fast", 1, -1, 1) == REDISMODULE_ERR)
rc = REDISMODULE_ERR;
return rc;;
}