forked from redpanda-data/connect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
switch.go
367 lines (314 loc) · 11 KB
/
switch.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
package processor
import (
"encoding/json"
"errors"
"fmt"
"sort"
"strconv"
"time"
"github.com/dafanshu/benthos/v3/internal/bloblang/mapping"
"github.com/dafanshu/benthos/v3/internal/docs"
"github.com/dafanshu/benthos/v3/internal/interop"
imessage "github.com/dafanshu/benthos/v3/internal/message"
"github.com/dafanshu/benthos/v3/lib/condition"
"github.com/dafanshu/benthos/v3/lib/log"
"github.com/dafanshu/benthos/v3/lib/message"
"github.com/dafanshu/benthos/v3/lib/metrics"
"github.com/dafanshu/benthos/v3/lib/response"
"github.com/dafanshu/benthos/v3/lib/types"
)
//------------------------------------------------------------------------------
func init() {
Constructors[TypeSwitch] = TypeSpec{
constructor: NewSwitch,
Categories: []Category{
CategoryComposition,
},
Summary: `
Conditionally processes messages based on their contents.`,
Description: `
For each switch case a [Bloblang query](/docs/guides/bloblang/about/) is checked and, if the result is true (or the check is empty) the child processors are executed on the message.`,
Footnotes: `
## Batching
When a switch processor executes on a [batch of messages](/docs/configuration/batching/) they are checked individually and can be matched independently against cases. During processing the messages matched against a case are processed as a batch, although the ordering of messages during case processing cannot be guaranteed to match the order as received.
At the end of switch processing the resulting batch will follow the same ordering as the batch was received. If any child processors have split or otherwise grouped messages this grouping will be lost as the result of a switch is always a single batch. In order to perform conditional grouping and/or splitting use the [` + "`group_by`" + ` processor](/docs/components/processors/group_by/).`,
config: docs.FieldComponent().Array().WithChildren(
docs.FieldDeprecated("condition").HasType(docs.FieldTypeCondition).OmitWhen(func(v, _ interface{}) (string, bool) {
m, ok := v.(map[string]interface{})
if !ok {
return "", false
}
return "field condition is deprecated in favour of check", m["type"] == "static" && m["static"] == true
}),
docs.FieldBloblang(
"check",
"A [Bloblang query](/docs/guides/bloblang/about/) that should return a boolean value indicating whether a message should have the processors of this case executed on it. If left empty the case always passes. If the check mapping throws an error the message will be flagged [as having failed](/docs/configuration/error_handling) and will not be tested against any other cases.",
`this.type == "foo"`,
`this.contents.urls.contains("https://benthos.dev/")`,
).HasDefault(""),
docs.FieldCommon(
"processors",
"A list of [processors](/docs/components/processors/about/) to execute on a message.",
).HasDefault([]interface{}{}).Array().HasType(docs.FieldTypeProcessor),
docs.FieldAdvanced(
"fallthrough",
"Indicates whether, if this case passes for a message, the next case should also be executed.",
).HasDefault(false).HasType(docs.FieldTypeBool),
),
Examples: []docs.AnnotatedExample{
{
Title: "I Hate George",
Summary: `
We have a system where we're counting a metric for all messages that pass through our system. However, occasionally we get messages from George where he's rambling about dumb stuff we don't care about.
For Georges messages we want to instead emit a metric that gauges how angry he is about being ignored and then we drop it.`,
Config: `
pipeline:
processors:
- switch:
- check: this.user.name.first != "George"
processors:
- metric:
type: counter
name: MessagesWeCareAbout
- processors:
- metric:
type: gauge
name: GeorgesAnger
value: ${! json("user.anger") }
- bloblang: root = deleted()
`,
},
},
}
}
//------------------------------------------------------------------------------
// SwitchCaseConfig contains a condition, processors and other fields for an
// individual case in the Switch processor.
type SwitchCaseConfig struct {
Condition condition.Config `json:"condition" yaml:"condition"`
Check string `json:"check" yaml:"check"`
Processors []Config `json:"processors" yaml:"processors"`
Fallthrough bool `json:"fallthrough" yaml:"fallthrough"`
}
// NewSwitchCaseConfig returns a new SwitchCaseConfig with default values.
func NewSwitchCaseConfig() SwitchCaseConfig {
cond := condition.NewConfig()
cond.Type = condition.TypeStatic
cond.Static = true
return SwitchCaseConfig{
Condition: cond,
Check: "",
Processors: []Config{},
Fallthrough: false,
}
}
// UnmarshalJSON ensures that when parsing configs that are in a map or slice
// the default values are still applied.
func (s *SwitchCaseConfig) UnmarshalJSON(bytes []byte) error {
type confAlias SwitchCaseConfig
aliased := confAlias(NewSwitchCaseConfig())
if err := json.Unmarshal(bytes, &aliased); err != nil {
return err
}
*s = SwitchCaseConfig(aliased)
return nil
}
// UnmarshalYAML ensures that when parsing configs that are in a map or slice
// the default values are still applied.
func (s *SwitchCaseConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
type confAlias SwitchCaseConfig
aliased := confAlias(NewSwitchCaseConfig())
if err := unmarshal(&aliased); err != nil {
return err
}
*s = SwitchCaseConfig(aliased)
return nil
}
//------------------------------------------------------------------------------
// SwitchConfig is a config struct containing fields for the Switch processor.
type SwitchConfig []SwitchCaseConfig
// NewSwitchConfig returns a default SwitchConfig.
func NewSwitchConfig() SwitchConfig {
return SwitchConfig{}
}
//------------------------------------------------------------------------------
// switchCase contains a condition, processors and other fields for an
// individual case in the Switch processor.
type switchCase struct {
check *mapping.Executor
processors []types.Processor
fallThrough bool
}
// Switch is a processor that only applies child processors under a certain
// condition.
type Switch struct {
cases []switchCase
log log.Modular
mCount metrics.StatCounter
mSent metrics.StatCounter
}
func isDefaultCaseCond(cond condition.Config) bool {
return cond.Type == condition.TypeStatic && cond.Static
}
// NewSwitch returns a Switch processor.
func NewSwitch(
conf Config, mgr types.Manager, log log.Modular, stats metrics.Type,
) (Type, error) {
deprecated := false
for _, caseConf := range conf.Switch {
if deprecated || !isDefaultCaseCond(caseConf.Condition) {
deprecated = true
}
if deprecated {
if len(caseConf.Check) > 0 {
return nil, errors.New("cannot use both deprecated condition field in combination with field check")
}
}
}
if deprecated {
return newSwitchDeprecated(conf, mgr, log, stats)
}
var cases []switchCase
for i, caseConf := range conf.Switch {
prefix := strconv.Itoa(i)
var err error
var check *mapping.Executor
var procs []types.Processor
if len(caseConf.Check) > 0 {
if check, err = interop.NewBloblangMapping(mgr, caseConf.Check); err != nil {
return nil, fmt.Errorf("failed to parse case %v check: %w", i, err)
}
}
if len(caseConf.Processors) == 0 {
return nil, fmt.Errorf("case [%v] has no processors, in order to have a no-op case use a `noop` processor", i)
}
for j, procConf := range caseConf.Processors {
pMgr, pLog, pStats := interop.LabelChild(prefix+"."+strconv.Itoa(j), mgr, log, stats)
var proc types.Processor
if proc, err = New(procConf, pMgr, pLog, pStats); err != nil {
return nil, fmt.Errorf("case [%v] processor [%v]: %w", i, j, err)
}
procs = append(procs, proc)
}
cases = append(cases, switchCase{
check: check,
processors: procs,
fallThrough: caseConf.Fallthrough,
})
}
return &Switch{
cases: cases,
log: log,
mCount: stats.GetCounter("count"),
mSent: stats.GetCounter("sent"),
}, nil
}
//------------------------------------------------------------------------------
func reorderFromGroup(group *imessage.SortGroup, parts []types.Part) {
partToIndex := map[types.Part]int{}
for _, p := range parts {
if i := group.GetIndex(p); i >= 0 {
partToIndex[p] = i
}
}
sort.SliceStable(parts, func(i, j int) bool {
if index, found := partToIndex[parts[i]]; found {
i = index
}
if index, found := partToIndex[parts[j]]; found {
j = index
}
return i < j
})
}
// ProcessMessage applies the processor to a message, either creating >0
// resulting messages or a response to be sent back to the message source.
func (s *Switch) ProcessMessage(msg types.Message) (msgs []types.Message, res types.Response) {
s.mCount.Incr(1)
var result []types.Part
var remaining []types.Part
var carryOver []types.Part
sortGroup, sortMsg := imessage.NewSortGroup(msg)
remaining = make([]types.Part, sortMsg.Len())
sortMsg.Iter(func(i int, p types.Part) error {
remaining[i] = p
return nil
})
for i, switchCase := range s.cases {
passed, failed := carryOver, []types.Part{}
// Form a message to test against, consisting of fallen through messages
// from prior cases plus remaining messages that haven't passed a case
// yet.
testMsg := message.New(nil)
testMsg.Append(remaining...)
for j, p := range remaining {
test := switchCase.check == nil
if !test {
var err error
if test, err = switchCase.check.QueryPart(j, testMsg); err != nil {
s.log.Errorf("Failed to test case %v: %v\n", i, err)
FlagErr(p, err)
result = append(result, p)
continue
}
}
if test {
passed = append(passed, p)
} else {
failed = append(failed, p)
}
}
carryOver = nil
remaining = failed
if len(passed) > 0 {
execMsg := message.New(nil)
execMsg.SetAll(passed)
msgs, res := ExecuteAll(switchCase.processors, execMsg)
if res != nil && res.Error() != nil {
return nil, res
}
for _, m := range msgs {
m.Iter(func(_ int, p types.Part) error {
if switchCase.fallThrough {
carryOver = append(carryOver, p)
} else {
result = append(result, p)
}
return nil
})
}
}
}
result = append(result, remaining...)
if len(result) > 1 {
reorderFromGroup(sortGroup, result)
}
resMsg := message.New(nil)
resMsg.SetAll(result)
if resMsg.Len() == 0 {
return nil, response.NewAck()
}
s.mSent.Incr(int64(resMsg.Len()))
return []types.Message{resMsg}, nil
}
// CloseAsync shuts down the processor and stops processing requests.
func (s *Switch) CloseAsync() {
for _, s := range s.cases {
for _, proc := range s.processors {
proc.CloseAsync()
}
}
}
// WaitForClose blocks until the processor has closed down.
func (s *Switch) WaitForClose(timeout time.Duration) error {
stopBy := time.Now().Add(timeout)
for _, s := range s.cases {
for _, proc := range s.processors {
if err := proc.WaitForClose(time.Until(stopBy)); err != nil {
return err
}
}
}
return nil
}
//------------------------------------------------------------------------------