-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathcontainer.go
393 lines (369 loc) · 9.98 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
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
387
388
389
390
391
392
393
package di
import (
"errors"
"fmt"
"reflect"
)
// Container is a dependency injection container.
type Container struct {
// Dependency injection schema.
schema *defaultSchema
// Array of provider cleanups.
cleanups []func()
}
// New constructs container with provided options. Example usage (simplified):
//
// Define constructors and invocations:
//
// func NewHTTPServer(mux *http.ServeMux) *http.Server {
// return &http.Server{
// Handler: mux,
// }
// }
//
// func NewHTTPServeMux() *http.ServeMux {
// return http.ServeMux{}
// }
//
// func StartServer(server *http.Server) error {
// return server.ListenAndServe()
// }
//
// Use it with container:
//
// container, err := di.New(
// di.Provide(NewHTTPServer),
// di.Provide(NewHTTPServeMux),
// di.Invoke(StartServer),
// )
// if err != nil {
// // handle error
// }
func New(options ...Option) (_ *Container, err error) {
c := &Container{
schema: newDefaultSchema(),
cleanups: []func(){},
}
var di diopts
// apply container diopts
for _, opt := range options {
opt.apply(&di)
}
// provide container to advanced usage e.g. condition providing
_ = c.provide(func() *Container { return c })
if err := c.apply(di); err != nil {
return nil, err
}
return c, nil
}
// Apply applies options to container.
//
// err := container.Apply(
// di.Provide(NewHTTPServer),
// )
// if err != nil {
// // handle error
// }
func (c *Container) Apply(options ...Option) error {
var di diopts
for _, opt := range options {
opt.apply(&di)
}
return c.apply(di)
}
// Provide provides to container reliable way to build type. The constructor will be invoked lazily on-demand.
// For more information about constructors see Constructor interface. ProvideOption can add additional behavior to
// the process of type resolving.
func (c *Container) Provide(constructor Constructor, options ...ProvideOption) error {
if err := c.provide(constructor, options...); err != nil {
return errWithStack(err)
}
return nil
}
// ProvideValue provides value as is.
func (c *Container) ProvideValue(value Value, options ...ProvideOption) error {
if err := c.provideValue(value, options...); err != nil {
return errWithStack(err)
}
return nil
}
// Invocation is a function whose signature looks like:
//
// func StartServer(server *http.Server) error {
// return server.ListenAndServe()
// }
//
// Like a constructor invocation may have unlimited count of arguments and
// they will be resolved automatically. The invocation can return an optional error.
// Error will be returned as is.
type Invocation interface{}
// Invoke calls the function fn. It parses function parameters. Looks for it in a container.
// And invokes function with them. See Invocation for details.
func (c *Container) Invoke(invocation Invocation, options ...InvokeOption) error {
err := c.invoke(invocation, options...)
if err != nil && knownError(err) {
return errWithStack(err)
}
if err != nil {
return err
}
return nil
}
type Pointer interface{}
// Has checks that type exists in container, if not it return false.
//
// var server *http.Server
// if container.Has(&server) {
// // handle server existence
// }
//
// It like Resolve() but doesn't instantiate a type.
func (c *Container) Has(target Pointer, options ...ResolveOption) (bool, error) {
if _, err := c.find(target, options...); errors.Is(err, ErrTypeNotExists) {
return false, nil
} else if err != nil {
return false, err
}
return true, nil
}
// Resolve resolves type and fills target pointer.
//
// var server *http.Server
// if err := container.Resolve(&server); err != nil {
// // handle error
// }
func (c *Container) Resolve(ptr Pointer, options ...ResolveOption) error {
if err := c.resolve(ptr, options...); err != nil {
return errWithStack(err)
}
return nil
}
// ValueFunc is a lazy-loading wrapper for iteration.
type ValueFunc func() (interface{}, error)
// IterateFunc function that will be called on each instance in iterate selection.
type IterateFunc func(tags Tags, value ValueFunc) error
// Iterate iterates over group of Pointer type with IterateFunc.
//
// var servers []*http.Server
// iterFn := func(tags di.Tags, loader ValueFunc) error {
// i, err := loader()
// if err != nil {
// return err
// }
// // do stuff with result: i.(*http.Server)
// return nil
// }
// container.Iterate(&servers, iterFn)
func (c *Container) Iterate(target Pointer, fn IterateFunc, options ...ResolveOption) error {
node, err := c.find(target, options...)
if err != nil {
return err
}
group, ok := node.compiler.(*groupCompiler)
if ok {
for i, n := range group.matched {
err = fn(n.tags, func() (interface{}, error) {
v, err := n.Value(c.schema)
if err != nil {
return nil, err
}
return v.Interface(), nil
})
if err != nil {
return fmt.Errorf("%s with index %d failed: %s", node, i, err)
}
}
return nil
}
return fmt.Errorf("iteration can be used with groups only")
}
// Cleanup runs destructors in reverse order that was been created.
func (c *Container) Cleanup() {
for i := len(c.schema.cleanups) - 1; i >= 0; i-- {
c.schema.cleanups[i]()
}
}
// AddParent adds a parent container. Types are resolved from the container,
// it's parents, and ancestors. An error is a cycle is detected in ancestry tree.
func (c *Container) AddParent(parent *Container) error {
return c.schema.addParent(parent.schema)
}
func (c *Container) apply(di diopts) error {
for _, provide := range di.values {
if err := c.provideValue(provide.value, provide.options...); err != nil {
return fmt.Errorf("%s: %w", provide.frame, err)
}
}
// process di.Resolve() diopts
for _, provide := range di.provides {
if err := c.provide(provide.constructor, provide.options...); err != nil {
return fmt.Errorf("%s: %w", provide.frame, err)
}
}
// error omitted because if logger could not be resolved it will be default
// process di.Invoke() diopts
for _, invoke := range di.invokes {
err := c.invoke(invoke.fn, invoke.options...)
if err != nil && knownError(err) {
return fmt.Errorf("%s: %w", invoke.frame, err)
}
if err != nil {
return err
}
}
// process di.Resolve() diopts
for _, resolve := range di.resolves {
if err := c.resolve(resolve.target, resolve.options...); err != nil {
return fmt.Errorf("%s: %w", resolve.frame, err)
}
}
return nil
}
func (c *Container) provide(constructor Constructor, options ...ProvideOption) error {
if constructor == nil {
return fmt.Errorf("invalid constructor signature, got nil")
}
params := ProvideParams{}
// apply provide options
for _, opt := range options {
opt.applyProvide(¶ms)
}
n, err := newConstructorNode(constructor)
if err != nil {
return err
}
n.decorators = params.Decorators
for k, v := range params.Tags {
n.tags[k] = v
}
return c.provideNode(n, params)
}
func (c *Container) provideValue(value Value, options ...ProvideOption) error {
if value == nil {
return fmt.Errorf("invalid value, got nil")
}
params := ProvideParams{}
// apply provide diopts
for _, opt := range options {
opt.applyProvide(¶ms)
}
v := reflect.ValueOf(value)
n := &node{
compiler: valueCompiler{
rv: v,
},
rv: new(reflect.Value),
rt: v.Type(),
tags: params.Tags,
decorators: params.Decorators,
}
return c.provideNode(n, params)
}
func (c *Container) provideNode(n *node, params ProvideParams) error {
c.schema.register(n)
// register interfaces
for _, cur := range params.Interfaces {
i, err := inspectInterfacePointer(cur)
if err != nil {
return err
}
if !n.rt.Implements(i.Type) {
return fmt.Errorf("%s not implement %s", n, i.Type)
}
c.schema.register(&node{
rv: n.rv,
rt: i.Type,
tags: n.tags,
compiler: n.compiler,
decorators: n.decorators,
})
}
return nil
}
func (c *Container) resolve(ptr Pointer, options ...ResolveOption) error {
node, err := c.find(ptr, options...)
if err != nil {
return err
}
value, err := node.Value(c.schema)
if err != nil {
return fmt.Errorf("%s: %w", node, err)
}
rv := reflect.ValueOf(ptr)
target := rv.Elem()
if canInject(rv.Type()) {
for index := range parsePopulateFields(target.Type()) {
target.Field(index).Set(value.Field(index))
}
} else {
target.Set(value)
}
return nil
}
func (c *Container) invoke(invocation Invocation, _ ...InvokeOption) error {
// params := InvokeParams{}
// for _, opt := range diopts {
// opt.apply(¶ms)
// }
if invocation == nil {
return fmt.Errorf("%w, got %s", errInvalidInvocationSignature, "nil")
}
fn, valid := inspectFunction(invocation)
if !valid {
return fmt.Errorf("%w, got %s", errInvalidInvocationSignature, reflect.TypeOf(invocation))
}
if !validateInvocation(fn) {
return fmt.Errorf("%w, got %s", errInvalidInvocationSignature, reflect.TypeOf(invocation))
}
nodes, err := parseInvocationParameters(fn, c.schema)
if err != nil {
return err
}
var args []reflect.Value
for _, node := range nodes {
if err := c.schema.prepare(node); err != nil {
return err
}
v, err := node.Value(c.schema)
if err != nil {
return fmt.Errorf("%s: %s", node, err)
}
args = append(args, v)
}
res := funcResult(fn.Call(args))
if len(res) == 0 {
return nil
}
return res.error(0)
}
func (c *Container) find(ptr Pointer, options ...ResolveOption) (*node, error) {
if ptr == nil {
return nil, fmt.Errorf("target must be a pointer, got nil")
}
if reflect.ValueOf(ptr).Kind() != reflect.Ptr {
return nil, fmt.Errorf("target must be a pointer, got %s", reflect.TypeOf(ptr))
}
params := ResolveParams{}
// apply extract diopts
for _, opt := range options {
opt.applyResolve(¶ms)
}
node, err := c.schema.find(reflect.TypeOf(ptr).Elem(), params.Tags)
if err != nil {
return nil, err
}
if err := c.schema.prepare(node); err != nil {
return nil, err
}
return node, nil
}
type diopts struct {
// Array of di.Provide() options.
provides []provideOptions
// Array of di.ProvideValue() options.
values []provideValueOptions
// Array of di.Invoke() options.
invokes []invokeOptions
// Array of di.Resolve() options.
resolves []resolveOptions
}