forked from valkey-io/valkey-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bloomfilter.go
372 lines (301 loc) · 8.81 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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
package valkeyprob
import (
"context"
"errors"
"math"
"strconv"
"github.com/valkey-io/valkey-go"
)
const (
// NOTE: https://redis.io/docs/data-types/bitmaps/
maxSize = 1 << 32
)
const (
bloomFilterAddMultiScript = `
local hashIterations = tonumber(ARGV[1])
local numElements = tonumber(#ARGV) - 1
local filterKey = KEYS[1]
local counterKey = KEYS[2]
local counter = 0
local oneBits = 0
for i=1, numElements do
local bitset = redis.call('BITFIELD', filterKey, 'SET', 'u1', ARGV[i+1], '1')
oneBits = oneBits + bitset[1]
if i % hashIterations == 0 then
if oneBits ~= hashIterations then
counter = counter + 1
end
oneBits = 0
end
end
return redis.call('INCRBY', counterKey, counter)
`
bloomFilterExistsMultiScript = `
local hashIterations = tonumber(ARGV[1])
local numElements = tonumber(#ARGV) - 1
local filterKey = KEYS[1]
local result = {}
local oneBits = 0
for i=1, numElements do
local index = tonumber(ARGV[i+1])
local bitset = redis.call('BITFIELD', filterKey, 'GET', 'u1', index)
oneBits = oneBits + bitset[1]
if i % hashIterations == 0 then
table.insert(result, oneBits == hashIterations)
oneBits = 0
end
end
return result
`
bloomFilterExistsMultiReadOnlyScript = `
local hashIterations = tonumber(ARGV[1])
local numElements = tonumber(#ARGV) - 1
local filterKey = KEYS[1]
local result = {}
local oneBits = 0
for i=1, numElements do
local index = tonumber(ARGV[i+1])
local bitset = redis.call('BITFIELD_RO', filterKey, 'GET', 'u1', index)
oneBits = oneBits + bitset[1]
if i % hashIterations == 0 then
table.insert(result, oneBits == hashIterations)
oneBits = 0
end
end
return result
`
bloomFilterResetScript = `
local filterKey = KEYS[1]
local counterKey = KEYS[2]
redis.call('SET', filterKey, "")
redis.call('SET', counterKey, 0)
return 1
`
bloomFilterDeleteScript = `
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")
)
// BloomFilterOptions is used to configure BloomFilter.
type BloomFilterOptions struct {
enableReadOperation bool
}
// BloomFilterOptionFunc is used to configure BloomFilter.
type BloomFilterOptionFunc func(*BloomFilterOptions)
// WithEnableReadOperation enables read operation.
// If enabled, Exists and ExistsMulti methods will be available as read-only operations.
// NOTE: If enabled, minimum valkey version should be 7.0.0.
func WithEnableReadOperation(enableReadOperations bool) BloomFilterOptionFunc {
return func(o *BloomFilterOptions) {
o.enableReadOperation = enableReadOperations
}
}
// BloomFilter based on Valkey 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 Valkey 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) (uint64, error)
}
type bloomFilter struct {
client valkey.Client
// name is the name of the Bloom filter.
// It is used as a key in the Valkey.
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 *valkey.Lua
addMultiKeys []string
existsMultiScript *valkey.Lua
existsMultiKeys []string
}
// NewBloomFilter creates a new Bloom filter.
// NOTE: 'name:c' is used as a counter key in the Valkey
// to keep track of the number of items in the Bloom filter for Count method.
func NewBloomFilter(
client valkey.Client,
name string,
expectedNumberOfItems uint,
falsePositiveRate float64,
opts ...BloomFilterOptionFunc,
) (BloomFilter, error) {
if len(name) == 0 {
return nil, ErrEmptyName
}
if falsePositiveRate <= 0 {
return nil, ErrFalsePositiveRateLessThanEqualZero
}
if falsePositiveRate > 1 {
return nil, ErrFalsePositiveRateGreaterThanOne
}
size := numberOfBloomFilterBits(expectedNumberOfItems, falsePositiveRate)
if size == 0 {
return nil, ErrBitsSizeZero
}
if size > maxSize {
return nil, ErrBitsSizeTooLarge
}
hashIterations := numberOfBloomFilterHashFunctions(size, expectedNumberOfItems)
options := &BloomFilterOptions{}
for _, opt := range opts {
opt(options)
}
var existsMultiScript *valkey.Lua
if options.enableReadOperation {
existsMultiScript = valkey.NewLuaScriptReadOnly(bloomFilterExistsMultiReadOnlyScript)
} else {
existsMultiScript = valkey.NewLuaScript(bloomFilterExistsMultiScript)
}
// 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: valkey.NewLuaScript(bloomFilterAddMultiScript),
addMultiKeys: []string{bfName, counterName},
existsMultiScript: existsMultiScript,
existsMultiKeys: []string{bfName},
}, nil
}
func numberOfBloomFilterBits(n uint, r float64) uint {
return uint(math.Ceil(-float64(n) * math.Log(r) / math.Pow(math.Log(2), 2)))
}
func numberOfBloomFilterHashFunctions(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)
return resp.Error()
}
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 valkey.IsValkeyNil(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(bloomFilterResetScript).
Numkeys(2).
Key(c.name, c.counter).
Build(),
)
return resp.Error()
}
func (c *bloomFilter) Delete(ctx context.Context) error {
resp := c.client.Do(
ctx,
c.client.B().
Eval().
Script(bloomFilterDeleteScript).
Numkeys(2).
Key(c.name, c.counter).
Build(),
)
return resp.Error()
}
func (c *bloomFilter) Count(ctx context.Context) (uint64, error) {
resp := c.client.Do(
ctx,
c.client.B().
Get().
Key(c.counter).
Build(),
)
count, err := resp.AsUint64()
if err != nil {
if valkey.IsValkeyNil(err) {
return 0, nil
}
return 0, err
}
return count, nil
}