Repository navigation
Expand file tree
/
Copy pathinvoke.go
More file actions
386 lines (313 loc) · 12.6 KB
/
Copy pathinvoke.go
File metadata and controls
386 lines (313 loc) · 12.6 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
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
378
379
380
381
382
383
384
385
386
package do
import (
"errors"
"fmt"
"reflect"
"sort"
"strings"
"unsafe"
typetostring "github.com/samber/go-type-to-string"
)
// invokeAnyByName retrieves and instantiates a service by name, returning it as interface{}.
// This function handles circular dependency detection, service resolution, and invocation hooks.
//
// Parameters:
// - i: The injector to search for the service
// - name: The name of the service to invoke
//
// Returns the service instance as interface{} and any error that occurred during invocation.
//
// This function is used internally by the DI container for service resolution and
// supports virtual scopes for dependency tracking and circular dependency detection.
func invokeAnyByName(i Injector, name string) (any, error) {
var invokerChain []string
injector := getInjectorOrDefault(i)
vScope, isVirtualScope := injector.(*virtualScope)
if isVirtualScope {
invokerChain = vScope.invokerChain
if err := vScope.detectCircularDependency(name); err != nil {
return nil, err
}
}
invokerChain = append(invokerChain, name)
serviceAny, serviceScope, found := injector.serviceGetRec(name)
if !found {
return nil, serviceNotFound(injector, ErrServiceNotFound, invokerChain)
}
if isVirtualScope {
vScope.addDependency(injector, name, serviceScope)
}
service, ok := serviceAny.(serviceWrapperAny)
if !ok {
return nil, serviceNotFound(injector, ErrServiceNotFound, invokerChain)
}
injector.RootScope().opts.onBeforeInvocation(serviceScope, name)
instance, err := service.getInstanceAny(newVirtualScope(serviceScope, invokerChain))
injector.RootScope().opts.onAfterInvocation(serviceScope, name, err)
if err != nil {
return nil, err
}
serviceScope.onServiceInvoke(name)
injector.RootScope().opts.Logf("DI: service %s invoked", name)
return instance, nil
}
// invokeByName retrieves and instantiates a service by name with type safety.
// This function handles circular dependency detection, service resolution, type checking,
// and invocation hooks.
//
// Parameters:
// - i: The injector to search for the service
// - name: The name of the service to invoke
//
// Returns the service instance with the correct type and any error that occurred during invocation.
//
// This function is used internally by the DI container for type-safe service resolution.
// It ensures that the returned service matches the expected type T.
func invokeByName[T any](i Injector, name string) (T, error) {
var invokerChain []string
injector := getInjectorOrDefault(i)
vScope, isVirtualScope := injector.(*virtualScope)
if isVirtualScope {
invokerChain = vScope.invokerChain
if err := vScope.detectCircularDependency(name); err != nil {
return empty[T](), err
}
}
invokerChain = append(invokerChain, name)
serviceAny, serviceScope, found := injector.serviceGetRec(name)
if !found {
return empty[T](), serviceNotFound(injector, ErrServiceNotFound, invokerChain)
}
if isVirtualScope {
vScope.addDependency(injector, name, serviceScope)
}
service, ok := serviceAny.(serviceWrapper[T])
if !ok {
return empty[T](), serviceTypeMismatch(inferServiceName[T](), serviceAny.(serviceWrapperAny).getTypeName()) //nolint:errcheck,forcetypeassert
}
injector.RootScope().opts.onBeforeInvocation(serviceScope, name)
instance, err := service.getInstance(newVirtualScope(serviceScope, invokerChain))
injector.RootScope().opts.onAfterInvocation(serviceScope, name, err)
if err != nil {
return empty[T](), err
}
serviceScope.onServiceInvoke(name)
injector.RootScope().opts.Logf("DI: service %s invoked", name)
return instance, nil
}
// invokeByGenericType looks for a service by its type and invokes the first matching service.
// When multiple services match the provided type or interface, the first service found
// will be invoked. This function is useful for interface-based dependency injection.
//
// Parameters:
// - i: The injector to search for the service
//
// Returns the service instance with the correct type and any error that occurred during invocation.
//
// @TODO: Selection is nondeterministic when multiple services satisfy T; consider deterministic ordering
// or explicit disambiguation to avoid surprising picks.
func invokeByGenericType[T any](i Injector) (T, error) {
injector := getInjectorOrDefault(i)
serviceAliasName := inferServiceName[T]()
var invokerChain []string
vScope, isVirtualScope := injector.(*virtualScope)
if isVirtualScope {
invokerChain = vScope.invokerChain
}
var serviceInstance any
var serviceScope *Scope
var serviceRealName string
var ok bool
injector.serviceForEachRec(func(name string, scope *Scope, s any) bool {
if serviceCanCastToGeneric[T](s) {
serviceInstance = s
serviceScope = scope
serviceRealName = s.(serviceWrapperGetName).getName() //nolint:errcheck,forcetypeassert
ok = true
// Stop or not stop, that's the question -> https://github.com/samber/do/issues/114
return false
}
return true
})
if !ok {
return empty[T](), serviceNotFound(injector, ErrServiceNotMatch, append(invokerChain, serviceAliasName))
}
if isVirtualScope {
if err := vScope.detectCircularDependency(serviceRealName); err != nil {
return empty[T](), err
}
}
injector.RootScope().opts.onBeforeInvocation(serviceScope, serviceAliasName)
instance, err := serviceInstance.(serviceWrapperGetInstanceAny).getInstanceAny( //nolint:errcheck,forcetypeassert
newVirtualScope(serviceScope, append(invokerChain, serviceRealName)),
)
injector.RootScope().opts.onAfterInvocation(serviceScope, serviceAliasName, err)
if err != nil {
return empty[T](), err
}
if isVirtualScope {
// We chose to register the real service name in invocation chain, because using the
// interface name would break cycle detection.
vScope.addDependency(injector, serviceRealName, serviceScope)
}
serviceScope.onServiceInvoke(serviceRealName)
injector.RootScope().opts.Logf("DI: service %s invoked", serviceAliasName)
return instance.(T), nil //nolint:errcheck,forcetypeassert
}
// invokeByTag injects services into struct fields based on struct tags.
// This function supports automatic dependency injection into struct fields
// using the `do` tag or a custom tag key specified in the injector options.
// If `implicitAliasing` is true and a service is not found by tag, the injector
// will fall back to searching for a service by the field's generic type, like `do.InvokeAs[T]`.
//
// Parameters:
// - i: The injector to search for services
// - structName: The name of the struct for error reporting
// - structValue: A reflect.Value pointing to the struct to inject into
// - implicitAliasing: Whether to fall back to generic type if service is not found by name
//
// Returns an error if injection fails for any reason.
//
// The function does not manipulate virtual scope because it is done by invokeAnyByName or invokeByGenericType.
//
// @TODO: When implicitAliasing is enabled and the tag name is empty, fallback by type may select an arbitrary
// matching service depending on iteration order; consider stable ordering or explicit disambiguation.
func invokeByTags(i Injector, structName string, structValue reflect.Value, implicitAliasing bool) error { //nolint:gocyclo
injector := getInjectorOrDefault(i)
// Ensure that servicePtr is a pointer to a struct
if structValue.Kind() != reflect.Pointer || structValue.Elem().Kind() != reflect.Struct {
return fmt.Errorf("DI: must be a pointer to a struct")
}
structValue = structValue.Elem()
// Iterate through the fields of the struct
for i := 0; i < structValue.NumField(); i++ {
field := structValue.Type().Field(i)
fieldValue := structValue.Field(i)
serviceName, ok := field.Tag.Lookup(coalesce(injector.RootScope().opts.StructTagKey, DefaultStructTagKey))
if !ok {
continue
}
// Keep track if tag was provided without an explicit name (eg: `do:""`)
wasTagNameEmpty := serviceName == ""
if !fieldValue.CanAddr() {
return fmt.Errorf("DI: field is not addressable `%s.%s`", structName, field.Name)
}
if !fieldValue.CanSet() {
// When a field is not exported, we override it.
// See https://stackoverflow.com/questions/42664837/how-to-access-unexported-struct-fields/43918797#43918797
// bearer:disable go_gosec_unsafe_unsafe
fieldValue = reflect.NewAt(fieldValue.Type(), unsafe.Pointer(fieldValue.UnsafeAddr())).Elem()
}
if serviceName == "" {
serviceName = typetostring.GetReflectValueType(fieldValue)
}
dependency, err := invokeAnyByName(injector, serviceName)
// @TODO: This fallback may pick an arbitrary matching service; selection order is not stable.
if err != nil && implicitAliasing && wasTagNameEmpty && errors.Is(err, ErrServiceNotFound) {
// Fallback: try to resolve by generic type of the field
toType := fieldValue.Type()
var resolvedName string
var found bool
injector.serviceForEachRec(func(name string, _ *Scope, s any) bool {
if serviceCanCastToType(s, toType) {
resolvedName = s.(serviceWrapperGetName).getName() //nolint:errcheck,forcetypeassert
found = true
// Stop or not stop, that's the question -> https://github.com/samber/do/issues/114
return false
}
return true
})
if found {
dependency, err = invokeAnyByName(injector, resolvedName)
}
}
if err != nil {
return err
}
dependencyValue := reflect.ValueOf(dependency)
// Should be checked before invocation, because we just built something that is not assignable to the field.
if !dependencyValue.Type().AssignableTo(fieldValue.Type()) {
return fmt.Errorf("DI: `%s` is not assignable to field `%s.%s`", serviceName, structName, field.Name)
}
// Should not panic, since we checked CanAddr() and CanSet() earlier.
fieldValue.Set(dependencyValue)
}
return nil
}
// serviceNotFound returns a detailed error indicating that the specified service was not found.
// This function provides helpful error messages that include available services and
// the invocation chain for debugging purposes.
func serviceNotFound(injector Injector, err error, chain []string) error {
name := chain[len(chain)-1]
services := injector.ListProvidedServices()
if len(services) == 0 {
if len(chain) > 1 {
return fmt.Errorf("%w `%s`, no service available, path: %s", err, name, humanReadableInvokerChain(chain))
}
return fmt.Errorf("%w `%s`, no service available", err, name)
}
serviceNames := getServiceNames(services)
sortedServiceNames := sortServiceNames(serviceNames)
if len(chain) > 1 {
return fmt.Errorf(
"%w `%s`, available services: %s, path: %s",
err,
name,
strings.Join(sortedServiceNames, ", "),
humanReadableInvokerChain(chain),
)
}
return fmt.Errorf("%w `%s`, available services: %s", err, name, strings.Join(sortedServiceNames, ", "))
}
// serviceTypeMismatch returns an error indicating that the specified service was found,
// but its type does not match the expected type. This typically occurs when a service
// is registered with one type but invoked with a different type.
func serviceTypeMismatch(invoking string, registered string) error {
return fmt.Errorf("DI: service found, but type mismatch: invoking `%s` but registered `%s`", invoking, registered)
}
// getServiceNames formats a list of ServiceDescription names for error reporting.
// This function converts ServiceDescription objects to formatted string names
// that can be displayed in error messages.
func getServiceNames(services []ServiceDescription) []string {
return mAp(services, func(desc ServiceDescription, _ int) string {
return fmt.Sprintf("`%s`", desc.Service)
})
}
// sortServiceNames sorts a list of service names alphabetically.
// This function ensures consistent ordering of service names in error messages
// and other output, making them easier to read and compare.
func sortServiceNames(names []string) []string {
sort.Strings(names)
return names
}
// humanReadableInvokerChain formats an invocation chain into a human-readable string.
// This function converts a slice of service names into a formatted string
// that shows the dependency chain for debugging purposes.
//
// This is useful for debugging circular dependencies and understanding
// the service resolution path that led to an error.
func humanReadableInvokerChain(invokerChain []string) string {
invokerChain = mAp(invokerChain, func(item string, _ int) string {
return fmt.Sprintf("`%s`", item)
})
return strings.Join(invokerChain, " -> ")
}
func handleProviderPanic[T any](provider Provider[T], i Injector) (svc T, err error) {
defer func() {
if r := recover(); r != nil {
if e, ok := r.(error); ok {
err = e
} else {
err = fmt.Errorf("DI: %v", r)
}
}
}()
_svc, _err := provider(i)
// do not return svc when err != nil
if _err != nil {
err = _err
} else {
svc = _svc
}
return svc, err
}