/
bloblang.go
244 lines (206 loc) · 6.58 KB
/
bloblang.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
package processor
import (
"fmt"
"time"
"github.com/Jeffail/benthos/v3/internal/bloblang"
"github.com/Jeffail/benthos/v3/internal/bloblang/mapping"
"github.com/Jeffail/benthos/v3/internal/bloblang/parser"
"github.com/Jeffail/benthos/v3/internal/docs"
"github.com/Jeffail/benthos/v3/lib/log"
"github.com/Jeffail/benthos/v3/lib/message"
"github.com/Jeffail/benthos/v3/lib/message/tracing"
"github.com/Jeffail/benthos/v3/lib/metrics"
"github.com/Jeffail/benthos/v3/lib/response"
"github.com/Jeffail/benthos/v3/lib/types"
"github.com/opentracing/opentracing-go"
olog "github.com/opentracing/opentracing-go/log"
)
//------------------------------------------------------------------------------
func init() {
Constructors[TypeBloblang] = TypeSpec{
constructor: NewBloblang,
Categories: []Category{
CategoryMapping,
CategoryParsing,
},
config: docs.FieldComponent().HasType(docs.FieldTypeString).IsBloblang().HasDefault(""),
Summary: `
Executes a [Bloblang](/docs/guides/bloblang/about) mapping on messages.`,
Description: `
Bloblang is a powerful language that enables a wide range of mapping, transformation and filtering tasks. For more information [check out the docs](/docs/guides/bloblang/about).
If your mapping is large and you'd prefer for it to live in a separate file then you can execute a mapping directly from a file with the expression ` + "`from \"<path>\"`" + `, where the path must be absolute, or relative from the location that Benthos is executed from.`,
Footnotes: `
## Error Handling
Bloblang mappings can fail, in which case the message remains unchanged, errors
are logged, and the message is flagged as having failed, allowing you to use
[standard processor error handling patterns](/docs/configuration/error_handling).
However, Bloblang itself also provides powerful ways of ensuring your mappings
do not fail by specifying desired fallback behaviour, which you can read about
[in this section](/docs/guides/bloblang/about#error-handling).`,
Examples: []docs.AnnotatedExample{
{
Title: "Mapping",
Summary: `
Given JSON documents containing an array of fans:
` + "```json" + `
{
"id":"foo",
"description":"a show about foo",
"fans":[
{"name":"bev","obsession":0.57},
{"name":"grace","obsession":0.21},
{"name":"ali","obsession":0.89},
{"name":"vic","obsession":0.43}
]
}
` + "```" + `
We can reduce the fans to only those with an obsession score above 0.5, giving us:
` + "```json" + `
{
"id":"foo",
"description":"a show about foo",
"fans":[
{"name":"bev","obsession":0.57},
{"name":"ali","obsession":0.89}
]
}
` + "```" + `
With the following config:`,
Config: `
pipeline:
processors:
- bloblang: |
root = this
root.fans = this.fans.filter(fan -> fan.obsession > 0.5)
`,
},
{
Title: "More Mapping",
Summary: `
When receiving JSON documents of the form:
` + "```json" + `
{
"locations": [
{"name": "Seattle", "state": "WA"},
{"name": "New York", "state": "NY"},
{"name": "Bellevue", "state": "WA"},
{"name": "Olympia", "state": "WA"}
]
}
` + "```" + `
We could collapse the location names from the state of Washington into a field ` + "`Cities`" + `:
` + "```json" + `
{"Cities": "Bellevue, Olympia, Seattle"}
` + "```" + `
With the following config:`,
Config: `
pipeline:
processors:
- bloblang: |
root.Cities = this.locations.
filter(loc -> loc.state == "WA").
map_each(loc -> loc.name).
sort().join(", ")
`,
},
},
}
}
//------------------------------------------------------------------------------
// BloblangConfig contains configuration fields for the Bloblang processor.
type BloblangConfig string
// NewBloblangConfig returns a BloblangConfig with default values.
func NewBloblangConfig() BloblangConfig {
return ""
}
//------------------------------------------------------------------------------
// Bloblang is a processor that performs a Bloblang mapping.
type Bloblang struct {
exec *mapping.Executor
log log.Modular
stats metrics.Type
mCount metrics.StatCounter
mErr metrics.StatCounter
mSent metrics.StatCounter
mBatchSent metrics.StatCounter
mDropped metrics.StatCounter
}
// NewBloblang returns a Bloblang processor.
func NewBloblang(
conf Config, mgr types.Manager, log log.Modular, stats metrics.Type,
) (Type, error) {
exec, err := bloblang.NewMapping("", string(conf.Bloblang))
if err != nil {
if perr, ok := err.(*parser.Error); ok {
return nil, fmt.Errorf("%v", perr.ErrorAtPosition([]rune(conf.Bloblang)))
}
return nil, err
}
return NewBloblangFromExecutor(exec, log, stats), nil
}
// NewBloblangFromExecutor returns a Bloblang processor.
func NewBloblangFromExecutor(exec *mapping.Executor, log log.Modular, stats metrics.Type) Type {
return &Bloblang{
exec: exec,
log: log,
stats: stats,
mCount: stats.GetCounter("count"),
mErr: stats.GetCounter("error"),
mSent: stats.GetCounter("sent"),
mBatchSent: stats.GetCounter("batch.sent"),
mDropped: stats.GetCounter("dropped"),
}
}
//------------------------------------------------------------------------------
// ProcessMessage applies the processor to a message, either creating >0
// resulting messages or a response to be sent back to the message source.
func (b *Bloblang) ProcessMessage(msg types.Message) ([]types.Message, types.Response) {
b.mCount.Incr(1)
newParts := make([]types.Part, 0, msg.Len())
msg.Iter(func(i int, part types.Part) error {
span := tracing.GetSpan(part)
if span == nil {
span = opentracing.StartSpan(TypeBloblang)
} else {
span = opentracing.StartSpan(
TypeBloblang,
opentracing.ChildOf(span.Context()),
)
}
p, err := b.exec.MapPart(i, msg)
if err != nil {
p = part.Copy()
b.mErr.Incr(1)
b.log.Errorf("%v\n", err)
FlagErr(p, err)
span.SetTag("error", true)
span.LogFields(
olog.String("event", "error"),
olog.String("type", err.Error()),
)
}
span.Finish()
if p != nil {
newParts = append(newParts, p)
} else {
b.mDropped.Incr(1)
}
return nil
})
if len(newParts) == 0 {
return nil, response.NewAck()
}
newMsg := message.New(nil)
newMsg.SetAll(newParts)
b.mBatchSent.Incr(1)
b.mSent.Incr(int64(newMsg.Len()))
return []types.Message{newMsg}, nil
}
// CloseAsync shuts down the processor and stops processing requests.
func (b *Bloblang) CloseAsync() {
}
// WaitForClose blocks until the processor has closed down.
func (b *Bloblang) WaitForClose(timeout time.Duration) error {
return nil
}
//------------------------------------------------------------------------------