/
jq.go
321 lines (272 loc) · 8.57 KB
/
jq.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
package processor
import (
"bytes"
"encoding/json"
"fmt"
"time"
"github.com/Jeffail/benthos/v3/internal/docs"
"github.com/Jeffail/benthos/v3/internal/tracing"
"github.com/Jeffail/benthos/v3/lib/log"
"github.com/Jeffail/benthos/v3/lib/message"
"github.com/Jeffail/benthos/v3/lib/metrics"
"github.com/Jeffail/benthos/v3/lib/response"
"github.com/Jeffail/benthos/v3/lib/types"
"github.com/itchyny/gojq"
)
func init() {
Constructors[TypeJQ] = TypeSpec{
constructor: NewJQ,
Status: docs.StatusStable,
Categories: []Category{
CategoryMapping,
},
Summary: `
Transforms and filters messages using jq queries.`,
Description: `
:::note Try out Bloblang
For better performance and improved capabilities try out native Benthos mapping with the [bloblang processor](/docs/components/processors/bloblang).
:::
The provided query is executed on each message, targeting either the contents
as a structured JSON value or as a raw string using the field ` + "`raw`" + `,
and the message is replaced with the query result.
Message metadata is also accessible within the query from the variable
` + "`$metadata`" + `.
This processor uses the [gojq library][gojq], and therefore does not require
jq to be installed as a dependency. However, this also means there are some
differences in how these queries are executed versus the jq cli which you can
[read about here][gojq-difference].
If the query does not emit any value then the message is filtered, if the query
returns multiple values then the resulting message will be an array containing
all values.
The full query syntax is described in [jq's documentation][jq-docs].
## Error Handling
Queries 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).`,
Footnotes: `
[gojq]: https://github.com/itchyny/gojq
[gojq-difference]: https://github.com/itchyny/gojq#difference-to-jq
[jq-docs]: https://stedolan.github.io/jq/manual/`,
Examples: []docs.AnnotatedExample{
{
Title: "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:
- jq:
query: '{Cities: .locations | map(select(.state == "WA").name) | sort | join(", ") }'
`,
},
},
FieldSpecs: docs.FieldSpecs{
docs.FieldCommon("query", "The jq query to filter and transform messages with."),
docs.FieldAdvanced("raw", "Whether to process the input as a raw string instead of as JSON."),
docs.FieldAdvanced("output_raw", "Whether to output raw text (unquoted) instead of JSON strings when the emitted values are string types."),
},
}
}
//------------------------------------------------------------------------------
// JQConfig contains configuration fields for the JQ processor.
type JQConfig struct {
Query string `json:"query" yaml:"query"`
Raw bool `json:"raw" yaml:"raw"`
OutputRaw bool `json:"output_raw" yaml:"output_raw"`
}
// NewJQConfig returns a JQConfig with default values.
func NewJQConfig() JQConfig {
return JQConfig{
Query: ".",
}
}
//------------------------------------------------------------------------------
var jqCompileOptions = []gojq.CompilerOption{
gojq.WithVariables([]string{"$metadata"}),
}
// JQ is a processor that passes messages through gojq.
type JQ struct {
conf JQConfig
log log.Modular
stats metrics.Type
code *gojq.Code
mCount metrics.StatCounter
mCountParts metrics.StatCounter
mSent metrics.StatCounter
mBatchSent metrics.StatCounter
mDropped metrics.StatCounter
mDroppedParts metrics.StatCounter
mErr metrics.StatCounter
mErrJSONParse metrics.StatCounter
mErrJSONSet metrics.StatCounter
mErrQuery metrics.StatCounter
}
// NewJQ returns a JQ processor.
func NewJQ(
conf Config, mgr types.Manager, log log.Modular, stats metrics.Type,
) (Type, error) {
j := &JQ{
conf: conf.JQ,
stats: stats,
log: log,
mCount: stats.GetCounter("count"),
mCountParts: stats.GetCounter("count_parts"),
mSent: stats.GetCounter("sent"),
mBatchSent: stats.GetCounter("batch.count"),
mDropped: stats.GetCounter("dropped"),
mDroppedParts: stats.GetCounter("dropped_num_parts"),
mErr: stats.GetCounter("error"),
mErrJSONParse: stats.GetCounter("error.json_parse"),
mErrJSONSet: stats.GetCounter("error.json_set"),
mErrQuery: stats.GetCounter("error.query"),
}
query, err := gojq.Parse(j.conf.Query)
if err != nil {
return nil, fmt.Errorf("error parsing jq query: %w", err)
}
j.code, err = gojq.Compile(query, jqCompileOptions...)
if err != nil {
return nil, fmt.Errorf("error compiling jq query: %w", err)
}
return j, nil
}
//------------------------------------------------------------------------------
func (j *JQ) getPartMetadata(part types.Part) map[string]interface{} {
metadata := map[string]interface{}{}
part.Metadata().Iter(func(k, v string) error {
metadata[k] = v
return nil
})
return metadata
}
func (j *JQ) getPartValue(part types.Part, raw bool) (obj interface{}, err error) {
if raw {
return string(part.Get()), nil
}
obj, err = part.JSON()
if err == nil {
obj, err = message.CopyJSON(obj)
}
if err != nil {
j.mErrJSONParse.Incr(1)
j.log.Debugf("Failed to parse part into json: %v\n", err)
return nil, err
}
return obj, nil
}
// ProcessMessage applies the processor to a message, either creating >0
// resulting messages or a response to be sent back to the message source.
func (j *JQ) ProcessMessage(msg types.Message) ([]types.Message, types.Response) {
j.mCount.Incr(1)
newMsg := msg.Copy()
iteratePartsFilterableWithSpan(TypeJQ, nil, newMsg, func(index int, span *tracing.Span, part types.Part) (bool, error) {
in, err := j.getPartValue(part, j.conf.Raw)
if err != nil {
j.mErr.Incr(1)
return false, err
}
metadata := j.getPartMetadata(part)
var emitted []interface{}
iter := j.code.Run(in, metadata)
for {
out, ok := iter.Next()
if !ok {
break
}
if err, ok := out.(error); ok {
j.log.Debugf(err.Error())
j.mErr.Incr(1)
j.mErrQuery.Incr(1)
return false, err
}
j.mSent.Incr(1)
emitted = append(emitted, out)
}
if j.conf.OutputRaw {
raw, err := j.marshalRaw(emitted)
if err != nil {
j.log.Debugf("Failed to marshal raw text: %s", err)
j.mErr.Incr(1)
return false, err
}
// Sometimes the query result is an empty string. Example:
// echo '{ "foo": "" }' | jq .foo
// In that case we want pass on the empty string instead of treating it as
// an empty message and dropping it
if len(raw) == 0 && len(emitted) == 0 {
j.mDroppedParts.Incr(1)
return false, nil
}
part.Set(raw)
return true, nil
} else if len(emitted) > 1 {
if err = part.SetJSON(emitted); err != nil {
j.log.Debugf("Failed to set part JSON: %v\n", err)
j.mErr.Incr(1)
j.mErrJSONSet.Incr(1)
return false, err
}
} else if len(emitted) == 1 {
if err = part.SetJSON(emitted[0]); err != nil {
j.log.Debugf("Failed to set part JSON: %v\n", err)
j.mErr.Incr(1)
j.mErrJSONSet.Incr(1)
return false, err
}
} else {
j.mDroppedParts.Incr(1)
return false, nil
}
return true, nil
})
if newMsg.Len() == 0 {
j.mDropped.Incr(1)
return nil, response.NewAck()
}
j.mBatchSent.Incr(1)
j.mSent.Incr(int64(newMsg.Len()))
return []types.Message{newMsg}, nil
}
// CloseAsync shuts down the processor and stops processing requests.
func (*JQ) CloseAsync() {
}
// WaitForClose blocks until the processor has closed down.
func (*JQ) WaitForClose(timeout time.Duration) error {
return nil
}
func (j *JQ) marshalRaw(values []interface{}) ([]byte, error) {
buf := bytes.NewBufferString("")
for index, el := range values {
var rawResult []byte
val, isString := el.(string)
if isString {
rawResult = []byte(val)
} else {
marshalled, err := json.Marshal(el)
if err != nil {
return nil, fmt.Errorf("failed marshal JQ result at index %d: %w", index, err)
}
rawResult = marshalled
}
if _, err := buf.Write(rawResult); err != nil {
return nil, fmt.Errorf("failed to write JQ result at index %d: %w", index, err)
}
}
bs := buf.Bytes()
return bs, nil
}