-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathschema_registry.go
420 lines (369 loc) · 12.3 KB
/
schema_registry.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
package kafka
import (
"encoding/binary"
"encoding/json"
"fmt"
"net/http"
"github.com/grafana/sobek"
"github.com/linkedin/goavro/v2"
"github.com/riferrei/srclient"
"github.com/santhosh-tekuri/jsonschema/v5"
"go.k6.io/k6/js/common"
)
type Element string
const (
Key Element = "key"
Value Element = "value"
MagicPrefixSize int = 5
ConcurrentRequests int = 16
)
type BasicAuth struct {
Username string `json:"username"`
Password string `json:"password"`
}
type SchemaRegistryConfig struct {
EnableCaching bool `json:"enableCaching"`
URL string `json:"url"`
BasicAuth BasicAuth `json:"basicAuth"`
TLS TLSConfig `json:"tls"`
}
const (
TopicNameStrategy string = "TopicNameStrategy"
RecordNameStrategy string = "RecordNameStrategy"
TopicRecordNameStrategy string = "TopicRecordNameStrategy"
)
// Schema is a wrapper around the schema registry schema.
// The Codec() and JsonSchema() methods will return the respective codecs (duck-typing).
type Schema struct {
EnableCaching bool `json:"enableCaching"`
ID int `json:"id"`
Schema string `json:"schema"`
SchemaType *srclient.SchemaType `json:"schemaType"`
Version int `json:"version"`
References []srclient.Reference `json:"references"`
Subject string `json:"subject"`
codec *goavro.Codec
jsonSchema *jsonschema.Schema
}
type SubjectNameConfig struct {
Schema string `json:"schema"`
Topic string `json:"topic"`
Element Element `json:"element"`
SubjectNameStrategy string `json:"subjectNameStrategy"`
}
type WireFormat struct {
SchemaID int `json:"schemaId"`
Data []byte `json:"data"`
}
// Codec ensures access to Codec
// Will try to initialize a new one if it hasn't been initialized before
// Will return nil if it can't initialize a codec from the schema
func (s *Schema) Codec() *goavro.Codec {
if s.codec == nil {
codec, err := goavro.NewCodec(s.Schema)
if err == nil {
s.codec = codec
}
}
return s.codec
}
// JsonSchema ensures access to JsonSchema
// Will try to initialize a new one if it hasn't been initialized before
// Will return nil if it can't initialize a json schema from the schema
func (s *Schema) JsonSchema() *jsonschema.Schema {
if s.jsonSchema == nil {
jsonSchema, err := jsonschema.CompileString("schema.json", s.Schema)
if err == nil {
s.jsonSchema = jsonSchema
}
}
return s.jsonSchema
}
func (k *Kafka) schemaRegistryClientClass(call sobek.ConstructorCall) *sobek.Object {
runtime := k.vu.Runtime()
var configuration *SchemaRegistryConfig
var schemaRegistryClient *srclient.SchemaRegistryClient
if len(call.Arguments) == 1 {
if params, ok := call.Argument(0).Export().(map[string]interface{}); ok {
if b, err := json.Marshal(params); err != nil {
common.Throw(runtime, err)
} else {
if err = json.Unmarshal(b, &configuration); err != nil {
common.Throw(runtime, err)
}
}
}
schemaRegistryClient = k.schemaRegistryClient(configuration)
}
schemaRegistryClientObject := runtime.NewObject()
// This is the schema registry client object itself
if err := schemaRegistryClientObject.Set("This", schemaRegistryClient); err != nil {
common.Throw(runtime, err)
}
err := schemaRegistryClientObject.Set("getSchema", func(call sobek.FunctionCall) sobek.Value {
if len(call.Arguments) == 0 {
common.Throw(runtime, ErrNotEnoughArguments)
}
if schemaRegistryClient == nil {
common.Throw(runtime, ErrNoSchemaRegistryClient)
}
var schema *Schema
if params, ok := call.Argument(0).Export().(map[string]interface{}); ok {
if b, err := json.Marshal(params); err != nil {
common.Throw(runtime, err)
} else {
if err = json.Unmarshal(b, &schema); err != nil {
common.Throw(runtime, err)
}
}
}
return runtime.ToValue(k.getSchema(schemaRegistryClient, schema))
})
if err != nil {
common.Throw(runtime, err)
}
err = schemaRegistryClientObject.Set("createSchema", func(call sobek.FunctionCall) sobek.Value {
if len(call.Arguments) == 0 {
common.Throw(runtime, ErrNotEnoughArguments)
}
if schemaRegistryClient == nil {
common.Throw(runtime, ErrNoSchemaRegistryClient)
}
var schema *Schema
if params, ok := call.Argument(0).Export().(map[string]interface{}); ok {
if b, err := json.Marshal(params); err != nil {
common.Throw(runtime, err)
} else {
if err = json.Unmarshal(b, &schema); err != nil {
common.Throw(runtime, err)
}
}
}
return runtime.ToValue(k.createSchema(schemaRegistryClient, schema))
})
if err != nil {
common.Throw(runtime, err)
}
var subjectNameConfig *SubjectNameConfig
err = schemaRegistryClientObject.Set("getSubjectName", func(call sobek.FunctionCall) sobek.Value {
if len(call.Arguments) == 0 {
common.Throw(runtime, ErrNotEnoughArguments)
}
if params, ok := call.Argument(0).Export().(map[string]interface{}); ok {
if b, err := json.Marshal(params); err != nil {
common.Throw(runtime, err)
} else {
if err = json.Unmarshal(b, &subjectNameConfig); err != nil {
common.Throw(runtime, err)
}
}
}
return runtime.ToValue(k.getSubjectName(subjectNameConfig))
})
if err != nil {
common.Throw(runtime, err)
}
err = schemaRegistryClientObject.Set("serialize", func(call sobek.FunctionCall) sobek.Value {
if len(call.Arguments) == 0 {
common.Throw(runtime, ErrNotEnoughArguments)
}
var metadata *Container
if params, ok := call.Argument(0).Export().(map[string]interface{}); ok {
if b, err := json.Marshal(params); err != nil {
common.Throw(runtime, err)
} else {
if err = json.Unmarshal(b, &metadata); err != nil {
common.Throw(runtime, err)
}
}
}
return runtime.ToValue(k.serialize(metadata))
})
if err != nil {
common.Throw(runtime, err)
}
err = schemaRegistryClientObject.Set("deserialize", func(call sobek.FunctionCall) sobek.Value {
if len(call.Arguments) == 0 {
common.Throw(runtime, ErrNotEnoughArguments)
}
var metadata *Container
if params, ok := call.Argument(0).Export().(map[string]interface{}); ok {
if b, err := json.Marshal(params); err != nil {
common.Throw(runtime, err)
} else {
if err = json.Unmarshal(b, &metadata); err != nil {
common.Throw(runtime, err)
}
}
}
return runtime.ToValue(k.deserialize(metadata))
})
if err != nil {
common.Throw(runtime, err)
}
return schemaRegistryClientObject
}
// schemaRegistryClient creates a schemaRegistryClient instance
// with the given configuration. It will also configure auth and TLS credentials if exists.
func (k *Kafka) schemaRegistryClient(config *SchemaRegistryConfig) *srclient.SchemaRegistryClient {
runtime := k.vu.Runtime()
var srClient *srclient.SchemaRegistryClient
tlsConfig, err := GetTLSConfig(config.TLS)
if err != nil {
// Ignore the error if we're not using TLS
if err.Code != noTLSConfig {
common.Throw(runtime, err)
}
srClient = srclient.CreateSchemaRegistryClient(config.URL)
}
if tlsConfig != nil {
httpClient := &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
},
}
srClient = srclient.CreateSchemaRegistryClientWithOptions(
config.URL, httpClient, ConcurrentRequests)
}
if config.BasicAuth.Username != "" && config.BasicAuth.Password != "" {
srClient.SetCredentials(config.BasicAuth.Username, config.BasicAuth.Password)
}
// The default value for a boolean is false, so the caching
// feature of the srclient package will be disabled.
srClient.CachingEnabled(config.EnableCaching)
return srClient
}
// getSchema returns the schema for the given subject and schema ID and version.
func (k *Kafka) getSchema(client *srclient.SchemaRegistryClient, schema *Schema) *Schema {
// If EnableCache is set, check if the schema is in the cache.
if schema.EnableCaching {
if schema, ok := k.schemaCache[schema.Subject]; ok {
return schema
}
}
runtime := k.vu.Runtime()
// The client always caches the schema.
var schemaInfo *srclient.Schema
var err error
// Default version of the schema is the latest version.
if schema.Version == 0 {
schemaInfo, err = client.GetLatestSchema(schema.Subject)
} else {
schemaInfo, err = client.GetSchemaByVersion(
schema.Subject, schema.Version)
}
if err == nil {
wrappedSchema := &Schema{
EnableCaching: schema.EnableCaching,
ID: schemaInfo.ID(),
Version: schemaInfo.Version(),
Schema: schemaInfo.Schema(),
SchemaType: schemaInfo.SchemaType(),
References: schemaInfo.References(),
Subject: schema.Subject,
}
// If the Cache is set, cache the schema.
if wrappedSchema.EnableCaching {
k.schemaCache[wrappedSchema.Subject] = wrappedSchema
}
return wrappedSchema
} else {
err := NewXk6KafkaError(schemaNotFound, "Failed to get schema from schema registry", err)
common.Throw(runtime, err)
return nil
}
}
// createSchema creates a new schema in the schema registry.
func (k *Kafka) createSchema(client *srclient.SchemaRegistryClient, schema *Schema) *Schema {
runtime := k.vu.Runtime()
schemaInfo, err := client.CreateSchema(
schema.Subject,
schema.Schema,
*schema.SchemaType,
schema.References...)
if err != nil {
err := NewXk6KafkaError(schemaCreationFailed, "Failed to create schema.", err)
common.Throw(runtime, err)
return nil
}
wrappedSchema := &Schema{
EnableCaching: schema.EnableCaching,
ID: schemaInfo.ID(),
Version: schemaInfo.Version(),
Schema: schemaInfo.Schema(),
SchemaType: schemaInfo.SchemaType(),
References: schemaInfo.References(),
Subject: schema.Subject,
}
if schema.EnableCaching {
k.schemaCache[schema.Subject] = wrappedSchema
}
return wrappedSchema
}
// getSubjectName returns the subject name for the given schema and topic.
func (k *Kafka) getSubjectName(subjectNameConfig *SubjectNameConfig) string {
if subjectNameConfig.SubjectNameStrategy == "" ||
subjectNameConfig.SubjectNameStrategy == TopicNameStrategy {
return subjectNameConfig.Topic + "-" + string(subjectNameConfig.Element)
}
runtime := k.vu.Runtime()
var schemaMap map[string]interface{}
err := json.Unmarshal([]byte(subjectNameConfig.Schema), &schemaMap)
if err != nil {
common.Throw(runtime, NewXk6KafkaError(
failedUnmarshalSchema, "Failed to unmarshal schema", err))
}
recordName := ""
if namespace, ok := schemaMap["namespace"]; ok {
if namespace, ok := namespace.(string); ok {
recordName = namespace + "."
} else {
err := NewXk6KafkaError(failedTypeCast, "Failed to cast to string", nil)
common.Throw(runtime, err)
}
}
if name, ok := schemaMap["name"]; ok {
if name, ok := name.(string); ok {
recordName += name
} else {
err := NewXk6KafkaError(failedTypeCast, "Failed to cast to string", nil)
common.Throw(runtime, err)
}
}
if subjectNameConfig.SubjectNameStrategy == RecordNameStrategy {
return recordName
}
if subjectNameConfig.SubjectNameStrategy == TopicRecordNameStrategy {
return subjectNameConfig.Topic + "-" + recordName
}
err = NewXk6KafkaError(failedToEncode, fmt.Sprintf(
"Unknown subject name strategy: %v", subjectNameConfig.SubjectNameStrategy), nil)
common.Throw(runtime, err)
return ""
}
// encodeWireFormat adds the proprietary 5-byte prefix to the Avro, ProtoBuf or
// JSONSchema payload.
// https://docs.confluent.io/platform/current/schema-registry/serdes-develop/index.html#wire-format
func (k *Kafka) encodeWireFormat(data []byte, schemaID int) []byte {
schemaIDBytes := make([]byte, MagicPrefixSize-1)
binary.BigEndian.PutUint32(schemaIDBytes, uint32(schemaID))
return append(append([]byte{0}, schemaIDBytes...), data...)
}
// decodeWireFormat removes the proprietary 5-byte prefix from the Avro, ProtoBuf
// or JSONSchema payload.
// https://docs.confluent.io/platform/current/schema-registry/serdes-develop/index.html#wire-format
func (k *Kafka) decodeWireFormat(message []byte) []byte {
runtime := k.vu.Runtime()
if len(message) < MagicPrefixSize {
err := NewXk6KafkaError(messageTooShort,
"Invalid message: message too short to contain schema id.", nil)
common.Throw(runtime, err)
return nil
}
if message[0] != 0 {
err := NewXk6KafkaError(messageTooShort, "Invalid message: invalid start byte.", nil)
common.Throw(runtime, err)
return nil
}
return message[MagicPrefixSize:]
}