-
Notifications
You must be signed in to change notification settings - Fork 208
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This adds Scope.Decorate which lets the user decorate an existing provider for a given type by overriding that with another provider. For example, c := dig.New() c.Provide(func() *Logger { return Logger { Name: "Default", } }) c.Decorate(func(l *Logger) *Logger { return Logger { Name: "Decorated", } }) the code snippet above shows a provider that injects a *Logger type into the top-level scope. Then it adds a decorator which takes in the *Logger type and replaces its name with something else. Once that has been done, the following Invoke will get the decorated name: dig.Invoke(func(l *Logger) { l.Log(l.Name) // will log "Decorated" }) Decorations are limited to its scope only. i.e. a child's decorator does not affect the parent scope or any of the ancestor scopes. A parent's decorator does affect the child and the descendant scopes. One limitation: a Scope can only decorate a type once. It is possible, however, to create a child scope and then decorate once more in the child scope. In such case, the parent's decorator will be executed prior to the child's decorator. In terms of implementation, an additional set of types were added. Namely: decorator: This is an interface that abstract a decorator that was provided to a Scope. decoratorNode: This implements the decorator interface. DecorateOption: Functional options for Scope.Decorate. Unimplemented. In addition, Scope also has new fields to keep track of all the decorators and decorated values/value groups that were injected in the scope directly. The way they work is quite similar to providers and values/value groups list. Basically, decorators are analogous to providers (constructors), and it keeps a separated list of decorated values and value groups in addition to provider-injected values and value groups.
- Loading branch information
Showing
12 changed files
with
1,003 additions
and
39 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,213 @@ | ||
// Copyright (c) 2022 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 ( | ||
"fmt" | ||
"reflect" | ||
|
||
"go.uber.org/dig/internal/digreflect" | ||
"go.uber.org/dig/internal/dot" | ||
) | ||
|
||
type decorator interface { | ||
Call(c containerStore) error | ||
ID() dot.CtorID | ||
} | ||
|
||
type decoratorNode struct { | ||
dcor interface{} | ||
dtype reflect.Type | ||
|
||
id dot.CtorID | ||
|
||
// Location where this function was defined. | ||
location *digreflect.Func | ||
|
||
// Whether the decorator owned by this node was already called. | ||
called bool | ||
|
||
// Parameters of the decorator. | ||
params paramList | ||
|
||
// Results of the decorator. | ||
results resultList | ||
|
||
// order of this node in each Scopes' graphHolders. | ||
orders map[*Scope]int | ||
|
||
// scope this node was originally provided to. | ||
s *Scope | ||
} | ||
|
||
func newDecoratorNode(dcor interface{}, s *Scope) (*decoratorNode, error) { | ||
dval := reflect.ValueOf(dcor) | ||
dtype := dval.Type() | ||
dptr := dval.Pointer() | ||
|
||
pl, err := newParamList(dtype, s) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
rl, err := newResultList(dtype, resultOptions{}) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
n := &decoratorNode{ | ||
dcor: dcor, | ||
dtype: dtype, | ||
id: dot.CtorID(dptr), | ||
location: digreflect.InspectFunc(dcor), | ||
orders: make(map[*Scope]int), | ||
params: pl, | ||
results: rl, | ||
s: s, | ||
} | ||
return n, nil | ||
} | ||
|
||
func (n *decoratorNode) Call(s containerStore) error { | ||
if n.called { | ||
return nil | ||
} | ||
|
||
if err := shallowCheckDependencies(s, n.params); err != nil { | ||
return errMissingDependencies{ | ||
Func: n.location, | ||
Reason: err, | ||
} | ||
} | ||
|
||
args, err := n.params.BuildList(n.s, true /* decorating */) | ||
if err != nil { | ||
return errArgumentsFailed{ | ||
Func: n.location, | ||
Reason: err, | ||
} | ||
} | ||
|
||
results := reflect.ValueOf(n.dcor).Call(args) | ||
if err := n.results.ExtractList(n.s, true /* decorated */, results); err != nil { | ||
return err | ||
} | ||
n.called = true | ||
return nil | ||
} | ||
|
||
func (n *decoratorNode) ID() dot.CtorID { return n.id } | ||
|
||
// DecorateOption modifies the default behavior of Provide. | ||
// Currently, there is no implementation of it yet. | ||
type DecorateOption interface { | ||
noOptionsYet() | ||
} | ||
|
||
// Decorate provides a decorator for a type that has already been provided in the Container. | ||
// Decorations at this level affect all scopes of the container. | ||
// See Scope.Decorate for information on how to use this method. | ||
func (c *Container) Decorate(decorator interface{}, opts ...DecorateOption) error { | ||
return c.scope.Decorate(decorator, opts...) | ||
} | ||
|
||
// Decorate provides a decorator for a type that has already been provided in the Scope. | ||
// | ||
// Similar to Provide, Decorate takes in a function with zero or more dependencies and one | ||
// or more results. Decorate can be used to modify a type that was already introduced to the | ||
// Scope, or completely replace it with a new object. | ||
// | ||
// For example, | ||
// s.Decorate(func(log *zap.Logger) *zap.Logger { | ||
// return log.Named("myapp") | ||
// }) | ||
// | ||
// This takes in a value, augments it with a name, and returns a replacement for it. Functions | ||
// in the Scope's dependency graph that use *zap.Logger will now use the *zap.Logger | ||
// returned by this decorator. | ||
// | ||
// A decorator can also take in multiple parameters and replace one of them: | ||
// s.Decorate(func(log *zap.Logger, cfg *Config) *zap.Logger { | ||
// return log.Named(cfg.Name) | ||
// }) | ||
// | ||
// Or replace a subset of them: | ||
// s.Decorate(func( | ||
// log *zap.Logger, | ||
// cfg *Config, | ||
// scope metrics.Scope | ||
// ) (*zap.Logger, metrics.Scope) { | ||
// log = log.Named(cfg.Name) | ||
// scope = scope.With(metrics.Tag("service", cfg.Name)) | ||
// return log, scope | ||
// }) | ||
// | ||
// Decorating a Scope affects all the child scopes of this Scope. | ||
// | ||
// Similar to a provider, the decorator function gets called *at most once*. | ||
func (s *Scope) Decorate(decorator interface{}, opts ...DecorateOption) error { | ||
_ = opts // there are no options at this time | ||
|
||
dn, err := newDecoratorNode(decorator, s) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
keys := findResultKeys(dn.results) | ||
for _, k := range keys { | ||
if len(s.decorators[k]) > 0 { | ||
return fmt.Errorf("cannot decorate using function %v: %s already decorated", | ||
dn.dtype, | ||
k, | ||
) | ||
} | ||
s.decorators[k] = append(s.decorators[k], dn) | ||
} | ||
return nil | ||
} | ||
|
||
func findResultKeys(r resultList) []key { | ||
// use BFS to search for all keys included in a resultList. | ||
var ( | ||
q []result | ||
keys []key | ||
) | ||
q = append(q, r) | ||
|
||
for len(q) > 0 { | ||
res := q[0] | ||
q = q[1:] | ||
|
||
switch innerResult := res.(type) { | ||
case resultSingle: | ||
keys = append(keys, key{t: innerResult.Type, name: innerResult.Name}) | ||
case resultGrouped: | ||
keys = append(keys, key{t: innerResult.Type.Elem(), group: innerResult.Group}) | ||
case resultObject: | ||
for _, f := range innerResult.Fields { | ||
q = append(q, f.Result) | ||
} | ||
case resultList: | ||
q = append(q, innerResult.Results...) | ||
} | ||
} | ||
return keys | ||
} |
Oops, something went wrong.