forked from andrewberls/predis
/
mock.clj
621 lines (515 loc) · 17.3 KB
/
mock.clj
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
(ns predis.mock
(:require [clojure.set :as clj.set]
[clojure.string :as string]
(predis
[core :as core]
[util :as util])
(predis.util
[range :as util.range]
[zset :as util.zset])))
(def err-badint
"ERR value is not an integer or out of range")
(def err-indexrange
"ERR index out of range")
(def err-srcdest
"ERR source and destination objects are the same")
(def err-syntax
"ERR syntax error")
(def err-wrongtype
"WRONGTYPE Operation against a key holding the wrong kind of value")
(defn err-arity [cmd]
(format "ERR wrong number of arguments for %s" cmd))
;;
; Need to distinguish types internally, both represented
; with Clojure maps
(def empty-zset (with-meta {} {:predis/type "zset"})) ; member -> score
(def empty-hash (with-meta {} {:predis/type "hash"}))
(defn- set-at [redis k]
(set (core/get redis k)))
(defn- hash-at [redis k]
(or (core/get redis k) empty-hash))
(defn- zset-at [redis k]
(or (core/get redis k) empty-zset))
(defn- replace-seq
"If s is a non-empty seq, replace it at key k in store
Otherwise remove it from the store"
[store k xs]
(if (seq xs)
(swap! store assoc k xs)
(swap! store dissoc k)))
;;
(deftype MockClient [store]
core/IRedis
;; Keys
(core/del [this k-or-ks]
(let [[store' nremoved] (->> (util/vec-wrap k-or-ks)
(util/counting-dissoc @store))]
(reset! store store')
nremoved))
(core/unlink [this k-or-ks]
(core/del this k-or-ks))
(core/exists [this k]
(if (core/get this k) 1 0))
(core/keys [this pat]
(let [re (re-pattern (string/escape pat {\* ".*" \? ".?"}))
key-matches
(fn [k]
(let [match (re-find re k)]
; Bit of hackery to support empty keys (legal!)
(not (and (empty? match) (not= match k)))))]
(filter key-matches (keys @store))))
(core/randomkey [this]
(first (shuffle (keys @store))))
(core/rename [this k new-k]
(assert (not= k new-k) err-srcdest)
(core/set this new-k (core/get this k))
(core/del this k)
"OK")
(core/renamenx [this k new-k]
(if-not (core/get this new-k)
(do
(core/rename this k new-k)
1)
0))
(core/type [this k]
(let [x (core/get this k)]
(cond
(string? x) "string"
(set? x) "set"
(map? x) (let [t (:predis/type (meta x))]
(assert t "Invalid metadata!")
t)
(sequential? x) "list"
:else "none")))
(core/scan [this cursor]
(core/scan this cursor {}))
(core/scan [this cursor {:keys [match count] :as opts}]
; Note - `count` is a hint for the implementation, and
; is ignored here
(let [pat (or match "*")
ks (core/keys this pat)]
["0" ks]))
;; Server
(core/flushdb [this]
(reset! store {})
"OK")
(core/dbsize [this]
(count (keys @store)))
;; Connection
(core/ping [this] "PONG")
;; Strings
(core/append [this k v]
(let [do-append (fn [old-str] (str old-str v))]
(swap! store update-in [k] do-append)
(core/strlen this k)))
(core/decr [this k]
(core/decrby this k 1))
(core/decrby [this k decrement]
(let [do-decrby (fn [old]
(->> (- (if old (Integer/parseInt old) 0) decrement)
str))]
(swap! store update-in [k] do-decrby)
(Integer/parseInt (core/get this k))))
(core/get [this k]
(get @store (str k)))
(core/getrange [this k start stop]
(let [s (or (core/get this k) "")
len (count s)
last-idx (dec len)
start' (util.range/normalized-start-idx s start)
stop' (cond
(> stop last-idx) last-idx
(< stop (- len)) 0 ; Only difference from normalized-stop-idx
(< stop 0) (+ len stop)
:else stop)]
(if (or (empty? s) (> start last-idx) (> start' stop'))
""
(subs s start' (inc stop')))))
(core/getset [this k v]
(when-let [old (core/get this k)]
(core/set this k v)
old))
(core/incr [this k]
(core/incrby this k 1))
(core/incrby [this k increment]
(let [do-incrby (fn [old]
(->> (+ (if old (Integer/parseInt old) 0) increment)
str))]
(swap! store update-in [k] do-incrby)
(Integer/parseInt (core/get this k))))
(core/incrbyfloat [this k increment]
(let [do-incrby (fn [old]
(->> (+ (if old (Double/parseDouble old) 0) increment)
str))]
(swap! store update-in [k] do-incrby)
(core/get this k)))
(core/mget [this ks]
(util/values-at @store (map str ks)))
(core/mset [this kvs]
(assert (even? (count (flatten kvs))) (err-arity "MSET"))
(doseq [[k v] kvs]
(core/set this k v))
"OK")
(core/msetnx [this kvs]
(assert (even? (count (flatten kvs))) (err-arity "MSETNX"))
(let [key-missing? (fn [[k v]] (nil? (core/get this k)))]
(if (every? key-missing? kvs)
(do
(core/mset this kvs)
1)
0)))
(core/set [this k v]
(swap! store assoc (str k) (str v))
"OK")
(core/setnx [this k v]
(if-not (core/get this k)
(do
(core/set this k v)
1)
0))
(core/strlen [this k]
(let [s (or (core/get this k) "")]
(assert (string? s) err-wrongtype)
(count s)))
;; Hashes
(core/hdel [this k f-or-fs]
(if-let [m (core/get this k)]
(let [[m' nremoved] (->> (util/vec-wrap f-or-fs)
(util/counting-dissoc m))]
(replace-seq store k m')
nremoved)
0))
(core/hexists [this k f]
(if (core/hget this k f) 1 0))
(core/hget [this k f]
(let [m (hash-at this k)]
(get m (str f))))
(core/hgetall [this k]
(let [vs (seq (or (core/get this k) []))]
(apply concat (or vs []))))
(core/hincrby [this k f increment]
(let [do-hincrby (fn [old]
(let [m (or old empty-hash)
old-v (Integer/parseInt (get m (str f) "0"))]
(assoc m f (str (+ old-v increment)))))]
(swap! store update-in [k] do-hincrby)
(Integer/parseInt (core/hget this k f))))
(core/hincrbyfloat [this k f increment]
(let [do-hincrby (fn [m]
(let [old (Double/parseDouble (get m (str f) "0"))]
(assoc m f (str (+ old increment)))))]
(swap! store update-in [k] do-hincrby)
(Double/parseDouble (core/hget this k f))))
(core/hkeys [this k]
(or (keys (core/get this k))
[]))
(core/hlen [this k]
(let [m (hash-at this k)]
(count (keys m))))
(core/hmget [this k f-or-fs]
(let [m (hash-at this k)
fs' (util/vec-wrap f-or-fs)]
(util/values-at m fs')))
(core/hmset [this k kvs]
(let [kvs' (map util/stringify-tuple kvs)
do-merge (fn [m]
(->> (concat (seq (or m {})) kvs')
(into empty-hash)))]
(swap! store update-in [k] do-merge)
"OK"))
(core/hset [this k f v]
(let [m (hash-at this k)
do-hset (fn [old] (assoc (or old empty-hash) (str f) (str v)))]
(if (contains? m f)
(do
(swap! store update-in [k] do-hset)
0)
(do
(swap! store update-in [k] do-hset)
1))))
(core/hsetnx [this k f v]
(let [m (hash-at this k)]
(if (contains? m f)
0
(do
(core/hset this k f v)
1))))
(core/hvals [this k]
(let [m (hash-at this k)]
(or (vals (sort m)) [])))
;; Lists
(core/lindex [this k idx]
(let [vs (vec (core/get this k))
last-idx (dec (count vs))
idx' (util.range/normalized-stop-idx vs idx)]
; Differ from lrange here
(when (<= idx last-idx)
(get vs idx'))))
(core/linsert [this k pos pivot v]
(let [vs (vec (core/get this k))
pos' (string/lower-case pos)]
(assert (#{"before" "after"} pos') err-syntax)
(if (seq vs)
(if (contains? (set vs) pivot)
(let [split-idx (if (= pos' "before")
(.indexOf vs pivot)
(inc (.indexOf vs pivot)))
[before after] (split-at split-idx vs)
vs' (concat before [(str v)] after)]
(swap! store assoc k vs')
(core/llen this k))
-1)
0)))
(core/llen [this k]
(count (core/get this k)))
(core/lpop [this k]
(let [vs (core/get this k)]
(when (seq vs)
(let [v (first vs)
vs' (rest vs)]
(replace-seq store k vs')
v))))
(core/lpush [this k v-or-vs]
(let [vs' (util/vec-wrap v-or-vs)
do-push (fn [old-vs new-v] (cons new-v (or (seq old-vs) '())))]
(doseq [v vs']
(swap! store update-in [k] do-push (str v)))
(core/llen this k)))
(core/lpushx [this k v]
(let [vs (core/get this k)]
(if (seq vs)
(core/lpush this k v)
(core/llen this k))))
(core/lrange [this k start stop]
(let [vs (vec (core/get this k))]
(if (or (empty? vs) (> start (dec (count vs))))
[]
(let [start' (util.range/normalized-start-idx vs start)
stop' (util.range/normalized-stop-idx vs stop)
indices (if (= start' stop')
[start']
(range start' (inc stop')))]
(map (partial get vs) indices)))))
(core/lrem [this k cnt v]
(assert (number? cnt) err-badint)
(let [vs (core/get this k)]
(if (seq vs)
(let [v' (str v)
[vs' nremoved] (cond
(> cnt 0) (util/remove-first-n vs cnt v')
(< cnt 0) (util/remove-last-n vs (Math/abs cnt) v')
(= cnt 0) (util/remove-all vs v'))]
(replace-seq store k vs')
nremoved)
0)))
(core/ltrim [this k start stop]
; Lots of tricky boundary cases here. See http://redis.io/commands/ltrim
(if (and (>= start 0) (>= stop 0) (> start stop))
(swap! store dissoc k)
(let [vs (vec (core/get this k))]
(when (seq vs)
(if (> start (count vs))
(swap! store dissoc k)
(let [start' (util.range/normalized-start-idx vs start)
stop' (util.range/normalized-stop-idx vs stop)
vs' (subvec vs start' (inc stop'))]
(replace-seq store k vs'))))))
"OK")
(core/rpop [this k]
(let [vs (core/get this k)]
(when (seq vs)
(let [v (last vs)
vs' (butlast vs)]
(replace-seq store k vs')
v))))
(core/rpoplpush [this src dest]
(when-let [vs (seq (core/get this src))]
(let [v (last vs)]
(replace-seq store src (butlast vs))
(core/rpush this dest v)
v)))
(core/lset [this k idx v]
(let [vs (vec (core/get this k))
idx' (util.range/normalized-stop-idx vs idx)
vs' (assoc vs idx' v)]
(assert (< idx' (count vs)) err-indexrange)
(swap! store assoc k vs')
"OK"))
(core/rpush [this k v-or-vs]
(let [vs' (util/vec-wrap v-or-vs)
do-push (fn [old-vs] (apply conj (util/to-vec old-vs) (map str vs')))]
(swap! store update-in [k] do-push)
(core/llen this k)))
(core/rpushx [this k v]
(let [vs (core/get this k)]
(if (seq vs)
(core/rpush this k v)
(core/llen this k))))
; Sets
(core/sadd [this k m-or-ms]
(let [s (or (core/get this k) #{})
[s' nadded] (->> (util/vec-wrap m-or-ms)
(map str)
(util/counting-union s))]
(swap! store assoc k (set (map str s')))
nadded))
(core/scard [this k]
(count (core/get this k)))
(core/sdiff [this k-or-ks]
(let [ks' (util/vec-wrap k-or-ks)
diff (->> (apply clj.set/difference
(set-at this (first ks'))
(map (partial set-at this) (rest ks')))
seq)]
(or diff [])))
(core/sdiffstore [this dest k-or-ks]
(let [diff (set (core/sdiff this k-or-ks))]
(swap! store assoc dest diff)
(core/scard this dest)))
(core/sinter [this k-or-ks]
(let [ks' (util/vec-wrap k-or-ks)
inter (->> (apply clj.set/intersection
(set-at this (first ks'))
(map (partial set-at this) (rest ks')))
seq)]
(or inter [])))
(core/sinterstore [this dest k-or-ks]
(let [inter (set (core/sinter this k-or-ks))]
(swap! store assoc dest inter)
(core/scard this dest)))
(core/sismember [this k m]
(if (contains? (set-at this k) (str m)) 1 0))
(core/smembers [this k]
(seq (set-at this k)))
(core/smove [this src dest m]
(if (contains? (set-at this src) m)
(do
(core/srem this src m)
(core/sadd this dest m)
1)
0))
(core/spop [this k]
(if-let [s (core/get this k)]
(let [m (first (shuffle s))]
(core/srem this k m)
m)))
(core/srandmember [this k]
(first (core/srandmember this k 1)))
(core/srandmember [this k cnt]
(when-let [s (get this k)]
(take cnt (shuffle s))))
(core/srem [this k m-or-ms]
(let [ms' (map str (util/vec-wrap m-or-ms))
s (set-at this k)]
(if (seq s)
(let [[s' nremoved] (util/counting-disj s ms')]
(replace-seq store k s')
nremoved)
0)))
(sunion [this k-or-ks]
(let [ks' (util/vec-wrap k-or-ks)]
(apply clj.set/union
(set-at this (first ks'))
(map (partial set-at this) (rest ks')))))
(core/sunionstore [this dest k-or-ks]
(let [union (core/sunion this k-or-ks)]
(swap! store assoc dest union)
(core/scard this dest)))
; Sorted Sets
(core/zadd [this k score m]
(let [m' (str m)
zset (zset-at this k)
do-zadd (fn [_] (assoc zset m' (long score)))
ret (if (contains? zset m') 0 1)]
(swap! store update-in [k] do-zadd)
ret))
(core/zadd [this k kvs]
(reduce (fn [acc [score m]] (+ acc (core/zadd this k score m)))
0
kvs))
(zcard [this k]
(let [zset (zset-at this k)]
(count zset)))
(zcount [this k min-score max-score]
(->> (zset-at this k)
(util.zset/zrangebyscore min-score max-score)
count))
(zincrby [this k increment m]
(let [do-zincrby
(fn [old]
(let [zset (or old empty-zset)
new-score (+ (get zset m 0.0) increment)]
(assoc zset m new-score)))]
(swap! store update-in [k] do-zincrby)
(str (get (core/get this k) m))))
;;(zinterstore [this dest numkeys ks weights])
;;(zlexcount [this k min-val max-val])
(core/zrange [this k start stop]
(core/zrange this k start stop {}))
(core/zrange [this k start stop {:keys [withscores]}]
(let [zset (vec (util.zset/sort-zset (zset-at this k)))]
(if (or (empty? zset) (> start (dec (count zset))))
[]
(let [tups (->> (util.range/indices-for zset start stop)
(map (partial get zset))
(map util/stringify-tuple))]
(util.zset/zset-response tups withscores)))))
;;(zrangebylex [this k min-val max-val opts?])
(core/zrangebyscore [this k min-score max-score]
(core/zrangebyscore this k min-score max-score {}))
; TODO: offset, count
(core/zrangebyscore [this k min-score max-score {:keys [withscores offset count]}]
(let [tups (->> (zset-at this k)
(util.zset/zrangebyscore min-score max-score)
(map util/stringify-tuple))]
(util.zset/zset-response tups withscores)))
(zrank [this k m]
(when-let [zset (seq (zset-at this k))]
(let [vs (->> (util.zset/sort-zset zset)
(mapv first))
idx (.indexOf vs m)]
(when (>= idx 0)
idx))))
(zrem [this k m-or-ms]
(let [zset (zset-at this k)]
(if (seq zset)
(let [[zset' nremoved] (->> (util/vec-wrap m-or-ms)
(util/counting-dissoc zset))]
(replace-seq store k zset')
nremoved)
0)))
;;(zremrangebylex [this k min-val max-val])
;(zremrangebyscore [this k min-score max-score])
(core/zrevrange [this k start stop]
(core/zrevrange this k start stop {}))
(core/zrevrange [this k start stop {:keys [withscores]}]
(let [zset (vec (reverse (util.zset/sort-zset (zset-at this k))))]
(if (or (empty? zset) (> start (dec (count zset))))
[]
(let [tups (->> (util.range/indices-for zset start stop)
(map (partial get zset))
(map util/stringify-tuple))]
(util.zset/zset-response tups withscores)))))
;(zrevrangebyscore [this k max-score min-score opts])
(zrevrank [this k m]
(when-let [zset (seq (zset-at this k))]
(let [vs (->> (util.zset/sort-zset zset)
(map first)
reverse
vec)
idx (.indexOf vs m)]
(when (>= idx 0)
idx))))
(zscore [this k m]
(let [zset (zset-at this k)]
(when-let [score (get zset m)]
(str score))))
;(zunionstore [dest numkeys ks weights])
;;(zscan [this k cursor] [this k cursor opts])
)
;;
(defn ->redis
([]
(->redis {}))
([init-state]
(->MockClient (atom init-state))))