-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
encoder.go
625 lines (562 loc) · 21.3 KB
/
encoder.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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
// Copyright 2018 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package changefeedccl
import (
"bytes"
"context"
"encoding/binary"
gojson "encoding/json"
"io/ioutil"
"net/url"
"path/filepath"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/ccl/changefeedccl/changefeedbase"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/rowenc"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/httputil"
"github.com/cockroachdb/cockroach/pkg/util/json"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/errors"
)
const (
confluentSchemaContentType = `application/vnd.schemaregistry.v1+json`
confluentSubjectSuffixKey = `-key`
confluentSubjectSuffixValue = `-value`
)
// encodeRow holds all the pieces necessary to encode a row change into a key or
// value.
type encodeRow struct {
// datums is the new value of a changed table row.
datums rowenc.EncDatumRow
// updated is the mvcc timestamp corresponding to the latest update in
// `datums`.
updated hlc.Timestamp
// deleted is true if row is a deletion. In this case, only the primary
// key columns are guaranteed to be set in `datums`.
deleted bool
// tableDesc is a TableDescriptor for the table containing `datums`.
// It's valid for interpreting the row at `updated`.
tableDesc catalog.TableDescriptor
// prevDatums is the old value of a changed table row. The field is set
// to nil if the before value for changes was not requested (OptDiff).
prevDatums rowenc.EncDatumRow
// prevDeleted is true if prevDatums is missing or is a deletion.
prevDeleted bool
// prevTableDesc is a TableDescriptor for the table containing `prevDatums`.
// It's valid for interpreting the row at `updated.Prev()`.
prevTableDesc catalog.TableDescriptor
}
// Encoder turns a row into a serialized changefeed key, value, or resolved
// timestamp. It represents one of the `format=` changefeed options.
type Encoder interface {
// EncodeKey encodes the primary key of the given row. The columns of the
// datums are expected to match 1:1 with the `Columns` field of the
// `TableDescriptor`, but only the primary key fields will be used. The
// returned bytes are only valid until the next call to Encode*.
EncodeKey(context.Context, encodeRow) ([]byte, error)
// EncodeValue encodes the primary key of the given row. The columns of the
// datums are expected to match 1:1 with the `Columns` field of the
// `TableDescriptor`. The returned bytes are only valid until the next call
// to Encode*.
EncodeValue(context.Context, encodeRow) ([]byte, error)
// EncodeResolvedTimestamp encodes a resolved timestamp payload for the
// given topic name. The returned bytes are only valid until the next call
// to Encode*.
EncodeResolvedTimestamp(context.Context, string, hlc.Timestamp) ([]byte, error)
}
func getEncoder(
opts map[string]string, targets jobspb.ChangefeedTargets, u *sinkURL,
) (Encoder, error) {
switch changefeedbase.FormatType(opts[changefeedbase.OptFormat]) {
case ``, changefeedbase.OptFormatJSON:
return makeJSONEncoder(opts)
case changefeedbase.OptFormatAvro:
return newConfluentAvroEncoder(opts, targets, u)
case changefeedbase.OptFormatNative:
return &nativeEncoder{}, nil
default:
return nil, errors.Errorf(`unknown %s: %s`, changefeedbase.OptFormat, opts[changefeedbase.OptFormat])
}
}
// jsonEncoder encodes changefeed entries as JSON. Keys are the primary key
// columns in a JSON array. Values are a JSON object mapping every column name
// to its value. Updated timestamps in rows and resolved timestamp payloads are
// stored in a sub-object under the `__crdb__` key in the top-level JSON object.
type jsonEncoder struct {
updatedField, beforeField, wrapped, keyOnly, keyInValue bool
alloc rowenc.DatumAlloc
buf bytes.Buffer
}
var _ Encoder = &jsonEncoder{}
func makeJSONEncoder(opts map[string]string) (*jsonEncoder, error) {
e := &jsonEncoder{
keyOnly: changefeedbase.EnvelopeType(opts[changefeedbase.OptEnvelope]) == changefeedbase.OptEnvelopeKeyOnly,
wrapped: changefeedbase.EnvelopeType(opts[changefeedbase.OptEnvelope]) == changefeedbase.OptEnvelopeWrapped,
}
_, e.updatedField = opts[changefeedbase.OptUpdatedTimestamps]
_, e.beforeField = opts[changefeedbase.OptDiff]
if e.beforeField && !e.wrapped {
return nil, errors.Errorf(`%s is only usable with %s=%s`,
changefeedbase.OptDiff, changefeedbase.OptEnvelope, changefeedbase.OptEnvelopeWrapped)
}
_, e.keyInValue = opts[changefeedbase.OptKeyInValue]
if e.keyInValue && !e.wrapped {
return nil, errors.Errorf(`%s is only usable with %s=%s`,
changefeedbase.OptKeyInValue, changefeedbase.OptEnvelope, changefeedbase.OptEnvelopeWrapped)
}
return e, nil
}
// EncodeKey implements the Encoder interface.
func (e *jsonEncoder) EncodeKey(_ context.Context, row encodeRow) ([]byte, error) {
jsonEntries, err := e.encodeKeyRaw(row)
if err != nil {
return nil, err
}
j, err := json.MakeJSON(jsonEntries)
if err != nil {
return nil, err
}
e.buf.Reset()
j.Format(&e.buf)
return e.buf.Bytes(), nil
}
func (e *jsonEncoder) encodeKeyRaw(row encodeRow) ([]interface{}, error) {
colIdxByID := catalog.ColumnIDToOrdinalMap(row.tableDesc.PublicColumns())
primaryIndex := row.tableDesc.GetPrimaryIndex()
jsonEntries := make([]interface{}, primaryIndex.NumColumns())
for i := 0; i < primaryIndex.NumColumns(); i++ {
colID := primaryIndex.GetColumnID(i)
idx, ok := colIdxByID.Get(colID)
if !ok {
return nil, errors.Errorf(`unknown column id: %d`, colID)
}
datum := row.datums[idx]
datum, col := row.datums[idx], row.tableDesc.PublicColumns()[idx]
if err := datum.EnsureDecoded(col.GetType(), &e.alloc); err != nil {
return nil, err
}
var err error
jsonEntries[i], err = tree.AsJSON(datum.Datum, time.UTC)
if err != nil {
return nil, err
}
}
return jsonEntries, nil
}
// EncodeValue implements the Encoder interface.
func (e *jsonEncoder) EncodeValue(_ context.Context, row encodeRow) ([]byte, error) {
if e.keyOnly || (!e.wrapped && row.deleted) {
return nil, nil
}
var after map[string]interface{}
if !row.deleted {
columns := row.tableDesc.PublicColumns()
after = make(map[string]interface{}, len(columns))
for i, col := range columns {
datum := row.datums[i]
if err := datum.EnsureDecoded(col.GetType(), &e.alloc); err != nil {
return nil, err
}
var err error
after[col.GetName()], err = tree.AsJSON(datum.Datum, time.UTC)
if err != nil {
return nil, err
}
}
}
var before map[string]interface{}
if row.prevDatums != nil && !row.prevDeleted {
columns := row.prevTableDesc.PublicColumns()
before = make(map[string]interface{}, len(columns))
for i, col := range columns {
datum := row.prevDatums[i]
if err := datum.EnsureDecoded(col.GetType(), &e.alloc); err != nil {
return nil, err
}
var err error
before[col.GetName()], err = tree.AsJSON(datum.Datum, time.UTC)
if err != nil {
return nil, err
}
}
}
var jsonEntries map[string]interface{}
if e.wrapped {
if after != nil {
jsonEntries = map[string]interface{}{`after`: after}
} else {
jsonEntries = map[string]interface{}{`after`: nil}
}
if e.beforeField {
if before != nil {
jsonEntries[`before`] = before
} else {
jsonEntries[`before`] = nil
}
}
if e.keyInValue {
keyEntries, err := e.encodeKeyRaw(row)
if err != nil {
return nil, err
}
jsonEntries[`key`] = keyEntries
}
} else {
jsonEntries = after
}
if e.updatedField {
var meta map[string]interface{}
if e.wrapped {
meta = jsonEntries
} else {
meta = make(map[string]interface{}, 1)
jsonEntries[jsonMetaSentinel] = meta
}
meta[`updated`] = row.updated.AsOfSystemTime()
}
j, err := json.MakeJSON(jsonEntries)
if err != nil {
return nil, err
}
e.buf.Reset()
j.Format(&e.buf)
return e.buf.Bytes(), nil
}
// EncodeResolvedTimestamp implements the Encoder interface.
func (e *jsonEncoder) EncodeResolvedTimestamp(
_ context.Context, _ string, resolved hlc.Timestamp,
) ([]byte, error) {
meta := map[string]interface{}{
`resolved`: tree.TimestampToDecimalDatum(resolved).Decimal.String(),
}
var jsonEntries interface{}
if e.wrapped {
jsonEntries = meta
} else {
jsonEntries = map[string]interface{}{
jsonMetaSentinel: meta,
}
}
return gojson.Marshal(jsonEntries)
}
// confluentAvroEncoder encodes changefeed entries as Avro's binary or textual
// JSON format. Keys are the primary key columns in a record. Values are all
// columns in a record.
type confluentAvroEncoder struct {
registryURL string
schemaPrefix string
updatedField, beforeField, keyOnly bool
targets jobspb.ChangefeedTargets
keyCache map[tableIDAndVersion]confluentRegisteredKeySchema
valueCache map[tableIDAndVersionPair]confluentRegisteredEnvelopeSchema
resolvedCache map[string]confluentRegisteredEnvelopeSchema
httpClient *httputil.Client
}
type tableIDAndVersion uint64
type tableIDAndVersionPair [2]tableIDAndVersion // [before, after]
func makeTableIDAndVersion(id descpb.ID, version descpb.DescriptorVersion) tableIDAndVersion {
return tableIDAndVersion(id)<<32 + tableIDAndVersion(version)
}
type confluentRegisteredKeySchema struct {
schema *avroDataRecord
registryID int32
}
type confluentRegisteredEnvelopeSchema struct {
schema *avroEnvelopeRecord
registryID int32
}
var _ Encoder = &confluentAvroEncoder{}
func newConfluentAvroEncoder(
opts map[string]string, targets jobspb.ChangefeedTargets, u *sinkURL,
) (*confluentAvroEncoder, error) {
e := &confluentAvroEncoder{registryURL: opts[changefeedbase.OptConfluentSchemaRegistry]}
if u != nil {
err := e.setupHTTPClient(*u)
if err != nil {
return nil, err
}
} else {
e.httpClient = httputil.DefaultClient
}
e.schemaPrefix = opts[changefeedbase.OptAvroSchemaPrefix]
e.targets = targets
switch opts[changefeedbase.OptEnvelope] {
case string(changefeedbase.OptEnvelopeKeyOnly):
e.keyOnly = true
case string(changefeedbase.OptEnvelopeWrapped):
default:
return nil, errors.Errorf(`%s=%s is not supported with %s=%s`,
changefeedbase.OptEnvelope, opts[changefeedbase.OptEnvelope], changefeedbase.OptFormat, changefeedbase.OptFormatAvro)
}
_, e.updatedField = opts[changefeedbase.OptUpdatedTimestamps]
if e.updatedField && e.keyOnly {
return nil, errors.Errorf(`%s is only usable with %s=%s`,
changefeedbase.OptUpdatedTimestamps, changefeedbase.OptEnvelope, changefeedbase.OptEnvelopeWrapped)
}
_, e.beforeField = opts[changefeedbase.OptDiff]
if e.beforeField && e.keyOnly {
return nil, errors.Errorf(`%s is only usable with %s=%s`,
changefeedbase.OptDiff, changefeedbase.OptEnvelope, changefeedbase.OptEnvelopeWrapped)
}
if _, ok := opts[changefeedbase.OptKeyInValue]; ok {
return nil, errors.Errorf(`%s is not supported with %s=%s`,
changefeedbase.OptKeyInValue, changefeedbase.OptFormat, changefeedbase.OptFormatAvro)
}
if len(e.registryURL) == 0 {
return nil, errors.Errorf(`WITH option %s is required for %s=%s`,
changefeedbase.OptConfluentSchemaRegistry, changefeedbase.OptFormat, changefeedbase.OptFormatAvro)
}
e.keyCache = make(map[tableIDAndVersion]confluentRegisteredKeySchema)
e.valueCache = make(map[tableIDAndVersionPair]confluentRegisteredEnvelopeSchema)
e.resolvedCache = make(map[string]confluentRegisteredEnvelopeSchema)
return e, nil
}
// Setup the httputil.Client to use when dialing Confluent schema registry. If `registry_client_cert`
// and `registry_client_key` are set as query params in the sinkURL, client should trust the corresponding
// cert while dialing. Otherwise, use the DefaultConfig.
func (e *confluentAvroEncoder) setupHTTPClient(u sinkURL) error {
var tlsEnabled bool
var caCert []byte
if tlsEnabledString := u.consumeParam(changefeedbase.SinkParamRegistryTLSEnabled); tlsEnabledString != "" {
_, err := strToBool(tlsEnabledString, &tlsEnabled)
if err != nil {
return errors.Wrapf(err, `param %s must be a bool`, changefeedbase.SinkParamRegistryTLSEnabled)
}
}
if caCertString := u.consumeParam(changefeedbase.SinkParamRegistryCACert); caCertString != "" {
err := decodeBase64FromString(caCertString, &caCert)
if err != nil {
return errors.Wrapf(err, `param %s must be base 64 encoded`, changefeedbase.SinkParamRegistryCACert)
}
}
if tlsEnabled {
var err error
e.httpClient, err = newClientFromTLSKeyPair(caCert)
if err != nil {
return err
}
} else if caCert != nil {
return errors.Errorf(`%s requires %s=true`, changefeedbase.SinkParamRegistryCACert, changefeedbase.SinkParamRegistryTLSEnabled)
} else {
e.httpClient = httputil.DefaultClient
}
return nil
}
// Get the raw SQL-formatted string for a table name
// and apply full_table_name and avro_schema_prefix options
func (e *confluentAvroEncoder) rawTableName(desc catalog.TableDescriptor) string {
return e.schemaPrefix + e.targets[desc.GetID()].StatementTimeName
}
// EncodeKey implements the Encoder interface.
func (e *confluentAvroEncoder) EncodeKey(ctx context.Context, row encodeRow) ([]byte, error) {
cacheKey := makeTableIDAndVersion(row.tableDesc.GetID(), row.tableDesc.GetVersion())
registered, ok := e.keyCache[cacheKey]
if !ok {
var err error
tableName := e.rawTableName(row.tableDesc)
registered.schema, err = indexToAvroSchema(row.tableDesc, row.tableDesc.GetPrimaryIndex(), tableName, e.schemaPrefix)
if err != nil {
return nil, err
}
// NB: This uses the kafka name escaper because it has to match the name
// of the kafka topic.
subject := SQLNameToKafkaName(tableName) + confluentSubjectSuffixKey
registered.registryID, err = e.register(ctx, ®istered.schema.avroRecord, subject)
if err != nil {
return nil, err
}
// TODO(dan): Bound the size of this cache.
e.keyCache[cacheKey] = registered
}
// https://docs.confluent.io/current/schema-registry/docs/serializer-formatter.html#wire-format
header := []byte{
changefeedbase.ConfluentAvroWireFormatMagic,
0, 0, 0, 0, // Placeholder for the ID.
}
binary.BigEndian.PutUint32(header[1:5], uint32(registered.registryID))
return registered.schema.BinaryFromRow(header, row.datums)
}
// EncodeValue implements the Encoder interface.
func (e *confluentAvroEncoder) EncodeValue(ctx context.Context, row encodeRow) ([]byte, error) {
if e.keyOnly {
return nil, nil
}
var cacheKey tableIDAndVersionPair
if e.beforeField && row.prevTableDesc != nil {
cacheKey[0] = makeTableIDAndVersion(row.prevTableDesc.GetID(), row.prevTableDesc.GetVersion())
}
cacheKey[1] = makeTableIDAndVersion(row.tableDesc.GetID(), row.tableDesc.GetVersion())
registered, ok := e.valueCache[cacheKey]
if !ok {
var beforeDataSchema *avroDataRecord
if e.beforeField && row.prevTableDesc != nil {
var err error
beforeDataSchema, err = tableToAvroSchema(row.prevTableDesc, `before`, e.schemaPrefix)
if err != nil {
return nil, err
}
}
afterDataSchema, err := tableToAvroSchema(row.tableDesc, avroSchemaNoSuffix, e.schemaPrefix)
if err != nil {
return nil, err
}
opts := avroEnvelopeOpts{afterField: true, beforeField: e.beforeField, updatedField: e.updatedField}
registered.schema, err = envelopeToAvroSchema(e.rawTableName(row.tableDesc), opts, beforeDataSchema, afterDataSchema, e.schemaPrefix)
if err != nil {
return nil, err
}
// NB: This uses the kafka name escaper because it has to match the name
// of the kafka topic.
subject := SQLNameToKafkaName(e.rawTableName(row.tableDesc)) + confluentSubjectSuffixValue
registered.registryID, err = e.register(ctx, ®istered.schema.avroRecord, subject)
if err != nil {
return nil, err
}
// TODO(dan): Bound the size of this cache.
e.valueCache[cacheKey] = registered
}
var meta avroMetadata
if registered.schema.opts.updatedField {
meta = map[string]interface{}{
`updated`: row.updated,
}
}
var beforeDatums, afterDatums rowenc.EncDatumRow
if row.prevDatums != nil && !row.prevDeleted {
beforeDatums = row.prevDatums
}
if !row.deleted {
afterDatums = row.datums
}
// https://docs.confluent.io/current/schema-registry/docs/serializer-formatter.html#wire-format
header := []byte{
changefeedbase.ConfluentAvroWireFormatMagic,
0, 0, 0, 0, // Placeholder for the ID.
}
binary.BigEndian.PutUint32(header[1:5], uint32(registered.registryID))
return registered.schema.BinaryFromRow(header, meta, beforeDatums, afterDatums)
}
// EncodeResolvedTimestamp implements the Encoder interface.
func (e *confluentAvroEncoder) EncodeResolvedTimestamp(
ctx context.Context, topic string, resolved hlc.Timestamp,
) ([]byte, error) {
registered, ok := e.resolvedCache[topic]
if !ok {
opts := avroEnvelopeOpts{resolvedField: true}
var err error
registered.schema, err = envelopeToAvroSchema(topic, opts, nil /* before */, nil /* after */, e.schemaPrefix /* namespace */)
if err != nil {
return nil, err
}
// NB: This uses the kafka name escaper because it has to match the name
// of the kafka topic.
subject := SQLNameToKafkaName(topic) + confluentSubjectSuffixValue
registered.registryID, err = e.register(ctx, ®istered.schema.avroRecord, subject)
if err != nil {
return nil, err
}
// TODO(dan): Bound the size of this cache.
e.resolvedCache[topic] = registered
}
var meta avroMetadata
if registered.schema.opts.resolvedField {
meta = map[string]interface{}{
`resolved`: resolved,
}
}
// https://docs.confluent.io/current/schema-registry/docs/serializer-formatter.html#wire-format
header := []byte{
changefeedbase.ConfluentAvroWireFormatMagic,
0, 0, 0, 0, // Placeholder for the ID.
}
binary.BigEndian.PutUint32(header[1:5], uint32(registered.registryID))
return registered.schema.BinaryFromRow(header, meta, nil /* beforeRow */, nil /* afterRow */)
}
func (e *confluentAvroEncoder) register(
ctx context.Context, schema *avroRecord, subject string,
) (int32, error) {
type confluentSchemaVersionRequest struct {
Schema string `json:"schema"`
}
type confluentSchemaVersionResponse struct {
ID int32 `json:"id"`
}
url, err := url.Parse(e.registryURL)
if err != nil {
return 0, err
}
url.Path = filepath.Join(url.EscapedPath(), `subjects`, subject, `versions`)
schemaStr := schema.codec.Schema()
if log.V(1) {
log.Infof(ctx, "registering avro schema %s %s", url, schemaStr)
}
req := confluentSchemaVersionRequest{Schema: schemaStr}
var buf bytes.Buffer
if err := gojson.NewEncoder(&buf).Encode(req); err != nil {
return 0, err
}
var id int32
// Since network services are often a source of flakes, add a few retries here
// before we give up and return an error that will bubble up and tear down the
// entire changefeed, though that error is marked as retryable so that the job
// itself can attempt to start the changefeed again. TODO(dt): If the registry
// is down or constantly returning errors, we can't make progress. Continuing
// to indicate that we're "running" in this case can be misleading, as we
// really aren't anymore. Right now the MO in CDC is try and try again
// forever, so doing so here is consistent with the behavior elsewhere, but we
// should revisit this more broadly as this pattern can easily mask real,
// actionable issues in the operator's environment that which they might be
// able to resolve if we made them visible in a failure instead.
if err := retry.WithMaxAttempts(ctx, base.DefaultRetryOptions(), 3, func() error {
resp, err := e.httpClient.Post(ctx, url.String(), confluentSchemaContentType, &buf)
if err != nil {
return errors.Wrap(err, "contacting confluent schema registry")
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
body, _ := ioutil.ReadAll(resp.Body)
return errors.Errorf(`registering schema to %s %s: %s`, url.String(), resp.Status, body)
}
var res confluentSchemaVersionResponse
if err := gojson.NewDecoder(resp.Body).Decode(&res); err != nil {
return errors.Wrap(err, "decoding confluent schema registry reply")
}
id = res.ID
return nil
}); err != nil {
log.Warningf(ctx, "%+v", err)
return 0, MarkRetryableError(err)
}
return id, nil
}
// nativeEncoder only implements EncodeResolvedTimestamp.
// Unfortunately, the encoder assumes that it operates with encodeRow -- something
// that's just not the case when emitting raw KVs.
// In addition, there is a kafka specific concept (topic) that's exposed at the Encoder level.
// TODO(yevgeniy): Refactor encoder interface so that it operates on kvfeed events.
// In addition, decouple the concept of topic from the Encoder.
type nativeEncoder struct{}
func (e *nativeEncoder) EncodeKey(ctx context.Context, row encodeRow) ([]byte, error) {
panic("EncodeKey should not be called on nativeEncoder")
}
func (e *nativeEncoder) EncodeValue(ctx context.Context, row encodeRow) ([]byte, error) {
panic("EncodeValue should not be called on nativeEncoder")
}
func (e *nativeEncoder) EncodeResolvedTimestamp(
ctx context.Context, s string, ts hlc.Timestamp,
) ([]byte, error) {
return protoutil.Marshal(&ts)
}
var _ Encoder = &nativeEncoder{}