forked from RedisJSON/RedisJSON
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrejson.c
2055 lines (1813 loc) · 70 KB
/
rejson.c
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
/*
* Copyright 2017-2019 Redis Labs Ltd. and Contributors
*
* This file is available under the Redis Labs Source Available License Agreement
*/
#include "rejson.h"
#include "cache.h"
// A struct to keep module the module context
typedef struct {
JSONObjectCtx *joctx;
} ModuleCtx;
static ModuleCtx JSONCtx;
// == Helpers ==
#define NODEVALUE_AS_DOUBLE(n) (N_INTEGER == n->type ? (double)n->value.intval : n->value.numval)
#define NODETYPE(n) (n ? n->type : N_NULL)
struct JSONPathNode_t;
static void maybeClearPathCache(JSONType_t *jt, const struct JSONPathNode_t *pn);
/* Returns the string representation of a the node's type. */
static inline char *NodeTypeStr(const NodeType nt) {
static char *types[] = {"null", "boolean", "integer", "number", "string", "object", "array"};
switch (nt) {
case N_NULL:
return types[0];
case N_BOOLEAN:
return types[1];
case N_INTEGER:
return types[2];
case N_NUMBER:
return types[3];
case N_STRING:
return types[4];
case N_DICT:
return types[5];
case N_ARRAY:
return types[6];
case N_KEYVAL:
return NULL; // this **should** never be reached
}
return NULL; // this is never reached
}
/* Check if a search path is the root search path. */
static inline int SearchPath_IsRootPath(const SearchPath *sp) {
return (1 == sp->len && NT_ROOT == sp->nodes[0].type);
}
/* Stores everything about a resolved path. */
typedef struct JSONPathNode_t {
const char *spath; // the path's string
size_t spathlen; // the path's string length
Node *n; // the referenced node
Node *p; // its parent
SearchPath sp; // the search path
char *sperrmsg; // the search path error message
size_t sperroffset; // the search path error offset
PathError err; // set in case of path error
int errlevel; // indicates the level of the error in the path
} JSONPathNode_t;
/* Call this to free the struct's contents. */
void JSONPathNode_Free(JSONPathNode_t *jpn) {
if (jpn) {
SearchPath_Free(&jpn->sp);
RedisModule_Free(jpn);
}
}
/* Sets n to the target node by path.
* p is n's parent, errors are set into err and level is the error's depth
* Returns PARSE_OK if parsing successful
*/
int NodeFromJSONPath(Node *root, const RedisModuleString *path, JSONPathNode_t **jpn) {
// initialize everything
JSONPathNode_t *_jpn = RedisModule_Calloc(1, sizeof(JSONPathNode_t));
_jpn->errlevel = -1;
JSONSearchPathError_t jsperr = {0};
// path must be valid from the root or it's an error
_jpn->sp = NewSearchPath(0);
_jpn->spath = RedisModule_StringPtrLen(path, &_jpn->spathlen);
if (PARSE_ERR == ParseJSONPath(_jpn->spath, _jpn->spathlen, &_jpn->sp, &jsperr)) {
SearchPath_Free(&_jpn->sp);
_jpn->sp.nodes = NULL; // in case someone tries to free it later
_jpn->sperrmsg = jsperr.errmsg;
_jpn->sperroffset = jsperr.offset;
*jpn = _jpn;
return PARSE_ERR;
}
// if there are any errors return them
if (!SearchPath_IsRootPath(&_jpn->sp)) {
_jpn->err = SearchPath_FindEx(&_jpn->sp, root, &_jpn->n, &_jpn->p, &_jpn->errlevel);
} else {
// deal with edge case of setting root's parent
_jpn->n = root;
}
*jpn = _jpn;
return PARSE_OK;
}
/* Replies with an error about a search path */
void ReplyWithSearchPathError(RedisModuleCtx *ctx, JSONPathNode_t *jpn) {
sds err = sdscatfmt(sdsempty(), "ERR Search path error at offset %I: %s",
(long long)jpn->sperroffset + 1, jpn->sperrmsg ? jpn->sperrmsg : "(null)");
RedisModule_ReplyWithError(ctx, err);
sdsfree(err);
}
/* Replies with an error about a wrong type of node in a path */
void ReplyWithPathTypeError(RedisModuleCtx *ctx, NodeType expected, NodeType actual) {
sds err = sdscatfmt(sdsempty(), REJSON_ERROR_PATH_WRONGTYPE, NodeTypeStr(expected),
NodeTypeStr(actual));
RedisModule_ReplyWithError(ctx, err);
sdsfree(err);
}
/* Generic path error reply handler */
void ReplyWithPathError(RedisModuleCtx *ctx, const JSONPathNode_t *jpn) {
// TODO: report actual position in path & literal token
PathNode *epn = &jpn->sp.nodes[jpn->errlevel];
sds err = sdsempty();
switch (jpn->err) {
case E_OK:
err = sdscat(err, "ERR nothing wrong with path");
break;
case E_BADTYPE:
if (NT_KEY == epn->type) {
err = sdscatfmt(err, "ERR invalid key '[\"%s\"]' at level %i in path",
epn->value.key, jpn->errlevel);
} else {
err = sdscatfmt(err, "ERR invalid index '[%i]' at level %i in path",
epn->value.index, jpn->errlevel);
}
break;
case E_NOINDEX:
err = sdscatfmt(err, "ERR index '[%i]' out of range at level %i in path",
epn->value.index, jpn->errlevel);
break;
case E_NOKEY:
err = sdscatfmt(err, "ERR key '%s' does not exist at level %i in path", epn->value.key,
jpn->errlevel);
break;
default:
err = sdscatfmt(err, "ERR unknown path error at level %i in path", jpn->errlevel);
break;
} // switch (err)
RedisModule_ReplyWithError(ctx, err);
sdsfree(err);
}
/* The custom Redis data type. */
static RedisModuleType *JSONType;
// == Module JSON commands ==
/**
* JSON.RESP <key> [path]
* Return the JSON in `key` in RESP.
*
* `path` defaults to root if not provided.
* This command uses the following mapping from JSON to RESP:
* - JSON Null is mapped to the RESP Null Bulk String
* - JSON `false` and `true` values are mapped to the respective RESP Simple Strings
* - JSON Numbers are mapped to RESP Integers or RESP Bulk Strings, depending on type
* - JSON Strings are mapped to RESP Bulk Strings
* - JSON Arrays are represented as RESP Arrays in which first element is the simple string `[`
* followed by the array's elements
* - JSON Objects are represented as RESP Arrays in which first element is the simple string `{`.
Each successive entry represents a key-value pair as a two-entries array of bulk strings.
*
* Reply: Array, specifically the JSON's RESP form.
*/
int JSONResp_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if ((argc < 2) || (argc > 3)) {
RedisModule_WrongArity(ctx);
return REDISMODULE_ERR;
}
RedisModule_AutoMemory(ctx);
// key must be empty (reply with null) or a JSON type
RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[1], REDISMODULE_READ);
int type = RedisModule_KeyType(key);
if (REDISMODULE_KEYTYPE_EMPTY == type) {
RedisModule_ReplyWithNull(ctx);
return REDISMODULE_OK;
} else if (RedisModule_ModuleTypeGetType(key) != JSONType) {
{
RedisModule_ReplyWithError(ctx, REDISMODULE_ERRORMSG_WRONGTYPE);
return REDISMODULE_ERR;
}
}
// validate path
JSONType_t *jt = RedisModule_ModuleTypeGetValue(key);
JSONPathNode_t *jpn = NULL;
RedisModuleString *spath =
(3 == argc ? argv[2] : RedisModule_CreateString(ctx, OBJECT_ROOT_PATH, 1));
if (PARSE_OK != NodeFromJSONPath(jt->root, spath, &jpn)) {
ReplyWithSearchPathError(ctx, jpn);
goto error;
}
if (E_OK == jpn->err) {
ObjectTypeToRespReply(ctx, jpn->n);
} else {
ReplyWithPathError(ctx, jpn);
goto error;
}
JSONPathNode_Free(jpn);
return REDISMODULE_OK;
error:
JSONPathNode_Free(jpn);
return REDISMODULE_ERR;
}
/**
* JSON.DEBUG <subcommand & arguments>
* Report information.
*
* Supported subcommands are:
* `MEMORY <key> [path]` - report the memory usage in bytes of a value. `path` defaults to root if
* not provided.
* `HELP` - replies with a helpful message
*
* Reply: depends on the subcommand used:
* `MEMORY` returns an integer, specifically the size in bytes of the value
* `HELP` returns an array, specifically with the help message
*/
int JSONDebug_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
// check for minimal arity
if (argc < 2) {
RedisModule_WrongArity(ctx);
return REDISMODULE_ERR;
}
RedisModule_AutoMemory(ctx);
size_t subcmdlen;
const char *subcmd = RedisModule_StringPtrLen(argv[1], &subcmdlen);
if (!strncasecmp("memory", subcmd, subcmdlen)) {
// verify we have enough arguments
if ((argc < 3) || (argc > 4)) {
RedisModule_WrongArity(ctx);
return REDISMODULE_ERR;
}
// reply to getkeys-api requests
if (RedisModule_IsKeysPositionRequest(ctx)) {
RedisModule_KeyAtPos(ctx, 2);
return REDISMODULE_OK;
}
// key must be empty (reply with null) or a JSON type
RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[2], REDISMODULE_READ);
int type = RedisModule_KeyType(key);
if (REDISMODULE_KEYTYPE_EMPTY == type) {
RedisModule_ReplyWithNull(ctx);
return REDISMODULE_OK;
} else if (RedisModule_ModuleTypeGetType(key) != JSONType) {
RedisModule_ReplyWithError(ctx, REDISMODULE_ERRORMSG_WRONGTYPE);
return REDISMODULE_ERR;
}
// validate path
JSONType_t *jt = RedisModule_ModuleTypeGetValue(key);
JSONPathNode_t *jpn = NULL;
RedisModuleString *spath =
(4 == argc ? argv[3] : RedisModule_CreateString(ctx, OBJECT_ROOT_PATH, 1));
if (PARSE_OK != NodeFromJSONPath(jt->root, spath, &jpn)) {
ReplyWithSearchPathError(ctx, jpn);
JSONPathNode_Free(jpn);
return REDISMODULE_ERR;
}
if (E_OK == jpn->err) {
RedisModule_ReplyWithLongLong(ctx, (long long)ObjectTypeMemoryUsage(jpn->n));
JSONPathNode_Free(jpn);
return REDISMODULE_OK;
} else {
ReplyWithPathError(ctx, jpn);
JSONPathNode_Free(jpn);
return REDISMODULE_ERR;
}
} else if (!strncasecmp("help", subcmd, subcmdlen)) {
const char *help[] = {"MEMORY <key> [path] - reports memory usage",
"HELP - this message", NULL};
RedisModule_ReplyWithArray(ctx, REDISMODULE_POSTPONED_ARRAY_LEN);
int i = 0;
for (; NULL != help[i]; i++) {
RedisModule_ReplyWithStringBuffer(ctx, help[i], strlen(help[i]));
}
RedisModule_ReplySetArrayLength(ctx, i);
return REDISMODULE_OK;
} else { // unknown subcommand
RedisModule_ReplyWithError(ctx, "ERR unknown subcommand - try `JSON.DEBUG HELP`");
return REDISMODULE_ERR;
}
return REDISMODULE_OK; // this is never reached
}
/**
* JSON.TYPE <key> [path]
* Reports the type of JSON value at `path`.
* `path` defaults to root if not provided. If the `key` or `path` do not exist, null is returned.
* Reply: Simple string, specifically the type.
*/
int JSONType_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
// check args
if ((argc < 2) || (argc > 3)) {
RedisModule_WrongArity(ctx);
return REDISMODULE_ERR;
}
RedisModule_AutoMemory(ctx);
// key must be empty or a JSON type
RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[1], REDISMODULE_READ);
int type = RedisModule_KeyType(key);
if (REDISMODULE_KEYTYPE_EMPTY == type) {
RedisModule_ReplyWithNull(ctx);
return REDISMODULE_OK;
}
if (RedisModule_ModuleTypeGetType(key) != JSONType) {
RedisModule_ReplyWithError(ctx, REDISMODULE_ERRORMSG_WRONGTYPE);
return REDISMODULE_ERR;
}
// validate path
JSONType_t *jt = RedisModule_ModuleTypeGetValue(key);
JSONPathNode_t *jpn = NULL;
RedisModuleString *spath =
(3 == argc ? argv[2] : RedisModule_CreateString(ctx, OBJECT_ROOT_PATH, 1));
if (PARSE_OK != NodeFromJSONPath(jt->root, spath, &jpn)) {
ReplyWithSearchPathError(ctx, jpn);
JSONPathNode_Free(jpn);
return REDISMODULE_ERR;
}
// make the type-specifc reply, or deal with path errors
if (E_OK == jpn->err) {
RedisModule_ReplyWithSimpleString(ctx, NodeTypeStr(NODETYPE(jpn->n)));
} else {
// reply with null if there are **any** non-existing elements along the path
RedisModule_ReplyWithNull(ctx);
}
JSONPathNode_Free(jpn);
return REDISMODULE_OK;
}
/**
* JSON.ARRLEN <key> [path]
* JSON.OBJLEN <key> [path]
* JSON.STRLEN <key> [path]
* Report the length of the JSON value at `path` in `key`.
*
* `path` defaults to root if not provided. If the `key` or `path` do not exist, null is returned.
*
* Reply: Integer, specifically the length of the value.
*/
int JSONLen_GenericCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
// check args
if ((argc < 2) || (argc > 3)) {
RedisModule_WrongArity(ctx);
return REDISMODULE_ERR;
}
RedisModule_AutoMemory(ctx);
// the actual command
const char *cmd = RedisModule_StringPtrLen(argv[0], NULL);
// key must be empty or a JSON type
RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[1], REDISMODULE_READ);
int type = RedisModule_KeyType(key);
if (REDISMODULE_KEYTYPE_EMPTY == type) {
RedisModule_ReplyWithNull(ctx);
return REDISMODULE_OK;
}
if (RedisModule_ModuleTypeGetType(key) != JSONType) {
RedisModule_ReplyWithError(ctx, REDISMODULE_ERRORMSG_WRONGTYPE);
return REDISMODULE_ERR;
}
// validate path
JSONType_t *jt = RedisModule_ModuleTypeGetValue(key);
JSONPathNode_t *jpn = NULL;
RedisModuleString *spath =
(3 == argc ? argv[2] : RedisModule_CreateString(ctx, OBJECT_ROOT_PATH, 1));
if (PARSE_OK != NodeFromJSONPath(jt->root, spath, &jpn)) {
ReplyWithSearchPathError(ctx, jpn);
goto error;
}
// deal with path errors
if (E_OK != jpn->err) {
ReplyWithPathError(ctx, jpn);
goto error;
}
// determine the type of target value based on command name
NodeType expected, actual = NODETYPE(jpn->n);
if (!strcasecmp("json.arrlen", cmd))
expected = N_ARRAY;
else if (!strcasecmp("json.objlen", cmd))
expected = N_DICT;
else // must be json.strlen
expected = N_STRING;
// reply with the length per type, or with an error if the wrong type is encountered
if (actual == expected) {
RedisModule_ReplyWithLongLong(ctx, Node_Length(jpn->n));
} else {
ReplyWithPathTypeError(ctx, expected, actual);
goto error;
}
JSONPathNode_Free(jpn);
return REDISMODULE_OK;
error:
JSONPathNode_Free(jpn);
return REDISMODULE_ERR;
}
/**
* JSON.OBJKEYS <key> [path]
* Return the keys in the object that's referenced by `path`.
*
* `path` defaults to root if not provided. If the object is empty, or either `key` or `path` do not
* exist then null is returned.
*
* Reply: Array, specifically the key names as bulk strings.
*/
int JSONObjKeys_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
// check args
if ((argc < 2) || (argc > 3)) {
RedisModule_WrongArity(ctx);
return REDISMODULE_ERR;
}
RedisModule_AutoMemory(ctx);
// key must be empty or a JSON type
RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[1], REDISMODULE_READ);
int type = RedisModule_KeyType(key);
if (REDISMODULE_KEYTYPE_EMPTY == type) {
RedisModule_ReplyWithNull(ctx);
return REDISMODULE_OK;
}
if (RedisModule_ModuleTypeGetType(key) != JSONType) {
RedisModule_ReplyWithError(ctx, REDISMODULE_ERRORMSG_WRONGTYPE);
return REDISMODULE_ERR;
}
// validate path
JSONType_t *jt = RedisModule_ModuleTypeGetValue(key);
JSONPathNode_t *jpn = NULL;
RedisModuleString *spath =
(3 == argc ? argv[2] : RedisModule_CreateString(ctx, OBJECT_ROOT_PATH, 1));
if (PARSE_OK != NodeFromJSONPath(jt->root, spath, &jpn)) {
ReplyWithSearchPathError(ctx, jpn);
goto error;
}
// deal with path errors
if (E_NOINDEX == jpn->err || E_NOKEY == jpn->err) {
// reply with null if there are **any** non-existing elements along the path
RedisModule_ReplyWithNull(ctx);
goto ok;
} else if (E_OK != jpn->err) {
ReplyWithPathError(ctx, jpn);
goto error;
}
// reply with the object's keys if it is a dictionary, error otherwise
if (N_DICT == NODETYPE(jpn->n)) {
int len = Node_Length(jpn->n);
RedisModule_ReplyWithArray(ctx, len);
for (int i = 0; i < len; i++) {
// TODO: need an iterator for keys in dict
const char *k = jpn->n->value.dictval.entries[i]->value.kvval.key;
RedisModule_ReplyWithStringBuffer(ctx, k, strlen(k));
}
} else {
ReplyWithPathTypeError(ctx, N_DICT, NODETYPE(jpn->n));
goto error;
}
ok:
JSONPathNode_Free(jpn);
return REDISMODULE_OK;
error:
JSONPathNode_Free(jpn);
return REDISMODULE_ERR;
}
/**
* JSON.SET <key> <path> <json> [NX|XX]
* Sets the JSON value at `path` in `key`
*
* For new Redis keys the `path` must be the root. For existing keys, when the entire `path` exists,
* the value that it contains is replaced with the `json` value.
*
* A key (with its respective value) is added to a JSON Object (in a Redis ReJSON data type key) if
* and only if it is the last child in the `path`. The optional subcommands modify this behavior for
* both new Redis ReJSON data type keys as well as JSON Object keys in them:
* `NX` - only set the key if it does not already exists
* `XX` - only set the key if it already exists
*
* Reply: Simple String `OK` if executed correctly, or Null Bulk if the specified `NX` or `XX`
* conditions were not met.
*/
int JSONSet_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
// check args
if ((argc < 4) || (argc > 5)) {
RedisModule_WrongArity(ctx);
return REDISMODULE_ERR;
}
RedisModule_AutoMemory(ctx);
// key must be empty or a JSON type
RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[1], REDISMODULE_READ | REDISMODULE_WRITE);
int type = RedisModule_KeyType(key);
if (REDISMODULE_KEYTYPE_EMPTY != type && RedisModule_ModuleTypeGetType(key) != JSONType) {
RedisModule_ReplyWithError(ctx, REDISMODULE_ERRORMSG_WRONGTYPE);
return REDISMODULE_ERR;
}
JSONPathNode_t *jpn = NULL;
Object *jo = NULL;
char *jerr = NULL;
// subcommand for key creation behavior modifiers NX and XX
int subnx = 0, subxx = 0;
if (argc > 4) {
const char *subcmd = RedisModule_StringPtrLen(argv[4], NULL);
if (!strcasecmp("nx", subcmd)) {
subnx = 1;
} else if (!strcasecmp("xx", subcmd)) {
// new keys can be created only if the XX flag is off
if (REDISMODULE_KEYTYPE_EMPTY == type) goto null;
subxx = 1;
} else {
RedisModule_ReplyWithError(ctx, RM_ERRORMSG_SYNTAX);
return REDISMODULE_ERR;
}
}
// JSON must be valid
size_t jsonlen;
const char *json = RedisModule_StringPtrLen(argv[3], &jsonlen);
if (!jsonlen) {
RedisModule_ReplyWithError(ctx, REJSON_ERROR_EMPTY_STRING);
return REDISMODULE_ERR;
}
// Create object from json
if (JSONOBJECT_OK != CreateNodeFromJSON(JSONCtx.joctx, json, jsonlen, &jo, &jerr)) {
if (jerr) {
RedisModule_ReplyWithError(ctx, jerr);
RedisModule_Free(jerr);
} else {
RM_LOG_WARNING(ctx, "%s", REJSON_ERROR_JSONOBJECT_ERROR);
RedisModule_ReplyWithError(ctx, REJSON_ERROR_JSONOBJECT_ERROR);
}
return REDISMODULE_ERR;
}
// initialize or get JSON type container
JSONType_t *jt = NULL;
if (REDISMODULE_KEYTYPE_EMPTY == type) {
jt = RedisModule_Calloc(1, sizeof(JSONType_t));
jt->root = jo;
} else {
jt = RedisModule_ModuleTypeGetValue(key);
}
/* Validate path against the existing object root, and pretend that the new object is the root
* if the key is empty. This will be caught immediately afterwards because new keys must be
* created at the root.
*/
if (PARSE_OK != NodeFromJSONPath(jt->root, argv[2], &jpn)) {
ReplyWithSearchPathError(ctx, jpn);
goto error;
}
int isRootPath = SearchPath_IsRootPath(&jpn->sp);
// handle an empty key
if (REDISMODULE_KEYTYPE_EMPTY == type) {
// new keys must be created at the root
if (E_OK != jpn->err || !isRootPath) {
RedisModule_ReplyWithError(ctx, REJSON_ERROR_NEW_NOT_ROOT);
goto error;
}
RedisModule_ModuleTypeSetValue(key, JSONType, jt);
goto ok;
}
// handle an existing key, first make sure there weren't any obvious path errors
if (E_OK != jpn->err && E_NOKEY != jpn->err) {
ReplyWithPathError(ctx, jpn);
goto error;
}
// verify that we're dealing with the last child in case of an object
if (E_NOKEY == jpn->err && jpn->errlevel != jpn->sp.len - 1) {
RedisModule_ReplyWithError(ctx, REJSON_ERROR_PATH_NONTERMINAL_KEY);
goto error;
}
// replace a value according to its container type
if (E_OK == jpn->err) {
NodeType ntp = NODETYPE(jpn->p);
// an existing value in the root or an object can be replaced only if the NX is off
if (subnx && (isRootPath || N_DICT == ntp)) {
goto null;
}
// other containers, i.e. arrays, do not sport the NX or XX behavioral modification agents
if (N_ARRAY == ntp && (subnx || subxx)) {
RedisModule_ReplyWithError(ctx, RM_ERRORMSG_SYNTAX);
goto error;
}
if (isRootPath) {
// replacing the root is easy
RedisModule_DeleteKey(key);
jt = RedisModule_Calloc(1, sizeof(JSONType_t));
jt->root = jo;
RedisModule_ModuleTypeSetValue(key, JSONType, jt);
} else if (N_DICT == NODETYPE(jpn->p)) {
if (OBJ_OK != Node_DictSet(jpn->p, jpn->sp.nodes[jpn->sp.len - 1].value.key, jo)) {
RM_LOG_WARNING(ctx, "%s", REJSON_ERROR_DICT_SET);
RedisModule_ReplyWithError(ctx, REJSON_ERROR_DICT_SET);
goto error;
}
} else { // must be an array
int index = jpn->sp.nodes[jpn->sp.len - 1].value.index;
if (index < 0) index = Node_Length(jpn->p) + index;
if (OBJ_OK != Node_ArraySet(jpn->p, index, jo)) {
RM_LOG_WARNING(ctx, "%s", REJSON_ERROR_ARRAY_SET);
RedisModule_ReplyWithError(ctx, REJSON_ERROR_ARRAY_SET);
goto error;
}
// unlike DictSet, ArraySet does not free so we need to call it explicitly
Node_Free(jpn->n);
}
} else { // must be E_NOKEY
// new keys in the dictionary can be created only if the XX flag is off
if (subxx) {
goto null;
}
if (OBJ_OK != Node_DictSet(jpn->p, jpn->sp.nodes[jpn->sp.len - 1].value.key, jo)) {
RM_LOG_WARNING(ctx, "%s", REJSON_ERROR_DICT_SET);
RedisModule_ReplyWithError(ctx, REJSON_ERROR_DICT_SET);
goto error;
}
}
ok:
maybeClearPathCache(jt, jpn);
RedisModule_ReplyWithSimpleString(ctx, "OK");
JSONPathNode_Free(jpn);
RedisModule_ReplicateVerbatim(ctx);
return REDISMODULE_OK;
null:
RedisModule_ReplyWithNull(ctx);
JSONPathNode_Free(jpn);
if (jo) Node_Free(jo);
return REDISMODULE_OK;
error:
JSONPathNode_Free(jpn);
if (jt && REDISMODULE_KEYTYPE_EMPTY == type) {
RedisModule_Free(jt);
}
if (jo) Node_Free(jo);
return REDISMODULE_ERR;
}
static void maybeClearPathCache(JSONType_t *jt, const JSONPathNode_t *pn) {
if (!jt->lruEntries) {
return;
}
const char *pathStr = pn->spath;
size_t pathLen = pn->spathlen;
if (pn->sp.hasLeadingDot) {
pathStr++;
pathLen--;
}
if (pathLen == 0) {
LruCache_ClearKey(REJSON_LRUCACHE_GLOBAL, jt);
} else {
LruCache_ClearValues(REJSON_LRUCACHE_GLOBAL, jt, pathStr, pathLen);
}
}
static sds getSerializedJson(JSONType_t *jt, const JSONPathNode_t *pathInfo,
const JSONSerializeOpt *opts, int *wasFound, sds *target) {
// printf("Requesting value for path %.*s\n", (int)pathLen, path);
// Normalize the path. If the original path begins with a dot, strip it
const char *pathStr = pathInfo->spath;
size_t pathLen = pathInfo->spathlen;
int shouldCache = 1;
sds ret = NULL;
if (pathInfo->sp.hasLeadingDot) {
pathStr++;
pathLen--;
}
if (pathInfo->n) {
switch (pathInfo->n->type) {
// Don't store trivial types in the cache - i.e. those which aren't
// costly to serialize.
case N_NULL:
case N_BOOLEAN:
case N_INTEGER:
case N_NUMBER:
shouldCache = 0;
break;
default:
shouldCache = 1;
break;
}
} else {
shouldCache = 0;
}
if (shouldCache) {
ret = LruCache_GetValue(REJSON_LRUCACHE_GLOBAL, jt, pathStr, pathLen);
}
if (ret) {
*wasFound = 1;
if (target) {
*target = sdscatsds(*target, ret);
}
return ret;
}
// Otherwise, serialize
if (target) {
ret = *target;
} else {
ret = sdsempty();
}
SerializeNodeToJSON(pathInfo->n, opts, &ret);
if (shouldCache) {
LruCache_AddValue(REJSON_LRUCACHE_GLOBAL, jt, pathStr, pathLen, ret, sdslen(ret));
}
*wasFound = 0;
if (target) {
*target = ret;
}
return ret;
}
static int isCachableOptions(const JSONSerializeOpt *opts) {
return (!opts->indentstr || *opts->indentstr == 0) &&
(!opts->newlinestr || *opts->newlinestr == 0) &&
(!opts->spacestr || *opts->spacestr) == 0 && (opts->noescape == 0);
}
static void sendSingleResponse(RedisModuleCtx *ctx, JSONType_t *jt, const JSONPathNode_t *pn,
const JSONSerializeOpt *options) {
sds json = NULL;
if (!isCachableOptions(options)) {
json = sdsempty();
SerializeNodeToJSON(pn->n, options, &json);
RedisModule_ReplyWithStringBuffer(ctx, json, sdslen(json));
sdsfree(json);
return;
}
int isFromCache = 0;
json = getSerializedJson(jt, pn, options, &isFromCache, NULL);
// Send the response now
RedisModule_ReplyWithStringBuffer(ctx, json, sdslen(json));
if (!isFromCache) {
sdsfree(json);
}
}
static void sendMultiResponse(RedisModuleCtx *ctx, JSONType_t *jt, JSONPathNode_t **pns,
size_t npns, const JSONSerializeOpt *options) {
sds json = NULL;
if (!isCachableOptions(options)) {
// Use legacy behavior
json = sdsempty();
Node *objReply = NewDictNode(npns);
for (int i = 0; i < npns; i++) {
// add the path to the reply only if it isn't there already
Node *target;
int ret = Node_DictGet(objReply, pns[i]->spath, &target);
if (OBJ_ERR == ret) {
Node_DictSet(objReply, pns[i]->spath, pns[i]->n);
}
}
SerializeNodeToJSON(objReply, options, &json);
RedisModule_ReplyWithStringBuffer(ctx, json, sdslen(json));
sdsfree(json);
// avoid removing the actual data by resetting the reply dict
// TODO: need a non-freeing Del
for (int i = 0; i < objReply->value.dictval.len; i++) {
objReply->value.dictval.entries[i]->value.kvval.val = NULL;
}
Node_Free(objReply);
return;
}
json = sdsempty();
json = sdscat(json, "{");
for (int i = 0; i < npns; i++) {
json = JSONSerialize_String(json, pns[i]->spath, pns[i]->spathlen, 1);
json = sdscatlen(json, ":", 1);
// Append to the buffer
int dummy;
getSerializedJson(jt, pns[i], options, &dummy, &json);
if (i < npns - 1) {
json = sdscat(json, ",");
}
}
json = sdscat(json, "}");
RedisModule_ReplyWithStringBuffer(ctx, json, sdslen(json));
sdsfree(json);
}
/**
* JSON.GET <key> [INDENT indentation-string] [NEWLINE newline-string] [SPACE space-string]
* [path ...]
* Return the value at `path` in JSON serialized form.
*
* This command accepts multiple `path`s, and defaults to the value's root when none are given.
*
* The following subcommands change the reply's and are all set to the empty string by default:
* - `INDENT` sets the indentation string for nested levels
* - `NEWLINE` sets the string that's printed at the end of each line
* - `SPACE` sets the string that's put between a key and a value
* - `NOESCAPE` Don't escape any JSON characters.
*
* Reply: Bulk String, specifically the JSON serialization.
* The reply's structure depends on the on the number of paths. A single path results in the
* value being itself is returned, whereas multiple paths are returned as a JSON object in which
* each path is a key.
*/
int JSONGet_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if ((argc < 2)) {
RedisModule_WrongArity(ctx);
return REDISMODULE_ERR;
}
RedisModule_AutoMemory(ctx);
// key must be empty (reply with null) or an object type
RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[1], REDISMODULE_READ);
int type = RedisModule_KeyType(key);
if (REDISMODULE_KEYTYPE_EMPTY == type) {
RedisModule_ReplyWithNull(ctx);
return REDISMODULE_OK;
} else if (RedisModule_ModuleTypeGetType(key) != JSONType) {
RedisModule_ReplyWithError(ctx, REDISMODULE_ERRORMSG_WRONGTYPE);
return REDISMODULE_ERR;
}
// check for optional arguments
int pathpos = 2;
JSONSerializeOpt jsopt = {0};
if (pathpos < argc) {
RMUtil_ParseArgsAfter("indent", argv, argc, "c", &jsopt.indentstr);
if (jsopt.indentstr) {
pathpos += 2;
} else {
jsopt.indentstr = "";
}
}
if (pathpos < argc) {
RMUtil_ParseArgsAfter("newline", argv, argc, "c", &jsopt.newlinestr);
if (jsopt.newlinestr) {
pathpos += 2;
} else {
jsopt.newlinestr = "";
}
}
if (pathpos < argc) {
RMUtil_ParseArgsAfter("space", argv, argc, "c", &jsopt.spacestr);
if (jsopt.spacestr) {
pathpos += 2;
} else {
jsopt.spacestr = "";
}
}
if (RMUtil_ArgExists("noescape", argv, argc, 2)) {
jsopt.noescape = 1;
pathpos++;
}
// validate paths, if none provided default to root
JSONType_t *jt = RedisModule_ModuleTypeGetValue(key);
int npaths = argc - pathpos;
int jpnslen = 0;
JSONPathNode_t **jpns = RedisModule_Calloc(MAX(npaths, 1), sizeof(JSONPathNode_t *));
if (!npaths) { // default to root
NodeFromJSONPath(jt->root, RedisModule_CreateString(ctx, OBJECT_ROOT_PATH, 1), &jpns[0]);
jpnslen = 1;
} else {
while (jpnslen < npaths) {
// validate path correctness
if (PARSE_OK != NodeFromJSONPath(jt->root, argv[pathpos + jpnslen], &jpns[jpnslen])) {
ReplyWithSearchPathError(ctx, jpns[jpnslen]);
jpnslen++;
goto error;
}
// deal with path errors
if (E_OK != jpns[jpnslen]->err) {
ReplyWithPathError(ctx, jpns[jpnslen]);
jpnslen++;
goto error;
}
jpnslen++;
} // while (jpnslen < npaths)
}
// return the single path's JSON value, or wrap all paths-values as an object
if (1 == jpnslen) {
sendSingleResponse(ctx, jt, jpns[0], &jsopt);
} else {
sendMultiResponse(ctx, jt, jpns, jpnslen, &jsopt);
}
// check whether serialization had succeeded
// if (!sdslen(json)) {
// RM_LOG_WARNING(ctx, "%s", REJSON_ERROR_SERIALIZE);
// RedisModule_ReplyWithError(ctx, REJSON_ERROR_SERIALIZE);
// goto error;
// }
for (int i = 0; i < jpnslen; i++) {
JSONPathNode_Free(jpns[i]);
}
RedisModule_Free(jpns);
return REDISMODULE_OK;
error:
for (int i = 0; i < jpnslen; i++) {
JSONPathNode_Free(jpns[i]);
}
RedisModule_Free(jpns);
return REDISMODULE_ERR;
}
/**
* JSON.MGET <key> [<key> ...] <path>
* Returns the values at `path` from multiple `key`s. Non-existing keys and non-existing paths
* are reported as null. Reply: Array of Bulk Strings, specifically the JSON serialization of
* the value at each key's path.
*/
int JSONMGet_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if ((argc < 2)) {
RedisModule_WrongArity(ctx);
return REDISMODULE_ERR;
}
if (RedisModule_IsKeysPositionRequest(ctx)) {
for (int i = 1; i < argc - 1; i++) RedisModule_KeyAtPos(ctx, i);
return REDISMODULE_OK;
}
RedisModule_AutoMemory(ctx);
// validate search path
size_t spathlen;
const char *spath = RedisModule_StringPtrLen(argv[argc - 1], &spathlen);
JSONPathNode_t jpn = {0};
JSONSearchPathError_t jsperr = {0};
jpn.sp = NewSearchPath(0);
if (PARSE_ERR == ParseJSONPath(spath, spathlen, &jpn.sp, &jsperr)) {
jpn.sperrmsg = jsperr.errmsg;
jpn.sperroffset = jsperr.offset;
ReplyWithSearchPathError(ctx, &jpn);
goto error;
}
// iterate keys
RedisModule_ReplyWithArray(ctx, argc - 2);
int isRootPath = SearchPath_IsRootPath(&jpn.sp);
JSONSerializeOpt jsopt = {0};
for (int i = 1; i < argc - 1; i++) {
RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[i], REDISMODULE_READ);