-
-
Notifications
You must be signed in to change notification settings - Fork 564
/
Copy pathservice_data.go
1626 lines (1542 loc) Β· 52 KB
/
service_data.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
package service
import (
"bytes"
"fmt"
"strings"
"text/template"
"goa.design/goa/codegen"
"goa.design/goa/expr"
)
// Services holds the data computed from the design needed to generate the code
// of the services.
var Services = make(ServicesData)
var (
// initTypeTmpl is the template used to render the code that initializes a
// projected type or viewed result type or a result type.
initTypeCodeTmpl = template.Must(template.New("initTypeCode").Funcs(template.FuncMap{"goify": codegen.Goify}).Parse(initTypeCodeT))
// validateTypeCodeTmpl is the template used to render the code to
// validate a projected type or a viewed result type.
validateTypeCodeTmpl = template.Must(template.New("validateType").Funcs(template.FuncMap{"goify": codegen.Goify}).Parse(validateTypeT))
)
type (
// ServicesData encapsulates the data computed from the service designs.
ServicesData map[string]*Data
// RequirementsData is the list of security requirements.
RequirementsData []*RequirementData
// SchemesData is the list of security schemes.
SchemesData []*SchemeData
// Data contains the data used to render the code related to a single
// service.
Data struct {
// Name is the service name.
Name string
// Description is the service description.
Description string
// StructName is the service struct name.
StructName string
// VarName is the service variable name (first letter in lowercase).
VarName string
// PkgName is the name of the package containing the generated service
// code.
PkgName string
// ViewsPkg is the name of the package containing the projected and viewed
// result types.
ViewsPkg string
// Methods lists the service interface methods.
Methods []*MethodData
// Schemes is the list of security schemes required by the service methods.
Schemes SchemesData
// Scope initialized with all the service types.
Scope *codegen.NameScope
// ViewScope initialized with all the viewed types.
ViewScope *codegen.NameScope
// userTypes lists the type definitions that the service depends on.
userTypes []*UserTypeData
// errorTypes lists the error type definitions that the service depends on.
errorTypes []*UserTypeData
// errorInits list the information required to generate error init
// functions.
errorInits []*ErrorInitData
// projectedTypes lists the types which uses pointers for all fields to
// define view specific validation logic.
projectedTypes []*ProjectedTypeData
// viewedResultTypes lists all the viewed method result types.
viewedResultTypes []*ViewedResultTypeData
}
// ErrorInitData describes an error returned by a service method of type
// ErrorResult.
ErrorInitData struct {
// Name is the name of the init function.
Name string
// Description is the error description.
Description string
// ErrName is the name of the error.
ErrName string
// TypeName is the error struct type name.
TypeName string
// TypeRef is the reference to the error type.
TypeRef string
// Temporary indicates whether the error is temporary.
Temporary bool
// Timeout indicates whether the error is due to timeouts.
Timeout bool
// Fault indicates whether the error is server-side fault.
Fault bool
}
// MethodData describes a single service method.
MethodData struct {
// Name is the method name.
Name string
// Description is the method description.
Description string
// VarName is the Go method name.
VarName string
// Payload is the name of the payload type if any,
Payload string
// PayloadDef is the payload type definition if any.
PayloadDef string
// PayloadRef is a reference to the payload type if any,
PayloadRef string
// PayloadDesc is the payload type description if any.
PayloadDesc string
// PayloadEx is an example of a valid payload value.
PayloadEx interface{}
// StreamingPayload is the name of the streaming payload type if any.
StreamingPayload string
// StreamingPayloadDef is the streaming payload type definition if any.
StreamingPayloadDef string
// StreamingPayloadRef is a reference to the streaming payload type if any.
StreamingPayloadRef string
// StreamingPayloadDesc is the streaming payload type description if any.
StreamingPayloadDesc string
// StreamingPayloadEx is an example of a valid streaming payload value.
StreamingPayloadEx interface{}
// Result is the name of the result type if any.
Result string
// ResultDef is the result type definition if any.
ResultDef string
// ResultRef is the reference to the result type if any.
ResultRef string
// ResultDesc is the result type description if any.
ResultDesc string
// ResultEx is an example of a valid result value.
ResultEx interface{}
// Errors list the possible errors defined in the design if any.
Errors []*ErrorInitData
// Requirements contains the security requirements for the
// method.
Requirements RequirementsData
// Schemes contains the security schemes types used by the
// method.
Schemes SchemesData
// ViewedResult contains the data required to generate the code handling
// views if any.
ViewedResult *ViewedResultTypeData
// ServerStream indicates that the service method receives a payload
// stream or sends a result stream or both.
ServerStream *StreamData
// ClientStream indicates that the service method receives a result
// stream or sends a payload result or both.
ClientStream *StreamData
// StreamKind is the kind of the stream (payload or result or bidirectional).
StreamKind expr.StreamKind
}
// StreamData is the data used to generate client and server interfaces that
// a streaming endpoint implements. It is initialized if a method defines a
// streaming payload or result or both.
StreamData struct {
// Interface is the name of the stream interface.
Interface string
// VarName is the name of the struct type that implements the stream
// interface.
VarName string
// SendName is the name of the send function.
SendName string
// SendDesc is the description for the send function.
SendDesc string
// SendTypeName is the type name sent through the stream.
SendTypeName string
// SendTypeRef is the reference to the type sent through the stream.
SendTypeRef string
// RecvName is the name of the receive function.
RecvName string
// RecvDesc is the description for the recv function.
RecvDesc string
// RecvTypeName is the type name received from the stream.
RecvTypeName string
// RecvTypeRef is the reference to the type received from the stream.
RecvTypeRef string
// MustClose indicates whether the stream should implement the Close()
// function.
MustClose bool
// EndpointStruct is the name of the endpoint struct that holds a payload
// reference (if any) and the endpoint server stream. It is set only if the
// client sends a normal payload and server streams a result.
EndpointStruct string
// Kind is the kind of the stream (payload or result or bidirectional).
Kind expr.StreamKind
}
// RequirementData lists the schemes and scopes defined by a single
// security requirement.
RequirementData struct {
// Schemes list the requirement schemes.
Schemes []*SchemeData
// Scopes list the required scopes.
Scopes []string
}
// UserTypeData contains the data describing a user-defined type.
UserTypeData struct {
// Name is the type name.
Name string
// VarName is the corresponding Go type name.
VarName string
// Description is the type human description.
Description string
// Def is the type definition Go code.
Def string
// Ref is the reference to the type.
Ref string
// Type is the underlying type.
Type expr.UserType
}
// SchemeData describes a single security scheme.
SchemeData struct {
// Kind is the type of scheme, one of "Basic", "APIKey", "JWT"
// or "OAuth2".
Type string
// SchemeName is the name of the scheme.
SchemeName string
// Name refers to a header or parameter name, based on In's
// value.
Name string
// UsernameField is the name of the payload field that should be
// initialized with the basic auth username if any.
UsernameField string
// UsernamePointer is true if the username field is a pointer.
UsernamePointer bool
// UsernameAttr is the name of the attribute that contains the
// username.
UsernameAttr string
// UsernameRequired specifies whether the attribute that
// contains the username is required.
UsernameRequired bool
// PasswordField is the name of the payload field that should be
// initialized with the basic auth password if any.
PasswordField string
// PasswordPointer is true if the password field is a pointer.
PasswordPointer bool
// PasswordAttr is the name of the attribute that contains the
// password.
PasswordAttr string
// PasswordRequired specifies whether the attribute that
// contains the password is required.
PasswordRequired bool
// CredField contains the name of the payload field that should
// be initialized with the API key, the JWT token or the OAuth2
// access token.
CredField string
// CredPointer is true if the credential field is a pointer.
CredPointer bool
// CredRequired specifies if the key is a required attribute.
CredRequired bool
// KeyAttr is the name of the attribute that contains
// the security tag (for APIKey, OAuth2, and JWT schemes).
KeyAttr string
// Scopes lists the scopes that apply to the scheme.
Scopes []string
// Flows describes the OAuth2 flows.
Flows []*expr.FlowExpr
// In indicates the request element that holds the credential.
In string
}
// ViewedResultTypeData contains the data used to generate a viewed result type
// (i.e. a method result type with more than one view). The viewed result
// type holds the projected type and a view based on which it creates the
// projected type. It also contains the code to validate the viewed result
// type and the functions to initialize a viewed result type from a result
// type and vice versa.
ViewedResultTypeData struct {
// the viewed result type
*UserTypeData
// Views lists the views defined on the viewed result type.
Views []*ViewData
// Validate is the validation run on the viewed result type.
Validate *ValidateData
// Init is the constructor code to initialize a viewed result type from
// a result type.
Init *InitData
// ResultInit is the constructor code to initialize a result type
// from the viewed result type.
ResultInit *InitData
// FullName is the fully qualified name of the viewed result type.
FullName string
// FullRef is the complete reference to the viewed result type
// (including views package name).
FullRef string
// IsCollection indicates whether the viewed result type is a collection.
IsCollection bool
// ViewName is the view name to use to render the result type. It is set
// only if the result type has at most one view.
ViewName string
// ViewsPkg is the views package name.
ViewsPkg string
}
// ViewData contains data about a result type view.
ViewData struct {
// Name is the view name.
Name string
// Description is the view description.
Description string
// Attributes is the list of attributes rendered in the view.
Attributes []string
// TypeVarName is the Go variable name of the type that defines the view.
TypeVarName string
}
// ProjectedTypeData contains the data used to generate a projected type for
// the corresponding user type or result type in the service package. The
// generated type uses pointers for all fields. It also contains the data
// to generate view-based validation logic and transformation functions to
// convert a projected type to its corresponding service type and vice versa.
ProjectedTypeData struct {
// the projected type
*UserTypeData
// Validations lists the validation functions to run on the projected type.
// If the projected type corresponds to a result type then a validation
// function for each view is generated. For user types, only one validation
// function is generated.
Validations []*ValidateData
// Projections contains the code to create a projected type based on
// views. If the projected type corresponds to a result type, then a
// function for each view is generated.
Projections []*InitData
// TypeInits contains the code to convert a projected type to its
// corresponding service type. If the projected type corresponds to a
// result type, then a function for each view is generated.
TypeInits []*InitData
// ViewsPkg is the views package name.
ViewsPkg string
// Views lists the views defined on the projected type.
Views []*ViewData
}
// InitData contains the data to render a constructor to initialize service
// types from viewed result types and vice versa.
InitData struct {
// Name is the name of the constructor function.
Name string
// Description is the function description.
Description string
// Args lists arguments to this function.
Args []*InitArgData
// ReturnTypeRef is the reference to the return type.
ReturnTypeRef string
// Code is the transformation code.
Code string
// Helpers contain the helpers used in the transformation code.
Helpers []*codegen.TransformFunctionData
}
// InitArgData represents a single constructor argument.
InitArgData struct {
// Name is the argument name.
Name string
// Ref is the reference to the argument type.
Ref string
}
// ValidateData contains data to render a validate function to validate a
// projected type or a viewed result type based on views.
ValidateData struct {
// Name is the validation function name.
Name string
// Ref is the reference to the type on which the validation function
// is defined.
Ref string
// Description is the description for the validation function.
Description string
// Validate is the validation code.
Validate string
}
)
// Get retrieves the data for the service with the given name computing it if
// needed. It returns nil if there is no service with the given name.
func (d ServicesData) Get(name string) *Data {
if data, ok := d[name]; ok {
return data
}
service := expr.Root.Service(name)
if service == nil {
return nil
}
d[name] = d.analyze(service)
return d[name]
}
// Method returns the service method data for the method with the given name,
// nil if there isn't one.
func (s *Data) Method(name string) *MethodData {
for _, m := range s.Methods {
if m.Name == name {
return m
}
}
return nil
}
// Scheme returns the scheme data with the given scheme name.
func (r RequirementsData) Scheme(name string) *SchemeData {
for _, req := range r {
for _, s := range req.Schemes {
if s.SchemeName == name {
return s
}
}
}
return nil
}
// Dup creates a copy of the scheme data.
func (s *SchemeData) Dup() *SchemeData {
return &SchemeData{
Type: s.Type,
SchemeName: s.SchemeName,
Name: s.Name,
UsernameField: s.UsernameField,
UsernamePointer: s.UsernamePointer,
UsernameAttr: s.UsernameAttr,
UsernameRequired: s.UsernameRequired,
PasswordField: s.PasswordField,
PasswordPointer: s.PasswordPointer,
PasswordAttr: s.PasswordAttr,
PasswordRequired: s.PasswordRequired,
CredField: s.CredField,
CredPointer: s.CredPointer,
CredRequired: s.CredRequired,
KeyAttr: s.KeyAttr,
Scopes: s.Scopes,
Flows: s.Flows,
In: s.In,
}
}
// Append appends a scheme data to schemes only if it doesn't exist.
func (s SchemesData) Append(d *SchemeData) SchemesData {
found := false
for _, se := range s {
if se.SchemeName == d.SchemeName {
found = true
break
}
}
if found {
return s
}
return append(s, d)
}
// analyze creates the data necessary to render the code of the given service.
// It records the user types needed by the service definition in userTypes.
func (d ServicesData) analyze(service *expr.ServiceExpr) *Data {
var (
scope *codegen.NameScope
viewScope *codegen.NameScope
pkgName string
viewspkg string
types []*UserTypeData
errTypes []*UserTypeData
errorInits []*ErrorInitData
projTypes []*ProjectedTypeData
viewedRTs []*ViewedResultTypeData
seenErrors map[string]struct{}
seen map[string]struct{}
seenProj map[string]*ProjectedTypeData
seenViewed map[string]*ViewedResultTypeData
)
{
scope = codegen.NewNameScope()
scope.Unique("Use") // Reserve "Use" for Endpoints struct Use method.
viewScope = codegen.NewNameScope()
pkgName = scope.HashedUnique(service, strings.ToLower(codegen.Goify(service.Name, false)), "svc")
viewspkg = pkgName + "views"
seen = make(map[string]struct{})
seenErrors = make(map[string]struct{})
seenProj = make(map[string]*ProjectedTypeData)
seenViewed = make(map[string]*ViewedResultTypeData)
// A function to convert raw object type to user type.
makeUserType := func(att *expr.AttributeExpr, name, id string) {
if _, ok := att.Type.(*expr.Object); ok {
att.Type = &expr.UserTypeExpr{
AttributeExpr: expr.DupAtt(att),
TypeName: name,
UID: id,
}
}
if ut, ok := att.Type.(expr.UserType); ok {
seen[ut.ID()] = struct{}{}
}
}
for _, e := range service.Methods {
name := codegen.Goify(e.Name, true)
// Create user type for raw object payloads
makeUserType(e.Payload, name+"Payload", service.Name+"#"+name+"Payload")
// Create user type for raw object streaming payloads
makeUserType(e.StreamingPayload, name+"StreamingPayload", service.Name+"#"+name+"StreamingPayload")
// Create user type for raw object results
makeUserType(e.Result, name+"Result", service.Name+"#"+name+"Result")
}
recordError := func(er *expr.ErrorExpr) {
errTypes = append(errTypes, collectTypes(er.AttributeExpr, scope, seen)...)
if er.Type == expr.ErrorResult {
if _, ok := seenErrors[er.Name]; ok {
return
}
seenErrors[er.Name] = struct{}{}
errorInits = append(errorInits, buildErrorInitData(er, scope))
}
}
for _, er := range service.Errors {
recordError(er)
}
// A function to collect inner user types from an attribute expression
collectUserTypes := func(att *expr.AttributeExpr) {
if ut, ok := att.Type.(expr.UserType); ok {
att = ut.Attribute()
}
types = append(types, collectTypes(att, scope, seen)...)
}
for _, m := range service.Methods {
// collect inner user types
collectUserTypes(m.Payload)
collectUserTypes(m.StreamingPayload)
collectUserTypes(m.Result)
if _, ok := m.Result.Type.(*expr.ResultTypeExpr); ok {
// collect projected types for the corresponding result type
projected := expr.DupAtt(m.Result)
projTypes = append(projTypes, collectProjectedTypes(projected, m.Result, viewspkg, scope, viewScope, seenProj)...)
}
for _, er := range m.Errors {
recordError(er)
}
}
}
for _, t := range expr.Root.Types {
if svcs, ok := t.Attribute().Meta["type:generate:force"]; ok {
att := &expr.AttributeExpr{Type: t}
if len(svcs) > 0 {
// Force generate type only in the specified services
for _, svc := range svcs {
if svc == service.Name {
types = append(types, collectTypes(att, scope, seen)...)
break
}
}
} else {
// Force generate type in all the services
types = append(types, collectTypes(att, scope, seen)...)
}
}
}
var (
methods []*MethodData
schemes SchemesData
)
{
methods = make([]*MethodData, len(service.Methods))
for i, e := range service.Methods {
m := buildMethodData(e, pkgName, service, scope)
if rt, ok := e.Result.Type.(*expr.ResultTypeExpr); ok {
if vrt, ok := seenViewed[m.Result]; ok {
m.ViewedResult = vrt
} else {
projected := seenProj[rt.ID()]
projAtt := &expr.AttributeExpr{Type: projected.Type}
vrt := buildViewedResultType(e.Result, projAtt, viewspkg, scope, viewScope)
viewedRTs = append(viewedRTs, vrt)
seenViewed[vrt.Name] = vrt
m.ViewedResult = vrt
}
}
methods[i] = m
for _, s := range m.Schemes {
schemes = schemes.Append(s)
}
}
}
var (
desc string
)
{
desc = service.Description
if desc == "" {
desc = fmt.Sprintf("Service is the %s service interface.", service.Name)
}
}
data := &Data{
Name: service.Name,
Description: desc,
VarName: codegen.Goify(service.Name, false),
StructName: codegen.Goify(service.Name, true),
PkgName: pkgName,
ViewsPkg: viewspkg,
Methods: methods,
Schemes: schemes,
Scope: scope,
ViewScope: viewScope,
errorTypes: errTypes,
errorInits: errorInits,
userTypes: types,
projectedTypes: projTypes,
viewedResultTypes: viewedRTs,
}
d[service.Name] = data
return data
}
// typeContext returns a contextual attribute for service types. Service types
// are Go types and uses non-pointers to hold attributes having default values.
func typeContext(pkg string, scope *codegen.NameScope) *codegen.AttributeContext {
return codegen.NewAttributeContext(false, false, true, pkg, scope)
}
// projectedTypeContext returns a contextual attribute for a projected type.
// Projected types are Go types that uses pointers for all attributes (even the
// required ones).
func projectedTypeContext(pkg string, scope *codegen.NameScope) *codegen.AttributeContext {
return codegen.NewAttributeContext(true, false, true, pkg, scope)
}
// collectTypes recurses through the attribute to gather all user types and
// records them in userTypes.
func collectTypes(at *expr.AttributeExpr, scope *codegen.NameScope, seen map[string]struct{}) (data []*UserTypeData) {
if at == nil || at.Type == expr.Empty {
return
}
collect := func(at *expr.AttributeExpr) []*UserTypeData { return collectTypes(at, scope, seen) }
switch dt := at.Type.(type) {
case expr.UserType:
if _, ok := seen[dt.ID()]; ok {
return nil
}
data = append(data, &UserTypeData{
Name: dt.Name(),
VarName: scope.GoTypeName(at),
Description: dt.Attribute().Description,
Def: scope.GoTypeDef(dt.Attribute(), false, true),
Ref: scope.GoTypeRef(at),
Type: dt,
})
seen[dt.ID()] = struct{}{}
data = append(data, collect(dt.Attribute())...)
case *expr.Object:
for _, nat := range *dt {
data = append(data, collect(nat.Attribute)...)
}
case *expr.Array:
data = append(data, collect(dt.ElemType)...)
case *expr.Map:
data = append(data, collect(dt.KeyType)...)
data = append(data, collect(dt.ElemType)...)
}
return
}
// buildErrorInitData creates the data needed to generate code around endpoint error return values.
func buildErrorInitData(er *expr.ErrorExpr, scope *codegen.NameScope) *ErrorInitData {
_, temporary := er.AttributeExpr.Meta["goa:error:temporary"]
_, timeout := er.AttributeExpr.Meta["goa:error:timeout"]
_, fault := er.AttributeExpr.Meta["goa:error:fault"]
return &ErrorInitData{
Name: fmt.Sprintf("Make%s", codegen.Goify(er.Name, true)),
Description: er.Description,
ErrName: er.Name,
TypeName: scope.GoTypeName(er.AttributeExpr),
TypeRef: scope.GoTypeRef(er.AttributeExpr),
Temporary: temporary,
Timeout: timeout,
Fault: fault,
}
}
// buildMethodData creates the data needed to render the given endpoint. It
// records the user types needed by the service definition in userTypes.
func buildMethodData(m *expr.MethodExpr, svcPkgName string, service *expr.ServiceExpr, scope *codegen.NameScope) *MethodData {
var (
vname string
desc string
payloadName string
payloadDef string
payloadRef string
payloadDesc string
payloadEx interface{}
spayloadName string
spayloadDef string
spayloadRef string
spayloadDesc string
spayloadEx interface{}
rname string
resultDef string
resultRef string
resultDesc string
resultEx interface{}
errors []*ErrorInitData
reqs RequirementsData
schemes SchemesData
svrStream *StreamData
cliStream *StreamData
)
vname = scope.Unique(codegen.Goify(m.Name, true), "Endpoint")
desc = m.Description
if desc == "" {
desc = codegen.Goify(m.Name, true) + " implements " + m.Name + "."
}
if m.Payload.Type != expr.Empty {
payloadName = scope.GoTypeName(m.Payload)
payloadRef = scope.GoTypeRef(m.Payload)
if dt, ok := m.Payload.Type.(expr.UserType); ok {
payloadDef = scope.GoTypeDef(dt.Attribute(), false, true)
}
payloadDesc = m.Payload.Description
if payloadDesc == "" {
payloadDesc = fmt.Sprintf("%s is the payload type of the %s service %s method.",
payloadName, m.Service.Name, m.Name)
}
payloadEx = m.Payload.Example(expr.Root.API.Random())
}
if m.StreamingPayload.Type != expr.Empty {
spayloadName = scope.GoTypeName(m.StreamingPayload)
spayloadRef = scope.GoTypeRef(m.StreamingPayload)
if dt, ok := m.StreamingPayload.Type.(expr.UserType); ok {
spayloadDef = scope.GoTypeDef(dt.Attribute(), false, true)
}
spayloadDesc = m.StreamingPayload.Description
if spayloadDesc == "" {
spayloadDesc = fmt.Sprintf("%s is the streaming payload type of the %s service %s method.",
spayloadName, m.Service.Name, m.Name)
}
spayloadEx = m.StreamingPayload.Example(expr.Root.API.Random())
}
if m.Result.Type != expr.Empty {
rname = scope.GoTypeName(m.Result)
resultRef = scope.GoTypeRef(m.Result)
if dt, ok := m.Result.Type.(expr.UserType); ok {
resultDef = scope.GoTypeDef(dt.Attribute(), false, true)
}
resultDesc = m.Result.Description
if resultDesc == "" {
resultDesc = fmt.Sprintf("%s is the result type of the %s service %s method.",
rname, m.Service.Name, m.Name)
}
resultEx = m.Result.Example(expr.Root.API.Random())
}
if len(m.Errors) > 0 {
errors = make([]*ErrorInitData, len(m.Errors))
for i, er := range m.Errors {
errors[i] = buildErrorInitData(er, scope)
}
}
if m.IsStreaming() {
svrStream = &StreamData{
Interface: vname + "ServerStream",
VarName: scope.Unique(codegen.Goify(m.Name, true), "ServerStream"),
EndpointStruct: vname + "EndpointInput",
Kind: m.Stream,
SendName: "Send",
SendDesc: fmt.Sprintf("Send streams instances of %q.", rname),
SendTypeName: rname,
SendTypeRef: resultRef,
MustClose: true,
}
cliStream = &StreamData{
Interface: vname + "ClientStream",
VarName: scope.Unique(codegen.Goify(m.Name, true), "ClientStream"),
Kind: m.Stream,
RecvName: "Recv",
RecvDesc: fmt.Sprintf("Recv reads instances of %q from the stream.", rname),
RecvTypeName: rname,
RecvTypeRef: resultRef,
}
if m.Stream == expr.ClientStreamKind || m.Stream == expr.BidirectionalStreamKind {
switch m.Stream {
case expr.ClientStreamKind:
if resultRef != "" {
svrStream.SendName = "SendAndClose"
svrStream.SendDesc = fmt.Sprintf("SendAndClose streams instances of %q and closes the stream.", rname)
svrStream.MustClose = false
cliStream.RecvName = "CloseAndRecv"
cliStream.RecvDesc = fmt.Sprintf("CloseAndRecv stops sending messages to the stream and reads instances of %q from the stream.", rname)
} else {
cliStream.MustClose = true
}
case expr.BidirectionalStreamKind:
cliStream.MustClose = true
}
svrStream.RecvName = "Recv"
svrStream.RecvDesc = fmt.Sprintf("Recv reads instances of %q from the stream.", spayloadName)
svrStream.RecvTypeName = spayloadName
svrStream.RecvTypeRef = spayloadRef
cliStream.SendName = "Send"
cliStream.SendDesc = fmt.Sprintf("Send streams instances of %q.", spayloadName)
cliStream.SendTypeName = spayloadName
cliStream.SendTypeRef = spayloadRef
}
}
for _, req := range m.Requirements {
var rs SchemesData
for _, s := range req.Schemes {
sch := buildSchemeData(s, m)
rs = rs.Append(sch)
schemes = schemes.Append(sch)
}
reqs = append(reqs, &RequirementData{Schemes: rs, Scopes: req.Scopes})
}
return &MethodData{
Name: m.Name,
VarName: vname,
Description: desc,
Payload: payloadName,
PayloadDef: payloadDef,
PayloadRef: payloadRef,
PayloadDesc: payloadDesc,
PayloadEx: payloadEx,
StreamingPayload: spayloadName,
StreamingPayloadDef: spayloadDef,
StreamingPayloadRef: spayloadRef,
StreamingPayloadDesc: spayloadDesc,
StreamingPayloadEx: spayloadEx,
Result: rname,
ResultDef: resultDef,
ResultRef: resultRef,
ResultDesc: resultDesc,
ResultEx: resultEx,
Errors: errors,
Requirements: reqs,
Schemes: schemes,
ServerStream: svrStream,
ClientStream: cliStream,
StreamKind: m.Stream,
}
}
// buildSchemeData builds the scheme data for the given scheme and method expr.
func buildSchemeData(s *expr.SchemeExpr, m *expr.MethodExpr) *SchemeData {
if !expr.IsObject(m.Payload.Type) {
return nil
}
switch s.Kind {
case expr.BasicAuthKind:
userAtt := expr.TaggedAttribute(m.Payload, "security:username")
user := codegen.Goify(userAtt, true)
passAtt := expr.TaggedAttribute(m.Payload, "security:password")
pass := codegen.Goify(passAtt, true)
var scopes []string
if len(s.Scopes) > 0 {
scopes = make([]string, len(s.Scopes))
for i, s := range s.Scopes {
scopes[i] = s.Name
}
}
return &SchemeData{
Type: s.Kind.String(),
SchemeName: s.SchemeName,
UsernameAttr: userAtt,
UsernameField: user,
UsernamePointer: m.Payload.IsPrimitivePointer(userAtt, true),
UsernameRequired: m.Payload.IsRequired(userAtt),
PasswordAttr: passAtt,
PasswordField: pass,
PasswordPointer: m.Payload.IsPrimitivePointer(passAtt, true),
PasswordRequired: m.Payload.IsRequired(passAtt),
Scopes: scopes,
}
case expr.APIKeyKind:
if keyAtt := expr.TaggedAttribute(m.Payload, "security:apikey:"+s.SchemeName); keyAtt != "" {
key := codegen.Goify(keyAtt, true)
var scopes []string
if len(s.Scopes) > 0 {
scopes = make([]string, len(s.Scopes))
for i, s := range s.Scopes {
scopes[i] = s.Name
}
}
return &SchemeData{
Type: s.Kind.String(),
Name: s.Name,
SchemeName: s.SchemeName,
CredField: key,
CredPointer: m.Payload.IsPrimitivePointer(keyAtt, true),
CredRequired: m.Payload.IsRequired(keyAtt),
KeyAttr: keyAtt,
Scopes: scopes,
In: s.In,
}
}
case expr.JWTKind:
if keyAtt := expr.TaggedAttribute(m.Payload, "security:token"); keyAtt != "" {
key := codegen.Goify(keyAtt, true)
var scopes []string
if len(s.Scopes) > 0 {
scopes = make([]string, len(s.Scopes))
for i, s := range s.Scopes {
scopes[i] = s.Name
}
}
return &SchemeData{
Type: s.Kind.String(),
Name: s.Name,
SchemeName: s.SchemeName,
CredField: key,
CredPointer: m.Payload.IsPrimitivePointer(keyAtt, true),
CredRequired: m.Payload.IsRequired(keyAtt),
KeyAttr: keyAtt,
Scopes: scopes,
In: s.In,
}
}
case expr.OAuth2Kind:
if keyAtt := expr.TaggedAttribute(m.Payload, "security:accesstoken"); keyAtt != "" {
key := codegen.Goify(keyAtt, true)
var scopes []string
if len(s.Scopes) > 0 {
scopes = make([]string, len(s.Scopes))
for i, s := range s.Scopes {
scopes[i] = s.Name
}
}
return &SchemeData{
Type: s.Kind.String(),
Name: s.Name,
SchemeName: s.SchemeName,
CredField: key,
CredPointer: m.Payload.IsPrimitivePointer(keyAtt, true),
CredRequired: m.Payload.IsRequired(keyAtt),
KeyAttr: keyAtt,
Scopes: scopes,
Flows: s.Flows,
In: s.In,
}
}
}
return nil
}
// collectProjectedTypes builds a projected type for every user type found
// when recursing through the attributes. It stores the projected types in
// data.
func collectProjectedTypes(projected, att *expr.AttributeExpr, viewspkg string, scope, viewScope *codegen.NameScope, seen map[string]*ProjectedTypeData) (data []*ProjectedTypeData) {
collect := func(projected, att *expr.AttributeExpr) []*ProjectedTypeData {
return collectProjectedTypes(projected, att, viewspkg, scope, viewScope, seen)
}
switch pt := projected.Type.(type) {
case expr.UserType:
dt := att.Type.(expr.UserType)
if pd, ok := seen[dt.ID()]; ok {
// a projected type is already created for this user type. We change the
// attribute type to this seen projected type. The seen projected type
// can be nil if the attribute type has a circular type definition in
// which case we don't change the attribute type until the projected type
// is created during the recursion.
if pd != nil {
projected.Type = pd.Type
}
return
}
seen[dt.ID()] = nil
pt.Rename(pt.Name() + "View")
// We recurse before building the projected type so that user types within
// a projected type is also converted to their respective projected types.
types := collect(pt.Attribute(), dt.Attribute())
pd := buildProjectedType(projected, att, viewspkg, scope, viewScope)
seen[dt.ID()] = pd
data = append(data, pd)
data = append(data, types...)
case *expr.Array:
dt := att.Type.(*expr.Array)
data = append(data, collect(pt.ElemType, dt.ElemType)...)
case *expr.Map:
dt := att.Type.(*expr.Map)
data = append(data, collect(pt.KeyType, dt.KeyType)...)
data = append(data, collect(pt.ElemType, dt.ElemType)...)
case *expr.Object:
dt := att.Type.(*expr.Object)
for _, n := range *pt {
data = append(data, collect(n.Attribute, dt.Attribute(n.Name))...)
}
}
return
}
// buildProjectedType builds projected type for the given user type.
//
// viewspkg is the name of the views package
//
func buildProjectedType(projected, att *expr.AttributeExpr, viewspkg string, scope, viewScope *codegen.NameScope) *ProjectedTypeData {