-
Notifications
You must be signed in to change notification settings - Fork 0
/
inject.go
303 lines (273 loc) · 7.51 KB
/
inject.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
package inject
import (
"errors"
"fmt"
"reflect"
"slices"
"sync"
)
type Injector interface {
Get(reflect.Type) (reflect.Value, error)
}
type Injectable interface {
Type() reflect.Type
Inject(Injector) (reflect.Value, error)
}
func New(args ...any) (*Scope, error) {
return (*Scope)(nil).Scope(args...)
}
func Get[T any](inj Injector) (t T, err error) {
typ := reflect.TypeOf(t)
var rt reflect.Value
rt, err = inj.Get(typ)
if err != nil {
return
}
t = rt.Interface().(T)
return
}
func Inject[T any](j Injector, fn interface{}) (t T, err error) {
ttyp := reflect.TypeOf(&t).Elem()
fnval := reflect.ValueOf(fn)
fntyp := fnval.Type()
if err = checkFunc(fnval, fntyp); err != nil {
return
}
if fntyp.Out(0) != ttyp {
err = fmt.Errorf("return type does not match generic arg: expected: %s, got: %s", ttyp.String(), fntyp.Out(0).String())
return
}
var rt reflect.Value
rt, err = inject(j, fnval)
if err == nil {
t = rt.Interface().(T)
}
return
}
func inject(j Injector, fn reflect.Value) (val reflect.Value, err error) {
typ := fn.Type()
if err = checkFunc(fn, typ); err != nil {
return
}
// build the arguments and call the function
args := make([]reflect.Value, typ.NumIn())
for i := range args {
var arg reflect.Value
arg, err = j.Get(typ.In(i))
if err != nil {
err = errors.Join(fmt.Errorf("failed to get type '%s' from injector", typ.In(i).String()), err)
return
}
args[i] = arg
}
results := fn.Call(args)
// extract the optional error
if len(results) == 2 {
// we already know that results[1] has type error
if i := results[1].Interface(); i != nil {
err = fmt.Errorf("injected function returned an error: %v", i.(error))
return
}
}
val = results[0]
return
}
var typeOfError = reflect.TypeOf((*error)(nil)).Elem()
var typeOfAny = reflect.TypeOf((*any)(nil)).Elem()
func checkFunc(fn reflect.Value, typ reflect.Type) error {
if typ.Kind() != reflect.Func {
return fmt.Errorf("value is a %s, not a func: %v", fn.Kind().String(), fn)
}
if typ.NumOut() < 1 {
return fmt.Errorf("cannot inject function with no return values: %+v", fn)
}
if typ.NumOut() > 2 {
return fmt.Errorf("cannot inject function with more than 2 return values: %+v", fn)
}
if typ.NumOut() == 2 && typ.Out(1) != typeOfError {
return fmt.Errorf("cannot inject function with a non-error second return value: %s. %+v", typ.Out(1).String(), fn)
}
if typ.Out(0) == typeOfError {
return fmt.Errorf("cannot inject function with only an error return value: %s. %+v", typ.Out(0).String(), fn)
}
return nil
}
func As[T any](v T) Injectable {
t := reflect.TypeOf((*T)(nil)).Elem()
return asValueInjectable{t, func(i Injector) (reflect.Value, error) {
val, err := valueOf(reflect.ValueOf(v))
if err != nil {
return reflect.Value{}, err
}
return val.Inject(i)
}}
}
type asValueInjectable struct {
t reflect.Type
f func(Injector) (reflect.Value, error)
}
func (v asValueInjectable) Type() reflect.Type { return v.t }
func (v asValueInjectable) Inject(i Injector) (reflect.Value, error) { return v.f(i) }
type valueInjectable reflect.Value
func (v valueInjectable) Type() reflect.Type { return reflect.Value(v).Type() }
func (v valueInjectable) Inject(Injector) (reflect.Value, error) { return reflect.Value(v), nil }
type funcInjectable reflect.Value
func (f funcInjectable) Type() reflect.Type { return reflect.Value(f).Type().Out(0) }
func (f funcInjectable) Inject(j Injector) (reflect.Value, error) { return inject(j, reflect.Value(f)) }
type sliceInjectable struct {
typ reflect.Type
members []Injectable
}
func (s *sliceInjectable) Type() reflect.Type { return s.typ }
func (s *sliceInjectable) Inject(j Injector) (reflect.Value, error) {
vs := reflect.MakeSlice(s.typ, 0, len(s.members))
for _, m := range s.members {
v, err := m.Inject(j)
if err != nil {
return reflect.Value{}, err
}
vs = reflect.Append(vs, v)
}
return vs, nil
}
type Scope struct {
parent *Scope
values map[reflect.Type]Injectable
}
func (ph *Scope) Scope(args ...any) (*Scope, error) {
h := pool.Get().(*Scope)
h.parent = ph
h.add(As[Injector](h))
err := h.add(args...)
if err != nil {
return nil, err
}
return h, nil
}
func (h *Scope) add(args ...any) error {
for _, v := range args {
if inj, ok := v.(Injectable); ok {
if old, ok := h.values[inj.Type()]; ok {
return fmt.Errorf("cannot add value to scope with the same type already present. old: %+v, new: %+v", old, v)
} else {
h.values[inj.Type()] = inj
return nil
}
}
val := reflect.ValueOf(v)
switch val.Kind() {
case reflect.Slice:
// Only process unnamed slice types
if val.Type().Name() == "" {
if err := h.addSlice(val); err != nil {
return err
}
continue
}
fallthrough
default:
if inj, err := valueOf(val); err != nil {
return err
} else if old, ok := h.values[inj.Type()]; ok {
return fmt.Errorf("cannot add value to scope with the same type already present. old: %+v, new: %+v", old, val.Interface())
} else {
h.values[inj.Type()] = inj
}
}
}
return nil
}
func valueOf(v reflect.Value) (Injectable, error) {
if v.Type() == typeOfAny {
v = v.Elem()
}
typ := v.Type()
switch v.Kind() {
case reflect.Slice:
return nil, fmt.Errorf("cannot convert value of type %v to injectable", typ.String())
case reflect.Func:
if err := checkFunc(v, typ); err != nil {
return nil, err
}
return funcInjectable(v), nil
default:
return valueInjectable(v), nil
}
}
func (h *Scope) addSlice(v reflect.Value) error {
t := v.Type()
te := t.Elem()
if te == typeOfAny {
if v.Len() == 0 {
return nil // fmt.Errorf("cannot inject empty slice of any")
}
i, err := valueOf(v.Index(0))
if err != nil {
return err
}
te = i.Type()
t = reflect.SliceOf(te)
}
var si *sliceInjectable
if old, ok := h.values[t]; ok {
// Case 1: It exists in this scope: use it
if si, ok = old.(*sliceInjectable); !ok {
panic(fmt.Errorf("type should be a sliceInjectable, got %+v (%T)", old, old))
}
si.members = slices.Grow(si.members, v.Len())
} else if old, _ := h.parent.getInjectable(t); old != nil {
// Case 2: It exists in ancestor scope: clone it
if si, ok = old.(*sliceInjectable); !ok {
panic(fmt.Errorf("type should be a sliceInjectable, got %+v (%T)", old, old))
}
// explicitly copy to avoid reallocation when appending
mem := make([]Injectable, len(si.members), len(si.members)+v.Len())
copy(mem, si.members)
si = &sliceInjectable{typ: t, members: mem}
} else {
// Case 3: Doesn't exist yet: make a new one
si = &sliceInjectable{typ: t, members: make([]Injectable, 0, v.Len())}
}
// Append to the selected object
for i := 0; i < v.Len(); i++ {
iv, err := valueOf(v.Index(i))
if err != nil {
return err
}
if iv.Type() != te {
return fmt.Errorf("element not of same type as slice: %s != %s", iv, te)
}
si.members = append(si.members, iv)
}
h.values[t] = si
return nil
}
func (h *Scope) Get(t reflect.Type) (reflect.Value, error) {
i, _ := h.getInjectable(t)
if i == nil {
return reflect.Value{}, fmt.Errorf("failed to find type: %s", t.String())
}
return i.Inject(h)
}
func (h *Scope) getInjectable(t reflect.Type) (Injectable, int) {
if h == nil {
return nil, 0
}
if i, ok := h.values[t]; ok {
return i, 1
} else {
i, n := h.parent.getInjectable(t)
return i, n + 1
}
}
var pool sync.Pool = sync.Pool{New: func() any {
return &Scope{
parent: nil,
values: make(map[reflect.Type]Injectable),
}
}}
func (h *Scope) PutPool() {
h.parent = nil
clear(h.values)
pool.Put(h)
}