/
output_pubsub.go
370 lines (311 loc) · 11.2 KB
/
output_pubsub.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
368
369
370
package gcp
import (
"context"
"fmt"
"sync"
"cloud.google.com/go/pubsub"
"github.com/sourcegraph/conc/pool"
"google.golang.org/api/option"
"github.com/benthosdev/benthos/v4/public/service"
)
func newPubSubOutputConfig() *service.ConfigSpec {
defaults := pubsub.DefaultPublishSettings
return service.NewConfigSpec().
Stable().
Categories("Services", "GCP").
Summary("Sends messages to a GCP Cloud Pub/Sub topic. [Metadata](/docs/configuration/metadata) from messages are sent as attributes.").
Description(`
For information on how to set up credentials check out [this guide](https://cloud.google.com/docs/authentication/production).
### Troubleshooting
If you're consistently seeing `+"`Failed to send message to gcp_pubsub: context deadline exceeded`"+` error logs without any further information it is possible that you are encountering https://github.com/benthosdev/benthos/issues/1042, which occurs when metadata values contain characters that are not valid utf-8. This can frequently occur when consuming from Kafka as the key metadata field may be populated with an arbitrary binary value, but this issue is not exclusive to Kafka.
If you are blocked by this issue then a work around is to delete either the specific problematic keys:
`+"```yaml"+`
pipeline:
processors:
- mapping: |
meta kafka_key = deleted()
`+"```"+`
Or delete all keys with:
`+"```yaml"+`
pipeline:
processors:
- mapping: meta = deleted()
`+"```"+``).
Fields(
service.NewStringField("project").Description("The project ID of the topic to publish to."),
service.NewInterpolatedStringField("topic").Description("The topic to publish to."),
service.NewStringField("endpoint").
Default("").
Example("us-central1-pubsub.googleapis.com:443").
Example("us-west3-pubsub.googleapis.com:443").
Description("An optional endpoint to override the default of `pubsub.googleapis.com:443`. This can be used to connect to a region specific pubsub endpoint. For a list of valid values check out [this document.](https://cloud.google.com/pubsub/docs/reference/service_apis_overview#list_of_regional_endpoints)"),
service.NewInterpolatedStringField("ordering_key").
Optional().
Description("The ordering key to use for publishing messages.").
Advanced(),
service.NewIntField("max_in_flight").Default(64).Description("The maximum number of messages to have in flight at a given time. Increasing this may improve throughput."),
service.NewIntField("count_threshold").
Default(defaults.CountThreshold).
Description("Publish a pubsub buffer when it has this many messages"),
service.NewDurationField("delay_threshold").
Default(defaults.DelayThreshold.String()).
Description("Publish a non-empty pubsub buffer after this delay has passed."),
service.NewIntField("byte_threshold").
Default(defaults.ByteThreshold).
Description("Publish a batch when its size in bytes reaches this value."),
service.NewDurationField("publish_timeout").
Default(defaults.Timeout.String()).
Example("10s").
Example("5m").
Example("60m").
Description("The maximum length of time to wait before abandoning a publish attempt for a message.").
Advanced(),
service.NewMetadataExcludeFilterField("metadata").
Optional().
Description("Specify criteria for which metadata values are sent as attributes, all are sent by default."),
service.NewObjectField(
"flow_control",
service.NewIntField("max_outstanding_bytes").
Default(defaults.FlowControlSettings.MaxOutstandingBytes).
Description("Maximum size of buffered messages to be published. If less than or equal to zero, this is disabled."),
service.NewIntField("max_outstanding_messages").
Default(defaults.FlowControlSettings.MaxOutstandingMessages).
Description("Maximum number of buffered messages to be published. If less than or equal to zero, this is disabled."),
service.NewStringEnumField("limit_exceeded_behavior", "ignore", "block", "signal_error").
Default("block").
Description("Configures the behavior when trying to publish additional messages while the flow controller is full. The available options are block (default), ignore (disable), and signal_error (publish results will return an error)."),
).
Description("For a given topic, configures the PubSub client's internal buffer for messages to be published.").
Advanced(),
service.NewBatchPolicyField("batching").
Description("Configures a batching policy on this output. While the PubSub client maintains its own internal buffering mechanism, preparing larger batches of messages can further trade-off some latency for throughput."),
)
}
type pubsubOutput struct {
topicMut sync.Mutex
topics map[string]pubsubTopic
project string
clientOpts []option.ClientOption
client pubsubClient
clientCancel context.CancelFunc
publishSettings *pubsub.PublishSettings
topicQ *service.InterpolatedString
metaFilter *service.MetadataExcludeFilter
orderingKeyQ *service.InterpolatedString
}
func newPubSubOutput(conf *service.ParsedConfig) (*pubsubOutput, error) {
var settings pubsub.PublishSettings
project, err := conf.FieldString("project")
if err != nil {
return nil, err
}
topicQ, err := conf.FieldInterpolatedString("topic")
if err != nil {
return nil, err
}
metaFilter, err := conf.FieldMetadataExcludeFilter("metadata")
if err != nil {
return nil, err
}
var orderingKeyQ *service.InterpolatedString
if conf.Contains("ordering_key") {
if orderingKeyQ, err = conf.FieldInterpolatedString("ordering_key"); err != nil {
return nil, err
}
}
if settings.DelayThreshold, err = conf.FieldDuration("delay_threshold"); err != nil {
return nil, err
}
if settings.CountThreshold, err = conf.FieldInt("count_threshold"); err != nil {
return nil, err
}
if settings.ByteThreshold, err = conf.FieldInt("byte_threshold"); err != nil {
return nil, err
}
if settings.Timeout, err = conf.FieldDuration("publish_timeout"); err != nil {
return nil, err
}
flowConf := conf.Namespace("flow_control")
var flowControl pubsub.FlowControlSettings
if flowControl.MaxOutstandingBytes, err = flowConf.FieldInt("max_outstanding_bytes"); err != nil {
return nil, err
}
if flowControl.MaxOutstandingMessages, err = flowConf.FieldInt("max_outstanding_messages"); err != nil {
return nil, err
}
var limitBehavior string
if limitBehavior, err = flowConf.FieldString("limit_exceeded_behavior"); err != nil {
return nil, err
}
switch limitBehavior {
case "ignore":
flowControl.LimitExceededBehavior = pubsub.FlowControlIgnore
case "block":
flowControl.LimitExceededBehavior = pubsub.FlowControlBlock
case "signal_error":
flowControl.LimitExceededBehavior = pubsub.FlowControlSignalError
default:
return nil, fmt.Errorf("unrecognized flow control setting: %s", limitBehavior)
}
settings.FlowControlSettings = flowControl
var endpoint string
if endpoint, err = conf.FieldString("endpoint"); err != nil {
return nil, err
}
var opt []option.ClientOption
if endpoint != "" {
opt = []option.ClientOption{option.WithEndpoint(endpoint)}
}
return &pubsubOutput{
topics: make(map[string]pubsubTopic),
project: project,
clientOpts: opt,
publishSettings: &settings,
topicQ: topicQ,
metaFilter: metaFilter,
orderingKeyQ: orderingKeyQ,
}, nil
}
func (out *pubsubOutput) Connect(_ context.Context) error {
if out.client != nil {
return nil
}
clientCtx, clientCancel := context.WithCancel(context.Background())
client, err := pubsub.NewClient(clientCtx, out.project, out.clientOpts...)
if err != nil {
clientCancel()
return fmt.Errorf("failed to create pubsub client: %w", err)
}
out.client = &airGappedPubsubClient{client}
out.clientCancel = clientCancel
return nil
}
func (out *pubsubOutput) WriteBatch(ctx context.Context, batch service.MessageBatch) error {
topics := make(map[string]pubsubTopic)
p := pool.NewWithResults[*serverResult]().WithContext(ctx)
var batchErr *service.BatchError
batchErrFailed := func(i int, err error) {
if batchErr == nil {
batchErr = service.NewBatchError(batch, err)
}
batchErr.Failed(i, err)
}
for i, msg := range batch {
i := i
res, err := out.writeMessage(ctx, topics, msg)
if err != nil {
batchErrFailed(i, err)
continue
}
p.Go(func(ctx context.Context) (*serverResult, error) {
_, err := res.Get(ctx)
if err != nil {
return &serverResult{batchIndex: i, err: err}, nil
}
return nil, nil
})
}
getResults, err := p.Wait()
if err != nil {
return fmt.Errorf("failed to get publish results: %w", err)
}
for _, res := range getResults {
if res == nil {
continue
}
batchErrFailed(res.batchIndex, res.err)
}
if batchErr != nil && batchErr.IndexedErrors() > 0 {
return batchErr
}
return nil
}
func (out *pubsubOutput) Close(_ context.Context) error {
out.topicMut.Lock()
defer out.topicMut.Unlock()
for _, t := range out.topics {
t.Stop()
}
out.topics = nil
if out.clientCancel != nil {
out.clientCancel()
}
return nil
}
func (out *pubsubOutput) writeMessage(ctx context.Context, cachedTopics map[string]pubsubTopic, msg *service.Message) (publishResult, error) {
topicName, err := out.topicQ.TryString(msg)
if err != nil {
return nil, fmt.Errorf("failed to resolve topic name: %w", err)
}
topic, found := cachedTopics[topicName]
if !found {
t, err := out.getTopic(ctx, topicName)
if err != nil {
return nil, fmt.Errorf("failed to get topic: %s: %w", topicName, err)
}
cachedTopics[topicName] = t
topic = t
}
attr := make(map[string]string)
if err := out.metaFilter.Walk(msg, func(key, value string) error {
attr[key] = value
return nil
}); err != nil {
return nil, fmt.Errorf("failed to build message attributes: %w", err)
}
var orderingKey string
if out.orderingKeyQ != nil {
if orderingKey, err = out.orderingKeyQ.TryString(msg); err != nil {
return nil, fmt.Errorf("failed to build ordering key: %w", err)
}
}
data, err := msg.AsBytes()
if err != nil {
return nil, fmt.Errorf("failed to get bytes from message: %w", err)
}
return topic.Publish(ctx, &pubsub.Message{
Data: data,
Attributes: attr,
OrderingKey: orderingKey,
}), nil
}
func (out *pubsubOutput) getTopic(ctx context.Context, name string) (pubsubTopic, error) {
out.topicMut.Lock()
defer out.topicMut.Unlock()
if t, exists := out.topics[name]; exists {
return t, nil
}
t := out.client.Topic(name, out.publishSettings)
exists, err := t.Exists(ctx)
if err != nil {
return nil, fmt.Errorf("failed to validate topic '%v': %v", name, err)
}
if !exists {
return nil, fmt.Errorf("topic '%v' does not exist", name)
}
if out.orderingKeyQ != nil {
t.EnableOrdering()
}
out.topics[name] = t
return t, nil
}
type serverResult struct {
batchIndex int
err error
}
func init() {
if err := service.RegisterBatchOutput("gcp_pubsub", newPubSubOutputConfig(), func(conf *service.ParsedConfig, mgr *service.Resources) (out service.BatchOutput, batchPolicy service.BatchPolicy, maxInFlight int, err error) {
maxInFlight, err = conf.FieldInt("max_in_flight")
if err != nil {
return
}
batchPolicy, err = conf.FieldBatchPolicy("batching")
if err != nil {
return
}
out, err = newPubSubOutput(conf)
return
}); err != nil {
panic(err)
}
}