-
Notifications
You must be signed in to change notification settings - Fork 152
/
database.rb
386 lines (318 loc) · 8.15 KB
/
database.rb
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
require 'mock_redis/assertions'
require 'mock_redis/exceptions'
require 'mock_redis/hash_methods'
require 'mock_redis/list_methods'
require 'mock_redis/set_methods'
require 'mock_redis/string_methods'
require 'mock_redis/zset_methods'
require 'mock_redis/sort_method'
require 'mock_redis/indifferent_hash'
require 'mock_redis/info_method'
require 'mock_redis/utility_methods'
require 'mock_redis/geospatial_methods'
require 'mock_redis/stream_methods'
require 'mock_redis/connection_method'
class MockRedis
class Database
include HashMethods
include ListMethods
include SetMethods
include StringMethods
include ZsetMethods
include SortMethod
include InfoMethod
include UtilityMethods
include GeospatialMethods
include StreamMethods
include ConnectionMethod
attr_reader :data, :expire_times
def initialize(base, *_args)
@base = base
@data = MockRedis::IndifferentHash.new
@expire_times = []
end
def initialize_copy(_source)
@data = @data.clone
@data.each_key { |k| @data[k] = @data[k].clone }
@expire_times = @expire_times.map(&:clone)
end
# Redis commands go below this line and above 'private'
def call(command, &_block)
public_send(*command)
end
def auth(_)
'OK'
end
def bgrewriteaof
'Background append only file rewriting started'
end
def bgsave
'Background saving started'
end
def disconnect
nil
end
alias close disconnect
alias disconnect! close
def connected?
true
end
def dbsize
data.keys.length
end
def del(*keys)
keys = keys.flatten.map(&:to_s)
# assert_has_args(keys, 'del') # no longer errors in redis > v4.5
keys.
find_all { |key| data[key] }.
each { |k| persist(k) }.
each { |k| data.delete(k) }.
length
end
alias unlink del
def echo(msg)
msg.to_s
end
def expire(key, seconds)
assert_valid_integer(seconds)
pexpire(key, seconds.to_i * 1000)
end
def pexpire(key, ms)
assert_valid_integer(ms)
now, miliseconds = @base.now
now_ms = (now * 1000) + miliseconds
pexpireat(key, now_ms + ms.to_i)
end
def expireat(key, timestamp)
assert_valid_integer(timestamp)
pexpireat(key, timestamp.to_i * 1000)
end
def pexpireat(key, timestamp_ms)
assert_valid_integer(timestamp_ms)
if exists?(key)
timestamp = Rational(timestamp_ms.to_i, 1000)
set_expiration(key, @base.time_at(timestamp))
true
else
false
end
end
def exists(*keys)
keys.count { |key| data.key?(key) }
end
def exists?(*keys)
keys.each { |key| return true if data.key?(key) }
false
end
def flushdb
data.each_key { |k| del(k) }
'OK'
end
def dump(key)
value = data[key]
value ? Marshal.dump(value) : nil
end
def restore(key, ttl, value, replace: false)
if !replace && exists?(key)
raise Redis::CommandError, 'BUSYKEY Target key name already exists.'
end
data[key] = Marshal.load(value) # rubocop:disable Security/MarshalLoad
if ttl > 0
pexpire(key, ttl)
end
'OK'
end
def keys(format = '*')
data.keys.grep(redis_pattern_to_ruby_regex(format))
end
def scan(cursor, opts = {})
common_scan(data.keys, cursor, opts)
end
def scan_each(opts = {}, &block)
return to_enum(:scan_each, opts) unless block_given?
cursor = 0
loop do
cursor, keys = scan(cursor, opts)
keys.each(&block)
break if cursor == '0'
end
end
def lastsave
now.first
end
def persist(key)
if exists?(key) && has_expiration?(key)
remove_expiration(key)
true
else
false
end
end
def ping(response = 'PONG')
response
end
def quit
'OK'
end
def randomkey
data.keys[rand(data.length)]
end
def rename(key, newkey)
unless data.include?(key)
raise Redis::CommandError, 'ERR no such key'
end
if key != newkey
data[newkey] = data.delete(key)
if has_expiration?(key)
set_expiration(newkey, expiration(key))
remove_expiration(key)
end
end
'OK'
end
def renamenx(key, newkey)
unless data.include?(key)
raise Redis::CommandError, 'ERR no such key'
end
if exists?(newkey)
false
else
rename(key, newkey)
true
end
end
def save
'OK'
end
def ttl(key)
if !exists?(key)
-2
elsif has_expiration?(key)
now, = @base.now
expiration(key).to_i - now
else
-1
end
end
def pttl(key)
now, miliseconds = @base.now
now_ms = now * 1000 + miliseconds
if !exists?(key)
-2
elsif has_expiration?(key)
(expiration(key).to_r * 1000).to_i - now_ms
else
-1
end
end
def now
current_time = @base.options[:time_class].now
miliseconds = (current_time.to_r - current_time.to_i) * 1_000
[current_time.to_i, miliseconds.to_i]
end
alias time now
def type(key)
if !exists?(key)
'none'
elsif hashy?(key)
'hash'
elsif stringy?(key)
'string'
elsif listy?(key)
'list'
elsif sety?(key)
'set'
elsif zsety?(key)
'zset'
elsif streamy?(key)
'stream'
else
raise ArgumentError, "Not sure how #{data[key].inspect} got in here"
end
end
def script(subcommand, *args); end
def evalsha(*args); end
def eval(*args); end
private
def assert_valid_integer(integer)
unless looks_like_integer?(integer.to_s)
raise Redis::CommandError, 'ERR value is not an integer or out of range'
end
integer
end
def assert_valid_timeout(timeout)
if !looks_like_integer?(timeout.to_s)
raise Redis::CommandError, 'ERR timeout is not an integer or out of range'
elsif timeout < 0
raise Redis::CommandError, 'ERR timeout is negative'
end
timeout
end
def can_incr?(value)
value.nil? || looks_like_integer?(value)
end
def can_incr_float?(value)
value.nil? || looks_like_float?(value)
end
def extract_timeout(arglist)
options = arglist.last
if options.is_a?(Hash) && options[:timeout]
timeout = assert_valid_timeout(options[:timeout])
[arglist[0..-2], timeout]
elsif options.is_a?(Integer)
timeout = assert_valid_timeout(options)
[arglist[0..-2], timeout]
else
[arglist, 0]
end
end
def expiration(key)
expire_times.find { |(_, k)| k == key.to_s }.first
end
def has_expiration?(key)
expire_times.any? { |(_, k)| k == key.to_s }
end
def looks_like_integer?(str)
str =~ /^-?\d+$/
end
def looks_like_float?(str)
!!Float(str) rescue false
end
def redis_pattern_to_ruby_regex(pattern)
Regexp.new(
"^#{pattern}$".
gsub(/([+|(){}])/, '\\\\\1').
gsub(/(?<!\\)\?/, '\\1.').
gsub(/([^\\])\*/, '\\1.*')
)
end
def remove_expiration(key)
expire_times.delete_if do |(_t, k)|
key.to_s == k
end
end
def set_expiration(key, time)
remove_expiration(key)
found = expire_times.each_with_index.to_a.bsearch { |item, _| item.first >= time }
index = found ? found.last : -1
expire_times.insert(index, [time, key.to_s])
end
def zero_pad(string, desired_length)
padding = "\000" * [(desired_length - string.length), 0].max
string + padding
end
public
# This method isn't private, but it also isn't a Redis command, so
# it doesn't belong up above with all the Redis commands.
def expire_keys
now_sec, miliseconds = now
now_ms = now_sec * 1_000 + miliseconds
to_delete = expire_times.take_while do |(time, _key)|
(time.to_r * 1_000).to_i <= now_ms
end
to_delete.each do |(_time, key)|
del(key)
end
end
end
end