/
aws_lambda.go
303 lines (259 loc) · 9.97 KB
/
aws_lambda.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
package processor
import (
"fmt"
"sync"
"time"
"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/metrics"
"github.com/Jeffail/benthos/v3/lib/types"
"github.com/Jeffail/benthos/v3/lib/util/aws/lambda/client"
"github.com/opentracing/opentracing-go"
)
//------------------------------------------------------------------------------
func init() {
Constructors[TypeAWSLambda] = TypeSpec{
constructor: NewAWSLambda,
Version: "3.36.0",
Categories: []Category{
CategoryIntegration,
},
Summary: `
Invokes an AWS lambda for each message. The contents of the message is the
payload of the request, and the result of the invocation will become the new
contents of the message.`,
Description: `
It is possible to perform requests per message of a batch in parallel by setting
the ` + "`parallel`" + ` flag to ` + "`true`" + `. The ` + "`rate_limit`" + `
field can be used to specify a rate limit [resource](/docs/components/rate_limits/about)
to cap the rate of requests across parallel components service wide.
In order to map or encode the payload to a specific request body, and map the
response back into the original payload instead of replacing it entirely, you
can use the ` + "[`branch` processor](/docs/components/processors/branch)" + `.
### Error Handling
When Benthos is unable to connect to the AWS endpoint or is otherwise unable to invoke the target lambda function it will retry the request according to the configured number of retries. Once these attempts have been exhausted the failed message will continue through the pipeline with it's contents unchanged, but flagged as having failed, allowing you to use [standard processor error handling patterns](/docs/configuration/error_handling).
However, if the invocation of the function is successful but the function itself throws an error, then the message will have it's contents updated with a JSON payload describing the reason for the failure, and a metadata field ` + "`lambda_function_error`" + ` will be added to the message allowing you to detect and handle function errors with a ` + "[`branch`](/docs/components/processors/branch)" + `:
` + "```yaml" + `
pipeline:
processors:
- branch:
processors:
- aws_lambda:
function: foo
result_map: |
root = if meta().exists("lambda_function_error") {
throw("Invocation failed due to %v: %v".format(this.errorType, this.errorMessage))
} else {
this
}
output:
switch:
cases:
- check: errored()
output:
reject: ${! error() }
- output:
resource: somewhere_else
` + "```" + `
### Credentials
By default Benthos will use a shared credentials file when connecting to AWS
services. It's also possible to set them explicitly at the component level,
allowing you to transfer data across accounts. You can find out more
[in this document](/docs/guides/aws).`,
FieldSpecs: docs.FieldSpecs{
docs.FieldCommon("parallel", "Whether messages of a batch should be dispatched in parallel."),
}.Merge(client.FieldSpecs()),
Examples: []docs.AnnotatedExample{
{
Title: "Branched Invoke",
Summary: `
This example uses a ` + "[`branch` processor](/docs/components/processors/branch/)" + ` to map a new payload for triggering a lambda function with an ID and username from the original message, and the result of the lambda is discarded, meaning the original message is unchanged.`,
Config: `
pipeline:
processors:
- branch:
request_map: '{"id":this.doc.id,"username":this.user.name}'
processors:
- aws_lambda:
function: trigger_user_update
`,
},
},
}
Constructors[TypeLambda] = TypeSpec{
constructor: NewLambda,
Status: docs.StatusDeprecated,
Categories: []Category{
CategoryIntegration,
},
Summary: `
Invokes an AWS lambda for each message. The contents of the message is the
payload of the request, and the result of the invocation will become the new
contents of the message.`,
Description: `
## Alternatives
This processor has been renamed to ` + "[`aws_lambda`](/docs/components/processors/aws_lambda)" + `.
It is possible to perform requests per message of a batch in parallel by setting
the ` + "`parallel`" + ` flag to ` + "`true`" + `. The ` + "`rate_limit`" + `
field can be used to specify a rate limit [resource](/docs/components/rate_limits/about)
to cap the rate of requests across parallel components service wide.
In order to map or encode the payload to a specific request body, and map the
response back into the original payload instead of replacing it entirely, you
can use the ` + "[`branch` processor](/docs/components/processors/branch)" + `.
### Error Handling
When all retry attempts for a message are exhausted the processor cancels the
attempt. These failed messages will continue through the pipeline unchanged, but
can be dropped or placed in a dead letter queue according to your config, you
can read about these patterns [here](/docs/configuration/error_handling).
### Credentials
By default Benthos will use a shared credentials file when connecting to AWS
services. It's also possible to set them explicitly at the component level,
allowing you to transfer data across accounts. You can find out more
[in this document](/docs/guides/aws).`,
FieldSpecs: docs.FieldSpecs{
docs.FieldCommon("parallel", "Whether messages of a batch should be dispatched in parallel."),
}.Merge(client.FieldSpecs()),
Examples: []docs.AnnotatedExample{
{
Title: "Branched Invoke",
Summary: `
This example uses a ` + "[`branch` processor](/docs/components/processors/branch/)" + ` to map a new payload for triggering a lambda function with an ID and username from the original message, and the result of the lambda is discarded, meaning the original message is unchanged.`,
Config: `
pipeline:
processors:
- branch:
request_map: '{"id":this.doc.id,"username":this.user.name}'
processors:
- lambda:
function: trigger_user_update
`,
},
},
}
}
//------------------------------------------------------------------------------
// LambdaConfig contains configuration fields for the Lambda processor.
type LambdaConfig struct {
client.Config `json:",inline" yaml:",inline"`
Parallel bool `json:"parallel" yaml:"parallel"`
}
// NewLambdaConfig returns a LambdaConfig with default values.
func NewLambdaConfig() LambdaConfig {
return LambdaConfig{
Config: client.NewConfig(),
Parallel: false,
}
}
//------------------------------------------------------------------------------
// Lambda is a processor that invokes an AWS Lambda using the message as the
// request body, and returns the response.
type Lambda struct {
client *client.Type
parallel bool
conf LambdaConfig
log log.Modular
stats metrics.Type
mCount metrics.StatCounter
mErrLambda metrics.StatCounter
mErr metrics.StatCounter
mSent metrics.StatCounter
mBatchSent metrics.StatCounter
}
// NewAWSLambda returns a Lambda processor.
func NewAWSLambda(
conf Config, mgr types.Manager, log log.Modular, stats metrics.Type,
) (Type, error) {
return newLambda(conf.AWSLambda, mgr, log, stats)
}
// NewLambda returns a Lambda processor.
func NewLambda(
conf Config, mgr types.Manager, log log.Modular, stats metrics.Type,
) (Type, error) {
return newLambda(conf.Lambda, mgr, log, stats)
}
func newLambda(
conf LambdaConfig, mgr types.Manager, log log.Modular, stats metrics.Type,
) (Type, error) {
l := &Lambda{
conf: conf,
log: log,
stats: stats,
parallel: conf.Parallel,
mCount: stats.GetCounter("count"),
mErrLambda: stats.GetCounter("error.lambda"),
mErr: stats.GetCounter("error"),
mSent: stats.GetCounter("sent"),
mBatchSent: stats.GetCounter("batch.sent"),
}
var err error
if l.client, err = client.New(
conf.Config,
client.OptSetLogger(l.log),
// TODO: V4 Remove this
client.OptSetStats(metrics.Namespaced(l.stats, "client")),
client.OptSetManager(mgr),
); err != nil {
return nil, err
}
return l, 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 (l *Lambda) ProcessMessage(msg types.Message) ([]types.Message, types.Response) {
l.mCount.Incr(1)
var resultMsg types.Message
if !l.parallel || msg.Len() == 1 {
resultMsg = msg.Copy()
IteratePartsWithSpan("aws_lambda", nil, resultMsg, func(i int, _ opentracing.Span, p types.Part) error {
if err := l.client.InvokeV2(p); err != nil {
l.mErr.Incr(1)
l.mErrLambda.Incr(1)
l.log.Errorf("Lambda function '%v' failed: %v\n", l.conf.Config.Function, err)
return err
}
return nil
})
} else {
parts := make([]types.Part, msg.Len())
msg.Iter(func(i int, p types.Part) error {
parts[i] = p.Copy()
return nil
})
wg := sync.WaitGroup{}
wg.Add(msg.Len())
for i := 0; i < msg.Len(); i++ {
go func(index int) {
result, err := l.client.Invoke(message.Lock(msg, index))
if err == nil && result.Len() != 1 {
err = fmt.Errorf("unexpected response size: %v", result.Len())
}
if err != nil {
l.mErr.Incr(1)
l.mErrLambda.Incr(1)
l.log.Errorf("Lambda parallel request to '%v' failed: %v\n", l.conf.Config.Function, err)
FlagErr(parts[index], err)
} else {
parts[index] = result.Get(0)
}
wg.Done()
}(i)
}
wg.Wait()
resultMsg = message.New(nil)
resultMsg.SetAll(parts)
}
msgs := [1]types.Message{resultMsg}
l.mBatchSent.Incr(1)
l.mSent.Incr(int64(resultMsg.Len()))
return msgs[:], nil
}
// CloseAsync shuts down the processor and stops processing requests.
func (l *Lambda) CloseAsync() {
}
// WaitForClose blocks until the processor has closed down.
func (l *Lambda) WaitForClose(timeout time.Duration) error {
return nil
}
//------------------------------------------------------------------------------