forked from redis/rueidis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bloomfilter.go
354 lines (284 loc) · 7.84 KB
/
bloomfilter.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
package rueidisprob
import (
"context"
"errors"
"math"
"strconv"
"github.com/redis/rueidis"
)
const (
// NOTE: https://redis.io/docs/data-types/bitmaps/
maxSize = 1 << 32
)
const (
addMultiScript = `
local hashIterations = tonumber(ARGV[1])
local numElements = tonumber(#ARGV) - 1
local filterKey = KEYS[1]
local counterKey = KEYS[2]
local bitfieldArgs = { filterKey }
for i=2, numElements+1 do
table.insert(bitfieldArgs, 'SET')
table.insert(bitfieldArgs, 'u1')
table.insert(bitfieldArgs, ARGV[i])
table.insert(bitfieldArgs, '1')
end
local bitset = redis.call('BITFIELD', unpack(bitfieldArgs))
local counter = 0
local oneBits = 0
for i=1, #bitset do
oneBits = oneBits + bitset[i]
if i % hashIterations == 0 then
if oneBits ~= hashIterations then
counter = counter + 1
end
oneBits = 0
end
end
return redis.call('INCRBY', counterKey, counter)
`
existsMultiScript = `
local hashIterations = tonumber(ARGV[1])
local numElements = tonumber(#ARGV) - 1
local filterKey = KEYS[1]
local bitfieldArgs = { filterKey }
for i=2, numElements+1 do
local index = tonumber(ARGV[i])
table.insert(bitfieldArgs, 'GET')
table.insert(bitfieldArgs, 'u1')
table.insert(bitfieldArgs, index)
end
local bitset = redis.call('BITFIELD', unpack(bitfieldArgs))
local result = {}
local oneBits = 0
for i=1, #bitset do
oneBits = oneBits + bitset[i]
if i % hashIterations == 0 then
table.insert(result, oneBits == hashIterations)
oneBits = 0
end
end
return result
`
resetScript = `
local filterKey = KEYS[1]
local counterKey = KEYS[2]
redis.call('SET', filterKey, "")
redis.call('SET', counterKey, 0)
return 1
`
deleteScript = `
local filterKey = KEYS[1]
local counterKey = KEYS[2]
redis.call('DEL', filterKey)
redis.call('DEL', counterKey)
return 1
`
)
var (
ErrEmptyName = errors.New("name cannot be empty")
ErrFalsePositiveRateLessThanEqualZero = errors.New("false positive rate cannot be less than or equal to zero")
ErrFalsePositiveRateGreaterThanOne = errors.New("false positive rate cannot be greater than 1")
ErrBitsSizeZero = errors.New("bits size cannot be zero")
ErrBitsSizeTooLarge = errors.New("bits size is too large")
)
// BloomFilter based on Redis Bitmaps.
// BloomFilter uses 128-bit murmur3 hash function.
type BloomFilter interface {
// Add adds an item to the Bloom filter.
Add(ctx context.Context, key string) error
// AddMulti adds one or more items to the 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 Bloom filter.
Exists(ctx context.Context, key string) (bool, error)
// ExistsMulti checks if one or more items are in the 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)
// Reset resets the Bloom filter.
Reset(ctx context.Context) error
// Delete deletes the Bloom filter.
Delete(ctx context.Context) error
// Count returns count of items in Bloom filter.
Count(ctx context.Context) (uint, error)
}
type bloomFilter struct {
client rueidis.Client
// name is the name of the 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
existsMultiScript *rueidis.Lua
existsMultiKeys []string
}
// NewBloomFilter creates a new Bloom filter.
// NOTE: 'name:c' is used as a counter key in the Redis
// to keep track of the number of items in the Bloom filter for Count method.
func NewBloomFilter(
client rueidis.Client,
name string,
expectedNumberOfItems uint,
falsePositiveRate float64,
) (BloomFilter, error) {
if len(name) == 0 {
return nil, ErrEmptyName
}
if falsePositiveRate <= 0 {
return nil, ErrFalsePositiveRateLessThanEqualZero
}
if falsePositiveRate > 1 {
return nil, ErrFalsePositiveRateGreaterThanOne
}
size := numberOfBits(expectedNumberOfItems, falsePositiveRate)
if size == 0 {
return nil, ErrBitsSizeZero
}
if size > maxSize {
return nil, ErrBitsSizeTooLarge
}
hashIterations := numberOfHashFunctions(size, expectedNumberOfItems)
// NOTE: https://redis.io/docs/reference/cluster-spec/#hash-tags
bfName := "{" + name + "}"
counterName := bfName + ":c"
return &bloomFilter{
client: client,
name: bfName,
counter: counterName,
hashIterations: hashIterations,
hashIterationString: strconv.FormatUint(uint64(hashIterations), 10),
size: size,
addMultiScript: rueidis.NewLuaScript(addMultiScript),
addMultiKeys: []string{bfName, counterName},
existsMultiScript: rueidis.NewLuaScript(existsMultiScript),
existsMultiKeys: []string{bfName},
}, nil
}
func numberOfBits(n uint, r float64) uint {
return uint(math.Ceil(-float64(n) * math.Log(r) / math.Pow(math.Log(2), 2)))
}
func numberOfHashFunctions(s uint, n uint) uint {
return uint(math.Round(float64(s) / float64(n) * math.Log(2)))
}
func (c *bloomFilter) Add(ctx context.Context, key string) error {
return c.AddMulti(ctx, []string{key})
}
func (c *bloomFilter) AddMulti(ctx context.Context, keys []string) error {
if len(keys) == 0 {
return nil
}
indexes := c.indexes(keys)
args := make([]string, 0, len(indexes)+1)
args = append(args, c.hashIterationString)
args = append(args, indexes...)
resp := c.addMultiScript.Exec(ctx, c.client, c.addMultiKeys, args)
if resp.Error() != nil {
return resp.Error()
}
return nil
}
func (c *bloomFilter) indexes(keys []string) []string {
allIndexes := make([]string, 0, len(keys)*int(c.hashIterations))
size := uint64(c.size)
for _, key := range keys {
h1, h2 := hash([]byte(key))
for i := uint(0); i < c.hashIterations; i++ {
allIndexes = append(allIndexes, strconv.FormatUint(index(h1, h2, i, size), 10))
}
}
return allIndexes
}
func (c *bloomFilter) Exists(ctx context.Context, key string) (bool, error) {
exists, err := c.ExistsMulti(ctx, []string{key})
if err != nil {
return false, err
}
return exists[0], nil
}
func (c *bloomFilter) ExistsMulti(ctx context.Context, keys []string) ([]bool, error) {
if len(keys) == 0 {
return nil, nil
}
indexes := c.indexes(keys)
args := make([]string, 0, len(indexes)+1)
args = append(args, c.hashIterationString)
args = append(args, indexes...)
resp := c.existsMultiScript.Exec(ctx, c.client, c.existsMultiKeys, args)
if resp.Error() != nil {
return nil, resp.Error()
}
arr, err := resp.ToArray()
if err != nil {
return nil, err
}
result := make([]bool, len(keys))
for i, el := range arr {
v, err := el.AsBool()
if err != nil {
if rueidis.IsRedisNil(err) {
result[i] = false
continue
}
return nil, err
}
result[i] = v
}
return result, nil
}
func (c *bloomFilter) Reset(ctx context.Context) error {
resp := c.client.Do(
ctx,
c.client.B().
Eval().
Script(resetScript).
Numkeys(2).
Key(c.name, c.counter).
Build(),
)
if resp.Error() != nil {
return resp.Error()
}
return nil
}
func (c *bloomFilter) Delete(ctx context.Context) error {
resp := c.client.Do(
ctx,
c.client.B().
Eval().
Script(deleteScript).
Numkeys(2).
Key(c.name, c.counter).
Build(),
)
if resp.Error() != nil {
return resp.Error()
}
return nil
}
func (c *bloomFilter) Count(ctx context.Context) (uint, error) {
resp := c.client.Do(
ctx,
c.client.B().
Get().
Key(c.counter).
Build(),
)
if resp.Error() != nil {
if rueidis.IsRedisNil(resp.Error()) {
return 0, nil
}
return 0, resp.Error()
}
count, err := resp.AsUint64()
if err != nil {
return 0, err
}
return uint(count), nil
}