-
Notifications
You must be signed in to change notification settings - Fork 498
/
scripting.tcl
2427 lines (2127 loc) · 87.3 KB
/
scripting.tcl
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
foreach is_eval {0 1} {
foreach script_compatibility_api {server redis} {
# We run the tests using both the server APIs, e.g. server.call(), and redis APIs, e.g. redis.call(),
# in order to ensure compatibility.
if {$script_compatibility_api eq "server"} {
proc replace_script_redis_api_with_server {args} {
set new_string [regsub -all {redis\.} [lindex $args 0] {server.}]
return lreplace $args 0 0 $new_string
}
proc get_script_api_name {} {
return "server"
}
} else {
proc replace_script_redis_api_with_server {args} {
return {*}$args
}
proc get_script_api_name {} {
return "redis"
}
}
if {$is_eval == 1} {
proc run_script {args} {
set args [replace_script_redis_api_with_server $args]
r eval {*}$args
}
proc run_script_ro {args} {
set args [replace_script_redis_api_with_server $args]
r eval_ro {*}$args
}
proc run_script_on_connection {args} {
set args [replace_script_redis_api_with_server $args]
[lindex $args 0] eval {*}[lrange $args 1 end]
}
proc kill_script {args} {
r script kill
}
} else {
proc run_script {args} {
set args [replace_script_redis_api_with_server $args]
r function load replace [format "#!lua name=test\n%s.register_function('test', function(KEYS, ARGV)\n %s \nend)" [get_script_api_name] [lindex $args 0]]
if {[r readingraw] eq 1} {
# read name
assert_equal {test} [r read]
}
r fcall test {*}[lrange $args 1 end]
}
proc run_script_ro {args} {
set args [replace_script_redis_api_with_server $args]
r function load replace [format "#!lua name=test\n%s.register_function{function_name='test', callback=function(KEYS, ARGV)\n %s \nend, flags={'no-writes'}}" [get_script_api_name] [lindex $args 0]]
if {[r readingraw] eq 1} {
# read name
assert_equal {test} [r read]
}
r fcall_ro test {*}[lrange $args 1 end]
}
proc run_script_on_connection {args} {
set args [replace_script_redis_api_with_server $args]
set rd [lindex $args 0]
$rd function load replace [format "#!lua name=test\n%s.register_function('test', function(KEYS, ARGV)\n %s \nend)" [get_script_api_name] [lindex $args 1]]
# read name
$rd read
$rd fcall test {*}[lrange $args 2 end]
}
proc kill_script {args} {
r function kill
}
}
start_server {tags {"scripting"}} {
if {$is_eval eq 1 && $script_compatibility_api == "redis"} {
test {Script - disallow write on OOM} {
r config set maxmemory 1
catch {[r eval "redis.call('set', 'x', 1)" 0]} e
assert_match {*command not allowed when used memory*} $e
r config set maxmemory 0
} {OK} {needs:config-maxmemory}
} ;# is_eval
test {EVAL - Does Lua interpreter replies to our requests?} {
run_script {return 'hello'} 0
} {hello}
test {EVAL - Return _G} {
run_script {return _G} 0
} {}
test {EVAL - Return table with a metatable that raise error} {
run_script {local a = {}; setmetatable(a,{__index=function() foo() end}) return a} 0
} {}
test {EVAL - Return table with a metatable that call server} {
run_script {local a = {}; setmetatable(a,{__index=function() redis.call('set', 'x', '1') end}) return a} 1 x
# make sure x was not set
r get x
} {}
test {EVAL - Lua integer -> Redis protocol type conversion} {
run_script {return 100.5} 0
} {100}
test {EVAL - Lua string -> Redis protocol type conversion} {
run_script {return 'hello world'} 0
} {hello world}
test {EVAL - Lua true boolean -> Redis protocol type conversion} {
run_script {return true} 0
} {1}
test {EVAL - Lua false boolean -> Redis protocol type conversion} {
run_script {return false} 0
} {}
test {EVAL - Lua status code reply -> Redis protocol type conversion} {
run_script {return {ok='fine'}} 0
} {fine}
test {EVAL - Lua error reply -> Redis protocol type conversion} {
catch {
run_script {return {err='ERR this is an error'}} 0
} e
set _ $e
} {ERR this is an error}
test {EVAL - Lua table -> Redis protocol type conversion} {
run_script {return {1,2,3,'ciao',{1,2}}} 0
} {1 2 3 ciao {1 2}}
test {EVAL - Are the KEYS and ARGV arrays populated correctly?} {
run_script {return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}} 2 a{t} b{t} c{t} d{t}
} {a{t} b{t} c{t} d{t}}
test {EVAL - is Lua able to call Redis API?} {
r set mykey myval
run_script {return redis.call('get',KEYS[1])} 1 mykey
} {myval}
if {$is_eval eq 1 && $script_compatibility_api == "redis"} {
# eval sha is only relevant for is_eval Lua
test {EVALSHA - Can we call a SHA1 if already defined?} {
r evalsha fd758d1589d044dd850a6f05d52f2eefd27f033f 1 mykey
} {myval}
test {EVALSHA_RO - Can we call a SHA1 if already defined?} {
r evalsha_ro fd758d1589d044dd850a6f05d52f2eefd27f033f 1 mykey
} {myval}
test {EVALSHA - Can we call a SHA1 in uppercase?} {
r evalsha FD758D1589D044DD850A6F05D52F2EEFD27F033F 1 mykey
} {myval}
test {EVALSHA - Do we get an error on invalid SHA1?} {
catch {r evalsha NotValidShaSUM 0} e
set _ $e
} {NOSCRIPT*}
test {EVALSHA - Do we get an error on non defined SHA1?} {
catch {r evalsha ffd632c7d33e571e9f24556ebed26c3479a87130 0} e
set _ $e
} {NOSCRIPT*}
} ;# is_eval
test {EVAL - Redis integer -> Lua type conversion} {
r set x 0
run_script {
local foo = redis.pcall('incr',KEYS[1])
return {type(foo),foo}
} 1 x
} {number 1}
test {EVAL - Lua number -> Redis integer conversion} {
r del hash
run_script {
local foo = redis.pcall('hincrby','hash','field',200000000)
return {type(foo),foo}
} 0
} {number 200000000}
test {EVAL - Redis bulk -> Lua type conversion} {
r set mykey myval
run_script {
local foo = redis.pcall('get',KEYS[1])
return {type(foo),foo}
} 1 mykey
} {string myval}
test {EVAL - Redis multi bulk -> Lua type conversion} {
r del mylist
r rpush mylist a
r rpush mylist b
r rpush mylist c
run_script {
local foo = redis.pcall('lrange',KEYS[1],0,-1)
return {type(foo),foo[1],foo[2],foo[3],# foo}
} 1 mylist
} {table a b c 3}
test {EVAL - Redis status reply -> Lua type conversion} {
run_script {
local foo = redis.pcall('set',KEYS[1],'myval')
return {type(foo),foo['ok']}
} 1 mykey
} {table OK}
test {EVAL - Redis error reply -> Lua type conversion} {
r set mykey myval
run_script {
local foo = redis.pcall('incr',KEYS[1])
return {type(foo),foo['err']}
} 1 mykey
} {table {ERR value is not an integer or out of range}}
test {EVAL - Redis nil bulk reply -> Lua type conversion} {
r del mykey
run_script {
local foo = redis.pcall('get',KEYS[1])
return {type(foo),foo == false}
} 1 mykey
} {boolean 1}
test {EVAL - Is the Lua client using the currently selected DB?} {
r set mykey "this is DB 9"
r select 10
r set mykey "this is DB 10"
run_script {return redis.pcall('get',KEYS[1])} 1 mykey
} {this is DB 10} {singledb:skip}
test {EVAL - SELECT inside Lua should not affect the caller} {
# here we DB 10 is selected
r set mykey "original value"
run_script {return redis.pcall('select','9')} 0
set res [r get mykey]
r select 9
set res
} {original value} {singledb:skip}
if 0 {
test {EVAL - Script can't run more than configured time limit} {
r config set lua-time-limit 1
catch {
run_script {
local i = 0
while true do i=i+1 end
} 0
} e
set _ $e
} {*execution time*}
}
test {EVAL - Scripts do not block on blpop command} {
r lpush l 1
r lpop l
run_script {return redis.pcall('blpop','l',0)} 1 l
} {}
test {EVAL - Scripts do not block on brpop command} {
r lpush l 1
r lpop l
run_script {return redis.pcall('brpop','l',0)} 1 l
} {}
test {EVAL - Scripts do not block on brpoplpush command} {
r lpush empty_list1{t} 1
r lpop empty_list1{t}
run_script {return redis.pcall('brpoplpush','empty_list1{t}', 'empty_list2{t}',0)} 2 empty_list1{t} empty_list2{t}
} {}
test {EVAL - Scripts do not block on blmove command} {
r lpush empty_list1{t} 1
r lpop empty_list1{t}
run_script {return redis.pcall('blmove','empty_list1{t}', 'empty_list2{t}', 'LEFT', 'LEFT', 0)} 2 empty_list1{t} empty_list2{t}
} {}
test {EVAL - Scripts do not block on bzpopmin command} {
r zadd empty_zset 10 foo
r zmpop 1 empty_zset MIN
run_script {return redis.pcall('bzpopmin','empty_zset', 0)} 1 empty_zset
} {}
test {EVAL - Scripts do not block on bzpopmax command} {
r zadd empty_zset 10 foo
r zmpop 1 empty_zset MIN
run_script {return redis.pcall('bzpopmax','empty_zset', 0)} 1 empty_zset
} {}
test {EVAL - Scripts do not block on wait} {
run_script {return redis.pcall('wait','1','0')} 0
} {0}
test {EVAL - Scripts do not block on waitaof} {
run_script {return redis.pcall('waitaof','0','1','0')} 0
} {0 0}
test {EVAL - Scripts do not block on XREAD with BLOCK option} {
r del s
r xgroup create s g $ MKSTREAM
set res [run_script {return redis.pcall('xread','STREAMS','s','$')} 1 s]
assert {$res eq {}}
run_script {return redis.pcall('xread','BLOCK',0,'STREAMS','s','$')} 1 s
} {}
test {EVAL - Scripts do not block on XREADGROUP with BLOCK option} {
set res [run_script {return redis.pcall('xreadgroup','group','g','c','STREAMS','s','>')} 1 s]
assert {$res eq {}}
run_script {return redis.pcall('xreadgroup','group','g','c','BLOCK',0,'STREAMS','s','>')} 1 s
} {}
test {EVAL - Scripts do not block on XREAD with BLOCK option -- non empty stream} {
r XADD s * a 1
set res [run_script {return redis.pcall('xread','BLOCK',0,'STREAMS','s','$')} 1 s]
assert {$res eq {}}
set res [run_script {return redis.pcall('xread','BLOCK',0,'STREAMS','s','0-0')} 1 s]
assert {[lrange [lindex $res 0 1 0 1] 0 1] eq {a 1}}
}
test {EVAL - Scripts do not block on XREADGROUP with BLOCK option -- non empty stream} {
r XADD s * b 2
set res [
run_script {return redis.pcall('xreadgroup','group','g','c','BLOCK',0,'STREAMS','s','>')} 1 s
]
assert {[llength [lindex $res 0 1]] == 2}
lindex $res 0 1 0 1
} {a 1}
test {EVAL - Scripts can run non-deterministic commands} {
set e {}
catch {
run_script {redis.pcall('randomkey'); return redis.pcall('set','x','ciao')} 1 x
} e
set e
} {*OK*}
test {EVAL - No arguments to redis.call/pcall is considered an error} {
set e {}
catch {run_script {return redis.call()} 0} e
set e
} {*one argument*}
test {EVAL - redis.call variant raises a Lua error on Redis cmd error (1)} {
set e {}
catch {
run_script "redis.call('nosuchcommand')" 0
} e
set e
} {*Unknown Redis*}
test {EVAL - redis.call variant raises a Lua error on Redis cmd error (1)} {
set e {}
catch {
run_script "redis.call('get','a','b','c')" 0
} e
set e
} {*number of args*}
test {EVAL - redis.call variant raises a Lua error on Redis cmd error (1)} {
set e {}
r set foo bar
catch {
run_script {redis.call('lpush',KEYS[1],'val')} 1 foo
} e
set e
} {*against a key*}
test {EVAL - JSON string encoding a string larger than 2GB} {
run_script {
local s = string.rep("a", 1024 * 1024 * 1024)
return #cjson.encode(s..s..s)
} 0
} {3221225474} {large-memory} ;# length includes two double quotes at both ends
test {EVAL - JSON numeric decoding} {
# We must return the table as a string because otherwise
# the server converts floats to ints and we get 0 and 1023 instead
# of 0.0003 and 1023.2 as the parsed output.
run_script {return
table.concat(
cjson.decode(
"[0.0, -5e3, -1, 0.3e-3, 1023.2, 0e10]"), " ")
} 0
} {0 -5000 -1 0.0003 1023.2 0}
test {EVAL - JSON string decoding} {
run_script {local decoded = cjson.decode('{"keya": "a", "keyb": "b"}')
return {decoded.keya, decoded.keyb}
} 0
} {a b}
test {EVAL - JSON smoke test} {
run_script {
local some_map = {
s1="Some string",
n1=100,
a1={"Some","String","Array"},
nil1=nil,
b1=true,
b2=false}
local encoded = cjson.encode(some_map)
local decoded = cjson.decode(encoded)
assert(table.concat(some_map) == table.concat(decoded))
cjson.encode_keep_buffer(false)
encoded = cjson.encode(some_map)
decoded = cjson.decode(encoded)
assert(table.concat(some_map) == table.concat(decoded))
-- Table with numeric keys
local table1 = {one="one", [1]="one"}
encoded = cjson.encode(table1)
decoded = cjson.decode(encoded)
assert(decoded["one"] == table1["one"])
assert(decoded["1"] == table1[1])
-- Array
local array1 = {[1]="one", [2]="two"}
encoded = cjson.encode(array1)
decoded = cjson.decode(encoded)
assert(table.concat(array1) == table.concat(decoded))
-- Invalid keys
local invalid_map = {}
invalid_map[false] = "false"
local ok, encoded = pcall(cjson.encode, invalid_map)
assert(ok == false)
-- Max depth
cjson.encode_max_depth(1)
ok, encoded = pcall(cjson.encode, some_map)
assert(ok == false)
cjson.decode_max_depth(1)
ok, decoded = pcall(cjson.decode, '{"obj": {"array": [1,2,3,4]}}')
assert(ok == false)
-- Invalid numbers
ok, encoded = pcall(cjson.encode, {num1=0/0})
assert(ok == false)
cjson.encode_invalid_numbers(true)
ok, encoded = pcall(cjson.encode, {num1=0/0})
assert(ok == true)
-- Restore defaults
cjson.decode_max_depth(1000)
cjson.encode_max_depth(1000)
cjson.encode_invalid_numbers(false)
} 0
}
test {EVAL - cmsgpack can pack double?} {
run_script {local encoded = cmsgpack.pack(0.1)
local h = ""
for i = 1, #encoded do
h = h .. string.format("%02x",string.byte(encoded,i))
end
return h
} 0
} {cb3fb999999999999a}
test {EVAL - cmsgpack can pack negative int64?} {
run_script {local encoded = cmsgpack.pack(-1099511627776)
local h = ""
for i = 1, #encoded do
h = h .. string.format("%02x",string.byte(encoded,i))
end
return h
} 0
} {d3ffffff0000000000}
test {EVAL - cmsgpack pack/unpack smoke test} {
run_script {
local str_lt_32 = string.rep("x", 30)
local str_lt_255 = string.rep("x", 250)
local str_lt_65535 = string.rep("x", 65530)
local str_long = string.rep("x", 100000)
local array_lt_15 = {1, 2, 3, 4, 5}
local array_lt_65535 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}
local array_big = {}
for i=1, 100000 do
array_big[i] = i
end
local map_lt_15 = {a=1, b=2}
local map_big = {}
for i=1, 100000 do
map_big[tostring(i)] = i
end
local some_map = {
s1=str_lt_32,
s2=str_lt_255,
s3=str_lt_65535,
s4=str_long,
d1=0.1,
i1=1,
i2=250,
i3=65530,
i4=100000,
i5=2^40,
i6=-1,
i7=-120,
i8=-32000,
i9=-100000,
i10=-3147483648,
a1=array_lt_15,
a2=array_lt_65535,
a3=array_big,
m1=map_lt_15,
m2=map_big,
b1=false,
b2=true,
n=nil
}
local encoded = cmsgpack.pack(some_map)
local decoded = cmsgpack.unpack(encoded)
assert(table.concat(some_map) == table.concat(decoded))
local offset, decoded_one = cmsgpack.unpack_one(encoded, 0)
assert(table.concat(some_map) == table.concat(decoded_one))
assert(offset == -1)
local encoded_multiple = cmsgpack.pack(str_lt_32, str_lt_255, str_lt_65535, str_long)
local offset, obj = cmsgpack.unpack_limit(encoded_multiple, 1, 0)
assert(obj == str_lt_32)
offset, obj = cmsgpack.unpack_limit(encoded_multiple, 1, offset)
assert(obj == str_lt_255)
offset, obj = cmsgpack.unpack_limit(encoded_multiple, 1, offset)
assert(obj == str_lt_65535)
offset, obj = cmsgpack.unpack_limit(encoded_multiple, 1, offset)
assert(obj == str_long)
assert(offset == -1)
} 0
}
test {EVAL - cmsgpack can pack and unpack circular references?} {
run_script {local a = {x=nil,y=5}
local b = {x=a}
a['x'] = b
local encoded = cmsgpack.pack(a)
local h = ""
-- cmsgpack encodes to a depth of 16, but can't encode
-- references, so the encoded object has a deep copy recursive
-- depth of 16.
for i = 1, #encoded do
h = h .. string.format("%02x",string.byte(encoded,i))
end
-- when unpacked, re.x.x != re because the unpack creates
-- individual tables down to a depth of 16.
-- (that's why the encoded output is so large)
local re = cmsgpack.unpack(encoded)
assert(re)
assert(re.x)
assert(re.x.x.y == re.y)
assert(re.x.x.x.x.y == re.y)
assert(re.x.x.x.x.x.x.y == re.y)
assert(re.x.x.x.x.x.x.x.x.x.x.y == re.y)
-- maximum working depth:
assert(re.x.x.x.x.x.x.x.x.x.x.x.x.x.x.y == re.y)
-- now the last x would be b above and has no y
assert(re.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x)
-- so, the final x.x is at the depth limit and was assigned nil
assert(re.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x == nil)
return {h, re.x.x.x.x.x.x.x.x.y == re.y, re.y == 5}
} 0
} {82a17905a17881a17882a17905a17881a17882a17905a17881a17882a17905a17881a17882a17905a17881a17882a17905a17881a17882a17905a17881a17882a17905a17881a178c0 1 1}
test {EVAL - Numerical sanity check from bitop} {
run_script {assert(0x7fffffff == 2147483647, "broken hex literals");
assert(0xffffffff == -1 or 0xffffffff == 2^32-1,
"broken hex literals");
assert(tostring(-1) == "-1", "broken tostring()");
assert(tostring(0xffffffff) == "-1" or
tostring(0xffffffff) == "4294967295",
"broken tostring()")
} 0
} {}
test {EVAL - Verify minimal bitop functionality} {
run_script {assert(bit.tobit(1) == 1);
assert(bit.band(1) == 1);
assert(bit.bxor(1,2) == 3);
assert(bit.bor(1,2,4,8,16,32,64,128) == 255)
} 0
} {}
test {EVAL - Able to parse trailing comments} {
run_script {return 'hello' --trailing comment} 0
} {hello}
test {EVAL_RO - Successful case} {
r set foo bar
assert_equal bar [run_script_ro {return redis.call('get', KEYS[1]);} 1 foo]
}
test {EVAL_RO - Cannot run write commands} {
r set foo bar
catch {run_script_ro {redis.call('del', KEYS[1]);} 1 foo} e
set e
} {ERR Write commands are not allowed from read-only scripts*}
if {$is_eval eq 1 && $script_compatibility_api == "redis"} {
# script command is only relevant for is_eval Lua
test {SCRIPTING FLUSH - is able to clear the scripts cache?} {
r set mykey myval
r script load {return redis.call('get',KEYS[1])}
set v [r evalsha fd758d1589d044dd850a6f05d52f2eefd27f033f 1 mykey]
assert_equal $v myval
r script flush
assert_error {NOSCRIPT*} {r evalsha fd758d1589d044dd850a6f05d52f2eefd27f033f 1 mykey}
r eval {return redis.call('get',KEYS[1])} 1 mykey
set v [r evalsha fd758d1589d044dd850a6f05d52f2eefd27f033f 1 mykey]
assert_equal $v myval
r script flush
assert_error {NOSCRIPT*} {r evalsha fd758d1589d044dd850a6f05d52f2eefd27f033f 1 mykey}
}
test {SCRIPTING FLUSH ASYNC} {
for {set j 0} {$j < 100} {incr j} {
r script load "return $j"
}
assert { [string match "*number_of_cached_scripts:100*" [r info Memory]] }
r script flush async
assert { [string match "*number_of_cached_scripts:0*" [r info Memory]] }
}
test {SCRIPT EXISTS - can detect already defined scripts?} {
r eval "return 1+1" 0
r script exists a27e7e8a43702b7046d4f6a7ccf5b60cef6b9bd9 a27e7e8a43702b7046d4f6a7ccf5b60cef6b9bda
} {1 0}
test {SCRIPT LOAD - is able to register scripts in the scripting cache} {
list \
[r script load "return 'loaded'"] \
[r evalsha b534286061d4b9e4026607613b95c06c06015ae8 0]
} {b534286061d4b9e4026607613b95c06c06015ae8 loaded}
test "SORT is normally not alpha re-ordered for the scripting engine" {
r del myset
r sadd myset 1 2 3 4 10
r eval {return redis.call('sort',KEYS[1],'desc')} 1 myset
} {10 4 3 2 1} {cluster:skip}
test "SORT BY <constant> output gets ordered for scripting" {
r del myset
r sadd myset a b c d e f g h i l m n o p q r s t u v z aa aaa azz
r eval {return redis.call('sort',KEYS[1],'by','_')} 1 myset
} {a aa aaa azz b c d e f g h i l m n o p q r s t u v z} {cluster:skip}
test "SORT BY <constant> with GET gets ordered for scripting" {
r del myset
r sadd myset a b c
r eval {return redis.call('sort',KEYS[1],'by','_','get','#','get','_:*')} 1 myset
} {a {} b {} c {}} {cluster:skip}
} ;# is_eval
test "redis.sha1hex() implementation" {
list [run_script {return redis.sha1hex('')} 0] \
[run_script {return redis.sha1hex('Pizza & Mandolino')} 0]
} {da39a3ee5e6b4b0d3255bfef95601890afd80709 74822d82031af7493c20eefa13bd07ec4fada82f}
test "Measures elapsed time os.clock()" {
set escaped [run_script {
local start = os.clock()
while os.clock() - start < 1 do end
return {double = os.clock() - start}
} 0]
assert_morethan_equal $escaped 1 ;# 1 second
}
test "Prohibit dangerous lua methods in sandbox" {
assert_equal "" [run_script {
local allowed_methods = {"clock"}
-- Find a value from a tuple and return the position.
local indexOf = function(tuple, value)
for i, v in ipairs(tuple) do
if v == value then return i end
end
return nil
end
-- Check for disallowed methods and verify all allowed methods exist.
-- If an allowed method is found, it's removed from 'allowed_methods'.
-- If 'allowed_methods' is empty at the end, all allowed methods were found.
for key, value in pairs(os) do
local index = indexOf(allowed_methods, key)
if index == nil or type(value) ~= "function" then
return "Disallowed "..type(value)..":"..key
end
table.remove(allowed_methods, index)
end
if #allowed_methods ~= 0 then
return "Expected method not found: "..table.concat(allowed_methods, ",")
end
return ""
} 0]
}
test "Verify execution of prohibit dangerous Lua methods will fail" {
assert_error {ERR *attempt to call field 'execute'*} {run_script {os.execute()} 0}
assert_error {ERR *attempt to call field 'exit'*} {run_script {os.exit()} 0}
assert_error {ERR *attempt to call field 'getenv'*} {run_script {os.getenv()} 0}
assert_error {ERR *attempt to call field 'remove'*} {run_script {os.remove()} 0}
assert_error {ERR *attempt to call field 'rename'*} {run_script {os.rename()} 0}
assert_error {ERR *attempt to call field 'setlocale'*} {run_script {os.setlocale()} 0}
assert_error {ERR *attempt to call field 'tmpname'*} {run_script {os.tmpname()} 0}
}
test {Globals protection reading an undeclared global variable} {
catch {run_script {return a} 0} e
set e
} {ERR *attempted to access * global*}
test {Globals protection setting an undeclared global*} {
catch {run_script {a=10} 0} e
set e
} {ERR *Attempt to modify a readonly table*}
test {Test an example script DECR_IF_GT} {
set decr_if_gt {
local current
current = redis.call('get',KEYS[1])
if not current then return nil end
if current > ARGV[1] then
return redis.call('decr',KEYS[1])
else
return redis.call('get',KEYS[1])
end
}
r set foo 5
set res {}
lappend res [run_script $decr_if_gt 1 foo 2]
lappend res [run_script $decr_if_gt 1 foo 2]
lappend res [run_script $decr_if_gt 1 foo 2]
lappend res [run_script $decr_if_gt 1 foo 2]
lappend res [run_script $decr_if_gt 1 foo 2]
set res
} {4 3 2 2 2}
if {$is_eval eq 1 && $script_compatibility_api == "redis"} {
# random handling is only relevant for is_eval Lua
test {random numbers are random now} {
set rand1 [r eval {return tostring(math.random())} 0]
wait_for_condition 100 1 {
$rand1 ne [r eval {return tostring(math.random())} 0]
} else {
fail "random numbers should be random, now it's fixed value"
}
}
test {Scripting engine PRNG can be seeded correctly} {
set rand1 [r eval {
math.randomseed(ARGV[1]); return tostring(math.random())
} 0 10]
set rand2 [r eval {
math.randomseed(ARGV[1]); return tostring(math.random())
} 0 10]
set rand3 [r eval {
math.randomseed(ARGV[1]); return tostring(math.random())
} 0 20]
assert_equal $rand1 $rand2
assert {$rand2 ne $rand3}
}
} ;# is_eval
test {EVAL does not leak in the Lua stack} {
r script flush ;# reset Lua VM
r set x 0
# Use a non blocking client to speedup the loop.
set rd [valkey_deferring_client]
for {set j 0} {$j < 10000} {incr j} {
run_script_on_connection $rd {return redis.call("incr",KEYS[1])} 1 x
}
for {set j 0} {$j < 10000} {incr j} {
$rd read
}
assert {[s used_memory_lua] < 1024*100}
$rd close
r get x
} {10000}
if {$is_eval eq 1 && $script_compatibility_api == "redis"} {
test {SPOP: We can call scripts rewriting client->argv from Lua} {
set repl [attach_to_replication_stream]
#this sadd operation is for external-cluster test. If myset doesn't exist, 'del myset' won't get propagated.
r sadd myset ppp
r del myset
r sadd myset a b c
assert {[r eval {return redis.call('spop', 'myset')} 0] ne {}}
assert {[r eval {return redis.call('spop', 'myset', 1)} 0] ne {}}
assert {[r eval {return redis.call('spop', KEYS[1])} 1 myset] ne {}}
# this one below should not be replicated
assert {[r eval {return redis.call('spop', KEYS[1])} 1 myset] eq {}}
r set trailingkey 1
assert_replication_stream $repl {
{select *}
{sadd *}
{del *}
{sadd *}
{srem myset *}
{srem myset *}
{srem myset *}
{set *}
}
close_replication_stream $repl
} {} {needs:repl}
test {MGET: mget shouldn't be propagated in Lua} {
set repl [attach_to_replication_stream]
r mset a{t} 1 b{t} 2 c{t} 3 d{t} 4
#read-only, won't be replicated
assert {[r eval {return redis.call('mget', 'a{t}', 'b{t}', 'c{t}', 'd{t}')} 0] eq {1 2 3 4}}
r set trailingkey 2
assert_replication_stream $repl {
{select *}
{mset *}
{set *}
}
close_replication_stream $repl
} {} {needs:repl}
test {EXPIRE: We can call scripts rewriting client->argv from Lua} {
set repl [attach_to_replication_stream]
r set expirekey 1
#should be replicated as EXPIREAT
assert {[r eval {return redis.call('expire', KEYS[1], ARGV[1])} 1 expirekey 3] eq 1}
assert_replication_stream $repl {
{select *}
{set *}
{pexpireat expirekey *}
}
close_replication_stream $repl
} {} {needs:repl}
test {INCRBYFLOAT: We can call scripts expanding client->argv from Lua} {
# coverage for scripts calling commands that expand the argv array
# an attempt to add coverage for a possible bug in luaArgsToRedisArgv
# this test needs a fresh server so that lua_argv_size is 0.
# glibc realloc can return the same pointer even when the size changes
# still this test isn't able to trigger the issue, but we keep it anyway.
start_server {tags {"scripting"}} {
set repl [attach_to_replication_stream]
# a command with 5 argsument
r eval {redis.call('hmget', KEYS[1], 1, 2, 3)} 1 key
# then a command with 3 that is replicated as one with 4
r eval {redis.call('incrbyfloat', KEYS[1], 1)} 1 key
# then a command with 4 args
r eval {redis.call('set', KEYS[1], '1', 'KEEPTTL')} 1 key
assert_replication_stream $repl {
{select *}
{set key 1 KEEPTTL}
{set key 1 KEEPTTL}
}
close_replication_stream $repl
}
} {} {needs:repl}
} ;# is_eval
test {Call Redis command with many args from Lua (issue #1764)} {
run_script {
local i
local x={}
redis.call('del','mylist')
for i=1,100 do
table.insert(x,i)
end
redis.call('rpush','mylist',unpack(x))
return redis.call('lrange','mylist',0,-1)
} 1 mylist
} {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}
test {Number conversion precision test (issue #1118)} {
run_script {
local value = 9007199254740991
redis.call("set","foo",value)
return redis.call("get","foo")
} 1 foo
} {9007199254740991}
test {String containing number precision test (regression of issue #1118)} {
run_script {
redis.call("set", "key", "12039611435714932082")
return redis.call("get", "key")
} 1 key
} {12039611435714932082}
test {Verify negative arg count is error instead of crash (issue #1842)} {
catch { run_script { return "hello" } -12 } e
set e
} {ERR Number of keys can't be negative}
test {Scripts can handle commands with incorrect arity} {
assert_error "ERR Wrong number of args calling Redis command from script*" {run_script "redis.call('set','invalid')" 0}
assert_error "ERR Wrong number of args calling Redis command from script*" {run_script "redis.call('incr')" 0}
}
test {Correct handling of reused argv (issue #1939)} {
run_script {
for i = 0, 10 do
redis.call('SET', 'a{t}', '1')
redis.call('MGET', 'a{t}', 'b{t}', 'c{t}')
redis.call('EXPIRE', 'a{t}', 0)
redis.call('GET', 'a{t}')
redis.call('MGET', 'a{t}', 'b{t}', 'c{t}')
end
} 3 a{t} b{t} c{t}
}
test {Functions in the Redis namespace are able to report errors} {
catch {
run_script {
redis.sha1hex()
} 0
} e
set e
} {*wrong number*}
test {CLUSTER RESET can not be invoke from within a script} {
catch {
run_script {
redis.call('cluster', 'reset', 'hard')
} 0
} e
set _ $e
} {*command is not allowed*}
test {Script with RESP3 map} {
set expected_dict [dict create field value]
set expected_list [list field value]
# Sanity test for RESP3 without scripts
r HELLO 3
r hset hash field value
set res [r hgetall hash]
assert_equal $res $expected_dict
# Test RESP3 client with script in both RESP2 and RESP3 modes
set res [run_script {redis.setresp(3); return redis.call('hgetall', KEYS[1])} 1 hash]
assert_equal $res $expected_dict
set res [run_script {redis.setresp(2); return redis.call('hgetall', KEYS[1])} 1 hash]
assert_equal $res $expected_list
# Test RESP2 client with script in both RESP2 and RESP3 modes
r HELLO 2
set res [run_script {redis.setresp(3); return redis.call('hgetall', KEYS[1])} 1 hash]
assert_equal $res $expected_list
set res [run_script {redis.setresp(2); return redis.call('hgetall', KEYS[1])} 1 hash]
assert_equal $res $expected_list
} {} {resp3}
if {!$::log_req_res} { # this test creates a huge nested array which python can't handle (RecursionError: maximum recursion depth exceeded in comparison)
test {Script return recursive object} {
r readraw 1
set res [run_script {local a = {}; local b = {a}; a[1] = b; return a} 0]
# drain the response
while {true} {
if {$res == "-ERR reached lua stack limit"} {
break
}
assert_equal $res "*1"
set res [r read]
}
r readraw 0
# make sure the connection is still valid
assert_equal [r ping] {PONG}
}
}
test {Script check unpack with massive arguments} {
run_script {
local a = {}
for i=1,7999 do
a[i] = 1
end
return redis.call("lpush", "l", unpack(a))
} 1 l
} {7999}
test "Script read key with expiration set" {
r SET key value EX 10
assert_equal [run_script {
if redis.call("EXISTS", "key") then
return redis.call("GET", "key")
else
return redis.call("EXISTS", "key")
end
} 1 key] "value"
}
test "Script del key with expiration set" {
r SET key value EX 10
assert_equal [run_script {
redis.call("DEL", "key")
return redis.call("EXISTS", "key")