Skip to content

Commit

Permalink
Add Scope.Decorate (#313)
Browse files Browse the repository at this point in the history
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
sywhang authored Jan 27, 2022
1 parent f478a90 commit 1d9f0f1
Show file tree
Hide file tree
Showing 12 changed files with 1,003 additions and 39 deletions.
13 changes: 11 additions & 2 deletions constructor.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"fmt"
"reflect"

"go.uber.org/dig/internal/digerror"
"go.uber.org/dig/internal/digreflect"
"go.uber.org/dig/internal/dot"
)
Expand Down Expand Up @@ -135,7 +136,7 @@ func (n *constructorNode) Call(c containerStore) error {
}
}

args, err := n.paramList.BuildList(c)
args, err := n.paramList.BuildList(c, false /* decorating */)
if err != nil {
return errArgumentsFailed{
Func: n.location,
Expand All @@ -145,7 +146,7 @@ func (n *constructorNode) Call(c containerStore) error {

receiver := newStagingContainerWriter()
results := c.invoker()(reflect.ValueOf(n.ctor), args)
if err := n.resultList.ExtractList(receiver, results); err != nil {
if err := n.resultList.ExtractList(receiver, false /* decorating */, results); err != nil {
return errConstructorFailed{Func: n.location, Reason: err}
}

Expand Down Expand Up @@ -179,11 +180,19 @@ func (sr *stagingContainerWriter) setValue(name string, t reflect.Type, v reflec
sr.values[key{t: t, name: name}] = v
}

func (sr *stagingContainerWriter) setDecoratedValue(_ string, _ reflect.Type, _ reflect.Value) {
digerror.BugPanicf("stagingContainerWriter.setDecoratedValue must never be called")
}

func (sr *stagingContainerWriter) submitGroupedValue(group string, t reflect.Type, v reflect.Value) {
k := key{t: t, group: group}
sr.groups[k] = append(sr.groups[k], v)
}

func (sr *stagingContainerWriter) submitDecoratedGroupedValue(_ string, _ reflect.Type, _ reflect.Value) {
digerror.BugPanicf("stagingContainerWriter.submitDecoratedGroupedValue must never be called")
}

// Commit commits the received results to the provided containerWriter.
func (sr *stagingContainerWriter) Commit(cw containerWriter) {
for k, v := range sr.values {
Expand Down
23 changes: 23 additions & 0 deletions container.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,18 @@ type containerWriter interface {
// overwritten.
setValue(name string, t reflect.Type, v reflect.Value)

// setDecoratedValue sets a decorated value with the given name and type
// in the container. If a decorated value with the same name and type already
// exists, it will be overwritten.
setDecoratedValue(name string, t reflect.Type, v reflect.Value)

// submitGroupedValue submits a value to the value group with the provided
// name.
submitGroupedValue(name string, t reflect.Type, v reflect.Value)

// submitDecoratedGroupedValue submits a decorated value to the value group
// with the provided name.
submitDecoratedGroupedValue(name string, t reflect.Type, v reflect.Value)
}

// containerStore provides access to the Container's underlying data store.
Expand All @@ -94,11 +103,17 @@ type containerStore interface {
// Retrieves the value with the provided name and type, if any.
getValue(name string, t reflect.Type) (v reflect.Value, ok bool)

// Retrieves a decorated value with the provided name and type, if any.
getDecoratedValue(name string, t reflect.Type) (v reflect.Value, ok bool)

// Retrieves all values for the provided group and type.
//
// The order in which the values are returned is undefined.
getValueGroup(name string, t reflect.Type) []reflect.Value

// Retrieves all decorated values for the provided group and type, if any.
getDecoratedValueGroup(name string, t reflect.Type) (reflect.Value, bool)

// Returns the providers that can produce a value with the given name and
// type.
getValueProviders(name string, t reflect.Type) []provider
Expand All @@ -111,6 +126,14 @@ type containerStore interface {
// type across all the Scopes that are in effect of this containerStore.
getAllValueProviders(name string, t reflect.Type) []provider

// Returns the decorators that can produce values for the given name and
// type.
getValueDecorators(name string, t reflect.Type) []decorator

// Reutrns the decorators that can produce values for the given group and
// type.
getGroupDecorators(name string, t reflect.Type) []decorator

// Reports a list of stores (starting at this store) up to the root
// store.
storesToRoot() []containerStore
Expand Down
213 changes: 213 additions & 0 deletions decorate.go
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
}
Loading

0 comments on commit 1d9f0f1

Please sign in to comment.