-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.go
More file actions
335 lines (285 loc) · 8.82 KB
/
api.go
File metadata and controls
335 lines (285 loc) · 8.82 KB
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
package protolite
import (
"errors"
"fmt"
"io"
"os"
"reflect"
"strings"
"github.com/anirudhraja/protolite/registry"
"github.com/anirudhraja/protolite/wire"
)
// Protolite is the main interface for the library.
type Protolite interface {
// Parse parses the given data into a map of string to interface. This is used when schema is not known.
Parse(data []byte) (map[string]interface{}, error)
// MarshalWithSchema marshals data using a specific message schema
MarshalWithSchema(data map[string]interface{}, messageName string) ([]byte, error)
// UnmarshalWithSchema unmarshals data using a specific message schema
UnmarshalWithSchema(data []byte, messageName string) (map[string]interface{}, error)
// UnmarshalToStruct unmarshals protobuf data into a Go struct using reflection
UnmarshalToStruct(data []byte, messageName string, v interface{}) error
// LoadSchemaFromFile loads schema definitions from a .proto file
LoadSchemaFromFile(protoPath string) error
// LoadSchemaFromReader loads schema definitions from an io.Reader with a unique identifier
// The identifier is used as a unique key for the schema, while dependent imports are still loaded from file paths
LoadSchemaFromReader(reader io.Reader, identifier string) error
}
type protolite struct {
registry *registry.Registry
}
// Parse implements Protolite - parses protobuf data without schema knowledge.
func (p *protolite) Parse(data []byte) (map[string]interface{}, error) {
if len(data) == 0 {
return make(map[string]interface{}), nil
}
decoder := wire.NewDecoder(data)
result := make(map[string]interface{})
for {
field, err := decoder.DecodeField()
if err != nil {
return nil, fmt.Errorf("failed to decode field: %v", err)
}
if field == nil {
// End of data
break
}
// Use field number as key since we don't have schema
fieldKey := fmt.Sprintf("field_%d", field.FieldNumber)
// Convert wire type to more readable format
switch field.WireType {
case wire.WireVarint:
result[fieldKey] = map[string]interface{}{
"type": "varint",
"value": field.Data,
}
case wire.WireFixed64:
result[fieldKey] = map[string]interface{}{
"type": "fixed64",
"value": field.Data,
}
case wire.WireBytes:
result[fieldKey] = map[string]interface{}{
"type": "bytes",
"value": field.Data,
}
case wire.WireFixed32:
result[fieldKey] = map[string]interface{}{
"type": "fixed32",
"value": field.Data,
}
default:
result[fieldKey] = map[string]interface{}{
"type": "unknown",
"value": field.Data,
}
}
}
return result, nil
}
// LoadSchemaFromFile loads schema definitions from a .proto file
// It internally uses LoadSchemaFromReader by creating a reader from the file
func (p *protolite) LoadSchemaFromFile(protoPath string) error {
// Resolve the full path using registry's proto directories
fullPath, err := p.registry.FindProtoPath(protoPath)
if err != nil {
return err
}
// Open and read the file
file, err := os.Open(fullPath)
if err != nil {
return fmt.Errorf("failed to open proto file: %w", err)
}
defer file.Close()
// Use LoadSchema with the full path as identifier
return p.registry.LoadSchema(file, fullPath)
}
// LoadSchemaFromReader loads schema definitions from an io.Reader with a unique identifier
func (p *protolite) LoadSchemaFromReader(reader io.Reader, identifier string) error {
return p.registry.LoadSchema(reader, identifier)
}
// Additional helper methods that require schema
// MarshalWithSchema marshals data using a specific message schema
func (p *protolite) MarshalWithSchema(data map[string]interface{}, messageName string) ([]byte, error) {
message, err := p.registry.GetMessage(messageName)
if err != nil {
return nil, fmt.Errorf("message schema not found: %v", err)
}
protoBytes,err := wire.EncodeMessage(data, message, p.registry)
if err != nil {
return nil, fmt.Errorf("encoding failed: %w", err)
}
return protoBytes,err
}
// UnmarshalWithSchema unmarshals data using a specific message schema
func (p *protolite) UnmarshalWithSchema(data []byte, messageName string) (map[string]interface{}, error) {
message, err := p.registry.GetMessage(messageName)
if err != nil {
return nil, fmt.Errorf("message schema not found: %v", err)
}
decodedMessage, err := wire.DecodeMessage(data, message, p.registry)
if err != nil {
return nil, fmt.Errorf("decoding failed: %w", err)
}
result, ok := decodedMessage.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("expected type of map[string]interface{} got %T", decodedMessage)
}
return result, nil
}
// UnmarshalToStruct unmarshals protobuf data into a Go struct using reflection
func (p *protolite) UnmarshalToStruct(data []byte, messageName string, v interface{}) error {
// First unmarshal to map
result, err := p.UnmarshalWithSchema(data, messageName)
if err != nil {
return err
}
// Use reflection to populate the struct
return p.mapToStruct(result, v)
}
// mapToStruct uses reflection to copy map values to struct fields
func (p *protolite) mapToStruct(data map[string]interface{}, v interface{}) error {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr || rv.Elem().Kind() != reflect.Struct {
return errors.New("v must be a pointer to a struct")
}
rv = rv.Elem()
rt := rv.Type()
for i := 0; i < rv.NumField(); i++ {
field := rv.Field(i)
fieldType := rt.Field(i)
if !field.CanSet() {
continue
}
// Try to find matching data by field name with multiple strategies
var value interface{}
var found bool
// Strategy 1: Check exact match
if val, ok := data[fieldType.Name]; ok {
value = val
found = true
}
// Strategy 2: Check lowercase version
if !found {
lowerName := strings.ToLower(fieldType.Name)
if val, ok := data[lowerName]; ok {
value = val
found = true
}
}
// Strategy 3: Check snake_case conversion
if !found {
snakeName := toSnakeCase(fieldType.Name)
if val, ok := data[snakeName]; ok {
value = val
found = true
}
}
if !found {
continue
}
// Set the field value with type conversion
if err := p.setFieldValue(field, value); err != nil {
return fmt.Errorf("failed to set field %s: %v", fieldType.Name, err)
}
}
return nil
}
// setFieldValue sets a struct field value with appropriate type conversion
func (p *protolite) setFieldValue(field reflect.Value, value interface{}) error {
if value == nil {
return nil
}
rv := reflect.ValueOf(value)
// Handle type conversions
switch field.Kind() {
case reflect.String:
if rv.Kind() == reflect.String {
field.SetString(rv.String())
} else {
return fmt.Errorf("cannot convert %T to string", value)
}
case reflect.Int, reflect.Int32, reflect.Int64:
switch rv.Kind() {
case reflect.Int, reflect.Int32, reflect.Int64:
field.SetInt(rv.Int())
default:
return fmt.Errorf("cannot convert %T to int", value)
}
case reflect.Uint, reflect.Uint32, reflect.Uint64:
switch rv.Kind() {
case reflect.Uint, reflect.Uint32, reflect.Uint64:
field.SetUint(rv.Uint())
default:
return fmt.Errorf("cannot convert %T to uint", value)
}
case reflect.Float32, reflect.Float64:
switch rv.Kind() {
case reflect.Float32, reflect.Float64:
field.SetFloat(rv.Float())
default:
return fmt.Errorf("cannot convert %T to float", value)
}
case reflect.Bool:
if rv.Kind() == reflect.Bool {
field.SetBool(rv.Bool())
} else {
return fmt.Errorf("cannot convert %T to bool", value)
}
case reflect.Slice:
if rv.Kind() == reflect.Slice {
field.Set(rv)
} else {
return fmt.Errorf("cannot convert %T to slice", value)
}
default:
// Try direct assignment
if rv.Type().AssignableTo(field.Type()) {
field.Set(rv)
} else {
return fmt.Errorf("cannot assign %T to %s", value, field.Type())
}
}
return nil
}
// toSnakeCase converts CamelCase to snake_case
func toSnakeCase(s string) string {
if len(s) == 0 {
return s
}
var result []rune
runes := []rune(s)
for i, r := range runes {
if 'A' <= r && r <= 'Z' {
// Add underscore before uppercase letters when:
// 1. Not at the beginning, AND
// 2. Previous char is lowercase, OR
// 3. Previous char is uppercase AND next char is lowercase (end of acronym)
if i > 0 {
prev := runes[i-1]
needUnderscore := false
// Case 1: Previous char is lowercase
if 'a' <= prev && prev <= 'z' {
needUnderscore = true
}
// Case 2: Previous char is uppercase AND next char is lowercase (acronym boundary)
if 'A' <= prev && prev <= 'Z' && i+1 < len(runes) && 'a' <= runes[i+1] && runes[i+1] <= 'z' {
needUnderscore = true
}
if needUnderscore {
result = append(result, '_')
}
}
// Convert to lowercase
result = append(result, r-'A'+'a')
} else {
result = append(result, r)
}
}
return string(result)
}
func NewProtolite(ProtoDirectories []string) Protolite {
return &protolite{
registry: registry.NewRegistry(ProtoDirectories),
}
}