File size: 2,581 Bytes
1e92f2d |
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 |
package message
import (
"time"
"github.com/target/goalert/gadb"
)
// ThrottleConfigBuilder can be used to build advanced throttle configurations.
type ThrottleConfigBuilder struct {
parent *ThrottleConfigBuilder
msgTypes []gadb.EnumOutgoingMessagesType
dstTypes []string
rules []builderRules
max time.Duration
}
func (b *ThrottleConfigBuilder) top() *ThrottleConfigBuilder {
if b.parent != nil {
return b.parent
}
return b
}
// WithMsgTypes allows adding rules for messages matching at least one MessageType.
func (b *ThrottleConfigBuilder) WithMsgTypes(msgTypes ...gadb.EnumOutgoingMessagesType) *ThrottleConfigBuilder {
return &ThrottleConfigBuilder{
parent: b.top(),
msgTypes: msgTypes,
dstTypes: b.dstTypes,
}
}
// WithDestTypes allows adding rules for messages matching at least one DestType.
func (b *ThrottleConfigBuilder) WithDestTypes(destTypes ...string) *ThrottleConfigBuilder {
return &ThrottleConfigBuilder{
parent: b.top(),
msgTypes: b.msgTypes,
dstTypes: destTypes,
}
}
func (b *ThrottleConfigBuilder) setMax(rules []ThrottleRule) {
for _, r := range rules {
if r.Per > b.max {
b.max = r.Per
}
}
}
// AddRules will append a set of rules for the current filter (if any).
func (b *ThrottleConfigBuilder) AddRules(rules []ThrottleRule) {
b.top().rules = append(b.top().rules, builderRules{
msgTypes: b.msgTypes,
dstTypes: b.dstTypes,
rules: rules,
})
b.top().setMax(rules)
}
// Config will return a ThrottleConfig for the current top-level configuration.
func (b *ThrottleConfigBuilder) Config() ThrottleConfig {
var cfg builderConfig
// copy rules
cfg.rules = append(cfg.rules, b.top().rules...)
cfg.max = b.max
return &cfg
}
type builderRules struct {
msgTypes []gadb.EnumOutgoingMessagesType
dstTypes []string
rules []ThrottleRule
}
func (r builderRules) match(msg Message) bool {
typeMatch := len(r.msgTypes) == 0
for _, typ := range r.msgTypes {
if typ != msg.Type {
continue
}
typeMatch = true
break
}
if !typeMatch {
return false
}
destMatch := len(r.dstTypes) == 0
for _, dst := range r.dstTypes {
if dst != msg.Dest.Type {
continue
}
destMatch = true
break
}
return destMatch
}
type builderConfig struct {
rules []builderRules
max time.Duration
}
func (cfg *builderConfig) MaxDuration() time.Duration { return cfg.max }
func (cfg *builderConfig) Rules(msg Message) []ThrottleRule {
var rules []ThrottleRule
for _, set := range cfg.rules {
if !set.match(msg) {
continue
}
rules = append(rules, set.rules...)
}
return rules
}
|