-
Notifications
You must be signed in to change notification settings - Fork 70
/
mockSchemaRegistryClient.go
379 lines (313 loc) · 11.6 KB
/
mockSchemaRegistryClient.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
package srclient
import (
"errors"
"fmt"
"net/url"
"regexp"
"sort"
"time"
"github.com/linkedin/goavro/v2"
)
// Compile-time interface check
var _ ISchemaRegistryClient = new(MockSchemaRegistryClient)
// Currently unexported to not pollute the interface
var (
errInvalidSchemaType = errors.New("invalid schema type. valid values are Avro, Json, or Protobuf")
errSchemaAlreadyRegistered = errors.New("schema already registered")
errSchemaNotFound = errors.New("schema not found")
errSubjectNotFound = errors.New("subject not found")
errNotImplemented = errors.New("not implemented")
)
// MockSchemaRegistryClient represents an in-memory SchemaRegistryClient for testing purposes.
type MockSchemaRegistryClient struct {
// schemaRegistryURL is used to form errors
schemaRegistryURL string
// schemaVersions is a map of subject to a map of versions to the actual schema
schemaVersions map[string]map[int]*Schema
// schemaIDs is a map of schema ID to the actual schema
schemaIDs map[int]*Schema
// idCounter is used to generate unique IDs for each schema
idCounter int
}
// CreateMockSchemaRegistryClient initializes a MockSchemaRegistryClient
func CreateMockSchemaRegistryClient(mockURL string) *MockSchemaRegistryClient {
mockClient := &MockSchemaRegistryClient{
schemaRegistryURL: mockURL,
schemaVersions: map[string]map[int]*Schema{},
schemaIDs: map[int]*Schema{},
}
return mockClient
}
// avroRegex is used to remove whitespace from the schema string
var avroRegex = regexp.MustCompile(`\r?\n`)
// CreateSchema generates a new schema with the given details, references are unused
func (mck *MockSchemaRegistryClient) CreateSchema(subject string, schema string, schemaType SchemaType, _ ...Reference) (*Schema, error) {
mck.idCounter++
return mck.SetSchema(mck.idCounter, subject, schema, schemaType, -1)
}
// SetSchema overwrites a schema with the given id. Allows you to set a schema with a specific ID for testing purposes.
// Sets the ID counter to the given id if it is greater than the current counter. Version
// is used to set the version of the schema. If version is -1, the version will be set to the next available version.
func (mck *MockSchemaRegistryClient) SetSchema(id int, subject string, schema string, schemaType SchemaType, version int) (*Schema, error) {
if id > mck.idCounter {
mck.idCounter = id
}
switch schemaType {
case Avro, Json:
schema = avroRegex.ReplaceAllString(schema, " ")
case Protobuf:
break
default:
return nil, errInvalidSchemaType
}
resultFromSchemaCache, ok := mck.schemaVersions[subject]
if !ok {
return mck.generateVersion(id, subject, schema, schemaType, version)
}
// Verify if it's not the same schema as an existing version
for _, existing := range resultFromSchemaCache {
if existing.schema == schema {
posErr := url.Error{
Op: "POST",
URL: fmt.Sprintf("%s/subjects/%s/versions", mck.schemaRegistryURL, subject),
Err: errSchemaAlreadyRegistered,
}
return nil, &posErr
}
}
return mck.generateVersion(id, subject, schema, schemaType, version)
}
// GetSchema Returns a Schema for the given ID
func (mck *MockSchemaRegistryClient) GetSchema(schemaID int) (*Schema, error) {
thisSchema, ok := mck.schemaIDs[schemaID]
if !ok {
posErr := url.Error{
Op: "GET",
URL: fmt.Sprintf("%s/schemas/ids/%d", mck.schemaRegistryURL, schemaID),
Err: errSchemaNotFound,
}
return nil, &posErr
}
return thisSchema, nil
}
// GetLatestSchema Returns the highest ordinal version of a Schema for a given `concrete subject`
func (mck *MockSchemaRegistryClient) GetLatestSchema(subject string) (*Schema, error) {
// Error is never returned
versions, _ := mck.GetSchemaVersions(subject)
if len(versions) == 0 {
return nil, errSchemaNotFound
}
latestVersion := versions[len(versions)-1]
// This can't realistically throw an error
thisSchema, _ := mck.GetSchemaByVersion(subject, latestVersion)
return thisSchema, nil
}
// GetSchemaVersions Returns the array of versions this subject has previously registered
func (mck *MockSchemaRegistryClient) GetSchemaVersions(subject string) ([]int, error) {
versions := mck.allVersions(subject)
return versions, nil
}
// GetSubjectVersionsById Returns subject-version pairs identified by the schema ID.
func (mck *MockSchemaRegistryClient) GetSubjectVersionsById(schemaID int) (SubjectVersionResponse, error) {
for subjectName, schemaVersionsMap := range mck.schemaVersions {
for _, schema := range schemaVersionsMap {
if schema.id == schemaID {
subjectVersionResponse := make(SubjectVersionResponse, 0, len(schemaVersionsMap))
for schemaVersionKey := range schemaVersionsMap {
subjectVersionResponse = append(
subjectVersionResponse,
subjectVersionPair{
Subject: subjectName,
Version: schemaVersionKey,
},
)
}
return subjectVersionResponse, nil
}
}
}
posErr := url.Error{
Op: "GET",
URL: fmt.Sprintf("%s/schemas/ids/%d/versions", mck.schemaRegistryURL, schemaID),
Err: errSchemaNotFound,
}
return nil, &posErr
}
// GetSchemaByVersion Returns the given Schema according to the passed in subject and version number
func (mck *MockSchemaRegistryClient) GetSchemaByVersion(subject string, version int) (*Schema, error) {
var schema *Schema
schemaVersionMap, ok := mck.schemaVersions[subject]
if !ok {
posErr := url.Error{
Op: "GET",
URL: mck.schemaRegistryURL + fmt.Sprintf("/subjects/%s/versions/%d", subject, version),
Err: errSubjectNotFound,
}
return nil, &posErr
}
for id, schemaL := range schemaVersionMap {
if id == version {
schema = schemaL
}
}
if schema == nil {
posErr := url.Error{
Op: "GET",
URL: mck.schemaRegistryURL + fmt.Sprintf("/subjects/%s/versions/%d", subject, version),
Err: errSchemaNotFound,
}
return nil, &posErr
}
return schema, nil
}
// GetSubjects Returns all registered subjects
func (mck *MockSchemaRegistryClient) GetSubjects() ([]string, error) {
allSubjects := make([]string, len(mck.schemaVersions))
var count int
for subject := range mck.schemaVersions {
allSubjects[count] = subject
count++
}
return allSubjects, nil
}
// GetSchemaRegistryURL returns the URL of the schema registry
func (mck *MockSchemaRegistryClient) GetSchemaRegistryURL() string {
return mck.schemaRegistryURL
}
// GetSubjectsIncludingDeleted is not implemented and returns an error
func (mck *MockSchemaRegistryClient) GetSubjectsIncludingDeleted() ([]string, error) {
return nil, errNotImplemented
}
// DeleteSubject removes given subject from the cache
func (mck *MockSchemaRegistryClient) DeleteSubject(subject string, _ bool) error {
delete(mck.schemaVersions, subject)
return nil
}
// DeleteSubjectByVersion removes given subject's version from cache
func (mck *MockSchemaRegistryClient) DeleteSubjectByVersion(subject string, version int, _ bool) error {
_, ok := mck.schemaVersions[subject]
if !ok {
posErr := url.Error{
Op: "DELETE",
URL: fmt.Sprintf("%s/subjects/%s/versions/%d", mck.schemaRegistryURL, subject, version),
Err: errSubjectNotFound,
}
return &posErr
}
for schemaVersion := range mck.schemaVersions[subject] {
if schemaVersion == version {
delete(mck.schemaVersions[subject], schemaVersion)
return nil
}
}
posErr := url.Error{
Op: "GET",
URL: fmt.Sprintf("%s/subjects/%s/versions/%d", mck.schemaRegistryURL, subject, version),
Err: errSchemaNotFound,
}
return &posErr
}
// ChangeSubjectCompatibilityLevel is not implemented
func (mck *MockSchemaRegistryClient) ChangeSubjectCompatibilityLevel(string, CompatibilityLevel) (*CompatibilityLevel, error) {
return nil, errNotImplemented
}
// GetGlobalCompatibilityLevel is not implemented
func (mck *MockSchemaRegistryClient) GetGlobalCompatibilityLevel() (*CompatibilityLevel, error) {
return nil, errNotImplemented
}
// GetCompatibilityLevel is not implemented
func (mck *MockSchemaRegistryClient) GetCompatibilityLevel(string, bool) (*CompatibilityLevel, error) {
return nil, errNotImplemented
}
// SetCredentials is not implemented
func (mck *MockSchemaRegistryClient) SetCredentials(string, string) {
// Nothing because mockSchemaRegistryClient is actually very vulnerable
}
// SetBearerToken is not implemented
func (mck *MockSchemaRegistryClient) SetBearerToken(string) {
// Nothing because mockSchemaRegistryClient is actually very vulnerable
}
// SetTimeout is not implemented
func (mck *MockSchemaRegistryClient) SetTimeout(time.Duration) {
// Nothing because there is no timeout for cache
}
// CachingEnabled is not implemented
func (mck *MockSchemaRegistryClient) CachingEnabled(bool) {
// Nothing because caching is always enabled, duh
}
// ResetCache is not implemented
func (mck *MockSchemaRegistryClient) ResetCache() {
// Nothing because there is no lock for cache
}
// CodecCreationEnabled is not implemented
func (mck *MockSchemaRegistryClient) CodecCreationEnabled(bool) {
// Nothing because codecs do not matter in the inMem storage of schemas
}
// CodecJsonEnabled is not implemented
func (mck *MockSchemaRegistryClient) CodecJsonEnabled(value bool) {
// Nothing because codecs do not matter in the inMem storage of schemas
}
// IsSchemaCompatible is not implemented
func (mck *MockSchemaRegistryClient) IsSchemaCompatible(string, string, string, SchemaType, ...Reference) (bool, error) {
return false, errNotImplemented
}
// LookupSchema is not implemented
func (mck *MockSchemaRegistryClient) LookupSchema(string, string, SchemaType, ...Reference) (*Schema, error) {
return nil, errNotImplemented
}
/*
These classes are written as helpers and therefore, are not exported.
generateVersion will register a new version of the schema passed, it will NOT do any checks
for the schema being already registered, or for the advancing of the schema ID, these are expected to be
handled beforehand by the environment.
allVersions returns an ordered int[] with all versions for a given subject. It does NOT
qualify for key/value subjects, it expects to have a `concrete subject` passed on to do the checks.
*/
// generateVersion the next version of the schema for the given subject, givenVersion can be set to -1 to generate one.
func (mck *MockSchemaRegistryClient) generateVersion(id int, subject string, schema string, schemaType SchemaType, givenVersion int) (*Schema, error) {
schemaVersionMap := map[int]*Schema{}
currentVersion := 1
if givenVersion >= 0 {
currentVersion = givenVersion
}
// if existing versions are found, make sure to load in the version map
if existingMap := mck.schemaVersions[subject]; len(existingMap) > 0 {
schemaVersionMap = existingMap
// If no version was given, and existing versions are found, +1 the new number from the latest version
if givenVersion <= 0 {
versions := mck.allVersions(subject)
currentVersion = versions[len(versions)-1] + 1
}
}
// Add a codec, required otherwise Codec() panics and the mock registry is unusable
codec, err := goavro.NewCodec(schema)
if err != nil {
return nil, err
}
schemaToRegister := &Schema{
id: id,
schema: schema,
version: currentVersion,
codec: codec,
schemaType: &schemaType,
}
schemaVersionMap[currentVersion] = schemaToRegister
mck.schemaVersions[subject] = schemaVersionMap
mck.schemaIDs[schemaToRegister.id] = schemaToRegister
return schemaToRegister, nil
}
// allVersions returns all versions for a given subject, assumes it exists
func (mck *MockSchemaRegistryClient) allVersions(subject string) []int {
var versions []int
result, ok := mck.schemaVersions[subject]
if ok {
versions = make([]int, len(result))
var count int
for version := range result {
versions[count] = version
count++
}
}
sort.Ints(versions)
return versions
}