-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathengine_stringmap.go
330 lines (271 loc) · 8.61 KB
/
engine_stringmap.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
package expr
import (
"context"
"fmt"
"strconv"
"sync"
"github.com/cespare/xxhash/v2"
"github.com/google/cel-go/common/operators"
"github.com/ohler55/ojg/jp"
)
func newStringEqualityMatcher(concurrency int64) MatchingEngine {
return &stringLookup{
lock: &sync.RWMutex{},
vars: map[string]struct{}{},
equality: variableMap{},
inequality: inequalityMap{},
concurrency: concurrency,
}
}
type variableMap map[string][]*StoredExpressionPart
type inequalityMap map[string]variableMap
// stringLookup represents a very dumb lookup for string equality matching within
// expressions.
//
// This does nothing fancy: it takes strings from expressions then adds them a hashmap.
// For any incoming event, we take all strings and store them in a hashmap pointing to
// the ExpressionPart they match.
//
// Note that strings are (obviuously) hashed to store in a hashmap, leading to potential
// false postivies. Because the aggregate merging filters invalid expressions, this is
// okay: we still evaluate potential matches at the end of filtering.
//
// Due to this, we do not care about variable names for each string. Matching on string
// equality alone down the cost of evaluating non-matchingexpressions by orders of magnitude.
type stringLookup struct {
lock *sync.RWMutex
// vars stores variable names seen within expressions.
vars map[string]struct{}
// equality stores all strings referenced within expressions, mapped to the expression part.
// this performs string equality lookups.
equality variableMap
// inequality stores all variables referenced within inequality checks mapped to the value,
// which is then mapped to expression parts.
//
// this lets us quickly map neq in a fast manner
inequality inequalityMap
concurrency int64
}
func (s stringLookup) Type() EngineType {
return EngineTypeStringHash
}
func (n *stringLookup) Match(ctx context.Context, input map[string]any) ([]*StoredExpressionPart, error) {
l := &sync.Mutex{}
matched := []*StoredExpressionPart{}
pool := newErrPool(errPoolOpts{concurrency: n.concurrency})
neqOptimized := false
// First, handle equality matching.
for item := range n.vars {
path := item
pool.Go(func() error {
x, err := jp.ParseString(path)
if err != nil {
return err
}
// default to an empty string
str := ""
if res := x.Get(input); len(res) > 0 {
if value, ok := res[0].(string); ok {
str = value
}
}
m, opt := n.equalitySearch(ctx, path, str)
l.Lock()
matched = append(matched, m...)
if opt {
neqOptimized = true
}
l.Unlock()
return nil
})
}
if err := pool.Wait(); err != nil {
return nil, err
}
pool = newErrPool(errPoolOpts{concurrency: n.concurrency})
// Then, iterate through the inequality matches.
for item := range n.inequality {
path := item
pool.Go(func() error {
x, err := jp.ParseString(path)
if err != nil {
return err
}
// default to an empty string
str := ""
if res := x.Get(input); len(res) > 0 {
if value, ok := res[0].(string); ok {
str = value
}
}
m := n.inequalitySearch(ctx, path, str, neqOptimized, matched)
l.Lock()
matched = append(matched, m...)
l.Unlock()
return nil
})
}
return matched, pool.Wait()
}
// Search returns all ExpressionParts which match the given input, ignoring the variable name
// entirely.
//
// Note that Search does not match inequality items.
func (n *stringLookup) Search(ctx context.Context, variable string, input any) (matched []*StoredExpressionPart) {
str, ok := input.(string)
if !ok {
return nil
}
matched, _ = n.equalitySearch(ctx, variable, str)
return matched
}
func (n *stringLookup) equalitySearch(ctx context.Context, variable string, input string) (matched []*StoredExpressionPart, neqOptimized bool) {
n.lock.RLock()
defer n.lock.RUnlock()
hashedInput := n.hash(input)
// Iterate through all matching values, and only take those expressions which match our
// current variable name.
filtered := make([]*StoredExpressionPart, len(n.equality[hashedInput]))
i := 0
for _, part := range n.equality[hashedInput] {
if part.Ident != nil && *part.Ident != variable {
// The variables don't match.
continue
}
if part.GroupID.Flag() != OptimizeNone {
neqOptimized = true
}
filtered[i] = part
i++
}
filtered = filtered[0:i]
return filtered, neqOptimized
}
// inequalitySearch performs lookups for != matches.
func (n *stringLookup) inequalitySearch(ctx context.Context, variable string, input string, neqOptimized bool, currentMatches []*StoredExpressionPart) (matched []*StoredExpressionPart) {
if len(n.inequality[variable]) == 0 {
return nil
}
n.lock.RLock()
defer n.lock.RUnlock()
hashedInput := n.hash(input)
var found map[groupID]int8
if neqOptimized {
// If we're optimizing the "neq" value, we have a compound group which has both an == and != joined:
// `a == a && b != c`.
//
// In these cases, we'd naively return every StoredExpressionPart in the filter, as b != c - disregarding
// the `a == a` match.
//
// With optimizations, we check that there's the right number of string `==` matches in the group before
// evaluating !=, ensuring we keep allocations to a minimum.
found = map[groupID]int8{}
for _, match := range currentMatches {
found[match.GroupID]++
}
}
results := []*StoredExpressionPart{}
for value, exprs := range n.inequality[variable] {
if value == hashedInput {
continue
}
if !neqOptimized {
results = append(results, exprs...)
continue
}
for _, expr := range exprs {
res, ok := found[expr.GroupID]
if !ok || res < int8(expr.GroupID.Flag()) {
continue
}
results = append(results, expr)
}
}
return results
}
// hash hashes strings quickly via xxhash. this provides a _somewhat_ collision-free
// lookup while reducing memory for strings. note that internally, go maps store the
// raw key as a string, which uses extra memory. by compressing all strings via this
// hash, memory usage grows predictably even with long strings.
func (n *stringLookup) hash(input string) string {
ui := xxhash.Sum64String(input)
return strconv.FormatUint(ui, 36)
}
func (n *stringLookup) Add(ctx context.Context, p ExpressionPart) error {
// Primarily, we match `$string == lit` and `$string != lit`.
//
// Equality operators are easy: link the matching string to
// expressions that are candidates.
switch p.Predicate.Operator {
case operators.Equals:
n.lock.Lock()
defer n.lock.Unlock()
val := n.hash(p.Predicate.LiteralAsString())
n.vars[p.Predicate.Ident] = struct{}{}
if _, ok := n.equality[val]; !ok {
n.equality[val] = []*StoredExpressionPart{p.ToStored()}
return nil
}
n.equality[val] = append(n.equality[val], p.ToStored())
case operators.NotEquals:
n.lock.Lock()
defer n.lock.Unlock()
val := n.hash(p.Predicate.LiteralAsString())
// First, add the variable to inequality
if _, ok := n.inequality[p.Predicate.Ident]; !ok {
n.inequality[p.Predicate.Ident] = variableMap{
val: []*StoredExpressionPart{p.ToStored()},
}
return nil
}
n.inequality[p.Predicate.Ident][val] = append(n.inequality[p.Predicate.Ident][val], p.ToStored())
return nil
default:
return fmt.Errorf("StringHash engines only support string equality/inequality")
}
return nil
}
func (n *stringLookup) Remove(ctx context.Context, p ExpressionPart) error {
switch p.Predicate.Operator {
case operators.Equals:
n.lock.Lock()
defer n.lock.Unlock()
val := n.hash(p.Predicate.LiteralAsString())
coll, ok := n.equality[val]
if !ok {
// This could not exist as there's nothing mapping this variable for
// the given event name.
return ErrExpressionPartNotFound
}
// Remove the expression part from the leaf.
for i, eval := range coll {
if p.EqualsStored(eval) {
coll = append(coll[:i], coll[i+1:]...)
n.equality[val] = coll
return nil
}
}
return ErrExpressionPartNotFound
case operators.NotEquals:
n.lock.Lock()
defer n.lock.Unlock()
val := n.hash(p.Predicate.LiteralAsString())
// If the var isn't found, we can't remove.
if _, ok := n.inequality[p.Predicate.Ident]; !ok {
return ErrExpressionPartNotFound
}
// then merge the expression into the value that the expression has.
if _, ok := n.inequality[p.Predicate.Ident][val]; !ok {
return nil
}
for i, eval := range n.inequality[p.Predicate.Ident][val] {
if p.EqualsStored(eval) {
n.inequality[p.Predicate.Ident][val] = append(n.inequality[p.Predicate.Ident][val][:i], n.inequality[p.Predicate.Ident][val][i+1:]...)
return nil
}
}
return ErrExpressionPartNotFound
default:
return fmt.Errorf("StringHash engines only support string equality/inequality")
}
}