-
Notifications
You must be signed in to change notification settings - Fork 98
/
schema_compatibility.go
487 lines (407 loc) · 11.6 KB
/
schema_compatibility.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
package avro
import (
"errors"
"fmt"
"sync"
)
type recursionError struct{}
func (e recursionError) Error() string {
return ""
}
type compatKey struct {
reader [32]byte
writer [32]byte
}
// SchemaCompatibility determines the compatibility of schemas.
type SchemaCompatibility struct {
cache sync.Map // map[compatKey]error
}
// NewSchemaCompatibility creates a new schema compatibility instance.
func NewSchemaCompatibility() *SchemaCompatibility {
return &SchemaCompatibility{}
}
// Compatible determines the compatibility if the reader and writer schemas.
func (c *SchemaCompatibility) Compatible(reader, writer Schema) error {
return c.compatible(reader, writer)
}
func (c *SchemaCompatibility) compatible(reader, writer Schema) error {
key := compatKey{reader: reader.Fingerprint(), writer: writer.Fingerprint()}
if err, ok := c.cache.Load(key); ok {
if _, ok := err.(recursionError); ok {
// Break the recursion here.
return nil
}
if err == nil {
return nil
}
return err.(error)
}
c.cache.Store(key, recursionError{})
err := c.match(reader, writer)
if err != nil {
// We dont want to pay the cost of fmt.Errorf every time
err = errors.New(err.Error())
}
c.cache.Store(key, err)
return err
}
func (c *SchemaCompatibility) match(reader, writer Schema) error {
// If the schema is a reference, get the actual schema
if reader.Type() == Ref {
reader = reader.(*RefSchema).Schema()
}
if writer.Type() == Ref {
writer = writer.(*RefSchema).Schema()
}
if reader.Type() != writer.Type() {
if writer.Type() == Union {
// Reader must be compatible with all types in writer
for _, schema := range writer.(*UnionSchema).Types() {
if err := c.compatible(reader, schema); err != nil {
return err
}
}
return nil
}
if reader.Type() == Union {
// Writer must be compatible with at least one reader schema
var err error
for _, schema := range reader.(*UnionSchema).Types() {
err = c.compatible(schema, writer)
if err == nil {
return nil
}
}
return fmt.Errorf("reader union lacking writer schema %s", writer.Type())
}
switch writer.Type() {
case Int:
if reader.Type() == Long || reader.Type() == Float || reader.Type() == Double {
return nil
}
case Long:
if reader.Type() == Float || reader.Type() == Double {
return nil
}
case Float:
if reader.Type() == Double {
return nil
}
case String:
if reader.Type() == Bytes {
return nil
}
case Bytes:
if reader.Type() == String {
return nil
}
}
return fmt.Errorf("reader schema %s not compatible with writer schema %s", reader.Type(), writer.Type())
}
switch reader.Type() {
case Array:
return c.compatible(reader.(*ArraySchema).Items(), writer.(*ArraySchema).Items())
case Map:
return c.compatible(reader.(*MapSchema).Values(), writer.(*MapSchema).Values())
case Fixed:
r := reader.(*FixedSchema)
w := writer.(*FixedSchema)
if err := c.checkSchemaName(r, w); err != nil {
return err
}
if err := c.checkFixedSize(r, w); err != nil {
return err
}
case Enum:
r := reader.(*EnumSchema)
w := writer.(*EnumSchema)
if err := c.checkSchemaName(r, w); err != nil {
return err
}
if err := c.checkEnumSymbols(r, w); err != nil {
if r.HasDefault() {
return nil
}
return err
}
case Record:
r := reader.(*RecordSchema)
w := writer.(*RecordSchema)
if err := c.checkSchemaName(r, w); err != nil {
return err
}
if err := c.checkRecordFields(r, w); err != nil {
return err
}
case Union:
for _, schema := range writer.(*UnionSchema).Types() {
if err := c.compatible(reader, schema); err != nil {
return err
}
}
}
return nil
}
func (c *SchemaCompatibility) checkSchemaName(reader, writer NamedSchema) error {
if reader.Name() != writer.Name() {
if c.contains(reader.Aliases(), writer.FullName()) {
return nil
}
return fmt.Errorf("reader schema %s and writer schema %s names do not match", reader.FullName(), writer.FullName())
}
return nil
}
func (c *SchemaCompatibility) checkFixedSize(reader, writer *FixedSchema) error {
if reader.Size() != writer.Size() {
return fmt.Errorf("%s reader and writer fixed sizes do not match", reader.FullName())
}
return nil
}
func (c *SchemaCompatibility) checkEnumSymbols(reader, writer *EnumSchema) error {
for _, symbol := range writer.Symbols() {
if !c.contains(reader.Symbols(), symbol) {
return fmt.Errorf("reader %s is missing symbol %s", reader.FullName(), symbol)
}
}
return nil
}
func (c *SchemaCompatibility) checkRecordFields(reader, writer *RecordSchema) error {
for _, field := range reader.Fields() {
f, ok := c.getField(writer.Fields(), field, func(gfo *getFieldOptions) {
gfo.fieldAlias = true
})
if !ok {
if field.HasDefault() {
continue
}
return fmt.Errorf("reader field %s is missing in writer schema and has no default", field.Name())
}
if err := c.compatible(field.Type(), f.Type()); err != nil {
return err
}
}
return nil
}
func (c *SchemaCompatibility) contains(a []string, s string) bool {
for _, str := range a {
if str == s {
return true
}
}
return false
}
type getFieldOptions struct {
fieldAlias bool
elemAlias bool
}
func (c *SchemaCompatibility) getField(a []*Field, f *Field, optFns ...func(*getFieldOptions)) (*Field, bool) {
opt := getFieldOptions{}
for _, fn := range optFns {
fn(&opt)
}
for _, field := range a {
if field.Name() == f.Name() {
return field, true
}
if opt.fieldAlias {
if c.contains(f.Aliases(), field.Name()) {
return field, true
}
}
if opt.elemAlias {
if c.contains(field.Aliases(), f.Name()) {
return field, true
}
}
}
return nil, false
}
// Resolve returns a composite schema that allows decoding data written by the writer schema,
// and makes necessary adjustments to support the reader schema.
//
// It fails if the writer and reader schemas are not compatible.
func (c *SchemaCompatibility) Resolve(reader, writer Schema) (Schema, error) {
if err := c.compatible(reader, writer); err != nil {
return nil, err
}
schema, _, err := c.resolve(reader, writer)
return schema, err
}
// resolve requires the reader's schema to be already compatible with the writer's.
func (c *SchemaCompatibility) resolve(reader, writer Schema) (schema Schema, resolved bool, err error) {
if reader.Type() == Ref {
reader = reader.(*RefSchema).Schema()
}
if writer.Type() == Ref {
writer = writer.(*RefSchema).Schema()
}
if writer.Type() != reader.Type() {
if reader.Type() == Union {
for _, schema := range reader.(*UnionSchema).Types() {
// Compatibility is not guaranteed for every Union reader schema.
// Therefore, we need to check compatibility in every iteration.
if err := c.compatible(schema, writer); err != nil {
continue
}
sch, _, err := c.resolve(schema, writer)
if err != nil {
continue
}
return sch, true, nil
}
return nil, false, fmt.Errorf("reader union lacking writer schema %s", writer.Type())
}
if writer.Type() == Union {
schemas := make([]Schema, 0)
for _, schema := range writer.(*UnionSchema).Types() {
sch, _, err := c.resolve(reader, schema)
if err != nil {
return nil, false, err
}
schemas = append(schemas, sch)
}
s, err := NewUnionSchema(schemas, withWriterFingerprint(writer.Fingerprint()))
return s, true, err
}
if isPromotable(writer.Type(), reader.Type()) {
r := NewPrimitiveSchema(reader.Type(), reader.(*PrimitiveSchema).Logical(),
withWriterFingerprint(writer.Fingerprint()),
)
r.encodedType = writer.Type()
return r, true, nil
}
return nil, false, fmt.Errorf("failed to resolve composite schema for %s and %s", reader.Type(), writer.Type())
}
if isNative(writer.Type()) {
return reader, false, nil
}
if writer.Type() == Enum {
r := reader.(*EnumSchema)
w := writer.(*EnumSchema)
if err = c.checkEnumSymbols(r, w); err != nil {
if r.HasDefault() {
enum, _ := NewEnumSchema(r.Name(), r.Namespace(), r.Symbols(),
WithAliases(r.Aliases()),
WithDefault(r.Default()),
withWriterFingerprint(w.Fingerprint()),
)
enum.encodedSymbols = w.Symbols()
return enum, true, nil
}
return nil, false, err
}
return reader, false, nil
}
if writer.Type() == Fixed {
return reader, false, nil
}
if writer.Type() == Union {
schemas := make([]Schema, 0)
for _, s := range writer.(*UnionSchema).Types() {
sch, resolv, err := c.resolve(reader, s)
if err != nil {
return nil, false, err
}
schemas = append(schemas, sch)
resolved = resolv || resolved
}
s, err := NewUnionSchema(schemas, withWriterFingerprintIfResolved(writer.Fingerprint(), resolved))
if err != nil {
return nil, false, err
}
return s, resolved, nil
}
if writer.Type() == Array {
schema, resolved, err = c.resolve(reader.(*ArraySchema).Items(), writer.(*ArraySchema).Items())
if err != nil {
return nil, false, err
}
return NewArraySchema(schema, withWriterFingerprintIfResolved(writer.Fingerprint(), resolved)), resolved, nil
}
if writer.Type() == Map {
schema, resolved, err = c.resolve(reader.(*MapSchema).Values(), writer.(*MapSchema).Values())
if err != nil {
return nil, false, err
}
return NewMapSchema(schema, withWriterFingerprintIfResolved(writer.Fingerprint(), resolved)), resolved, nil
}
if writer.Type() == Record {
return c.resolveRecord(reader, writer)
}
return nil, false, fmt.Errorf("failed to resolve composite schema for %s and %s", reader.Type(), writer.Type())
}
func (c *SchemaCompatibility) resolveRecord(reader, writer Schema) (Schema, bool, error) {
w := writer.(*RecordSchema)
r := reader.(*RecordSchema)
fields := make([]*Field, 0)
seen := make(map[string]struct{})
var resolved bool
for _, wf := range w.Fields() {
rf, ok := c.getField(r.Fields(), wf, func(gfo *getFieldOptions) {
gfo.elemAlias = true
})
if !ok {
// The field was not found in the reader schema, it should be ignored.
f, _ := NewField(wf.Name(), wf.Type(), WithAliases(wf.aliases), WithOrder(wf.order))
f.def = wf.def
f.hasDef = wf.hasDef
f.action = FieldIgnore
fields = append(fields, f)
resolved = true
continue
}
ft, resolv, err := c.resolve(rf.Type(), wf.Type())
if err != nil {
return nil, false, err
}
f, _ := NewField(rf.Name(), ft, WithAliases(rf.aliases), WithOrder(rf.order))
f.def = rf.def
f.hasDef = rf.hasDef
fields = append(fields, f)
resolved = resolv || resolved
seen[rf.Name()] = struct{}{}
}
for _, rf := range r.Fields() {
if _, ok := seen[rf.Name()]; ok {
// This field has already been seen.
continue
}
// The schemas are already known to be compatible, so there must be a default on
// the field in the writer. Use the default.
f, _ := NewField(rf.Name(), rf.Type(), WithAliases(rf.aliases), WithOrder(rf.order))
f.def = rf.def
f.hasDef = rf.hasDef
f.action = FieldSetDefault
fields = append(fields, f)
resolved = true
}
schema, err := NewRecordSchema(r.Name(), r.Namespace(), fields,
WithAliases(r.Aliases()),
withWriterFingerprintIfResolved(writer.Fingerprint(), resolved),
)
return schema, resolved, err
}
func isNative(typ Type) bool {
switch typ {
case Null, Boolean, Int, Long, Float, Double, Bytes, String:
return true
default:
return false
}
}
func isPromotable(writerTyp, readerType Type) bool {
switch writerTyp {
case Int:
return readerType == Long || readerType == Float || readerType == Double
case Long:
return readerType == Float || readerType == Double
case Float:
return readerType == Double
case String:
return readerType == Bytes
case Bytes:
return readerType == String
default:
return false
}
}