-
Notifications
You must be signed in to change notification settings - Fork 207
/
dig.go
394 lines (349 loc) · 10.8 KB
/
dig.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
394
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package dig
import (
"bytes"
"errors"
"fmt"
"reflect"
)
var (
_noValue reflect.Value
_errType = reflect.TypeOf((*error)(nil)).Elem()
_parameterObjectType = reflect.TypeOf((*parameterObject)(nil)).Elem()
_paramType = reflect.TypeOf(Param{})
)
// A Container is a directed, acyclic graph of dependencies. Dependencies are
// constructed on-demand and returned from a cache thereafter, so they're
// effectively singletons.
type Container struct {
nodes map[reflect.Type]node
cache map[reflect.Type]reflect.Value
}
// New constructs a ready-to-use Container.
func New() *Container {
return &Container{
nodes: make(map[reflect.Type]node),
cache: make(map[reflect.Type]reflect.Value),
}
}
// Provide teaches the Container how to construct one or more new types. It
// accepts either a constructor function or an already-constructed object.
//
// Any function passed to Provide is assumed to be a constructor. Constructors
// can take any number of parameters, which will be supplied by the Container
// on demand. They must return at least one non-error value, all of which are
// then available in the Container. If the last returned value is an error, the
// Container inspects it to determine whether the constructor succeeded or
// failed. Regardless of position, returned errors are never put into the
// Container's dependency graph.
//
// All non-functions (including structs, pointers, Go's built-in collections,
// and primitive types like ints) are inserted into the Container as-is.
func (c *Container) Provide(constructor interface{}) error {
ctype := reflect.TypeOf(constructor)
if ctype == nil {
return errors.New("can't provide an untyped nil")
}
// Since we want to wrap any errors, don't return early.
var err error
if ctype.Kind() != reflect.Func {
err = c.provideInstance(constructor)
} else {
err = c.provideConstructor(constructor, ctype)
}
if err == nil {
return nil
}
return fmt.Errorf("can't provide %v: %v", ctype, err)
}
// Invoke runs a function, supplying its arguments from the Container. If the
// function's last return value is an error, that error is propagated to the
// caller. All other returned values (if any) are ignored.
//
// Passing anything other than a function to Invoke returns an error
// immediately.
func (c *Container) Invoke(function interface{}) error {
ftype := reflect.TypeOf(function)
if ftype.Kind() != reflect.Func {
return fmt.Errorf("can't invoke non-function %v (type %v)", function, ftype)
}
args, err := c.constructorArgs(ftype)
if err != nil {
return fmt.Errorf("failed to get arguments for %v (type %v): %v", function, ftype, err)
}
returned := reflect.ValueOf(function).Call(args)
if len(returned) == 0 {
return nil
}
if last := returned[len(returned)-1]; last.Type() == _errType && last.Interface() != nil {
return fmt.Errorf("failed to execute %v (type %v): %v", function, ftype, last.Interface())
}
return nil
}
func (c *Container) provideInstance(val interface{}) error {
vtype := reflect.TypeOf(val)
if vtype == _errType {
return errors.New("can't provide errors")
}
if vtype.Implements(_parameterObjectType) {
return errors.New("can't provide parameter objects")
}
if _, ok := c.nodes[vtype]; ok {
return errors.New("already in container")
}
c.nodes[vtype] = node{provides: vtype}
c.cache[vtype] = reflect.ValueOf(val)
return nil
}
func (c *Container) provideConstructor(ctor interface{}, ctype reflect.Type) error {
returnTypes := make(map[reflect.Type]struct{}, ctype.NumOut())
for i := 0; i < ctype.NumOut(); i++ {
rt := ctype.Out(i)
if rt == _errType {
// Don't register errors into the container.
continue
}
if rt.Implements(_parameterObjectType) {
return errors.New("can't provide parameter objects")
}
if _, ok := returnTypes[rt]; ok {
return fmt.Errorf("returns multiple %v", rt)
}
if _, ok := c.nodes[rt]; ok {
return fmt.Errorf("provides type %v, which is already in the container", rt)
}
returnTypes[rt] = struct{}{}
}
if len(returnTypes) == 0 {
return errors.New("must provide at least one non-error type")
}
nodes := make([]node, 0, len(returnTypes))
for rt := range returnTypes {
n, err := newNode(rt, ctor, ctype)
if err != nil {
return err
}
nodes = append(nodes, n)
c.nodes[rt] = n
}
for _, n := range nodes {
if err := c.isAcyclic(n); err != nil {
c.remove(nodes)
return fmt.Errorf("introduces a cycle: %v", err)
}
}
return nil
}
func (c *Container) isAcyclic(n node) error {
// TODO: use a map along with this for more speed
return detectCycles(n, c.nodes, nil)
}
func (c *Container) get(t reflect.Type) (reflect.Value, error) {
if v, ok := c.cache[t]; ok {
return v, nil
}
n, ok := c.nodes[t]
if !ok {
return _noValue, fmt.Errorf("type %v isn't in the container", t)
}
if err := c.contains(n.deps); err != nil {
return _noValue, fmt.Errorf("missing dependencies for type %v: %v", t, err)
}
args, err := c.constructorArgs(n.ctype)
if err != nil {
return _noValue, fmt.Errorf("couldn't get arguments for constructor %v: %v", n.ctype, err)
}
constructed := reflect.ValueOf(n.ctor).Call(args)
// Provide-time validation ensures that all constructors return at least
// one value.
if err := constructed[len(constructed)-1]; err.Type() == _errType && err.Interface() != nil {
return _noValue, fmt.Errorf("constructor %v for type %v failed: %v", n.ctype, t, err.Interface())
}
var ret reflect.Value
for _, con := range constructed {
ct := con.Type()
if ct == _errType {
continue
}
c.cache[ct] = con
if ct == t {
ret = con
}
}
return ret, nil
}
func (c *Container) contains(types []reflect.Type) error {
var missing []reflect.Type
for _, t := range types {
if _, ok := c.nodes[t]; !ok {
missing = append(missing, t)
}
}
if len(missing) > 0 {
return fmt.Errorf("container is missing types: %v", missing)
}
return nil
}
func (c *Container) remove(nodes []node) {
for _, n := range nodes {
delete(c.nodes, n.provides)
}
}
func (c *Container) constructorArgs(ctype reflect.Type) ([]reflect.Value, error) {
args := make([]reflect.Value, 0, ctype.NumIn())
for i := 0; i < ctype.NumIn(); i++ {
var (
arg reflect.Value
err error
)
t := ctype.In(i)
if t.Implements(_parameterObjectType) {
arg, err = getParameterObject(c, t)
} else {
arg, err = c.get(t)
}
if err != nil {
return nil, fmt.Errorf("couldn't get arguments for constructor %v: %v", ctype, err)
}
args = append(args, arg)
}
return args, nil
}
type node struct {
provides reflect.Type
ctor interface{}
ctype reflect.Type
deps []reflect.Type
}
func newNode(provides reflect.Type, ctor interface{}, ctype reflect.Type) (node, error) {
deps := make([]reflect.Type, 0, ctype.NumIn())
for i := 0; i < ctype.NumIn(); i++ {
t := ctype.In(i)
if t.Implements(_parameterObjectType) {
pdeps, err := getParameterDependencies(t)
if err != nil {
return node{}, err
}
deps = append(deps, pdeps...)
} else {
deps = append(deps, t)
}
}
return node{
provides: provides,
ctor: ctor,
ctype: ctype,
deps: deps,
}, nil
}
func cycleError(cycle []reflect.Type, last reflect.Type) error {
b := &bytes.Buffer{}
for _, t := range cycle {
fmt.Fprintf(b, "%v ->", t)
}
fmt.Fprintf(b, "%v", last)
return errors.New(b.String())
}
func detectCycles(n node, graph map[reflect.Type]node, path []reflect.Type) error {
for _, seen := range path {
if n.provides == seen {
return cycleError(path, n.provides)
}
}
path = append(path, n.provides)
for _, depType := range n.deps {
depNode, ok := graph[depType]
if !ok {
continue
}
if err := detectCycles(depNode, graph, path); err != nil {
return err
}
}
return nil
}
// Param is embedded inside structs to opt those structs in as Dig parameter
// objects.
//
// TODO usage docs
type Param struct{}
var _ parameterObject = Param{}
// Param is the only instance of parameterObject.
func (Param) parameterObject() {}
// Users embed the Param struct to opt a struct in as a parameter object.
// Param implements this interface so the struct into which Param is embedded
// also implements this interface. This provides us an easy way to check if
// something embeds Param without iterating through all its fields.
type parameterObject interface {
parameterObject()
}
// Returns dependencies introduced by a parameter object.
func getParameterDependencies(t reflect.Type) ([]reflect.Type, error) {
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
var deps []reflect.Type
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.PkgPath != "" {
continue // skip private fields
}
// Skip the embedded Param type.
if f.Anonymous && f.Type == _paramType {
continue
}
// THe user added a parameter object as a dependency. We don't recurse
// /yet/ so let's try to give an informative error message.
if f.Type.Implements(_parameterObjectType) {
return nil, fmt.Errorf(
"dig parameter objects may not be used as fields of other parameter objects: "+
"field %v (type %v) of %v is a parameter object", f.Name, f.Type, t)
}
deps = append(deps, f.Type)
}
return deps, nil
}
func getParameterObject(c *Container, t reflect.Type) (reflect.Value, error) {
dest := reflect.New(t).Elem()
result := dest
for t.Kind() == reflect.Ptr {
t = t.Elem()
dest.Set(reflect.New(t))
dest = dest.Elem()
}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.PkgPath != "" {
continue // skip private fields
}
// Skip the embedded Param type.
if f.Anonymous && f.Type == _paramType {
continue
}
v, err := c.get(f.Type)
if err != nil {
return result, fmt.Errorf(
"could not get field %v (type %v) of %v: %v", f.Name, f.Type, t, err)
}
dest.Field(i).Set(v)
}
return result, nil
}