forked from redis/rueidis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
countingbloomfilter.go
418 lines (339 loc) · 10.1 KB
/
countingbloomfilter.go
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
package rueidisprob
import (
"context"
"errors"
"math"
"strconv"
"github.com/redis/rueidis"
)
var (
ErrEmptyCountingBloomFilterName = errors.New("name cannot be empty")
ErrCountingBloomFilterFalsePositiveRateLessThanEqualZero = errors.New("false positive rate cannot be less than or equal to zero")
ErrCountingBloomFilterFalsePositiveRateGreaterThanOne = errors.New("false positive rate cannot be greater than 1")
ErrCountingBloomFilterBitsSizeZero = errors.New("bits size cannot be zero")
)
const (
countingBloomFilterAddMultiScript = `
local itemCount = tonumber(ARGV[1])
local numElements = tonumber(#ARGV) - 1
local filterKey = KEYS[1]
local counterKey = KEYS[2]
for i=2, numElements+1 do
redis.call('HINCRBY', filterKey, ARGV[i], 1)
end
return redis.call('INCRBY', counterKey, itemCount)
`
countingBloomFilterRemoveMultiScript = `
local function MergeTables(t1, t2)
for i=1, #t2 do
table.insert(t1, t2[i])
end
return t1
end
local numElements = tonumber(#ARGV) - 1
local hashIterations = tonumber(ARGV[#ARGV])
local filterKey = KEYS[1]
local counterKey = KEYS[2]
local indexCounter = {}
for i=1, numElements do
local index = ARGV[i]
local count = redis.call('HGET', filterKey, index)
if (not indexCounter[index]) then
if (not count) then
indexCounter[index] = 0
else
indexCounter[index] = tonumber(count)
end
end
end
local decreaseIndexes = {}
local deleteItemCount = 0
for i=1, numElements, hashIterations do
local isAbleToRemove = true
local temp = {}
local rollbackIndex = i
for j=i, i+hashIterations-1 do
local index = ARGV[j]
table.insert(temp, index)
indexCounter[index] = indexCounter[index] - 1
if indexCounter[index] < 0 then
isAbleToRemove = false
rollbackIndex = j
break
end
end
if isAbleToRemove then
decreaseIndexes = MergeTables(decreaseIndexes, temp)
deleteItemCount = deleteItemCount + 1
else
for j=i, rollbackIndex do
local index = ARGV[j]
indexCounter[index] = indexCounter[index] + 1
end
end
end
for i=1, #decreaseIndexes do
redis.call('HINCRBY', filterKey, decreaseIndexes[i], -1)
end
return redis.call('DECRBY', counterKey, deleteItemCount)
`
countingBloomFilterDeleteScript = `
local filterKey = KEYS[1]
local counterKey = KEYS[2]
redis.call('DEL', filterKey)
redis.call('DEL', counterKey)
return 1
`
)
// CountingBloomFilter based on Hashes.
// CountingBloomFilter uses 128-bit murmur3 hash function.
type CountingBloomFilter interface {
// Add adds an item to the Counting Bloom Filter.
Add(ctx context.Context, key string) error
// AddMulti adds one or more items to the Counting Bloom Filter.
// NOTE: If keys are too many, it can block the Redis server for a long time.
AddMulti(ctx context.Context, keys []string) error
// Exists checks if an item is in the Counting Bloom Filter.
Exists(ctx context.Context, key string) (bool, error)
// ExistsMulti checks if one or more items are in the Counting Bloom Filter.
// Returns a slice of bool values where each bool indicates
// whether the corresponding key was found.
ExistsMulti(ctx context.Context, keys []string) ([]bool, error)
// Remove removes an item from the Counting Bloom Filter.
Remove(ctx context.Context, key string) error
// RemoveMulti removes one or more items from the Counting Bloom Filter.
// NOTE: If keys are too many, it can block the Redis server for a long time.
RemoveMulti(ctx context.Context, keys []string) error
// Delete deletes the Counting Bloom Filter.
Delete(ctx context.Context) error
// ItemMinCount returns the minimum count of item in the Counting Bloom Filter.
// If the item is not in the Counting Bloom Filter, it returns a zero value.
// Minimum count is not always accurate because of the hash collisions.
ItemMinCount(ctx context.Context, key string) (uint64, error)
// ItemMinCountMulti returns the minimum count of items in the Counting Bloom Filter.
// If the item is not in the Counting Bloom Filter, it returns a zero value.
// Minimum count is not always accurate because of the hash collisions.
ItemMinCountMulti(ctx context.Context, keys []string) ([]uint64, error)
// Count returns count of items in Counting Bloom Filter.
Count(ctx context.Context) (uint64, error)
}
type countingBloomFilter struct {
client rueidis.Client
// name is the name of the Counting Bloom Filter.
// It is used as a key in the Redis.
name string
// counter is the name of the counter.
counter string
// hashIterations is the number of hash functions to use.
hashIterations uint
hashIterationString string
// size is the number of bits to use.
size uint
addMultiScript *rueidis.Lua
addMultiKeys []string
removeMultiScript *rueidis.Lua
removeMultiKeys []string
}
// NewCountingBloomFilter creates a new Counting Bloom Filter.
// NOTE: 'name:cbf:c' is used as a counter key in the Redis and
// 'name:cbf' is used as a filter key in the Redis
// to keep track of the number of items in the Counting Bloom Filter for Count method.
func NewCountingBloomFilter(
client rueidis.Client,
name string,
expectedNumberOfItems uint,
falsePositiveRate float64,
) (CountingBloomFilter, error) {
if len(name) == 0 {
return nil, ErrEmptyCountingBloomFilterName
}
if falsePositiveRate <= 0 {
return nil, ErrCountingBloomFilterFalsePositiveRateLessThanEqualZero
}
if falsePositiveRate >= 1 {
return nil, ErrCountingBloomFilterFalsePositiveRateGreaterThanOne
}
size := numberOfBloomFilterBits(expectedNumberOfItems, falsePositiveRate)
if size == 0 {
return nil, ErrCountingBloomFilterBitsSizeZero
}
hashIterations := numberOfBloomFilterHashFunctions(size, expectedNumberOfItems)
// NOTE: https://redis.io/docs/reference/cluster-spec/#hash-tags
baseName := "{" + name + "}"
bfName := baseName + ":cbf"
counterName := bfName + ":c"
return &countingBloomFilter{
client: client,
name: bfName,
counter: counterName,
hashIterations: hashIterations,
hashIterationString: strconv.FormatUint(uint64(hashIterations), 10),
size: size,
addMultiScript: rueidis.NewLuaScript(countingBloomFilterAddMultiScript),
addMultiKeys: []string{bfName, counterName},
removeMultiScript: rueidis.NewLuaScript(countingBloomFilterRemoveMultiScript),
removeMultiKeys: []string{bfName, counterName},
}, nil
}
func (f *countingBloomFilter) Add(ctx context.Context, key string) error {
return f.AddMulti(ctx, []string{key})
}
func (f *countingBloomFilter) AddMulti(ctx context.Context, keys []string) error {
if len(keys) == 0 {
return nil
}
indexes := f.indexes(keys)
args := make([]string, 0, len(indexes)+1)
args = append(args, strconv.Itoa(len(keys)))
args = append(args, indexes...)
resp := f.addMultiScript.Exec(ctx, f.client, f.addMultiKeys, args)
return resp.Error()
}
func (f *countingBloomFilter) indexes(keys []string) []string {
allIndexes := make([]string, 0, len(keys)*int(f.hashIterations))
size := uint64(f.size)
for _, key := range keys {
h1, h2 := hash([]byte(key))
for i := uint(0); i < f.hashIterations; i++ {
allIndexes = append(allIndexes, strconv.FormatUint(index(h1, h2, i, size), 10))
}
}
return allIndexes
}
func (f *countingBloomFilter) Exists(ctx context.Context, key string) (bool, error) {
exists, err := f.ExistsMulti(ctx, []string{key})
if err != nil {
return false, err
}
return exists[0], nil
}
func (f *countingBloomFilter) ExistsMulti(ctx context.Context, keys []string) ([]bool, error) {
if len(keys) == 0 {
return nil, nil
}
indexes := f.indexes(keys)
resp := f.client.Do(
ctx,
f.client.B().
Hmget().
Key(f.name).
Field(indexes...).
Build(),
)
if resp.Error() != nil {
return nil, resp.Error()
}
messages, err := resp.ToArray()
if err != nil {
return nil, err
}
result := make([]bool, 0, len(keys))
isExist := true
for i, message := range messages {
cnt, err := message.AsUint64()
if err != nil {
if !rueidis.IsRedisNil(err) {
return nil, err
}
isExist = false
}
if cnt == 0 {
isExist = false
}
if (i+1)%int(f.hashIterations) == 0 {
result = append(result, isExist)
isExist = true
}
}
return result, nil
}
func (f *countingBloomFilter) Remove(ctx context.Context, key string) error {
return f.RemoveMulti(ctx, []string{key})
}
func (f *countingBloomFilter) RemoveMulti(ctx context.Context, keys []string) error {
if len(keys) == 0 {
return nil
}
indexes := f.indexes(keys)
args := make([]string, 0, len(indexes)+1)
args = append(args, indexes...)
args = append(args, f.hashIterationString)
resp := f.removeMultiScript.Exec(ctx, f.client, f.removeMultiKeys, args)
return resp.Error()
}
func (f *countingBloomFilter) Delete(ctx context.Context) error {
resp := f.client.Do(
ctx,
f.client.B().
Eval().
Script(countingBloomFilterDeleteScript).
Numkeys(2).
Key(f.name, f.counter).
Build(),
)
return resp.Error()
}
func (f *countingBloomFilter) ItemMinCount(ctx context.Context, key string) (uint64, error) {
counts, err := f.ItemMinCountMulti(ctx, []string{key})
if err != nil {
return 0, err
}
return counts[0], nil
}
func (f *countingBloomFilter) ItemMinCountMulti(ctx context.Context, keys []string) ([]uint64, error) {
if len(keys) == 0 {
return nil, nil
}
indexes := f.indexes(keys)
resp := f.client.Do(
ctx,
f.client.B().
Hmget().
Key(f.name).
Field(indexes...).
Build(),
)
if resp.Error() != nil {
return nil, resp.Error()
}
messages, err := resp.ToArray()
if err != nil {
return nil, err
}
counts := make([]uint64, 0, len(messages))
minCount := uint64(math.MaxUint64)
for i, message := range messages {
cnt, err := message.AsUint64()
if err != nil {
if !rueidis.IsRedisNil(err) {
return nil, err
}
minCount = 0
}
if cnt < minCount {
minCount = cnt
}
if (i+1)%int(f.hashIterations) == 0 {
counts = append(counts, minCount)
minCount = uint64(math.MaxUint64)
}
}
return counts, nil
}
func (f *countingBloomFilter) Count(ctx context.Context) (uint64, error) {
resp := f.client.Do(
ctx,
f.client.B().
Get().
Key(f.counter).
Build(),
)
count, err := resp.AsUint64()
if err != nil {
if rueidis.IsRedisNil(err) {
return 0, nil
}
return 0, err
}
return count, nil
}