-
Notifications
You must be signed in to change notification settings - Fork 0
/
filter_traffic.go
62 lines (48 loc) · 1.33 KB
/
filter_traffic.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
package filter_traffic
type (
Filter[T comparable] interface {
Do(T) bool
}
FilterTrafficConfig struct {
Enabled bool
}
FilterTraffic[T comparable, TFilter PerValueFilter[T]] struct {
globalFilter GlobalFilter[T]
filter TFilter
enabled bool
}
)
var _ Filter[string] = FilterTraffic[string, GlobalFilter[string]]{}
func New[T comparable, TFilter PerValueFilter[T]](config FilterTrafficConfig, globalFilter GlobalFilter[T], other TFilter) FilterTraffic[T, TFilter] {
return FilterTraffic[T, TFilter]{
enabled: config.Enabled,
globalFilter: globalFilter,
filter: other,
}
}
func (r FilterTraffic[T, TFilter]) Do(key T) bool {
if !r.enabled {
return true
}
counter := r.globalFilter.Counter
if counter.counter.CompareAndSwap(counter.ResetNumber, 1) {
// This goto is used to avoid code duplication
// as we need to check if other filter rules should apply
// maybe to reset it or to check if it is still valid param
// passed in the argument ket<T>
goto checkOtherFilter
}
if counter.counter.Add(1) > r.globalFilter.Limit {
return false
}
checkOtherFilter:
counter = r.filter.GetCounter(key)
if counter == nil {
return false
}
if counter.counter.CompareAndSwap(counter.ResetNumber, 1) {
return true
}
old := counter.counter.Add(1)
return old < r.filter.GetLimit(key)
}