-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodule.cpp
2253 lines (1843 loc) · 70.1 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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdint>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <algorithm>
#include <ctime>
#include <chrono>
#include <cassert>
#include <limits>
#include "spfc.hpp"
#include "rbtree.hpp"
#include "haversine.hpp"
#include "redismodule.h"
using namespace std;
#define LONG_LAT_SCALE_FACTOR 1000000
#define RBTREE_ENCODING_VERSION 1
//static const char *date_fmt = "%d-%d-%d"; // MM-DD-YYY
//static const char *time_fmt = "%d:%d:%d"; // HH:MM
static const char *datetime_ifmt = "%d-%d-%dT%d:%d:%d"; // for use with strptime time parsing
static const char *datetime_ofmt = "%Y-%m-%dT%H:%M:%S"; // for use with strftime time parsing
static const char *descr_field = "descr";
static RedisModuleType *RBTreeType;
typedef struct rbtree_t {
RBNode *root;
RedisModuleDict *dict;
RedisModuleDict *obj_dict;
uint64_t object_count;
} RBTree;
/*======================= dyn mem management ===============================*/
void* operator new(size_t sz){
void *ptr = RedisModule_Alloc(sz);
return ptr;
}
void operator delete(void *p){
RedisModule_Free(p);
}
/*================ Aux. RedisModule functions ======================================= */
/* check to see if point defined in Value is contained in query region*/
bool contains(const QueryRegion qr, const Value val){
if (val.x < qr.x_lower || val.x > qr.x_upper)
return false;
else if (val.y < qr.y_lower || val.y > qr.y_upper)
return false;
else if (val.start < qr.t_lower || val.start > qr.t_upper)
return false;
return true;
}
/* cast a query in terms of the spfc function */
int cast_query_region(const QueryRegion qr, Region &r){
r.lower[0] = static_cast<uint64_t>((qr.x_lower + 180.0)*LONG_LAT_SCALE_FACTOR);
r.lower[1] = static_cast<uint64_t>((qr.y_lower + 90.0)*LONG_LAT_SCALE_FACTOR);
r.lower[2] = static_cast<uint64_t>(qr.t_lower);
r.upper[0] = static_cast<uint64_t>((qr.x_upper + 180.0)*LONG_LAT_SCALE_FACTOR);
r.upper[1] = static_cast<uint64_t>((qr.y_upper + 90.0)*LONG_LAT_SCALE_FACTOR);
r.upper[2] = static_cast<uint64_t>(qr.t_upper);
return 0;
}
int ParseLongLat(RedisModuleString *xstr, RedisModuleString *ystr, double &x, double &y){
if (RedisModule_StringToDouble(xstr, &x) == REDISMODULE_ERR)
return -1;
if (RedisModule_StringToDouble(ystr, &y) == REDISMODULE_ERR)
return -1;
return 0;
}
int ParseDateTime(RedisModuleString *datetimestr, time_t &epoch){
const char *ptr = RedisModule_StringPtrLen(datetimestr, NULL);
if (ptr == NULL) return -1;
setenv("TZ", "GMT", 1);
tm datetime;
memset(&datetime, 0, sizeof(tm));
if (sscanf(ptr, datetime_ifmt, &datetime.tm_year, &datetime.tm_mon, &datetime.tm_mday,
&datetime.tm_hour, &datetime.tm_min, &datetime.tm_sec) < 5) return -1;
datetime.tm_mon -= 1;
datetime.tm_year = (datetime.tm_year >= 2000) ? datetime.tm_year%100 + 100 : datetime.tm_year%100;
if (datetime.tm_mon < 0 || datetime.tm_mon > 11) return -1;
if (datetime.tm_mday <= 0 || datetime.tm_mday > 31) return -1;
if (datetime.tm_year < 0 || datetime.tm_year > 300) return -1;
epoch = mktime(&datetime);
unsetenv("TZ");
return 0;
}
int ParseRadius(RedisModuleString *radius_str, RedisModuleString *unit_str, double &radius){
double val;
if (RedisModule_StringToDouble(radius_str, &val) == REDISMODULE_ERR)
return -1;
const char *str = RedisModule_StringPtrLen(unit_str, NULL);
if (strcmp(str, "mi") == 0){
val *= 1.60934;
radius = val;
} else if (strcmp(str, "m") == 0){
val /= 1000;
radius = val;
} else if (strcmp(str, "ft") == 0){
val /= 3281;
radius = val;
} else if (strcmp(str, "km") == 0){
radius = val;
} else {
return -1;
}
return 0;
}
void InsertObjectInList(RBTree *tree, long long obj_id, RBNode *x){
int nokey;
multimap<time_t, RBNode*> *mmap =
(multimap<time_t, RBNode*>*)RedisModule_DictGetC(tree->obj_dict,
&obj_id, sizeof(long long), &nokey);
if (nokey || mmap == NULL){
mmap = new multimap<time_t, RBNode*>();
RedisModule_DictReplaceC(tree->obj_dict, &obj_id, sizeof(long long), mmap);
}
mmap->insert({x->val.start, x});
tree->object_count++;
return;
}
void RemoveObjectFromList(RBTree *tree, long long obj_id, RBNode *x){
int nokey;
multimap<time_t, RBNode*> *mmap =
(multimap<time_t, RBNode*>*)RedisModule_DictGetC(
tree->obj_dict, &obj_id, sizeof(long long), &nokey);
if (nokey || mmap == NULL) return;
auto range = mmap->equal_range(x->val.start);
for (auto iter=range.first;iter != range.second;iter++){
if (iter->second == x){
mmap->erase(iter->first);
break;
}
}
return;
}
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;
}
/*================== Get RBTree with key ================================= */
/* Return the native data type. NULL if does not yet exist, throw -1 exception
if the key exists but for a different type. */
RBTree* GetRBTree(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) != RBTreeType){
RedisModule_CloseKey(key);
throw -1;
}
RBTree *tree = (RBTree*)RedisModule_ModuleTypeGetValue(key);
RedisModule_CloseKey(key);
return tree;
}
/* Create a new data type, throw -1 exception if already exists for a different type */
RBTree* CreateRBTree(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) != RBTreeType){
RedisModule_CloseKey(key);
throw -1;
}
RBTree *tree = NULL;
if (keytype == REDISMODULE_KEYTYPE_EMPTY){
tree = (RBTree*)RedisModule_Calloc(1, sizeof(RBTree));
tree->dict = RedisModule_CreateDict(NULL);
tree->obj_dict = RedisModule_CreateDict(NULL);
RedisModule_ModuleTypeSetValue(key, RBTreeType, tree);
} else {
tree = (RBTree*)RedisModule_ModuleTypeGetValue(key);
}
RedisModule_CloseKey(key);
return tree;
}
/* =============== module tree manipulation functions ==================*/
RBNode* delete_min(RedisModuleCtx *ctx, RBTree *tree, RBNode *node){
if (node->left == NULL) {
RedisModule_DictDelC(tree->dict, &(node->val.id), sizeof(long long), NULL);
if (node->val.obj_id > 0) RemoveObjectFromList(tree, node->val.obj_id, node);
delete node;
return NULL;
}
if (!IsRed(node->left) && !IsRed(node->left->left))
node = MoveRedLeft(node);
node->left = delete_min(ctx, tree, node->left);
return balance(node);
}
void RBTreeDeleteMin(RedisModuleCtx *ctx, RBTree *tree){
if (tree == NULL || tree->root == NULL)
return;
if (!IsRed(tree->root->left) && !IsRed(tree->root->right))
tree->root->red = true;
tree->root = delete_min(ctx, tree, tree->root);
if (tree->root != NULL)
tree->root->red = false;
}
RBNode* delete_key(RedisModuleCtx *ctx, RBTree *tree, RBNode *node, Seqn s, long long id, int level = 0){
if (node == NULL) return NULL;
if (cmpseqnums(s, node->s) < 0 || (cmpseqnums(s, node->s) == 0 && id != node->val.id)){
if (node->left != NULL && !IsRed(node->left) && !IsRed(node->left->left)){
node = MoveRedLeft(node);
}
node->left = delete_key(ctx, tree, node->left, s, id, level+1);
} else {
if (IsRed(node->left)) node = RotateRight(node);
if (cmpseqnums(s, node->s) == 0 && id == node->val.id && node->right == NULL){
if (node->val.obj_id > 0) RemoveObjectFromList(tree, node->val.obj_id, node);
RedisModule_DictDelC(tree->dict, &id, sizeof(long long), NULL);
delete node;
return NULL;
}
if (node->right != NULL && !IsRed(node->right) && !IsRed(node->right->left))
node = MoveRedRight(node);
if (cmpseqnums(s, node->s) == 0){
if (id == node->val.id){
RBNode *xnode = minimum(node->right);
if (node->val.obj_id > 0) RemoveObjectFromList(tree, node->val.obj_id, node);
node->s = xnode->s;
node->val = xnode->val;
node->maxseqn = xnode->maxseqn;
node->right = delete_min(ctx, tree, node->right);
if (node->right) node->maxseqn = node->right->maxseqn;
if (node->val.obj_id > 0) InsertObjectInList(tree, node->val.obj_id, node);
node->count = 1 + GetNodeCount(node->left) + GetNodeCount(node->right);
RedisModule_DictDelC(tree->dict, &id, sizeof(long long), NULL);
RedisModule_DictReplaceC(tree->dict, &(node->val.id), sizeof(long long), node);
}
} else if (cmpseqnums(s, node->maxseqn) <= 0){
node->right = delete_key(ctx, tree, node->right, s, id, level+1);
}
}
node->count = 1 + GetNodeCount(node->left) + GetNodeCount(node->right);
return balance(node);
}
int RBTreeDelete(RedisModuleCtx *ctx, RBTree *tree, Seqn s, long long eventid){
if (tree == NULL || tree->root == NULL) return -1;
if (!IsRed(tree->root->left) && !IsRed(tree->root->right))
tree->root->red = true;
tree->root = delete_key(ctx, tree, tree->root, s, eventid);
if (tree->root != NULL) tree->root->red = false;
return 0;
}
RBNode* rbtree_insert(RBTree *tree, RBNode *node, Seqn s, Value val, int level=0){
if (node == NULL){
RBNode *x = new RBNode();
x->s = s;
x->maxseqn = s;
x->val = val;
x->red = true;
x->count = 1;
x->left = x->right = NULL;
if (x->val.obj_id > 0) InsertObjectInList(tree, x->val.obj_id, x);
RedisModule_DictSetC(tree->dict, &(x->val.id), sizeof(long long), x);
return x;
}
if (cmpseqnums(s, node->s) <= 0){
node->left = rbtree_insert(tree, node->left, s, val, level+1);
} else {
node->right = rbtree_insert(tree, node->right, s, val, level+1);
node->maxseqn = node->right->maxseqn;
}
if (IsRed(node->right) && !IsRed(node->left)) node = RotateLeft(node);
if (IsRed(node->left) && IsRed(node->left->left)) node = RotateRight(node);
if (IsRed(node->left) && IsRed(node->right)) FlipColors(node);
node->count = 1 + GetNodeCount(node->left) + GetNodeCount(node->right);
return node;
}
int RBTreeInsert(RBTree *tree, Seqn s, Value val){
if (tree == NULL) return -1;
RBNode *node = rbtree_insert(tree, tree->root, s, val);
if (node == NULL) return -1;
node->red = false;
tree->root = node;
return 0;
}
/* in-order travsal */
void print_tree(RedisModuleCtx *ctx, RedisModuleString *keystr, RBNode *node, int level = 0){
if (node == NULL) return;
// print left
print_tree(ctx, keystr, node->left, level+1);
// print node
double x = node->val.x;
double y = node->val.y;
char scratch[64];
strftime(scratch, 64, datetime_ofmt, gmtime(&(node->val.start)));
RedisModuleString *node_descr = GetDescriptionField(ctx, keystr, node->val.id);
RedisModule_Log(ctx, "info", "print (level %d) %s %.6f/%.6f id=%lld %s red=%d cat=%ld",
level, node_descr, x, y, node->val.id, scratch, node->red, node->val.cat);
RedisModule_FreeString(ctx, node_descr);
// print right
print_tree(ctx, keystr, node->right, level+1);
}
long long RBTreePrint(RedisModuleCtx *ctx, RedisModuleString *keystr){
RBTree *tree = GetRBTree(ctx, keystr);
if (tree == NULL || tree->root == NULL){
RedisModule_Log(ctx, "info", "%s is empty", RedisModule_StringPtrLen(keystr, NULL));
return 0;
}
RedisModule_Log(ctx, "info", "print tree: %s", RedisModule_StringPtrLen(keystr, NULL));
print_tree(ctx, keystr, tree->root);
return tree->root->count;
}
/* non-recursive implementation */
int RBTreeQuery(RBTree *tree, const QueryRegion qr, vector<Result> &results){
Region r;
cast_query_region(qr, r);
Seqn prev, next;
if (!next_match(r, prev, next)) return 0;
stack<NodeSt> s;
if (tree->root) s.push({tree->root, 0});
while (!s.empty()){
if (s.top().visited == 0){ /* if needed, visit left */
// visit left
s.top().visited++;
if (s.top().node->left && cmpseqnums(next, s.top().node->s) <= 0){
s.push({s.top().node->left, 0});
}
} else if (s.top().visited == 1){ /* check node. if needed, visit right */
s.top().visited++;
next = s.top().node->s;
Seqn prev = next;
if (contains(qr, s.top().node->val)){
results.push_back({s.top().node->s, s.top().node->val});
} else if (!next_match(r, prev, next))
break;
if (s.top().node->right && cmpseqnums(next, s.top().node->maxseqn) <= 0){
s.push({s.top().node->right, 0});
}
} else { /* both left right visited */
s.pop();
}
}
return 0;
}
/* ------------------ RBTree type methods -----------------------------*/
extern "C" void* RBTreeTypeRdbLoad(RedisModuleIO *rdb, int encver){
if (encver != RBTREE_ENCODING_VERSION){
RedisModule_LogIOError(rdb, "warning", "rdbload: unnable to encode for encver %d", encver);
return NULL;
}
RBTree *tree = (RBTree*)RedisModule_Calloc(1, sizeof(RBTree));
tree->dict = RedisModule_CreateDict(NULL);
tree->obj_dict = RedisModule_CreateDict(NULL);
tree->object_count = 0;
uint64_t n_nodes = RedisModule_LoadUnsigned(rdb);
RedisModule_LogIOError(rdb, "debug", "rdbload: %llu nodes", n_nodes);
for (uint64_t i=0;i<n_nodes;i++){
Seqn s; // load seqn
s.arr[0] = RedisModule_LoadUnsigned(rdb);
s.arr[1] = RedisModule_LoadUnsigned(rdb);
s.arr[2] = RedisModule_LoadUnsigned(rdb);
Value val; // load id, longitude, latitude, start, end, descr
val.x = RedisModule_LoadDouble(rdb);
val.y = RedisModule_LoadDouble(rdb);
val.id = RedisModule_LoadSigned(rdb);
val.obj_id = RedisModule_LoadSigned(rdb);
val.cat = RedisModule_LoadUnsigned(rdb);
val.start = static_cast<time_t>(RedisModule_LoadSigned(rdb));
val.end = static_cast<time_t>(RedisModule_LoadSigned(rdb));
if (RBTreeInsert(tree, s, val) < 0){
RedisModule_LogIOError(rdb, "warning", "rdbload: unable to insert %ld", val.id);
return NULL;
}
}
return (void*)tree;
}
extern "C" void RBTreeTypeRdbSave(RedisModuleIO *rdb, void *value){
RBTree *tree = (RBTree*)value;
RedisModuleDictIter *iter = RedisModule_DictIteratorStartC(tree->dict, "^", NULL, 0);
uint64_t sz = RedisModule_DictSize(tree->dict);
RedisModule_SaveUnsigned(rdb, sz);
RedisModule_LogIOError(rdb, "debug", "rdbsave: %llu nodes", sz);
unsigned char *dict_key;
RBNode *node;
while ((dict_key = (unsigned char*)RedisModule_DictNextC(iter, NULL, (void**)&node)) != NULL){
// save seqn
RedisModule_SaveUnsigned(rdb, node->s.arr[0]);
RedisModule_SaveUnsigned(rdb, node->s.arr[1]);
RedisModule_SaveUnsigned(rdb, node->s.arr[2]);
// long./lat.
RedisModule_SaveDouble(rdb, node->val.x);
RedisModule_SaveDouble(rdb, node->val.y);
// id
RedisModule_SaveSigned(rdb, node->val.id);
RedisModule_SaveSigned(rdb, node->val.obj_id);
RedisModule_SaveUnsigned(rdb, node->val.cat);
// time start/end
RedisModule_SaveSigned(rdb, node->val.start);
RedisModule_SaveSigned(rdb, node->val.end);
}
RedisModule_DictIteratorStop(iter);
}
extern "C" void RBTreeTypeAofRewrite(RedisModuleIO *aof, RedisModuleString *key, void *value){
RBTree *tree = (RBTree*)value;
uint64_t sz = RedisModule_DictSize(tree->dict);
RedisModule_LogIOError(aof, "debug", "AofRewrite: %llu nodes", sz);
RedisModuleDictIter *iter = RedisModule_DictIteratorStartC(tree->dict, "^", NULL, 0);
char s1[16];
char s2[16];
char px[16];
char py[16];
unsigned char *dict_key = NULL;
RBNode *node = NULL;
while ((dict_key = (unsigned char*)RedisModule_DictNextC(iter, NULL, (void**)&node)) != NULL){
strftime(s1, 16, "%Y-%m-%dT%H:%M", gmtime(&(node->val.start)));
strftime(s2, 16, "%Y-%m-%dT%H:%M", gmtime(&(node->val.end)));
snprintf(px, 16, "%.6f", node->val.x);
snprintf(py, 16, "%.6f", node->val.y);
if (node->val.obj_id == 0){
RedisModule_EmitAOF(aof, "reventis.insertrepl", "sccccl",
key, px, py, s1, s2, node->val.id);
} else {
RedisModule_EmitAOF(aof, "reventis.updaterepl", "scccll",
key, px, py, s1, node->val.obj_id, node->val.id);
}
unsigned long long cat_id = 0x0001ULL;
long long pos = 1;
while (cat_id){
if (cat_id & node->val.cat){
RedisModule_EmitAOF(aof, "reventis.addcategory", "sl", key, pos);
}
cat_id <<= 1;
pos++;
}
}
RedisModule_DictIteratorStop(iter);
}
extern "C" void RBTreeTypeFree(void *value){
RBTree *tree = (RBTree*)value;
RedisModuleDictIter *iter = RedisModule_DictIteratorStartC(tree->dict, "^", NULL, 0);
long long *dict_key = NULL;
size_t keylen;
RBNode *node = NULL;
while ((dict_key = (long long*)RedisModule_DictNextC(iter, &keylen, (void**)&node)) != NULL){
delete node;
}
RedisModule_DictIteratorStop(iter);
iter = RedisModule_DictIteratorStartC(tree->obj_dict, "^", NULL, 0);
multimap<time_t, RBNode*> *mm = NULL;
while ((dict_key = (long long*)RedisModule_DictNextC(iter, &keylen, (void**)&mm)) != NULL){
delete mm;
}
RedisModule_DictIteratorStop(iter);
RedisModule_FreeDict(NULL, tree->dict);
RedisModule_FreeDict(NULL, tree->obj_dict);
}
extern "C" size_t RBTreeTypeMemUsage(const void *value){
RBTree *tree = (RBTree*)value;
uint64_t n_nodes = RedisModule_DictSize(tree->dict);
uint64_t n_objects = 0;
RedisModuleDictIter *iter = RedisModule_DictIteratorStartC(tree->obj_dict, "^", NULL, 0);
unsigned char *dict_key = NULL;
size_t keylen;
multimap<time_t, RBNode*> *mmap;
while ((dict_key = (unsigned char*)RedisModule_DictNextC(iter, &keylen, (void**)&mmap)) != NULL){
n_objects += mmap->size();
}
RedisModule_DictIteratorStop(iter);
return n_nodes*sizeof(RBNode) + n_objects*(sizeof(RBNode*) + sizeof(long long));
}
extern "C" void RBTreeTypeDigest(RedisModuleDigest *digest, void *value){
REDISMODULE_NOT_USED(digest);
REDISMODULE_NOT_USED(value);
}
/* ---------------RedisCommand functions ------------------------------*/
int RBTreeQueryResults(RedisModuleCtx *ctx, RedisModuleString *key,
RedisModuleString *x1str, RedisModuleString *x2str,
RedisModuleString *y1str, RedisModuleString *y2str,
RedisModuleString *startdatetimestr, RedisModuleString *enddatetimestr,
vector<Result> &results){
double x1, y1;
if (ParseLongLat(x1str, y1str, x1, y1) < 0){
RedisModule_ReplyWithError(ctx, "ERR - Unable to parse lower longitude/latitude arg values");
return REDISMODULE_ERR;
}
double x2, y2;
if (ParseLongLat(x2str, y2str, x2, y2) < 0){
RedisModule_ReplyWithError(ctx, "ERR - Unable to parse upper longitude/latitude arg values");
return REDISMODULE_ERR;
}
if (x1 < -180.0 || x1 > 180.0 || x2 < -180.0 || x2 > 180.0){
RedisModule_ReplyWithError(ctx, "ERR - longitude/latitude arg values out of range");
return REDISMODULE_ERR;
}
time_t t1, t2;
if (ParseDateTime(startdatetimestr, t1) < 0){
RedisModule_ReplyWithError(ctx, "ERR - Unable to parse lower date time arg values");
return REDISMODULE_ERR;
}
if (ParseDateTime(enddatetimestr, t2) < 0){
RedisModule_ReplyWithError(ctx, "ERR - Unable to parse upper date time arg values");
return REDISMODULE_ERR;
}
if (t1 > t2){
RedisModule_ReplyWithError(ctx, "ERR - start time cannot be later than end time");
return REDISMODULE_ERR;
}
RBTree *tree = NULL;
try {
tree = GetRBTree(ctx, key);
if (tree == NULL){
RedisModule_ReplyWithError(ctx, "ERR - No such key");
return REDISMODULE_ERR;
}
} catch (int &e){
RedisModule_ReplyWithError(ctx, "key already exists for different type");
return REDISMODULE_ERR;
}
QueryRegion qr;
qr.x_lower = x1;
qr.x_upper = x2;
qr.y_lower = y1;
qr.y_upper = y2;
qr.t_lower = t1;
qr.t_upper = t2;
if (RBTreeQuery(tree, qr, results) < 0){
RedisModule_ReplyWithError(ctx, "Err - Unable to query");
return REDISMODULE_ERR;
}
return REDISMODULE_OK;
}
int RBTreeInsertCommon(RedisModuleCtx *ctx, RedisModuleString *keystr,
RedisModuleString *longitudestr, RedisModuleString *latitudestr,
RedisModuleString *startdatetimestr, RedisModuleString *enddatetimestr,
unsigned long long cat_id, long long event_id){
double x, y;
if (ParseLongLat(longitudestr, latitudestr, x, y) < 0){
RedisModule_ReplyWithError(ctx, "ERR - bad longitude/latitude arg values");
return REDISMODULE_ERR;
}
if (x < -180.0 || x > 180.0 || y < -90.0 || y > 90.0){
RedisModule_ReplyWithError(ctx, "ERR - longitude/latitude args out of range");
return REDISMODULE_ERR;
}
time_t t1;
if (ParseDateTime(startdatetimestr, t1) < 0){
RedisModule_ReplyWithError(ctx, "ERR - Unable to parse start time");
return REDISMODULE_ERR;
}
time_t t2;
if (ParseDateTime(enddatetimestr, t2) < 0){
RedisModule_ReplyWithError(ctx, "ERR - Unable to parse end time");
return REDISMODULE_ERR;
}
if (t1 > t2){
RedisModule_ReplyWithError(ctx, "ERR - start time cannot be later than end time");
return REDISMODULE_ERR;
}
Point pnt;
pnt.arr[0] = static_cast<uint64_t>((x+180.0)*LONG_LAT_SCALE_FACTOR);
pnt.arr[1] = static_cast<uint64_t>((y+90.0)*LONG_LAT_SCALE_FACTOR);
pnt.arr[2] = static_cast<uint64_t>(t1);
Value val;
val.x = x;
val.y = y;
val.cat = cat_id;
val.id = event_id;
val.start = t1;
val.end = t2;
Seqn s;
spfc_encode(pnt, s);
RBTree *tree = NULL;
try {
tree = GetRBTree(ctx, keystr);
if (tree == NULL) tree = CreateRBTree(ctx, keystr);
} catch (int &e){
RedisModule_ReplyWithError(ctx, "ERR - key exists for different type. Delete first.");
return REDISMODULE_ERR;
}
if (RBTreeInsert(tree, s, val) < 0){
RedisModule_ReplyWithError(ctx, "ERR - Insert failed");
return REDISMODULE_ERR;
}
RedisModule_ReplyWithLongLong(ctx, event_id);
return REDISMODULE_OK;
}
/* args: key longitude latitude datetime-start datetime-end [id] */
extern "C" int RBTreeInsertRepl_RedisCmd(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){
if (argc < 6 || argc > 7) return RedisModule_WrongArity(ctx);
RedisModule_AutoMemory(ctx);
long long event_id;
if (argc == 6){
if (get_next_id(ctx, argv[1], event_id) == REDISMODULE_ERR){
RedisModule_ReplyWithError(ctx, "ERR - unable to assign event id");
return REDISMODULE_ERR;
}
} else {
if (RedisModule_StringToLongLong(argv[6], &event_id) == REDISMODULE_ERR){
RedisModule_ReplyWithError(ctx, "ERR - unable to parse event id");
return REDISMODULE_ERR;
}
}
int rc = RBTreeInsertCommon(ctx, argv[1], argv[2], argv[3], argv[4], argv[5], 0, event_id);
if (rc == REDISMODULE_ERR) return REDISMODULE_ERR;
rc = RedisModule_Replicate(ctx, "reventis.insertrepl", "sssssl",
argv[1], argv[2], argv[3], argv[4], argv[5], event_id);
if (rc == REDISMODULE_ERR){
RedisModule_Log(ctx, "warning", "Unable to replicate for id %lld", event_id);
return REDISMODULE_ERR;
}
return REDISMODULE_OK;
}
/* args: key longitude latitude datetime-start datetime-end title-description [id]*/
/* an optional event_id argument is included for replication commands */
/* return event-id assigned to entry */
extern "C" int RBTreeInsert_RedisCmd(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){
if (argc < 7 || argc > 8) return RedisModule_WrongArity(ctx);
RedisModule_AutoMemory(ctx);
long long event_id;
if (argc == 7){
if (get_next_id(ctx, argv[1], event_id) == REDISMODULE_ERR){
RedisModule_ReplyWithError(ctx, "ERR - unable to assign event id");
return REDISMODULE_ERR;
}
} else {
if (RedisModule_StringToLongLong(argv[7], &event_id) == REDISMODULE_ERR){
RedisModule_ReplyWithError(ctx, "ERR - unable to parse event id");
return REDISMODULE_ERR;
}
}
int rc = RBTreeInsertCommon(ctx, argv[1], argv[2], argv[3], argv[4], argv[5], 0, event_id);
if (rc == REDISMODULE_ERR) return REDISMODULE_ERR;
SetDescriptionField(ctx, argv[1], event_id, argv[6]);
/* replicate command with eventid tacked on as last argument */
rc = RedisModule_Replicate(ctx, "reventis.insert", "ssssssl",
argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], event_id);
if (rc == REDISMODULE_ERR){
RedisModule_Log(ctx, "warning", "Unable to replicate for id %ld", event_id);
return REDISMODULE_ERR;
}
return REDISMODULE_OK;
}
/* args: mytree eventid cat_id */
/* add=true to add a category, add=false to remove category*/
int ModifyCategories(RedisModuleCtx *ctx, RedisModuleString **argv, int argc, bool add=true){
RedisModule_AutoMemory(ctx);
RedisModuleString *keystr = argv[1];
long long event_id;
if (RedisModule_StringToLongLong(argv[2], &event_id) != REDISMODULE_OK){
RedisModule_ReplyWithError(ctx, "ERR - Unable to parse id arg value");
return REDISMODULE_ERR;
}
RBTree *tree = NULL;
try {
tree = GetRBTree(ctx, keystr);
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");
return REDISMODULE_ERR;
}
int nokey;
RBNode *idnode = (RBNode*)RedisModule_DictGetC(tree->dict, (void*)&event_id, sizeof(event_id), &nokey);
if (nokey || idnode == NULL){
RedisModule_ReplyWithError(ctx, "ERR - no such node");
return REDISMODULE_ERR;
}
for (int i=3;i<argc;i++){
long long cat_id;
if (RedisModule_StringToLongLong(argv[i], &cat_id) != REDISMODULE_OK){
RedisModule_ReplyWithError(ctx, "ERR - unable to parse cat id value");
return REDISMODULE_ERR;
}
if (add){
idnode->val.cat |= 0x0001ULL << (cat_id-1);
} else {
idnode->val.cat &= ~0x0001ULL << (cat_id-1);
}
}
RedisModule_Log(ctx, "debug", "modify category for node - %llx", idnode->val.cat);
RedisModule_ReplyWithSimpleString(ctx, "OK");
RedisModule_ReplicateVerbatim(ctx);
return REDISMODULE_OK;
}
/* args: mytree event_id [cat_id...}]*/
extern "C" int RBTreeAddCategory_RedisCmd(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){
if (argc < 4) return RedisModule_WrongArity(ctx);
return ModifyCategories(ctx, argv, argc, true);
}
/* args: mytree event_id [cat_id...]*/
extern "C" int RBTreeRemoveCategory_RedisCmd(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){
if (argc < 4) return RedisModule_WrongArity(ctx);
return ModifyCategories(ctx, argv, argc, false);
}
/* args: mytree event_id */
extern "C" int RBTreeLookup_RedisCmd(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){
if (argc != 3) return RedisModule_WrongArity(ctx);
RedisModule_AutoMemory(ctx);
RedisModuleString *keystr = argv[1];
long long event_id;
if (RedisModule_StringToLongLong(argv[2], &event_id) == REDISMODULE_ERR){
RedisModule_ReplyWithError(ctx, "ERR - Unable to parse id arg value");
return REDISMODULE_ERR;
}
RBTree *tree = NULL;
try {
tree = GetRBTree(ctx, keystr);
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");
return REDISMODULE_ERR;
}
int nokey;
RBNode *idnode = (RBNode*)RedisModule_DictGetC(tree->dict, (void*)&event_id, sizeof(event_id), &nokey);
if (nokey || idnode == NULL){
RedisModule_ReplyWithNull(ctx);
return REDISMODULE_OK;
}
char s1[64];
char s2[64];
strftime(s1, 64, datetime_ofmt, gmtime(&(idnode->val.start)));
strftime(s2, 64, datetime_ofmt, gmtime(&(idnode->val.end)));
RedisModuleString *descr = GetDescriptionField(ctx, keystr, event_id);
RedisModule_ReplyWithArray(ctx, 7);
RedisModule_ReplyWithString(ctx, descr);
RedisModule_ReplyWithLongLong(ctx, idnode->val.id);
RedisModule_ReplyWithLongLong(ctx, idnode->val.obj_id);
RedisModule_ReplyWithDouble(ctx, idnode->val.x);
RedisModule_ReplyWithDouble(ctx, idnode->val.y);
RedisModule_ReplyWithStringBuffer(ctx, s1, strlen(s1)+1);
RedisModule_ReplyWithStringBuffer(ctx, s2, strlen(s2)+1);
return REDISMODULE_OK;
}
/* args: mytree eventid */
extern "C" int RBTreeDelete_RedisCmd(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){
if (argc != 3) return RedisModule_WrongArity(ctx);
RedisModule_AutoMemory(ctx);
chrono::time_point<chrono::high_resolution_clock> start = chrono::high_resolution_clock::now();
RedisModuleString *keystr = argv[1];