forked from hamba/avro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
protocol.go
377 lines (314 loc) · 8.38 KB
/
protocol.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
package avro
import (
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"os"
jsoniter "github.com/json-iterator/go"
"github.com/mitchellh/mapstructure"
)
var (
protocolReserved = []string{"doc", "types", "messages", "protocol", "namespace"}
messageReserved = []string{"doc", "response", "request", "errors", "one-way"}
)
type protocolConfig struct {
doc string
props map[string]any
}
// ProtocolOption is a function that sets a protocol option.
type ProtocolOption func(*protocolConfig)
// WithProtoDoc sets the doc on a protocol.
func WithProtoDoc(doc string) ProtocolOption {
return func(opts *protocolConfig) {
opts.doc = doc
}
}
// WithProtoProps sets the properties on a protocol.
func WithProtoProps(props map[string]any) ProtocolOption {
return func(opts *protocolConfig) {
opts.props = props
}
}
// Protocol is an Avro protocol.
type Protocol struct {
name
properties
types []NamedSchema
messages map[string]*Message
doc string
hash string
}
// NewProtocol creates a protocol instance.
func NewProtocol(
name, namepsace string,
types []NamedSchema,
messages map[string]*Message,
opts ...ProtocolOption,
) (*Protocol, error) {
var cfg protocolConfig
for _, opt := range opts {
opt(&cfg)
}
n, err := newName(name, namepsace, nil)
if err != nil {
return nil, err
}
p := &Protocol{
name: n,
properties: newProperties(cfg.props, protocolReserved),
types: types,
messages: messages,
doc: cfg.doc,
}
b := md5.Sum([]byte(p.String()))
p.hash = hex.EncodeToString(b[:])
return p, nil
}
// Message returns a message with the given name or nil.
func (p *Protocol) Message(name string) *Message {
return p.messages[name]
}
// Doc returns the protocol doc.
func (p *Protocol) Doc() string {
return p.doc
}
// Hash returns the MD5 hash of the protocol.
func (p *Protocol) Hash() string {
return p.hash
}
// Types returns the types of the protocol.
func (p *Protocol) Types() []NamedSchema {
return p.types
}
// String returns the canonical form of the protocol.
func (p *Protocol) String() string {
types := ""
for _, f := range p.types {
types += f.String() + ","
}
if len(types) > 0 {
types = types[:len(types)-1]
}
messages := ""
for k, m := range p.messages {
messages += `"` + k + `":` + m.String() + ","
}
if len(messages) > 0 {
messages = messages[:len(messages)-1]
}
return `{"protocol":"` + p.Name() +
`","namespace":"` + p.Namespace() +
`","types":[` + types + `],"messages":{` + messages + `}}`
}
// Message is an Avro protocol message.
type Message struct {
properties
req *RecordSchema
resp Schema
errs *UnionSchema
oneWay bool
doc string
}
// NewMessage creates a protocol message instance.
func NewMessage(req *RecordSchema, resp Schema, errors *UnionSchema, oneWay bool, opts ...ProtocolOption) *Message {
var cfg protocolConfig
for _, opt := range opts {
opt(&cfg)
}
return &Message{
properties: newProperties(cfg.props, messageReserved),
req: req,
resp: resp,
errs: errors,
oneWay: oneWay,
doc: cfg.doc,
}
}
// Request returns the message request schema.
func (m *Message) Request() *RecordSchema {
return m.req
}
// Response returns the message response schema.
func (m *Message) Response() Schema {
return m.resp
}
// Errors returns the message errors union schema.
func (m *Message) Errors() *UnionSchema {
return m.errs
}
// OneWay determines of the message is a one way message.
func (m *Message) OneWay() bool {
return m.oneWay
}
// Doc returns the message doc.
func (m *Message) Doc() string {
return m.doc
}
// String returns the canonical form of the message.
func (m *Message) String() string {
fields := ""
for _, f := range m.req.fields {
fields += f.String() + ","
}
if len(fields) > 0 {
fields = fields[:len(fields)-1]
}
str := `{"request":[` + fields + `]`
if m.resp != nil {
str += `,"response":` + m.resp.String()
}
if m.errs != nil && len(m.errs.Types()) > 1 {
errs, _ := NewUnionSchema(m.errs.Types()[1:])
str += `,"errors":` + errs.String()
}
str += "}"
return str
}
// ParseProtocolFile parses an Avro protocol from a file.
func ParseProtocolFile(path string) (*Protocol, error) {
s, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return ParseProtocol(string(s))
}
// MustParseProtocol parses an Avro protocol, panicing if there is an error.
func MustParseProtocol(protocol string) *Protocol {
parsed, err := ParseProtocol(protocol)
if err != nil {
panic(err)
}
return parsed
}
// ParseProtocol parses an Avro protocol.
func ParseProtocol(protocol string) (*Protocol, error) {
cache := &SchemaCache{}
var m map[string]any
if err := jsoniter.Unmarshal([]byte(protocol), &m); err != nil {
return nil, err
}
seen := seenCache{}
return parseProtocol(m, seen, cache)
}
type protocol struct {
Protocol string `mapstructure:"protocol"`
Namespace string `mapstructure:"namespace"`
Doc string `mapstructure:"doc"`
Types []any `mapstructure:"types"`
Messages map[string]map[string]any `mapstructure:"messages"`
Props map[string]any `mapstructure:",remain"`
}
func parseProtocol(m map[string]any, seen seenCache, cache *SchemaCache) (*Protocol, error) {
var (
p protocol
meta mapstructure.Metadata
)
if err := decodeMap(m, &p, &meta); err != nil {
return nil, fmt.Errorf("avro: error decoding protocol: %w", err)
}
if err := checkParsedName(p.Protocol); err != nil {
return nil, err
}
var (
types []NamedSchema
err error
)
if len(p.Types) > 0 {
types, err = parseProtocolTypes(p.Namespace, p.Types, seen, cache)
if err != nil {
return nil, err
}
}
messages := map[string]*Message{}
if len(p.Messages) > 0 {
for k, msg := range p.Messages {
message, err := parseMessage(p.Namespace, msg, seen, cache)
if err != nil {
return nil, err
}
messages[k] = message
}
}
return NewProtocol(p.Protocol, p.Namespace, types, messages, WithProtoDoc(p.Doc), WithProtoProps(p.Props))
}
func parseProtocolTypes(namespace string, types []any, seen seenCache, cache *SchemaCache) ([]NamedSchema, error) {
ts := make([]NamedSchema, len(types))
for i, typ := range types {
schema, err := parseType(namespace, typ, seen, cache)
if err != nil {
return nil, err
}
namedSchema, ok := schema.(NamedSchema)
if !ok {
return nil, errors.New("avro: protocol types must be named schemas")
}
ts[i] = namedSchema
}
return ts, nil
}
type message struct {
Doc string `mapstructure:"doc"`
Request []map[string]any `mapstructure:"request"`
Response any `mapstructure:"response"`
Errors []any `mapstructure:"errors"`
OneWay bool `mapstructure:"one-way"`
Props map[string]any `mapstructure:",remain"`
}
func parseMessage(namespace string, m map[string]any, seen seenCache, cache *SchemaCache) (*Message, error) {
var (
msg message
meta mapstructure.Metadata
)
if err := decodeMap(m, &msg, &meta); err != nil {
return nil, fmt.Errorf("avro: error decoding message: %w", err)
}
fields := make([]*Field, len(msg.Request))
for i, f := range msg.Request {
field, err := parseField(namespace, f, seen, cache)
if err != nil {
return nil, err
}
fields[i] = field
}
request := &RecordSchema{
name: name{},
properties: properties{},
fields: fields,
}
var response Schema
if msg.Response != nil {
schema, err := parseType(namespace, msg.Response, seen, cache)
if err != nil {
return nil, err
}
if schema.Type() != Null {
response = schema
}
}
types := []Schema{NewPrimitiveSchema(String, nil)}
if len(msg.Errors) > 0 {
for _, e := range msg.Errors {
schema, err := parseType(namespace, e, seen, cache)
if err != nil {
return nil, err
}
if rec, ok := schema.(*RecordSchema); ok && !rec.IsError() {
return nil, errors.New("avro: errors record schema must be of type error")
}
types = append(types, schema)
}
}
errs, err := NewUnionSchema(types)
if err != nil {
return nil, err
}
oneWay := msg.OneWay
if hasKey(meta.Keys, "one-way") && oneWay && (len(errs.Types()) > 1 || response != nil) {
return nil, errors.New("avro: one-way messages cannot not have a response or errors")
}
if !oneWay && len(errs.Types()) <= 1 && response == nil {
oneWay = true
}
return NewMessage(request, response, errs, oneWay, WithProtoDoc(msg.Doc), WithProtoProps(msg.Props)), nil
}