-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
container.go
611 lines (501 loc) · 14.6 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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
package container
import (
"fmt"
"reflect"
)
// Container is a low-level dependency injection container which manages dependencies
// based on scopes and security policies. All providers can be run in a scope which
// may provide certain dependencies specifically for that scope or provide/deny access
// to dependencies based on that scope.
type Container struct {
providers map[Key]*node
scopeProviders map[Key]*scopeNode
nodes []*node
scopeNodes []*scopeNode
values map[Key]secureValue
scopedValues map[Scope]map[Key]reflect.Value
securityContext func(scope Scope, tag string) error
}
func NewContainer() *Container {
return &Container{
providers: map[Key]*node{},
scopeProviders: map[Key]*scopeNode{},
nodes: nil,
scopeNodes: nil,
values: map[Key]secureValue{},
scopedValues: map[Scope]map[Key]reflect.Value{},
}
}
type Input struct {
Key
Optional bool
}
type Output struct {
Key
SecurityChecker SecurityChecker
}
type Key struct {
Type reflect.Type
}
type Scope string
type node struct {
Provider
called bool
values []reflect.Value
err error
}
// Provider is a general dependency provider. Its scope parameter is used
// to receive scoped dependencies and gain access to general dependencies within
// its security policy. Access to dependencies provided by this provider can optionally
// be restricted to certain scopes based on SecurityCheckers.
type Provider struct {
// Constructor provides the dependencies
Constructor func(deps []reflect.Value, scope Scope) ([]reflect.Value, error)
// Needs are the keys for dependencies the constructor needs
Needs []Input
// Needs are the keys for dependencies the constructor provides
Provides []Output
// Scope is the scope within which the constructor runs
Scope Scope
IsScopeProvider bool
}
type scopeNode struct {
Provider
calledForScope map[Scope]bool
valuesForScope map[Scope][]reflect.Value
errsForScope map[Scope]error
}
// ScopeProvider provides scoped dependencies. Its constructor function will provide
// dependencies specific to the scope parameter. Instead of providing general dependencies
// with restricted access based on security checkers, ScopeProvider provides potentially different
// dependency instances to different scopes. It is assumed that a scoped provider
// can provide a dependency for any valid scope passed to it, although it can return an error
// to deny access.
type ScopeProvider struct {
// Constructor provides dependencies for the provided scope
Constructor func(scope Scope, deps []reflect.Value) ([]reflect.Value, error)
// Needs are the keys for dependencies the constructor needs
Needs []Input
// Needs are the keys for dependencies the constructor provides
Provides []Key
// Scope is the scope within which the constructor runs, if it is left empty,
// the constructor runs in the scope it was called with (this only applies to ScopeProvider).
Scope Scope
}
type secureValue struct {
value reflect.Value
securityChecker SecurityChecker
}
type SecurityChecker func(scope Scope) error
func (c *Container) RegisterProvider(provider Provider) error {
if !provider.IsScopeProvider {
n := &node{
Provider: provider,
called: false,
}
c.nodes = append(c.nodes, n)
for _, key := range provider.Provides {
if c.providers[key.Key] != nil {
return fmt.Errorf("TODO")
}
if c.scopeProviders[key.Key] != nil {
return fmt.Errorf("TODO")
}
c.providers[key.Key] = n
}
} else {
n := &scopeNode{
Provider: provider,
calledForScope: map[Scope]bool{},
valuesForScope: map[Scope][]reflect.Value{},
errsForScope: map[Scope]error{},
}
c.scopeNodes = append(c.scopeNodes, n)
for _, key := range provider.Provides {
if c.providers[key.Key] != nil {
return fmt.Errorf("TODO")
}
if c.scopeProviders[key.Key] != nil {
return fmt.Errorf("TODO")
}
c.scopeProviders[key.Key] = n
}
return nil
}
return nil
}
//func (c *Container) RegisterScopeProvider(provider *ScopeProvider) error {
// n := &scopeNode{
// ScopeProvider: provider,
// calledForScope: map[Scope]bool{},
// valuesForScope: map[Scope][]reflect.Value{},
// errsForScope: map[Scope]error{},
// }
//
// c.scopeNodes = append(c.scopeNodes, n)
//
// for _, key := range provider.Provides {
// if c.scopeProviders[key] != nil {
// return fmt.Errorf("TODO")
// }
//
// c.scopeProviders[key] = n
// }
//
// return nil
//}
func (c *Container) resolve(scope Scope, input Input, stack map[interface{}]bool) (reflect.Value, error) {
if scope != "" {
if val, ok := c.scopedValues[scope][input.Key]; ok {
return val, nil
}
if provider, ok := c.scopeProviders[input.Key]; ok {
if stack[provider] {
return reflect.Value{}, fmt.Errorf("fatal: cycle detected")
}
if provider.calledForScope[scope] {
return reflect.Value{}, fmt.Errorf("error: %v", provider.errsForScope[scope])
}
var deps []reflect.Value
for _, need := range provider.Needs {
subScope := provider.Scope
// for ScopeProvider we default to the calling scope
if subScope == "" {
subScope = scope
}
stack[provider] = true
res, err := c.resolve(subScope, need, stack)
delete(stack, provider)
if err != nil {
return reflect.Value{}, err
}
deps = append(deps, res)
}
res, err := provider.Constructor(deps, scope)
provider.calledForScope[scope] = true
if err != nil {
provider.errsForScope[scope] = err
return reflect.Value{}, err
}
provider.valuesForScope[scope] = res
for i, val := range res {
p := provider.Provides[i]
if _, ok := c.scopedValues[scope][p.Key]; ok {
return reflect.Value{}, fmt.Errorf("value provided twice")
}
if c.scopedValues[scope] == nil {
c.scopedValues[scope] = map[Key]reflect.Value{}
}
c.scopedValues[scope][p.Key] = val
}
val, ok := c.scopedValues[scope][input.Key]
if !ok {
return reflect.Value{}, fmt.Errorf("internal error: bug")
}
return val, nil
}
}
if val, ok, err := c.getValue(scope, input.Key); ok {
if err != nil {
return reflect.Value{}, err
}
return val, nil
}
if provider, ok := c.providers[input.Key]; ok {
if stack[provider] {
return reflect.Value{}, fmt.Errorf("fatal: cycle detected")
}
if provider.called {
return reflect.Value{}, fmt.Errorf("error: %v", provider.err)
}
err := c.execNode(provider, stack)
if err != nil {
return reflect.Value{}, err
}
val, ok, err := c.getValue(scope, input.Key)
if !ok {
return reflect.Value{}, fmt.Errorf("internal error: bug")
}
return val, err
}
if input.Optional {
return reflect.Zero(input.Type), nil
}
return reflect.Value{}, fmt.Errorf("no provider")
}
func (c *Container) execNode(provider *node, stack map[interface{}]bool) error {
if provider.called {
return provider.err
}
var deps []reflect.Value
for _, need := range provider.Needs {
stack[provider] = true
res, err := c.resolve(provider.Scope, need, stack)
delete(stack, provider)
if err != nil {
return err
}
deps = append(deps, res)
}
res, err := provider.Constructor(deps, "")
provider.called = true
if err != nil {
provider.err = err
return err
}
provider.values = res
for i, val := range res {
p := provider.Provides[i]
if _, ok := c.values[p.Key]; ok {
return fmt.Errorf("value provided twice")
}
c.values[p.Key] = secureValue{
value: val,
securityChecker: p.SecurityChecker,
}
}
return nil
}
func (c *Container) getValue(scope Scope, key Key) (reflect.Value, bool, error) {
if val, ok := c.values[key]; ok {
if val.securityChecker != nil {
if err := val.securityChecker(scope); err != nil {
return reflect.Value{}, true, err
}
}
return val.value, true, nil
}
return reflect.Value{}, false, nil
}
func (c *Container) Resolve(scope Scope, key Key) (reflect.Value, error) {
val, err := c.resolve(scope, Input{
Key: key,
Optional: false,
}, map[interface{}]bool{})
if err != nil {
return reflect.Value{}, err
}
return val, nil
}
// InitializeAll attempts to call all providers instantiating the dependencies they provide
func (c *Container) InitializeAll() error {
for _, node := range c.nodes {
err := c.execNode(node, map[interface{}]bool{})
if err != nil {
return err
}
}
return nil
}
type StructArgs struct{}
func (StructArgs) isStructArgs() {}
type isStructArgs interface{ isStructArgs() }
var structArgsType = reflect.TypeOf(StructArgs{})
var isStructArgsTyp = reflect.TypeOf((*isStructArgs)(nil)).Elem()
var scopeTyp = reflect.TypeOf(Scope(""))
type InMarshaler func([]reflect.Value) reflect.Value
type inFieldMarshaler struct {
n int
inMarshaler InMarshaler
}
type OutMarshaler func(reflect.Value) []reflect.Value
func TypeToInput(typ reflect.Type) ([]Input, InMarshaler, error) {
if typ.AssignableTo(isStructArgsTyp) && typ.Kind() == reflect.Struct {
nFields := typ.NumField()
var res []Input
var marshalers []inFieldMarshaler
for i := 0; i < nFields; i++ {
field := typ.Field(i)
if field.Type == structArgsType {
marshalers = append(marshalers, inFieldMarshaler{
n: 0,
inMarshaler: func(values []reflect.Value) reflect.Value {
return reflect.ValueOf(StructArgs{})
},
})
} else {
fieldInputs, m, err := TypeToInput(field.Type)
if err != nil {
return nil, nil, err
}
optionalTag, ok := field.Tag.Lookup("optional")
if ok {
if len(fieldInputs) == 1 {
if optionalTag != "true" {
return nil, nil, fmt.Errorf("true is the only valid value for the optional tag, got %s", optionalTag)
}
fieldInputs[0].Optional = true
} else if len(fieldInputs) > 1 {
return nil, nil, fmt.Errorf("optional tag cannot be applied to nested StructArgs")
}
}
res = append(res, fieldInputs...)
marshalers = append(marshalers, inFieldMarshaler{
n: len(fieldInputs),
inMarshaler: m,
})
}
}
return res, structMarshaler(typ, marshalers), nil
} else if typ == scopeTyp {
return nil, nil, fmt.Errorf("can't convert type %T to %T", Scope(""), Input{})
} else {
return []Input{{
Key: Key{
Type: typ,
},
}}, func(values []reflect.Value) reflect.Value {
return values[0]
}, nil
}
}
func TypeToOutput(typ reflect.Type, securityContext func(scope Scope, tag string) error) ([]Output, OutMarshaler, error) {
if typ.AssignableTo(isStructArgsTyp) && typ.Kind() == reflect.Struct {
nFields := typ.NumField()
var res []Output
var marshalers []OutMarshaler
for i := 0; i < nFields; i++ {
field := typ.Field(i)
fieldOutputs, fieldMarshaler, err := TypeToOutput(field.Type, securityContext)
if err != nil {
return nil, nil, err
}
securityTag, ok := field.Tag.Lookup("security")
if ok {
if len(fieldOutputs) == 1 {
if securityContext == nil {
return nil, nil, fmt.Errorf("security tag is invalid in this context")
}
fieldOutputs[0].SecurityChecker = func(scope Scope) error {
return securityContext(scope, securityTag)
}
} else if len(fieldOutputs) > 1 {
return nil, nil, fmt.Errorf("security tag cannot be applied to nested StructArgs")
}
}
res = append(res, fieldOutputs...)
marshalers = append(marshalers, fieldMarshaler)
}
return res, func(value reflect.Value) []reflect.Value {
var vals []reflect.Value
for i := 0; i < nFields; i++ {
val := value.Field(i)
vals = append(vals, marshalers[i](val)...)
}
return vals
}, nil
} else if typ == scopeTyp {
return nil, nil, fmt.Errorf("can't convert type %T to %T", Scope(""), Input{})
} else {
return []Output{{
Key: Key{
Type: typ,
},
}}, func(val reflect.Value) []reflect.Value {
return []reflect.Value{val}
}, nil
}
}
func structMarshaler(typ reflect.Type, marshalers []inFieldMarshaler) func([]reflect.Value) reflect.Value {
return func(values []reflect.Value) reflect.Value {
structInst := reflect.Zero(typ)
for i, m := range marshalers {
val := m.inMarshaler(values[:m.n])
structInst.Field(i).Set(val)
values = values[m.n:]
}
return structInst
}
}
func (c *Container) Provide(constructor interface{}) error {
return c.ProvideWithScope(constructor, "")
}
func (c *Container) ProvideWithScope(constructor interface{}, scope Scope) error {
p, err := ConstructorToProvider(constructor, scope, c.securityContext)
if err != nil {
return err
}
return c.RegisterProvider(p)
}
func ConstructorToProvider(constructor interface{}, scope Scope, securityContext func(scope Scope, tag string) error) (Provider, error) {
ctrTyp := reflect.TypeOf(constructor)
if ctrTyp.Kind() != reflect.Func {
return Provider{}, fmt.Errorf("expected function got %T", constructor)
}
numIn := ctrTyp.NumIn()
numOut := ctrTyp.NumOut()
var scopeProvider bool
i := 0
if numIn >= 1 {
if in0 := ctrTyp.In(0); in0 == scopeTyp {
scopeProvider = true
i = 1
}
}
var inputs []Input
var inMarshalers []inFieldMarshaler
for ; i < numIn; i++ {
in, inMarshaler, err := TypeToInput(ctrTyp.In(i))
if err != nil {
return Provider{}, err
}
inputs = append(inputs, in...)
inMarshalers = append(inMarshalers, inFieldMarshaler{
n: len(in),
inMarshaler: inMarshaler,
})
}
var outputs []Output
var outMarshalers []OutMarshaler
for i := 0; i < numOut; i++ {
out, outMarshaler, err := TypeToOutput(ctrTyp.Out(i), securityContext)
if err != nil {
return Provider{}, err
}
outputs = append(outputs, out...)
outMarshalers = append(outMarshalers, outMarshaler)
}
ctrVal := reflect.ValueOf(constructor)
provideCtr := func(deps []reflect.Value, scope Scope) ([]reflect.Value, error) {
var inVals []reflect.Value
if scopeProvider {
inVals = append(inVals, reflect.ValueOf(scope))
}
nInMarshalers := len(inMarshalers)
for i = 0; i < nInMarshalers; i++ {
m := inMarshalers[i]
inVals = append(inVals, m.inMarshaler(deps[:m.n]))
deps = deps[m.n:]
}
outVals := ctrVal.Call(inVals)
var provides []reflect.Value
for i := 0; i < numOut; i++ {
provides = append(provides, outMarshalers[i](outVals[i])...)
}
return outVals, nil
}
return Provider{
Constructor: provideCtr,
Needs: inputs,
Provides: outputs,
Scope: scope,
IsScopeProvider: scopeProvider,
}, nil
}
func (c *Container) Invoke(fn interface{}) error {
fnTyp := reflect.TypeOf(fn)
if fnTyp.Kind() != reflect.Func {
return fmt.Errorf("expected function got %T", fn)
}
numIn := fnTyp.NumIn()
in := make([]reflect.Value, numIn)
for i := 0; i < numIn; i++ {
val, err := c.Resolve("", Key{Type: fnTyp.In(i)})
if err != nil {
return err
}
in[i] = val
}
_ = reflect.ValueOf(fn).Call(in)
return nil
}