-
Notifications
You must be signed in to change notification settings - Fork 3
/
destination_middleware.go
401 lines (345 loc) · 12.5 KB
/
destination_middleware.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
// Copyright © 2022 Meroxa, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package sdk
import (
"context"
"fmt"
"sort"
"strconv"
"time"
"github.com/conduitio/conduit-commons/config"
"github.com/conduitio/conduit-commons/opencdc"
"golang.org/x/time/rate"
)
// DestinationMiddleware wraps a Destination and adds functionality to it.
type DestinationMiddleware interface {
Wrap(Destination) Destination
}
// DefaultDestinationMiddleware returns a slice of middleware that should be
// added to all destinations unless there's a good reason not to.
func DefaultDestinationMiddleware() []DestinationMiddleware {
return []DestinationMiddleware{
DestinationWithRateLimit{},
DestinationWithRecordFormat{},
DestinationWithBatch{},
}
}
// DestinationWithMiddleware wraps the destination into the supplied middleware.
func DestinationWithMiddleware(d Destination, middleware ...DestinationMiddleware) Destination {
for _, m := range middleware {
d = m.Wrap(d)
}
return d
}
// -- DestinationWithBatch -----------------------------------------------------
const (
configDestinationBatchSize = "sdk.batch.size"
configDestinationBatchDelay = "sdk.batch.delay"
)
type ctxKeyBatchEnabled struct{}
// DestinationWithBatch adds support for batching on the destination. It adds
// two parameters to the destination config:
// - `sdk.batch.size` - Maximum size of batch before it gets written to the
// destination.
// - `sdk.batch.delay` - Maximum delay before an incomplete batch is written
// to the destination.
//
// To change the defaults of these parameters use the fields of this struct.
type DestinationWithBatch struct {
// DefaultBatchSize is the default value for the batch size.
DefaultBatchSize int
// DefaultBatchDelay is the default value for the batch delay.
DefaultBatchDelay time.Duration
}
func (d DestinationWithBatch) BatchSizeParameterName() string {
return configDestinationBatchSize
}
func (d DestinationWithBatch) BatchDelayParameterName() string {
return configDestinationBatchDelay
}
// Wrap a Destination into the batching middleware.
func (d DestinationWithBatch) Wrap(impl Destination) Destination {
return &destinationWithBatch{
Destination: impl,
defaults: d,
}
}
// setBatchEnabled stores the boolean in the context. If the context already
// contains the key it will update the boolean under that key and return the
// same context, otherwise it will return a new context with the stored value.
// This is used to signal to destinationPluginAdapter if the Destination is
// wrapped into DestinationWithBatch middleware.
func (DestinationWithBatch) setBatchEnabled(ctx context.Context, enabled bool) context.Context {
flag, ok := ctx.Value(ctxKeyBatchEnabled{}).(*bool)
if ok {
*flag = enabled
} else {
ctx = context.WithValue(ctx, ctxKeyBatchEnabled{}, &enabled)
}
return ctx
}
func (DestinationWithBatch) getBatchEnabled(ctx context.Context) bool {
flag, ok := ctx.Value(ctxKeyBatchEnabled{}).(*bool)
if !ok {
return false
}
return *flag
}
type destinationWithBatch struct {
Destination
defaults DestinationWithBatch
}
func (d *destinationWithBatch) Parameters() config.Parameters {
return mergeParameters(d.Destination.Parameters(), config.Parameters{
configDestinationBatchSize: {
Default: strconv.Itoa(d.defaults.DefaultBatchSize),
Description: "Maximum size of batch before it gets written to the destination.",
Type: config.ParameterTypeInt,
},
configDestinationBatchDelay: {
Default: d.defaults.DefaultBatchDelay.String(),
Description: "Maximum delay before an incomplete batch is written to the destination.",
Type: config.ParameterTypeDuration,
},
})
}
func (d *destinationWithBatch) Configure(ctx context.Context, config map[string]string) error {
// Batching is actually implemented in the plugin adapter because it is the
// only place we have access to acknowledgments.
// We need to signal back to the adapter that batching is enabled. We do
// this by changing a pointer that is stored in the context. It's a bit
// hacky, but the only way to propagate a value back to the adapter without
// changing the interface.
d.defaults.setBatchEnabled(ctx, true)
// set defaults in the config, they will be visible to the caller as well
if config[configDestinationBatchSize] == "" {
config[configDestinationBatchSize] = strconv.Itoa(d.defaults.DefaultBatchSize)
}
if config[configDestinationBatchDelay] == "" {
config[configDestinationBatchDelay] = d.defaults.DefaultBatchDelay.String()
}
return d.Destination.Configure(ctx, config)
}
// -- DestinationWithRateLimit -------------------------------------------------
const (
configDestinationRatePerSecond = "sdk.rate.perSecond"
configDestinationRateBurst = "sdk.rate.burst"
)
// DestinationWithRateLimit adds support for rate limiting to the destination.
// It adds two parameters to the destination config:
// - `sdk.rate.perSecond` - Maximum times the Write function can be called per
// second (0 means no rate limit).
// - `sdk.rate.burst` - Allow bursts of at most X writes (0 means that bursts
// are not allowed).
//
// To change the defaults of these parameters use the fields of this struct.
type DestinationWithRateLimit struct {
// DefaultRatePerSecond is the default value for the rate per second.
DefaultRatePerSecond float64
// DefaultBurst is the default value for the allowed burst count.
DefaultBurst int
}
func (d DestinationWithRateLimit) RatePerSecondParameterName() string {
return configDestinationRatePerSecond
}
func (d DestinationWithRateLimit) RateBurstParameterName() string {
return configDestinationRateBurst
}
// Wrap a Destination into the rate limiting middleware.
func (d DestinationWithRateLimit) Wrap(impl Destination) Destination {
return &destinationWithRateLimit{
Destination: impl,
defaults: d,
}
}
type destinationWithRateLimit struct {
Destination
defaults DestinationWithRateLimit
limiter *rate.Limiter
}
func (d *destinationWithRateLimit) Parameters() config.Parameters {
return mergeParameters(d.Destination.Parameters(), config.Parameters{
configDestinationRatePerSecond: {
Default: strconv.FormatFloat(d.defaults.DefaultRatePerSecond, 'f', -1, 64),
Description: "Maximum times records can be written per second (0 means no rate limit).",
Type: config.ParameterTypeFloat,
},
configDestinationRateBurst: {
Default: strconv.Itoa(d.defaults.DefaultBurst),
Description: "Allow bursts of at most X writes (1 or less means that bursts are not allowed). Only takes effect if a rate limit per second is set.",
Type: config.ParameterTypeInt,
},
})
}
func (d *destinationWithRateLimit) Configure(ctx context.Context, config map[string]string) error {
err := d.Destination.Configure(ctx, config)
if err != nil {
return err
}
limit := rate.Limit(d.defaults.DefaultRatePerSecond)
burst := d.defaults.DefaultBurst
limitRaw := config[configDestinationRatePerSecond]
if limitRaw != "" {
limitFloat, err := strconv.ParseFloat(limitRaw, 64)
if err != nil {
return fmt.Errorf("invalid %s: %w", configDestinationRatePerSecond, err)
}
limit = rate.Limit(limitFloat)
}
burstRaw := config[configDestinationRateBurst]
if burstRaw != "" {
burstInt, err := strconv.Atoi(burstRaw)
if err != nil {
return fmt.Errorf("invalid %s: %w", configDestinationRateBurst, err)
}
burst = burstInt
}
if limit > 0 {
if burst <= 0 {
burst = 1 // non-positive numbers would prevent all writes, we don't allow that, we default it to 1
}
d.limiter = rate.NewLimiter(limit, burst)
}
return nil
}
func (d *destinationWithRateLimit) Write(ctx context.Context, recs []opencdc.Record) (int, error) {
if d.limiter != nil {
err := d.limiter.Wait(ctx)
if err != nil {
return 0, fmt.Errorf("rate limiter: %w", err)
}
}
return d.Destination.Write(ctx, recs)
}
// -- DestinationWithRecordFormat ----------------------------------------------
const (
configDestinationRecordFormat = "sdk.record.format"
configDestinationRecordFormatOptions = "sdk.record.format.options"
)
// DestinationWithRecordFormat adds support for changing the output format of
// records, specifically of the Record.Bytes method. It adds two parameters to
// the destination config:
// - `sdk.record.format` - The format of the output record. The inclusion
// validation exposes a list of valid options.
// - `sdk.record.format.options` - Options are used to configure the format.
type DestinationWithRecordFormat struct {
// DefaultRecordFormat is the default record format.
DefaultRecordFormat string
RecordSerializers []RecordSerializer
}
func (d DestinationWithRecordFormat) RecordFormatParameterName() string {
return configDestinationRecordFormat
}
func (d DestinationWithRecordFormat) RecordFormatOptionsParameterName() string {
return configDestinationRecordFormatOptions
}
// DefaultRecordSerializers returns the list of record serializers that are used
// if DestinationWithRecordFormat.RecordSerializers is nil.
func (d DestinationWithRecordFormat) DefaultRecordSerializers() []RecordSerializer {
serializers := []RecordSerializer{
// define specific serializers here
TemplateRecordSerializer{},
}
// add generic serializers here, they are combined in all possible combinations
genericConverters := []Converter{
OpenCDCConverter{},
DebeziumConverter{},
}
genericEncoders := []Encoder{
JSONEncoder{},
}
for _, c := range genericConverters {
for _, e := range genericEncoders {
serializers = append(
serializers,
GenericRecordSerializer{
Converter: c,
Encoder: e,
},
)
}
}
return serializers
}
// Wrap a Destination into the record format middleware.
func (d DestinationWithRecordFormat) Wrap(impl Destination) Destination {
if d.DefaultRecordFormat == "" {
d.DefaultRecordFormat = defaultSerializer.Name()
}
if len(d.RecordSerializers) == 0 {
d.RecordSerializers = d.DefaultRecordSerializers()
}
// sort record serializers by name to ensure we can binary search them
sort.Slice(d.RecordSerializers, func(i, j int) bool { return d.RecordSerializers[i].Name() < d.RecordSerializers[j].Name() })
return &destinationWithRecordFormat{
Destination: impl,
defaults: d,
}
}
type destinationWithRecordFormat struct {
Destination
defaults DestinationWithRecordFormat
serializer RecordSerializer
}
func (d *destinationWithRecordFormat) formats() []string {
names := make([]string, len(d.defaults.RecordSerializers))
i := 0
for _, c := range d.defaults.RecordSerializers {
names[i] = c.Name()
i++
}
return names
}
func (d *destinationWithRecordFormat) Parameters() config.Parameters {
return mergeParameters(d.Destination.Parameters(), config.Parameters{
configDestinationRecordFormat: {
Default: d.defaults.DefaultRecordFormat,
Description: "The format of the output record.",
Validations: []config.Validation{
config.ValidationInclusion{List: d.formats()},
},
},
configDestinationRecordFormatOptions: {
Description: "Options to configure the chosen output record format. Options are key=value pairs separated with comma (e.g. opt1=val2,opt2=val2).",
},
})
}
func (d *destinationWithRecordFormat) Configure(ctx context.Context, config map[string]string) error {
err := d.Destination.Configure(ctx, config)
if err != nil {
return err
}
format := d.defaults.DefaultRecordFormat
if f, ok := config[configDestinationRecordFormat]; ok {
format = f
}
i := sort.SearchStrings(d.formats(), format)
// if the string is not found i is equal to the size of the slice
if i == len(d.defaults.RecordSerializers) {
return fmt.Errorf("invalid %s: %q not found in %v", configDestinationRecordFormat, format, d.formats())
}
serializer := d.defaults.RecordSerializers[i]
serializer, err = serializer.Configure(config[configDestinationRecordFormatOptions])
if err != nil {
return fmt.Errorf("invalid %s for %q: %w", configDestinationRecordFormatOptions, format, err)
}
d.serializer = serializer
return nil
}
func (d *destinationWithRecordFormat) Write(ctx context.Context, recs []opencdc.Record) (int, error) {
for i := range recs {
recs[i].SetSerializer(d.serializer)
}
return d.Destination.Write(ctx, recs)
}