-
Notifications
You must be signed in to change notification settings - Fork 290
/
annotated.go
1825 lines (1674 loc) · 49.5 KB
/
annotated.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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2020-2021 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 (
"context"
"errors"
"fmt"
"reflect"
"strings"
"go.uber.org/dig"
"go.uber.org/fx/internal/fxreflect"
)
// Annotated annotates a constructor provided to Fx with additional options.
//
// For example,
//
// func NewReadOnlyConnection(...) (*Connection, error)
//
// fx.Provide(fx.Annotated{
// Name: "ro",
// Target: NewReadOnlyConnection,
// })
//
// Is equivalent to,
//
// type result struct {
// fx.Out
//
// Connection *Connection `name:"ro"`
// }
//
// fx.Provide(func(...) (result, error) {
// conn, err := NewReadOnlyConnection(...)
// return result{Connection: conn}, err
// })
//
// Annotated cannot be used with constructors which produce fx.Out objects.
// When used with [Supply], Target is a value instead of a constructor.
//
// This type represents a less powerful version of the [Annotate] construct;
// prefer [Annotate] where possible.
type Annotated struct {
// If specified, this will be used as the name for all non-error values returned
// by the constructor. For more information on named values, see the documentation
// for the fx.Out type.
//
// A name option may not be provided if a group option is provided.
Name string
// If specified, this will be used as the group name for all non-error values returned
// by the constructor. For more information on value groups, see the package documentation.
//
// A group option may not be provided if a name option is provided.
//
// Similar to group tags, the group name may be followed by a `,flatten`
// option to indicate that each element in the slice returned by the
// constructor should be injected into the value group individually.
Group string
// Target is the constructor or value being annotated with fx.Annotated.
Target interface{}
}
func (a Annotated) String() string {
var fields []string
if len(a.Name) > 0 {
fields = append(fields, fmt.Sprintf("Name: %q", a.Name))
}
if len(a.Group) > 0 {
fields = append(fields, fmt.Sprintf("Group: %q", a.Group))
}
if a.Target != nil {
fields = append(fields, fmt.Sprintf("Target: %v", fxreflect.FuncName(a.Target)))
}
return fmt.Sprintf("fx.Annotated{%v}", strings.Join(fields, ", "))
}
var (
// field used for embedding fx.In type in generated struct.
_inAnnotationField = reflect.StructField{
Name: "In",
Type: reflect.TypeOf(In{}),
Anonymous: true,
}
// field used for embedding fx.Out type in generated struct.
_outAnnotationField = reflect.StructField{
Name: "Out",
Type: reflect.TypeOf(Out{}),
Anonymous: true,
}
)
// Annotation specifies how to wrap a target for [Annotate].
// It can be used to set up additional options for a constructor,
// or with [Supply], for a value.
type Annotation interface {
apply(*annotated) error
build(*annotated) (interface{}, error)
}
var (
_typeOfError = reflect.TypeOf((*error)(nil)).Elem()
_nilError = reflect.Zero(_typeOfError)
)
// annotationError is a wrapper for an error that was encountered while
// applying annotation to a function. It contains the specific error
// that it encountered as well as the target interface that was attempted
// to be annotated.
type annotationError struct {
target interface{}
err error
}
func (e *annotationError) Error() string {
return e.err.Error()
}
// Unwrap the wrapped error.
func (e *annotationError) Unwrap() error {
return e.err
}
type paramTagsAnnotation struct {
tags []string
}
var _ Annotation = paramTagsAnnotation{}
var (
errTagSyntaxSpace = errors.New(`multiple tags are not separated by space`)
errTagKeySyntax = errors.New("tag key is invalid, Use group, name or optional as tag keys")
errTagValueSyntaxQuote = errors.New(`tag value should start with double quote. i.e. key:"value" `)
errTagValueSyntaxEndingQuote = errors.New(`tag value should end in double quote. i.e. key:"value" `)
)
// Collections of key value pairs within a tag should be separated by a space.
// Eg: `group:"some" optional:"true"`.
func verifyTagsSpaceSeparated(tagIdx int, tag string) error {
if tagIdx > 0 && tag != "" && tag[0] != ' ' {
return errTagSyntaxSpace
}
return nil
}
// verify tag values are delimited with double quotes.
func verifyValueQuote(value string) (string, error) {
// starting quote should be a double quote
if value[0] != '"' {
return "", errTagValueSyntaxQuote
}
// validate tag value is within quotes
i := 1
for i < len(value) && value[i] != '"' {
if value[i] == '\\' {
i++
}
i++
}
if i >= len(value) {
return "", errTagValueSyntaxEndingQuote
}
return value[i+1:], nil
}
// Check whether the tag follows valid struct.
// format and returns an error if it's invalid. (i.e. not following
// tag:"value" space-separated list )
// Currently dig accepts only 'name', 'group', 'optional' as valid tag keys.
func verifyAnnotateTag(tag string) error {
tagIdx := 0
validKeys := map[string]struct{}{"group": {}, "optional": {}, "name": {}}
for ; tag != ""; tagIdx++ {
if err := verifyTagsSpaceSeparated(tagIdx, tag); err != nil {
return err
}
i := 0
if strings.TrimSpace(tag) == "" {
return nil
}
// parsing the key i.e. till reaching colon :
for i < len(tag) && tag[i] != ':' {
i++
}
key := strings.TrimSpace(tag[:i])
if _, ok := validKeys[key]; !ok {
return errTagKeySyntax
}
value, err := verifyValueQuote(tag[i+1:])
if err != nil {
return err
}
tag = value
}
return nil
}
// Given func(T1, T2, T3, ..., TN), this generates a type roughly
// equivalent to,
//
// struct {
// fx.In
//
// Field1 T1 `$tags[0]`
// Field2 T2 `$tags[1]`
// ...
// FieldN TN `$tags[N-1]`
// }
//
// If there has already been a ParamTag that was applied, this
// will return an error.
//
// If the tag is invalid and has mismatched quotation for example,
// (`tag_name:"tag_value') , this will return an error.
func (pt paramTagsAnnotation) apply(ann *annotated) error {
if len(ann.ParamTags) > 0 {
return errors.New("cannot apply more than one line of ParamTags")
}
for _, tag := range pt.tags {
if err := verifyAnnotateTag(tag); err != nil {
return err
}
}
ann.ParamTags = pt.tags
return nil
}
// build builds and returns a constructor after applying a ParamTags annotation
func (pt paramTagsAnnotation) build(ann *annotated) (interface{}, error) {
paramTypes, remap := pt.parameters(ann)
resultTypes, _ := ann.currentResultTypes()
origFn := reflect.ValueOf(ann.Target)
newFnType := reflect.FuncOf(paramTypes, resultTypes, false)
newFn := reflect.MakeFunc(newFnType, func(args []reflect.Value) []reflect.Value {
args = remap(args)
return origFn.Call(args)
})
return newFn.Interface(), nil
}
// parameters returns the type for the parameters of the annotated function,
// and a function that maps the arguments of the annotated function
// back to the arguments of the target function.
func (pt paramTagsAnnotation) parameters(ann *annotated) (
types []reflect.Type,
remap func([]reflect.Value) []reflect.Value,
) {
ft := reflect.TypeOf(ann.Target)
types = make([]reflect.Type, ft.NumIn())
for i := 0; i < ft.NumIn(); i++ {
types[i] = ft.In(i)
}
// No parameter annotations. Return the original types
// and an identity function.
if len(pt.tags) == 0 {
return types, func(args []reflect.Value) []reflect.Value {
return args
}
}
// Turn parameters into an fx.In struct.
inFields := []reflect.StructField{_inAnnotationField}
// there was a variadic argument, so it was pre-transformed
if len(types) > 0 && isIn(types[0]) {
paramType := types[0]
for i := 1; i < paramType.NumField(); i++ {
origField := paramType.Field(i)
field := reflect.StructField{
Name: origField.Name,
Type: origField.Type,
Tag: origField.Tag,
}
if i-1 < len(pt.tags) {
field.Tag = reflect.StructTag(pt.tags[i-1])
}
inFields = append(inFields, field)
}
types = []reflect.Type{reflect.StructOf(inFields)}
return types, func(args []reflect.Value) []reflect.Value {
param := args[0]
args[0] = reflect.New(paramType).Elem()
for i := 1; i < paramType.NumField(); i++ {
args[0].Field(i).Set(param.Field(i))
}
return args
}
}
for i, t := range types {
field := reflect.StructField{
Name: fmt.Sprintf("Field%d", i),
Type: t,
}
if i < len(pt.tags) {
field.Tag = reflect.StructTag(pt.tags[i])
}
inFields = append(inFields, field)
}
types = []reflect.Type{reflect.StructOf(inFields)}
return types, func(args []reflect.Value) []reflect.Value {
params := args[0]
args = args[:0]
for i := 0; i < ft.NumIn(); i++ {
args = append(args, params.Field(i+1))
}
return args
}
}
// ParamTags is an Annotation that annotates the parameter(s) of a function.
//
// When multiple tags are specified, each tag is mapped to the corresponding
// positional parameter.
// For example, the following will refer to a named database connection,
// and the default, unnamed logger:
//
// fx.Annotate(func(log *log.Logger, conn *sql.DB) *Handler {
// // ...
// }, fx.ParamTags("", `name:"ro"`))
//
// ParamTags cannot be used in a function that takes an fx.In struct as a
// parameter.
func ParamTags(tags ...string) Annotation {
return paramTagsAnnotation{tags}
}
type resultTagsAnnotation struct {
tags []string
}
var _ Annotation = resultTagsAnnotation{}
// Given func(T1, T2, T3, ..., TN), this generates a type roughly
// equivalent to,
//
// struct {
// fx.Out
//
// Field1 T1 `$tags[0]`
// Field2 T2 `$tags[1]`
// ...
// FieldN TN `$tags[N-1]`
// }
//
// If there has already been a ResultTag that was applied, this
// will return an error.
//
// If the tag is invalid and has mismatched quotation for example,
// (`tag_name:"tag_value') , this will return an error.
func (rt resultTagsAnnotation) apply(ann *annotated) error {
if len(ann.ResultTags) > 0 {
return errors.New("cannot apply more than one line of ResultTags")
}
for _, tag := range rt.tags {
if err := verifyAnnotateTag(tag); err != nil {
return err
}
}
ann.ResultTags = rt.tags
return nil
}
// build builds and returns a constructor after applying a ResultTags annotation
func (rt resultTagsAnnotation) build(ann *annotated) (interface{}, error) {
paramTypes := ann.currentParamTypes()
resultTypes, remapResults := rt.results(ann)
origFn := reflect.ValueOf(ann.Target)
newFnType := reflect.FuncOf(paramTypes, resultTypes, false)
newFn := reflect.MakeFunc(newFnType, func(args []reflect.Value) []reflect.Value {
results := origFn.Call(args)
return remapResults(results)
})
return newFn.Interface(), nil
}
// results returns the types of the results of the annotated function,
// and a function that maps the results of the target function,
// into a result compatible with the annotated function.
func (rt resultTagsAnnotation) results(ann *annotated) (
types []reflect.Type,
remap func([]reflect.Value) []reflect.Value,
) {
types, hasError := ann.currentResultTypes()
if hasError {
types = types[:len(types)-1]
}
// No result annotations. Return the original types
// and an identity function.
if len(rt.tags) == 0 {
return types, func(results []reflect.Value) []reflect.Value {
return results
}
}
// if there's no Out struct among the return types, there was no As annotation applied
// just replace original result types with an Out struct and apply tags
var (
newOut outStructInfo
existingOuts []reflect.Type
)
newOut.Fields = []reflect.StructField{_outAnnotationField}
newOut.Offsets = []int{}
for i, t := range types {
if !isOut(t) {
// this must be from the original function.
// apply the tags
field := reflect.StructField{
Name: fmt.Sprintf("Field%d", i),
Type: t,
}
if i < len(rt.tags) {
field.Tag = reflect.StructTag(rt.tags[i])
}
newOut.Offsets = append(newOut.Offsets, len(newOut.Fields))
newOut.Fields = append(newOut.Fields, field)
continue
}
// this must be from an As annotation
// apply the tags to the existing type
taggedFields := make([]reflect.StructField, t.NumField())
taggedFields[0] = _outAnnotationField
for j, tag := range rt.tags {
if j+1 < t.NumField() {
field := t.Field(j + 1)
taggedFields[j+1] = reflect.StructField{
Name: field.Name,
Type: field.Type,
Tag: reflect.StructTag(tag),
}
}
}
existingOuts = append(existingOuts, reflect.StructOf(taggedFields))
}
resType := reflect.StructOf(newOut.Fields)
outTypes := []reflect.Type{resType}
// append existing outs back to outTypes
outTypes = append(outTypes, existingOuts...)
if hasError {
outTypes = append(outTypes, _typeOfError)
}
return outTypes, func(results []reflect.Value) []reflect.Value {
var (
outErr error
outResults []reflect.Value
)
outResults = append(outResults, reflect.New(resType).Elem())
tIdx := 0
for i, r := range results {
if i == len(results)-1 && hasError {
// If hasError and this is the last item,
// we are guaranteed that this is an error
// object.
if err, _ := r.Interface().(error); err != nil {
outErr = err
}
continue
}
if i < len(newOut.Offsets) {
if fieldIdx := newOut.Offsets[i]; fieldIdx > 0 {
// fieldIdx 0 is an invalid index
// because it refers to uninitialized
// outs and would point to fx.Out in the
// struct definition. We need to check this
// to prevent panic from setting fx.Out to
// a value.
outResults[0].Field(fieldIdx).Set(r)
}
continue
}
if isOut(r.Type()) {
tIdx++
if tIdx < len(outTypes) {
newResult := reflect.New(outTypes[tIdx]).Elem()
for j := 1; j < outTypes[tIdx].NumField(); j++ {
newResult.Field(j).Set(r.Field(j))
}
outResults = append(outResults, newResult)
}
}
}
if hasError {
if outErr != nil {
outResults = append(outResults, reflect.ValueOf(outErr))
} else {
outResults = append(outResults, _nilError)
}
}
return outResults
}
}
// ResultTags is an Annotation that annotates the result(s) of a function.
// When multiple tags are specified, each tag is mapped to the corresponding
// positional result.
//
// For example, the following will produce a named database connection.
//
// fx.Annotate(func() (*sql.DB, error) {
// // ...
// }, fx.ResultTags(`name:"ro"`))
//
// ResultTags cannot be used on a function that returns an fx.Out struct.
func ResultTags(tags ...string) Annotation {
return resultTagsAnnotation{tags}
}
type outStructInfo struct {
Fields []reflect.StructField // fields of the struct
Offsets []int // Offsets[i] is the index of result i in Fields
}
type _lifecycleHookAnnotationType int
const (
_unknownHookType _lifecycleHookAnnotationType = iota
_onStartHookType
_onStopHookType
)
type lifecycleHookAnnotation struct {
Type _lifecycleHookAnnotationType
Target interface{}
}
var _ Annotation = (*lifecycleHookAnnotation)(nil)
func (la *lifecycleHookAnnotation) String() string {
name := "UnknownHookAnnotation"
switch la.Type {
case _onStartHookType:
name = _onStartHook
case _onStopHookType:
name = _onStopHook
}
return name
}
func (la *lifecycleHookAnnotation) apply(ann *annotated) error {
if la.Target == nil {
return fmt.Errorf(
"cannot use nil function for %q hook annotation",
la,
)
}
for _, h := range ann.Hooks {
if la.Type == h.Type {
return fmt.Errorf(
"cannot apply more than one %q hook annotation",
la,
)
}
}
ft := reflect.TypeOf(la.Target)
if ft.Kind() != reflect.Func {
return fmt.Errorf(
"must provide function for %q hook, got %v (%T)",
la,
la.Target,
la.Target,
)
}
if n := ft.NumOut(); n > 0 {
if n > 1 || ft.Out(0) != _typeOfError {
return fmt.Errorf(
"optional hook return may only be an error, got %v (%T)",
la.Target,
la.Target,
)
}
}
if ft.IsVariadic() {
return fmt.Errorf(
"hooks must not accept variadic parameters, got %v (%T)",
la.Target,
la.Target,
)
}
ann.Hooks = append(ann.Hooks, la)
return nil
}
// build builds and returns a constructor after applying a lifecycle hook annotation.
func (la *lifecycleHookAnnotation) build(ann *annotated) (interface{}, error) {
resultTypes, hasError := ann.currentResultTypes()
if !hasError {
resultTypes = append(resultTypes, _typeOfError)
}
hookInstaller, paramTypes, remapParams := la.buildHookInstaller(ann)
origFn := reflect.ValueOf(ann.Target)
newFnType := reflect.FuncOf(paramTypes, resultTypes, false)
newFn := reflect.MakeFunc(newFnType, func(args []reflect.Value) []reflect.Value {
// copy the original arguments before remapping the parameters
// so that we can apply them to the hookInstaller.
origArgs := make([]reflect.Value, len(args))
copy(origArgs, args)
args = remapParams(args)
results := origFn.Call(args)
if hasError {
errVal := results[len(results)-1]
results = results[:len(results)-1]
if err, _ := errVal.Interface().(error); err != nil {
// if constructor returned error, do not call hook installer
return append(results, errVal)
}
}
hookInstallerResults := hookInstaller.Call(append(results, origArgs...))
results = append(results, hookInstallerResults[0])
return results
})
return newFn.Interface(), nil
}
var (
_typeOfLifecycle = reflect.TypeOf((*Lifecycle)(nil)).Elem()
_typeOfContext = reflect.TypeOf((*context.Context)(nil)).Elem()
)
// buildHookInstaller returns a function that appends a hook to Lifecycle when called,
// along with the new parameter types and a function that maps arguments to the annotated constructor
func (la *lifecycleHookAnnotation) buildHookInstaller(ann *annotated) (
hookInstaller reflect.Value,
paramTypes []reflect.Type,
remapParams func([]reflect.Value) []reflect.Value, // function to remap parameters to function being annotated
) {
paramTypes = ann.currentParamTypes()
paramTypes, remapParams = injectLifecycle(paramTypes)
resultTypes, hasError := ann.currentResultTypes()
if hasError {
resultTypes = resultTypes[:len(resultTypes)-1]
}
// look for the context.Context type from the original hook function
// and then exclude it from the paramTypes of invokeFn because context.Context
// will be injected by the lifecycle
ctxPos := -1
ctxStructPos := -1
origHookFn := reflect.ValueOf(la.Target)
origHookFnT := reflect.TypeOf(la.Target)
invokeParamTypes := []reflect.Type{
_typeOfLifecycle,
}
for i := 0; i < origHookFnT.NumIn(); i++ {
t := origHookFnT.In(i)
if t == _typeOfContext && ctxPos < 0 {
ctxPos = i
continue
}
if !isIn(t) {
invokeParamTypes = append(invokeParamTypes, origHookFnT.In(i))
continue
}
fields := []reflect.StructField{_inAnnotationField}
for j := 1; j < t.NumField(); j++ {
field := t.Field(j)
if field.Type == _typeOfContext && ctxPos < 0 {
ctxStructPos = i
ctxPos = j
continue
}
fields = append(fields, field)
}
invokeParamTypes = append(invokeParamTypes, reflect.StructOf(fields))
}
invokeFnT := reflect.FuncOf(invokeParamTypes, []reflect.Type{}, false)
invokeFn := reflect.MakeFunc(invokeFnT, func(args []reflect.Value) (results []reflect.Value) {
lc := args[0].Interface().(Lifecycle)
args = args[1:]
hookArgs := make([]reflect.Value, origHookFnT.NumIn())
hookFn := func(ctx context.Context) (err error) {
// If the hook function has multiple parameters, and the first
// parameter is a context, inject the provided context.
if ctxStructPos < 0 {
offset := 0
for i := 0; i < len(hookArgs); i++ {
if i == ctxPos {
hookArgs[i] = reflect.ValueOf(ctx)
offset = 1
continue
}
if i-offset >= 0 && i-offset < len(args) {
hookArgs[i] = args[i-offset]
}
}
} else {
for i := 0; i < origHookFnT.NumIn(); i++ {
if i != ctxStructPos {
hookArgs[i] = args[i]
continue
}
t := origHookFnT.In(i)
v := reflect.New(t).Elem()
for j := 1; j < t.NumField(); j++ {
if j < ctxPos {
v.Field(j).Set(args[i].Field(j))
} else if j == ctxPos {
v.Field(j).Set(reflect.ValueOf(ctx))
} else {
v.Field(j).Set(args[i].Field(j - 1))
}
}
hookArgs[i] = v
}
}
hookResults := origHookFn.Call(hookArgs)
if len(hookResults) > 0 && hookResults[0].Type() == _typeOfError {
err, _ = hookResults[0].Interface().(error)
}
return err
}
lc.Append(la.buildHook(hookFn))
return results
})
installerType := reflect.FuncOf(append(resultTypes, paramTypes...), []reflect.Type{_typeOfError}, false)
hookInstaller = reflect.MakeFunc(installerType, func(args []reflect.Value) (results []reflect.Value) {
// build a private scope for hook function
var scope *dig.Scope
switch la.Type {
case _onStartHookType:
scope = ann.container.Scope("onStartHookScope")
case _onStopHookType:
scope = ann.container.Scope("onStopHookScope")
}
// provide the private scope with the current dependencies and results of the annotated function
results = []reflect.Value{_nilError}
ctor := makeHookScopeCtor(paramTypes, resultTypes, args)
if err := scope.Provide(ctor); err != nil {
results[0] = reflect.ValueOf(fmt.Errorf("error providing possible parameters for hook installer: %w", err))
return results
}
// invoking invokeFn appends the hook function to lifecycle
if err := scope.Invoke(invokeFn.Interface()); err != nil {
results[0] = reflect.ValueOf(fmt.Errorf("error invoking hook installer: %w", err))
return results
}
return results
})
return hookInstaller, paramTypes, remapParams
}
var (
_nameTag = "name"
_groupTag = "group"
)
// makeHookScopeCtor makes a constructor that provides all possible parameters
// that the lifecycle hook being appended can depend on. It also deduplicates
// duplicate param and result types, which is possible when using fx.Decorate,
// and uses values from results for providing the deduplicated types.
func makeHookScopeCtor(paramTypes []reflect.Type, resultTypes []reflect.Type, args []reflect.Value) interface{} {
type key struct {
t reflect.Type
name string
group string
}
seen := map[key]struct{}{}
outTypes := make([]reflect.Type, len(resultTypes))
for i, t := range resultTypes {
outTypes[i] = t
if isOut(t) {
for j := 1; j < t.NumField(); j++ {
field := t.Field(j)
seen[key{
t: field.Type,
name: field.Tag.Get(_nameTag),
group: field.Tag.Get(_groupTag),
}] = struct{}{}
}
continue
}
seen[key{t: t}] = struct{}{}
}
fields := []reflect.StructField{_outAnnotationField}
skippedParams := make([][]int, len(paramTypes))
for i, t := range paramTypes {
skippedParams[i] = []int{}
if isIn(t) {
for j := 1; j < t.NumField(); j++ {
origField := t.Field(j)
k := key{
t: origField.Type,
name: origField.Tag.Get(_nameTag),
group: origField.Tag.Get(_groupTag),
}
if _, ok := seen[k]; ok {
skippedParams[i] = append(skippedParams[i], j)
continue
}
field := reflect.StructField{
Name: fmt.Sprintf("Field%d", j-1),
Type: origField.Type,
Tag: origField.Tag,
}
fields = append(fields, field)
}
continue
}
k := key{t: t}
if _, ok := seen[k]; ok {
skippedParams[i] = append(skippedParams[i], i)
continue
}
field := reflect.StructField{
Name: fmt.Sprintf("Field%d", i),
Type: t,
}
fields = append(fields, field)
}
outTypes = append(outTypes, reflect.StructOf(fields))
ctorType := reflect.FuncOf([]reflect.Type{}, outTypes, false)
ctor := reflect.MakeFunc(ctorType, func(_ []reflect.Value) []reflect.Value {
nOut := len(outTypes)
results := make([]reflect.Value, nOut)
for i := 0; i < nOut-1; i++ {
results[i] = args[i]
}
v := reflect.New(outTypes[nOut-1]).Elem()
fieldIdx := 1
for i := nOut - 1; i < len(args); i++ {
paramIdx := i - (nOut - 1)
if isIn(paramTypes[paramIdx]) {
skippedIdx := 0
for j := 1; j < paramTypes[paramIdx].NumField(); j++ {
if len(skippedParams[paramIdx]) > 0 && skippedParams[paramIdx][skippedIdx] == j {
// skip
skippedIdx++
continue
}
v.Field(fieldIdx).Set(args[i].Field(j))
fieldIdx++
}
} else {
if len(skippedParams[paramIdx]) > 0 && skippedParams[paramIdx][0] == paramIdx {
continue
}
v.Field(fieldIdx).Set(args[i])
fieldIdx++
}
}
results[nOut-1] = v
return results
})
return ctor.Interface()
}
func injectLifecycle(paramTypes []reflect.Type) ([]reflect.Type, func([]reflect.Value) []reflect.Value) {
// since lifecycle already exists in param types, no need to inject again
if lifecycleExists(paramTypes) {
return paramTypes, func(args []reflect.Value) []reflect.Value {
return args
}
}
// If params are tagged or there's an untagged variadic argument,
// add a Lifecycle field to the param struct
if len(paramTypes) > 0 && isIn(paramTypes[0]) {
taggedParam := paramTypes[0]
fields := []reflect.StructField{
taggedParam.Field(0),
{
Name: "Lifecycle",
Type: _typeOfLifecycle,
},
}
for i := 1; i < taggedParam.NumField(); i++ {
fields = append(fields, taggedParam.Field(i))
}
newParamType := reflect.StructOf(fields)
return []reflect.Type{newParamType}, func(args []reflect.Value) []reflect.Value {
param := args[0]
args[0] = reflect.New(taggedParam).Elem()
for i := 1; i < taggedParam.NumField(); i++ {
args[0].Field(i).Set(param.Field(i + 1))
}
return args
}
}
return append([]reflect.Type{_typeOfLifecycle}, paramTypes...), func(args []reflect.Value) []reflect.Value {
return args[1:]
}
}
func lifecycleExists(paramTypes []reflect.Type) bool {
for _, t := range paramTypes {
if t == _typeOfLifecycle {
return true
}
if isIn(t) {
for i := 1; i < t.NumField(); i++ {
if t.Field(i).Type == _typeOfLifecycle {
return true
}
}
}
}
return false
}
func (la *lifecycleHookAnnotation) buildHook(fn func(context.Context) error) (hook Hook) {
switch la.Type {
case _onStartHookType:
hook.OnStart = fn
case _onStopHookType:
hook.OnStop = fn
}
return hook
}
// OnStart is an Annotation that appends an OnStart Hook to the application
// Lifecycle when that function is called. This provides a way to create
// Lifecycle OnStart (see Lifecycle type documentation) hooks without building a
// function that takes a dependency on the Lifecycle type.
//
// fx.Provide(
// fx.Annotate(
// NewServer,
// fx.OnStart(func(ctx context.Context, server Server) error {
// return server.Listen(ctx)
// }),
// )
// )
//
// Which is functionally the same as:
//
// fx.Provide(
// func(lifecycle fx.Lifecycle, p Params) Server {
// server := NewServer(p)
// lifecycle.Append(fx.Hook{
// OnStart: func(ctx context.Context) error {
// return server.Listen(ctx)
// },
// })
// return server
// }
// )
//
// It is also possible to use OnStart annotation with other parameter and result
// annotations, provided that the parameter of the function passed to OnStart
// matches annotated parameters and results.