-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinjector.go
More file actions
350 lines (314 loc) · 10.3 KB
/
injector.go
File metadata and controls
350 lines (314 loc) · 10.3 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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package goinject
import (
"context"
"fmt"
"reflect"
"strings"
)
var errorReflectType = reflect.TypeFor[error]()
var invocationContextReflectType = reflect.TypeFor[InvocationContext]()
// Injector defines bindings & scopes
type Injector struct {
bindings map[reflect.Type]map[string][]*binding // list of available bindings by type and annotations
scopes map[string]Scope // Scope by names
singletonScope *singletonScope
}
// NewInjector builds up a new Injector out of a list of Modules with singleton scope
func NewInjector(options ...Option) (*Injector, error) {
conf := &configuration{
bindings: []*binding{},
scopes: make(map[string]Scope),
knownProviders: []*provideOption{},
}
for _, option := range options {
err := option.apply(conf)
if err != nil {
return nil, err
}
}
singletonScope := newSingletonScope()
conf.scopes[Singleton] = singletonScope
conf.scopes[PerLookUp] = newPerLookUpScope()
injector := &Injector{
bindings: make(map[reflect.Type]map[string][]*binding),
scopes: make(map[string]Scope),
singletonScope: singletonScope,
}
injectorType := reflect.TypeFor[*Injector]()
injectorBinding := &binding{
typeof: injectorType,
provider: reflect.ValueOf(func() *Injector { return injector }),
providedType: injectorType,
scope: Singleton,
}
injector.scopes = conf.scopes
for _, b := range conf.bindings {
_, ok := injector.bindings[b.typeof]
if !ok {
injector.bindings[b.typeof] = make(map[string][]*binding)
}
injector.bindings[b.typeof][b.annotatedWith] = append(injector.bindings[b.typeof][b.annotatedWith], b)
}
injector.bindings[injectorType] = make(map[string][]*binding)
injector.bindings[injectorType][""] = []*binding{injectorBinding}
err := injector.eagerlyCreateSingletons()
if err != nil {
return nil, err
}
return injector, nil
}
// Shutdown clear underlying singleton scope
func (injector *Injector) Shutdown() {
injector.singletonScope.Shutdown()
injector.bindings = make(map[reflect.Type]map[string][]*binding)
injector.scopes = make(map[string]Scope)
}
// Invoke will execute the parameter function (which must be a function that optionally can return an error).
// argument of function will be resolved by the injector using configured providers & scope.
func (injector *Injector) Invoke(ctx context.Context, function any) (err error) {
// recover from potential panics in user code or reflection
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic during invocation: %v", r)
}
}()
if function == nil {
return newInvalidInputError("can't invoke on nil")
}
fvalue := reflect.ValueOf(function)
ftype := fvalue.Type()
if ftype.Kind() != reflect.Func {
return newInvalidInputError(
fmt.Sprintf("can't invoke non-function %v (type %v)", function, ftype))
}
// 2. check for Typed Nil, reflect.Call on a nil function value causes a panic.
if fvalue.IsNil() {
return newInvalidInputError(fmt.Sprintf("can't invoke nil function %v", ftype))
}
if ftype.NumOut() > 1 || (ftype.NumOut() == 1 && !ftype.Out(0).AssignableTo(errorReflectType)) {
return newInvalidInputError("can't invoke on function whose return type is not error or no return type")
}
res, err := injector.callFunctionWithArgumentInstance(ctx, fvalue)
if err != nil {
return fmt.Errorf("failed to call invokation function: %w", err)
}
if ftype.NumOut() == 0 {
return nil
}
// check slice access
if len(res) == 0 {
return fmt.Errorf("function expected to return error but reflection result was empty")
}
val := res[0].Interface()
// handle the case where the interface is nil (no error returned)
if val == nil {
return nil
}
// Assert it is an error
if invokationError, ok := val.(error); ok {
return fmt.Errorf("invokation returned error: %w", invokationError)
}
// fallback for edge cases where AssignableTo passed but assertion failed
return fmt.Errorf("return value was not an error interface: %v", val)
}
func (injector *Injector) eagerlyCreateSingletons() error {
for _, bindingsByAnnotation := range injector.bindings {
for _, bindingList := range bindingsByAnnotation {
for _, b := range bindingList {
if b.scope == Singleton {
_, err := injector.getScopedInstanceFromBinding(nil, b) //nolint:staticcheck
if err != nil {
return fmt.Errorf("failed to get singleton instance: %w", err)
}
}
}
}
}
return nil
}
func (injector *Injector) callFunctionWithArgumentInstance(
ctx context.Context,
fValue reflect.Value,
) ([]reflect.Value, error) {
fType := fValue.Type()
in := make([]reflect.Value, fType.NumIn())
var err error
for i := 0; i < fType.NumIn(); i++ {
if in[i], err = injector.getFunctionArgumentInstance(ctx, fType.In(i)); err != nil {
return []reflect.Value{}, fmt.Errorf("failed to resolve function argument #%d: %w", i, err)
}
}
res := fValue.Call(in)
return res, nil
}
func (injector *Injector) getFunctionArgumentInstance(ctx context.Context, argType reflect.Type) (reflect.Value, error) {
if EmbedsParams(argType) {
return injector.createEmbeddedParams(ctx, argType)
} else {
return injector.getInstanceOfAnnotatedType(ctx, argType, "", false)
}
}
func (injector *Injector) createEmbeddedParams(ctx context.Context, embeddedType reflect.Type) (reflect.Value, error) {
if embeddedType.Kind() == reflect.Ptr {
n := reflect.New(embeddedType.Elem())
return n, injector.setParamFields(ctx, n.Elem())
} else { // struct
n := reflect.New(embeddedType).Elem()
return n, injector.setParamFields(ctx, n)
}
}
func (injector *Injector) setParamFields(
ctx context.Context,
paramValue reflect.Value,
) error {
embeddedType := paramValue.Type()
for fieldIndex := 0; fieldIndex < embeddedType.NumField(); fieldIndex++ {
field := paramValue.Field(fieldIndex)
if field.Type() == _paramType {
continue
}
if tag, ok := embeddedType.Field(fieldIndex).Tag.Lookup("inject"); ok {
if !field.CanSet() {
return newInjectionError(field.Type(), tag, fmt.Errorf("use inject tag on unsettable field"))
}
var optional bool
for _, option := range strings.Split(tag, ",") {
if strings.TrimSpace(option) == "optional" {
optional = true
}
}
tag = strings.Split(tag, ",")[0]
instance, err := injector.getInstanceOfAnnotatedType(ctx, field.Type(), tag, optional)
if err != nil {
return newInjectionError(field.Type(), tag, err)
}
if instance.IsValid() {
field.Set(instance)
} else if optional {
continue
} else {
return newInjectionError(field.Type(), tag, fmt.Errorf("cannot get valid instance from scope"))
}
}
}
return nil
}
// getInstanceOfAnnotatedType resolves a type request within the injector
func (injector *Injector) getInstanceOfAnnotatedType(
ctx context.Context,
t reflect.Type,
annotation string,
optional bool,
) (reflect.Value, error) {
// if is slice, return as multi bindings
if t.Kind() == reflect.Slice {
bindings := injector.findBindingsForAnnotatedType(t.Elem(), annotation)
if len(bindings) > 0 {
n := reflect.MakeSlice(t, 0, len(bindings))
for _, binding := range bindings {
r, err := injector.getScopedInstanceFromBinding(ctx, binding)
if err != nil {
return reflect.Value{}, err
}
n = reflect.Append(n, r)
}
return n, nil
} else if optional {
return reflect.MakeSlice(t, 0, 0), nil
} else {
return reflect.MakeSlice(t, 0, 0), newInjectionError(t.Elem(), annotation,
fmt.Errorf("did not found binding, expected at least one"))
}
}
// check if there is a binding for this type & annotation
bindings := injector.findBindingsForAnnotatedType(t, annotation)
if len(bindings) > 1 {
return reflect.Value{},
newInjectionError(t, annotation, fmt.Errorf("found multiple bindings expected one"))
} else if len(bindings) == 1 {
return injector.getScopedInstanceFromBinding(ctx, bindings[0])
} else if injector.isProviderType(t) {
return injector.createProviderValue(t, annotation, optional), nil
} else if t == invocationContextReflectType {
return reflect.ValueOf(ctx), nil
} else if optional {
return reflect.Value{}, nil
} else {
return reflect.Value{},
newInjectionError(t, annotation, fmt.Errorf("did not found binding, expected one"))
}
}
func (injector *Injector) isProviderType(t reflect.Type) bool {
return t.Kind() == reflect.Func &&
t.NumIn() == 1 && t.In(0) == invocationContextReflectType &&
t.NumOut() == 2 && t.Out(1) == errorReflectType
}
func (injector *Injector) createProviderValue(
t reflect.Type,
annotation string,
optional bool,
) reflect.Value {
bindingType := t.Out(0)
return reflect.MakeFunc(t, func(args []reflect.Value) (results []reflect.Value) {
ctx := args[0].Interface().(context.Context)
instance, err := injector.getInstanceOfAnnotatedType(ctx, bindingType, annotation, optional)
var instanceVal reflect.Value
if instance.IsValid() {
instanceVal = instance
} else {
instanceVal = reflect.Zero(bindingType)
}
var errVal reflect.Value
if err != nil {
errVal = reflect.ValueOf(err)
} else {
errVal = reflect.Zero(errorReflectType)
}
return []reflect.Value{
instanceVal,
errVal,
}
})
}
func (injector *Injector) findBindingsForAnnotatedType(
t reflect.Type,
annotation string,
) []*binding {
if _, ok := injector.bindings[t]; ok && len(injector.bindings[t][annotation]) > 0 {
bindings := injector.bindings[t][annotation]
res := make([]*binding, len(bindings))
copy(res, bindings)
return res
}
return []*binding{}
}
func (injector *Injector) getScopedInstanceFromBinding(
ctx context.Context,
binding *binding,
) (reflect.Value, error) {
scope, err := injector.getScopeFromBinding(binding)
if err != nil {
return reflect.Value{}, err
}
val, err := scope.ResolveBinding(ctx, binding, func() (Instance, error) {
val, creationError := binding.create(ctx, injector)
destroyMethod := binding.destroyMethod
if creationError == nil && destroyMethod != nil && !val.IsZero() {
scope.RegisterDestructionCallback(
ctx,
func() { destroyMethod(val) },
)
}
return Instance(val), creationError
})
return reflect.Value(val), err
}
func (injector *Injector) getScopeFromBinding(
binding *binding,
) (Scope, error) {
if scope, ok := injector.scopes[binding.scope]; ok {
return scope, nil
}
return nil, newInjectionError(
binding.typeof, binding.annotatedWith, fmt.Errorf("unknown scope %q for binding", binding.scope))
}