-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathutil.go
273 lines (241 loc) · 7.87 KB
/
util.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
package portal
import (
"context"
"fmt"
"reflect"
"github.com/pkg/errors"
)
func nestedValue(ctx context.Context, any interface{}, chainingAttrs []string, cg *cacheGroup, enableCache bool) (interface{}, error) {
if len(chainingAttrs) == 0 {
return any, nil
}
if any == interface{}(nil) {
return nil, errors.New("object is nil")
}
rv := reflect.ValueOf(any)
attr := chainingAttrs[0]
meth, err := findMethod(rv, attr)
if err != nil {
if reflect.Indirect(rv).Kind() == reflect.Struct {
field := reflect.Indirect(rv).FieldByName(attr)
if field.IsValid() {
return nestedValue(ctx, field.Interface(), chainingAttrs[1:], nil, false)
}
}
// ignore method not found here.
// do nothing for mismatched fields.
logger.Warnf("[portal.nestedValue] %s", err)
return nil, nil
}
var ret interface{}
if enableCache {
cacheKey := genCacheKey(ctx, any, any, attr)
ret, err = invokeWithCache(ctx, rv, meth, attr, cg, cacheKey)
} else {
ret, err = invoke(ctx, rv, meth, attr)
}
if err != nil {
return nil, err
}
return nestedValue(ctx, ret, chainingAttrs[1:], cg, enableCache)
}
// invokeMethodOfAnyType calls the specified method of a value and return results.
// Note:
// - Context param is optional
// - Method must returns at least one result.
// - Max number of return values is two, and the last one must be of `error` type.
//
// Supported method definitions:
// - `func (f *FooType) Bar(v interface{}) error`
// - `func (f *FooType) Bar(v interface{}) string`
// - `func (f *FooType) Bar(ctx context.Context, v interface{}) error`
// - `func (f *FooType) Bar(ctx context.Context, v interface{}) string`
// - `func (f *FooType) Bar(ctx context.Context, v interface{}) (string, error)`
// - `func (f *FooType) Bar(ctx context.Context, v interface{}) (string, error)`
func invokeMethodOfAnyType(ctx context.Context, any interface{}, name string, args ...interface{}) (interface{}, error) {
return invokeMethodOfReflectedValue(ctx, reflect.ValueOf(any), name, args...)
}
func invokeMethodOfAnyTypeWithCache(ctx context.Context, any interface{}, name string, cg *cacheGroup, cacheKey *string, args ...interface{}) (interface{}, error) {
return invokeMethodOfReflectedValueWithCache(ctx, reflect.ValueOf(any), name, cg, cacheKey, args...)
}
func invokeMethodOfReflectedValue(ctx context.Context, any reflect.Value, name string, args ...interface{}) (interface{}, error) {
method, err := findMethod(any, name)
if err != nil {
return nil, err
}
return invoke(ctx, any, method, name, args...)
}
func invokeMethodOfReflectedValueWithCache(ctx context.Context, any reflect.Value, name string, cg *cacheGroup, cacheKey *string, args ...interface{}) (interface{}, error) {
method, err := findMethod(any, name)
if err != nil {
return nil, err
}
return invokeWithCache(ctx, any, method, name, cg, cacheKey, args...)
}
func invoke(ctx context.Context, any reflect.Value, method reflect.Value, methodName string, args ...interface{}) (interface{}, error) {
methodType := method.Type()
if shouldWithContext(methodType) {
args = append([]interface{}{ctx}, args...)
}
methodNameRepr := fmt.Sprintf("%s.%s", any.Type().String(), methodName)
numIn := methodType.NumIn()
if numIn > len(args) {
return reflect.ValueOf(nil), fmt.Errorf("method '%s' must has minimum %d params: %d", methodNameRepr, numIn, len(args))
}
if numIn != len(args) && !methodType.IsVariadic() {
return reflect.ValueOf(nil), fmt.Errorf("method '%s' must has %d params: %d", methodNameRepr, numIn, len(args))
}
numOut := methodType.NumOut()
switch numOut {
case 1:
// Cases like:
// func (f *FooType) Bar() error
// func (f *FooType) Bar() string
case 2:
// Cases like:
// func (f *FooType) Bar() (string, error)
if !methodType.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
return reflect.ValueOf(nil), fmt.Errorf("the last return value of method '%s' must be of `error` type", methodNameRepr)
}
default:
return reflect.ValueOf(nil), fmt.Errorf("method '%s' must returns one result with an optional error", methodNameRepr)
}
in := make([]reflect.Value, len(args))
for i := 0; i < len(args); i++ {
var inType reflect.Type
if methodType.IsVariadic() && i >= numIn-1 {
inType = methodType.In(numIn - 1).Elem()
} else {
inType = methodType.In(i)
}
argValue := reflect.ValueOf(args[i])
argType := argValue.Type()
if argType.ConvertibleTo(inType) {
in[i] = argValue.Convert(inType)
} else {
return reflect.ValueOf(nil), fmt.Errorf("param[%d] of method '%s' must be %s, not %s", i, methodNameRepr, argType, inType)
}
}
outs := method.Call(in)
switch len(outs) {
case 1:
return outs[0].Interface(), nil
case 2:
err := outs[1].Interface()
if err != nil {
return nil, errors.WithStack(err.(error))
}
return outs[0].Interface(), nil
default:
return nil, errors.Errorf("unexpected results returned by method '%s'", methodNameRepr)
}
}
func invokeWithCache(ctx context.Context, any reflect.Value, method reflect.Value, methodName string, cg *cacheGroup, cacheKey *string, args ...interface{}) (interface{}, error) {
if !cg.valid() || cacheKey == nil {
ret, err := invoke(ctx, any, method, methodName, args...)
return ret, errors.WithStack(err)
}
// singleflight, only one execution under multiple goroutines
v, err, _ := cg.g.Do(*cacheKey, func() (interface{}, error) {
if ret, err := cg.cache.Get(ctx, *cacheKey); err == nil {
return ret, nil
}
ret, err := invoke(ctx, any, method, methodName, args...)
if err == nil {
err = cg.cache.Set(ctx, *cacheKey, ret)
if err != nil {
return nil, errors.WithStack(err)
}
return ret, nil
}
return ret, errors.WithStack(err)
})
return v, err
}
func findMethod(any reflect.Value, name string) (reflect.Value, error) {
var vptr = any
if any.Kind() != reflect.Ptr {
vptr = reflect.New(any.Type())
vptr.Elem().Set(any)
}
method := vptr.MethodByName(name)
if method.IsValid() {
return method, nil
} else {
return reflect.Value{}, fmt.Errorf("method '%s' not found in '%s'", name, any.Type().String())
}
}
func shouldWithContext(funcType reflect.Type) bool {
return funcType.NumIn() > 0 && funcType.In(0).Name() == "Context"
}
// indirectStructTypeP get indirect struct type, panics if failed
func indirectStructTypeP(typ reflect.Type) reflect.Type {
typ, err := indirectStructTypeE(typ)
if err != nil {
panic(fmt.Sprintf("failed to get indirect struct type: %s", err))
}
return typ
}
func indirectStructTypeE(typ reflect.Type) (reflect.Type, error) {
switch typ.Kind() {
case reflect.Struct:
return typ, nil
case reflect.Slice:
return indirectStructTypeE(typ.Elem())
case reflect.Ptr:
return indirectStructTypeE(typ.Elem())
default:
return nil, fmt.Errorf("unsupported type '%s'", typ.Name())
}
}
func structName(v interface{}) string {
typ := reflect.TypeOf(v)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
if typ.Kind() != reflect.Struct {
panic("invalid struct type")
}
return typ.Name()
}
func isNil(in interface{}) bool {
if in == nil {
return true
}
v := reflect.ValueOf(in)
switch v.Kind() {
case reflect.Ptr, reflect.Interface, reflect.Map, reflect.Slice:
return v.IsNil()
default:
return false
}
}
func convertible(from, to interface{}) bool {
return reflect.TypeOf(from).ConvertibleTo(reflect.TypeOf(to))
}
// innerStructType gets the inner struct type.
// Cases:
// - ModelStruct
// - &ModelStruct
// - &&ModelStruct
func innerStructType(typ reflect.Type) (reflect.Type, error) {
switch typ.Kind() {
case reflect.Struct:
return typ, nil
case reflect.Ptr:
curType := typ
for ptrLevel := 0; ptrLevel < 2; ptrLevel++ {
switch curType.Elem().Kind() {
case reflect.Ptr:
curType = curType.Elem()
case reflect.Struct:
return curType.Elem(), nil
default:
return nil, errors.New("failed to get inner struct type")
}
}
return nil, errors.New("pointer level too deep")
default:
return nil, errors.New("failed to get inner struct type")
}
}