-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontainer.go
231 lines (183 loc) · 5.53 KB
/
container.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
package zeus
import (
"errors"
"reflect"
"slices"
"sync"
"github.com/otoru/zeus/errs"
"github.com/otoru/zeus/hooks"
)
// Container holds the registered factories for dependency resolution.
type Container struct {
providers map[reflect.Type]reflect.Value
instances map[reflect.Type]reflect.Value
mu sync.RWMutex
hooks Hooks
}
// New initializes and returns a new instance of the Container.
//
// Example:
//
// c := zeus.New()
func New() *Container {
hooks := new(hooks.LifecycleHooks)
providers := make(map[reflect.Type]reflect.Value)
instances := make(map[reflect.Type]reflect.Value)
container := new(Container)
container.hooks = hooks
container.providers = providers
container.instances = instances
return container
}
// resolve attempts to resolve a dependency of the given type.
// It checks for cyclic dependencies and ensures that all dependencies can be resolved.
// Returns the resolved value and any error encountered during resolution.
func (c *Container) resolve(t reflect.Type, stack []reflect.Type) (reflect.Value, error) {
if slices.Contains(stack, t) {
return reflect.Value{}, errs.CyclicDependencyError{TypeName: t.Name()}
}
c.mu.RLock()
instance, hasInstance := c.instances[t]
provider, hasProvider := c.providers[t]
c.mu.RUnlock()
if hasInstance {
return instance, nil
}
if !hasProvider {
return reflect.Value{}, errs.DependencyResolutionError{TypeName: t.Name()}
}
providerType := provider.Type()
dependencies := make([]reflect.Value, providerType.NumIn())
for i := range dependencies {
argType := providerType.In(i)
if argType.Implements(reflect.TypeOf((*Hooks)(nil)).Elem()) {
dependencies[i] = reflect.ValueOf(c.hooks)
continue
}
argValue, err := c.resolve(argType, append(stack, t))
if err != nil {
return reflect.Value{}, err
}
dependencies[i] = argValue
}
results := provider.Call(dependencies)
if len(results) == 2 && !results[1].IsNil() {
return reflect.Value{}, results[1].Interface().(error)
}
c.instances[t] = results[0]
return results[0], nil
}
// Provide registers a factory function for dependency resolution.
// It ensures that the factory is a function, has a valid return type, and checks for duplicate factories.
// Returns an error if any of these conditions are not met.
//
// Example:
//
// c := zeus.New()
// c.Provide(func() int { return 42 })
func (c *Container) Provide(factories ...interface{}) error {
c.mu.Lock()
defer c.mu.Unlock()
for _, factory := range factories {
factoryType := reflect.TypeOf(factory)
if factoryType.Kind() != reflect.Func {
return errs.NotAFunctionError{}
}
if numOut := factoryType.NumOut(); numOut < 1 || numOut > 2 {
return errs.InvalidFactoryReturnError{NumReturns: numOut}
}
if factoryType.NumOut() == 2 {
errorType := reflect.TypeOf((*error)(nil)).Elem()
if !factoryType.Out(1).Implements(errorType) {
return errs.UnexpectedReturnTypeError{TypeName: factoryType.Out(1).Name()}
}
}
serviceType := factoryType.Out(0)
if _, exists := c.providers[serviceType]; exists {
return errs.FactoryAlreadyProvidedError{TypeName: serviceType.Name()}
}
c.providers[serviceType] = reflect.ValueOf(factory)
}
return nil
}
// Run executes the provided function by resolving and injecting its dependencies.
// It ensures that the function has a valid signature and that all dependencies can be resolved.
// Returns an error if the function signature is invalid or if dependencies cannot be resolved.
//
// Example:
//
// c := zeus.New()
// c.Provide(func() int { return 42 })
// c.Run(func(i int) {
// fmt.Println(i) // Outputs: 42
// })
func (c *Container) Run(fn interface{}) error {
var result error
fnType := reflect.TypeOf(fn)
if fnType.Kind() != reflect.Func {
return errs.NotAFunctionError{}
}
if numOut := fnType.NumOut(); numOut > 1 {
return errs.InvalidFactoryReturnError{NumReturns: numOut}
}
if fnType.NumOut() == 1 && fnType.Out(0).Name() != "error" {
return errs.UnexpectedReturnTypeError{TypeName: fnType.Out(0).Name()}
}
dependencies := make([]reflect.Value, fnType.NumIn())
for i := range dependencies {
argType := fnType.In(i)
argValue, err := c.resolve(argType, nil)
if err != nil {
result = errors.Join(result, err)
break
}
dependencies[i] = argValue
}
if result != nil {
return result
}
if err := c.hooks.Start(); err != nil {
result = errors.Join(result, err)
}
if result != nil {
return result
}
results := reflect.ValueOf(fn).Call(dependencies)
if fnType.NumOut() == 1 && !results[0].IsNil() {
result = errors.Join(result, results[0].Interface().(error))
}
if err := c.hooks.Stop(); err != nil {
result = errors.Join(result, err)
}
return result
}
// Merge combines the factories of another container into the current container.
// If a factory from the other container conflicts with an existing factory in the current container,
// and they are not identical, a FactoryAlreadyProvidedError is returned.
//
// Example:
//
// containerA := New()
// containerB := New()
//
// containerA.Provide(func() string { return "Hello" })
// containerB.Provide(func() int { return 42 })
//
// err := containerA.Merge(containerB)
// if err != nil {
// // Handle merge error
// }
func (c *Container) Merge(other *Container) error {
c.mu.Lock()
defer c.mu.Unlock()
for t, factory := range other.providers {
if existingFactory, exists := c.providers[t]; exists {
if existingFactory.Pointer() != factory.Pointer() {
return errs.FactoryAlreadyProvidedError{TypeName: t.Name()}
}
continue
}
c.providers[t] = factory
}
return nil
}