-
Notifications
You must be signed in to change notification settings - Fork 345
Expand file tree
/
Copy pathprovide.go
More file actions
263 lines (232 loc) · 8.97 KB
/
Copy pathprovide.go
File metadata and controls
263 lines (232 loc) · 8.97 KB
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
// 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 fx
import (
"fmt"
"reflect"
"strings"
"go.uber.org/dig"
"go.uber.org/fx/internal/fxreflect"
)
// Provide registers any number of constructor functions, teaching the
// application how to instantiate various types. The supplied constructor
// function(s) may depend on other types available in the application, must
// return one or more objects, and may return an error. For example:
//
// // Constructs type *C, depends on *A and *B.
// func(*A, *B) *C
//
// // Constructs type *C, depends on *A and *B, and indicates failure by
// // returning an error.
// func(*A, *B) (*C, error)
//
// // Constructs types *B and *C, depends on *A, and can fail.
// func(*A) (*B, *C, error)
//
// The order in which constructors are provided doesn't matter, and passing
// multiple Provide options appends to the application's collection of
// constructors. Constructors are called only if one or more of their returned
// types are needed, and their results are cached for reuse (so instances of a
// type are effectively singletons within an application). Taken together,
// these properties make it perfectly reasonable to Provide a large number of
// constructors even if only a fraction of them are used.
//
// See the documentation of the In and Out types for advanced features,
// including optional parameters and named instances.
//
// See the documentation for [Private] for restricting access to constructors.
//
// Constructor functions should perform as little external interaction as
// possible, and should avoid spawning goroutines. Things like server listen
// loops, background timer loops, and background processing goroutines should
// instead be managed using Lifecycle callbacks.
func Provide(constructors ...any) Option {
return provideOption{
Targets: constructors,
Stack: fxreflect.CallerStack(1, 0),
}
}
type provideOption struct {
Targets []any
Stack fxreflect.Stack
}
func (o provideOption) apply(mod *module) {
var private bool
targets := make([]any, 0, len(o.Targets))
for _, target := range o.Targets {
if _, ok := target.(privateOption); ok {
private = true
continue
}
targets = append(targets, target)
}
for _, target := range targets {
mod.provides = append(mod.provides, provide{
Target: target,
Stack: o.Stack,
Private: private,
})
}
}
type privateOption struct{}
// Private is an option that can be passed as an argument to [Provide] or [Supply] to
// restrict access to the constructors being provided. Specifically,
// corresponding constructors can only be used within the current module
// or modules the current module contains. Other modules that contain this
// module won't be able to use the constructor.
//
// For example, the following would fail because the app doesn't have access
// to the inner module's constructor.
//
// fx.New(
// fx.Module("SubModule", fx.Provide(func() int { return 0 }, fx.Private)),
// fx.Invoke(func(a int) {}),
// )
var Private = privateOption{}
func (o provideOption) String() string {
items := make([]string, len(o.Targets))
for i, c := range o.Targets {
items[i] = fxreflect.FuncName(c)
}
return fmt.Sprintf("fx.Provide(%s)", strings.Join(items, ", "))
}
// Transient marks a constructor so that fx will provide a factory function
// that creates a new instance each time it is called. For example,
//
// fx.Provide(fx.Transient(NewA))
//
// where `NewA` is `func(...) *A` will register a provider for
// `func() *A`. Each call to the provided factory will run `NewA` and
// return a fresh *A (its dependencies are captured by the factory
// closure when the app starts).
func Transient(constructor any) any {
return transientOption{Target: constructor}
}
type transientOption struct {
Target any
}
func runProvide(c container, p provide, opts ...dig.ProvideOption) error {
constructor := p.Target
if _, ok := constructor.(Option); ok {
return fmt.Errorf("fx.Option should be passed to fx.New directly, "+
"not to fx.Provide: fx.Provide received %v from:\n%+v",
constructor, p.Stack)
}
switch constructor := constructor.(type) {
case annotationError:
// fx.Annotate failed. Turn it into an Fx error.
return fmt.Errorf(
"encountered error while applying annotation using fx.Annotate to %s: %w",
fxreflect.FuncName(constructor.target), constructor.err)
case annotated:
ctor, err := constructor.Build()
if err != nil {
return fmt.Errorf("fx.Provide(%v) from:\n%+vFailed: %w", constructor, p.Stack, err)
}
opts = append(opts, dig.LocationForPC(constructor.FuncPtr))
if err := c.Provide(ctor, opts...); err != nil {
return fmt.Errorf("fx.Provide(%v) from:\n%+vFailed: %w", constructor, p.Stack, err)
}
case Annotated:
ann := constructor
switch {
case len(ann.Group) > 0 && len(ann.Name) > 0:
return fmt.Errorf(
"fx.Annotated may specify only one of Name or Group: received %v from:\n%+v",
ann, p.Stack)
case len(ann.Name) > 0:
opts = append(opts, dig.Name(ann.Name))
case len(ann.Group) > 0:
opts = append(opts, dig.Group(ann.Group))
}
if err := c.Provide(ann.Target, opts...); err != nil {
return fmt.Errorf("fx.Provide(%v) from:\n%+vFailed: %w", ann, p.Stack, err)
}
case transientOption:
// Build a wrapper function of the form:
// func(deps...) func() (outs...)
// The inner func (factory) when called will execute the original
// constructor using the captured dependency values, producing a
// fresh set of outputs each time.
wrapper, err := buildTransientWrapper(constructor.Target)
if err != nil {
return fmt.Errorf("fx.Transient(%v) from:\n%+vFailed: %w", constructor.Target, p.Stack, err)
}
if err := c.Provide(wrapper, opts...); err != nil {
return fmt.Errorf("fx.Provide(fx.Transient(%v)) from:\n%+vFailed: %w", fxreflect.FuncName(constructor.Target), p.Stack, err)
}
default:
if reflect.TypeOf(constructor).Kind() == reflect.Func {
ft := reflect.ValueOf(constructor).Type()
for i := 0; i < ft.NumOut(); i++ {
t := ft.Out(i)
if t == reflect.TypeOf(Annotated{}) {
return fmt.Errorf(
"fx.Annotated should be passed to fx.Provide directly, "+
"it should not be returned by the constructor: "+
"fx.Provide received %v from:\n%+v",
fxreflect.FuncName(constructor), p.Stack)
}
}
}
if err := c.Provide(constructor, opts...); err != nil {
return fmt.Errorf("fx.Provide(%v) from:\n%+vFailed: %w", fxreflect.FuncName(constructor), p.Stack, err)
}
}
return nil
}
// buildTransientWrapper builds a wrapper function that captures the
// dependencies of the original constructor and returns a factory function
// which calls the original constructor each time it is invoked.
func buildTransientWrapper(constructor any) (any, error) {
v := reflect.ValueOf(constructor)
if v.Kind() != reflect.Func {
return nil, fmt.Errorf("transient target must be a function, got %T", constructor)
}
t := v.Type()
if t.IsVariadic() {
return nil, fmt.Errorf("transient constructors may not be variadic: %s", fxreflect.FuncName(constructor))
}
// Collect output types for the inner factory function.
outs := make([]reflect.Type, 0, t.NumOut())
for i := 0; i < t.NumOut(); i++ {
outs = append(outs, t.Out(i))
}
// factoryType is func() (outs...)
factoryType := reflect.FuncOf([]reflect.Type{}, outs, false)
// wrapperType is func(in...) factoryType
ins := make([]reflect.Type, 0, t.NumIn())
for i := 0; i < t.NumIn(); i++ {
ins = append(ins, t.In(i))
}
wrapperType := reflect.FuncOf(ins, []reflect.Type{factoryType}, false)
// Make the wrapper function.
wrapper := reflect.MakeFunc(wrapperType, func(in []reflect.Value) []reflect.Value {
// Create the factory function which captures the provided deps (in)
factory := reflect.MakeFunc(factoryType, func(_ []reflect.Value) []reflect.Value {
// Call the original constructor with captured deps.
results := v.Call(in)
// Return results as-is to caller of factory.
return results
})
return []reflect.Value{factory}
})
return wrapper.Interface(), nil
}