-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
349 lines (307 loc) · 10.3 KB
/
context.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
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
package pp_ioc
import (
"github.com/pkg/errors"
"github.com/wlad031/pp-algo/list"
logCtx "github.com/wlad031/pp-logging"
"reflect"
)
//region public
const (
// Name of the bean that represents the context itself
ContextBeanName = "ApplicationContext"
EnvironmentBeanName = "Environment"
TagValue = "value"
TagFactory = "factory"
TagQualifiers = "qualifiers"
TagQualifier = "qualifier"
TagPriority = "priority"
TagScope = "scope"
)
type Context interface {
// Creates and returns new Binder instance
NewBinder() *Binder
NewPropertySourceBinder() *Binder
GetBeanByName(name string) (interface{}, error) // TODO: implement
GetBeanByType(type_ reflect.Type) (interface{}, error) // TODO: implement
GetAllBeansByType(type_ reflect.Type) ([]interface{}, error) // TODO: implement
// Returns the context's environment
GetEnvironment() Environment
// Builds the entire container. Should be called
// to instantiate all the beans.
Build() error
// Refreshes the context. All bean definitions will stay the same,
// but all beans will be reinstantiated.
Refresh() error
}
// Context constructor
func NewContext() Context {
ctx := contextImpl{
logger: logCtx.Get("IOC"),
beanFactoryValidator: newBeanFactoryValidator(),
binders: newBinderContainer(),
beanDefinitions: newBeanDefinitionList(),
graph: newContextGraph(),
container: newBeanContainer(),
postProcessors: newPostProcessorContainer(),
environment: newEnvironment(),
initialized: false,
}
return &ctx
}
//endregion
//region private
type contextImpl struct {
logger logCtx.NamedLogger
beanFactoryValidator *beanFactoryValidator
binders *binderContainer
beanDefinitions *beanDefinitionContainer
graph *contextGraph
container *beanContainer
postProcessors *postProcessorContainer
environment Environment
initialized bool // TODO: use this field somewhere
}
func (ctx *contextImpl) NewBinder() *Binder {
binder := NewBinder()
_ = ctx.binders.add(binder)
return binder
}
func (ctx *contextImpl) NewPropertySourceBinder() *Binder {
return ctx.NewBinder().
Priority(PropertySourceHighestPriority).
Scope(ScopeSingleton)
}
func (ctx *contextImpl) GetBeanByName(name string) (interface{}, error) {
for bean := range ctx.container.iterate() {
for _, beanName := range bean.definition.key.qualifiers {
if beanName == name {
return bean.instance, nil
}
}
}
return nil, errors.New("Cannot find bean with name " + name)
}
func (ctx *contextImpl) GetBeanByType(type_ reflect.Type) (interface{}, error) {
for bean := range ctx.container.iterate() {
if bean.definition.key.type_ == type_ {
return bean.instance, nil
}
}
return nil, nil
}
func (ctx *contextImpl) GetAllBeansByType(type_ reflect.Type) ([]interface{}, error) {
var res []interface{}
for bean := range ctx.container.iterate() {
if bean.definition.key.type_.Implements(type_.Elem()) { // FIXME: doesn't work correctly
res = append(res, bean.instance)
}
}
return res, nil
}
func (ctx *contextImpl) GetEnvironment() Environment {
return ctx.environment
}
func (ctx *contextImpl) Build() error {
ctx.logger.Info("Building the context...")
e := ctx.bindEverything()
if e != nil {
return e
}
e = ctx.graph.build(ctx.beanDefinitions)
if e != nil {
return e
}
e = ctx.instantiateBeans()
if e != nil {
return e
}
e = ctx.runPostProcessors()
if e != nil {
return e
}
ctx.initialized = true
return nil
}
func (ctx *contextImpl) Refresh() error {
panic("implement me") // FIXME: refresh server correctly
//ctx.logger.Info("Refreshing the context...")
//ctx.beanDefinitions = newBeanDefinitionList()
//ctx.graph = newContextGraph()
//ctx.container = newBeanContainer()
//ctx.postProcessors = newPostProcessorContainer()
//ctx.environment = newEnvironment()
//ctx.initialized = false
//return ctx.Build()
}
func (ctx *contextImpl) bindEverything() error {
_ = ctx.binders.add(
ctx.createContextBinder(),
ctx.createEnvironmentBinder(),
)
nestedBinders := list.New()
for binder := range ctx.binders.iterate() {
e := binder.collectNestedBinders(nestedBinders)
if e != nil {
return e
}
}
for b := range nestedBinders.Iterate() {
_ = ctx.binders.add(b.(*Binder))
}
for binder := range ctx.binders.iterate() {
e := ctx.bind(binder)
if e != nil {
return errors.Wrap(e, "Error happened during binding "+binder.String())
}
}
return nil
}
// Creates a binder for context itself.
// Other beans will be able to use it as a normal dependency.
func (ctx *contextImpl) createContextBinder() *Binder {
return NewBinder().
Priority(ContextPriority).
Scope(ScopeSingleton).
Qualifiers(ContextBeanName).
Factory(func() (Context, error) {
return ctx, nil
})
}
// Creates a binder for environment instance.
// Other beans will be able to use it as a normal dependency.
func (ctx *contextImpl) createEnvironmentBinder() *Binder {
return NewBinder().
Priority(EnvironmentPriority).
Scope(ScopeSingleton).
Qualifiers(EnvironmentBeanName).
Factory(func() (Environment, error) {
return ctx.environment, nil
})
}
func (ctx *contextImpl) bind(binder *Binder) error {
if e := ctx.beanFactoryValidator.validate(binder.beanFactory); e != nil {
return e
}
dependencies, paramTypes := binder.beanFactory.collectDependencies()
definition := &beanDefinition{
key: binder.buildBindKey(),
dependencies: dependencies,
paramTypes: paramTypes,
scope: binder.scope,
priority: binder.priority,
factory: binder.beanFactory,
}
ctx.beanDefinitions.add(definition)
return nil
}
func (ctx *contextImpl) addBeanToContainers(bean *bean) error {
ctx.container.add(bean)
if bean.definition.isPropertySource() {
if e := ctx.environment.addPropertySource(bean); e != nil {
return e
}
}
if bean.definition.isPostProcessor() {
if e := ctx.postProcessors.add(bean); e != nil {
return e
}
}
return nil
}
func (ctx *contextImpl) getDependencyValueInstance(dependency *dependency) (reflect.Value, error) {
var propertyValue string
var e error
if dependency.valueProvider.hasDefault {
propertyValue = ctx.environment.GetPropertyOrDefault(dependency.qualifier, dependency.valueProvider.defaultValue)
} else {
propertyValue, e = ctx.environment.GetProperty(dependency.qualifier)
if e != nil {
return reflect.Value{}, e
}
}
return dependency.parsePropertyValue(propertyValue)
}
func (ctx *contextImpl) findDependencyBeanValue(dependency *dependency) (reflect.Value, error) {
var isBeanFound = false
var foundBean reflect.Value
for bean := range ctx.container.iterate() {
isBeanSuitable :=
(dependency.hasQualifier &&
bean.definition.isSuitableForDependencyByQualifier(dependency) &&
bean.definition.isSuitableForDependencyByType(dependency)) ||
(!dependency.hasQualifier &&
bean.definition.isSuitableForDependencyByType(dependency))
if isBeanFound && isBeanSuitable {
return reflect.Value{}, errors.New("Two or more beans are suitable for dependency " + dependency.String())
}
if isBeanSuitable {
isBeanFound = true
foundBean = reflect.ValueOf(bean.instance)
}
}
if !isBeanFound {
return reflect.Value{}, errors.New("Cannot find bean for dependency " + dependency.String())
}
return foundBean, nil
}
func (ctx *contextImpl) findDependencyValue(dependency *dependency) (reflect.Value, error) {
if dependency.isValue {
return ctx.getDependencyValueInstance(dependency)
}
if dependency.isBean {
return ctx.findDependencyBeanValue(dependency)
}
return reflect.Value{}, errors.New("Invalid dependency " + dependency.String())
}
// TODO: refactor this function
func (ctx *contextImpl) instantiateBeans() error {
ctx.logger.Info("Instantiation the beans...")
for definition := range ctx.graph.iterate() {
var paramValues []reflect.Value
var paramIndex uint16 = 0
for _, paramType := range definition.paramTypes {
if paramType.Kind() == reflect.Struct {
if !(definition.factory.isMethod && paramIndex == 0) {
structParam := reflect.New(paramType).Elem()
for i := 0; i < paramType.NumField(); i++ {
dependency := definition.dependencies[paramIndex]
instance, e := ctx.findDependencyValue(dependency)
if e != nil {
return e
}
structParam.FieldByName(dependency.name).Set(instance)
paramIndex += 1
}
paramValues = append(paramValues, structParam)
continue
}
}
dependency := definition.dependencies[paramIndex]
instance, e := ctx.findDependencyValue(dependency)
if e != nil {
return e
}
paramValues = append(paramValues, instance)
paramIndex += 1
}
bean, e := definition.createBean(paramValues)
if e != nil {
return e
}
e = ctx.addBeanToContainers(bean)
if e != nil {
return e
}
}
return nil
}
func (ctx *contextImpl) runPostProcessors() error {
for pp := range ctx.postProcessors.iterate() {
e := pp.PostProcess(ctx)
if e != nil {
return e
}
}
return nil
}
//endregion