/
service_data.go
1404 lines (1330 loc) Β· 47.1 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 codegen
import (
"fmt"
"goa.design/goa/codegen"
"goa.design/goa/codegen/service"
"goa.design/goa/expr"
)
// GRPCServices holds the data computed from the design needed to generate the
// transport code of the gRPC services.
var GRPCServices = make(ServicesData)
type (
// ServicesData contains the data computed from the gRPC service expressions
// indexed by service name.
ServicesData map[string]*ServiceData
// ServiceData contains the data used to render the code related to a
// single service.
ServiceData struct {
// Service contains the related service data.
Service *service.Data
// PkgName is the name of the generated package in *.pb.go.
PkgName string
// Name is the service name.
Name string
// Description is the service description.
Description string
// Endpoints describes the gRPC service endpoints.
Endpoints []*EndpointData
// Messages describes the message data for this service.
Messages []*service.UserTypeData
// ServerStruct is the name of the gRPC server struct.
ServerStruct string
// ClientStruct is the name of the gRPC client struct,
ClientStruct string
// ServerInit is the name of the constructor of the server struct.
ServerInit string
// ClientInit is the name of the constructor of the client struct.
ClientInit string
// ServerInterface is the name of the gRPC server interface implemented
// by the service.
ServerInterface string
// ClientInterface is the name of the gRPC client interface implemented
// by the service.
ClientInterface string
// ClientInterfaceInit is the name of the client constructor function in
// the generated pb.go package.
ClientInterfaceInit string
// Scope is the name scope for protocol buffers
Scope *codegen.NameScope
// transformHelpers is the list of transform functions required by the
// constructors.
transformHelpers []*codegen.TransformFunctionData
// validations contain the data to generate the validation functions to
// validate the initialized type.
validations []*ValidationData
}
// EndpointData contains the data used to render the code related to
// gRPC endpoint.
EndpointData struct {
// ServiceName is the name of the service.
ServiceName string
// PkgName is the name of the generated package in *.pb.go.
PkgName string
// ServicePkgName is the name of the service package name.
ServicePkgName string
// Method is the data for the underlying method expression.
Method *service.MethodData
// PayloadType is the type of the payload.
PayloadType expr.DataType
// PayloadRef is the fully qualified reference to the method payload.
PayloadRef string
// ResultRef is the fully qualified reference to the method result.
ResultRef string
// ViewedResultRef is the fully qualified reference to the viewed result.
ViewedResultRef string
// Request is the gRPC request data.
Request *RequestData
// Response is the gRPC response data.
Response *ResponseData
// MetadataSchemes lists all the security requirement schemes that
// apply to the method and are encoded in the request metadata.
MetadataSchemes service.SchemesData
// MessageSchemes lists all the security requirement schemes that
// apply to the method and are encoded in the request message.
MessageSchemes service.SchemesData
// Errors describes the method gRPC errors.
Errors []*ErrorData
// server side
// ServerStruct is the name of the gRPC server struct.
ServerStruct string
// ServerInterface is the name of the gRPC server interface implemented
// by the service.
ServerInterface string
// ServerStream is the server stream data.
ServerStream *StreamData
// client side
// ClientMethodName is the name of the gRPC method generated by protoc-gen-go.
ClientMethodName string
// ClientStruct is the name of the gRPC client struct,
ClientStruct string
// ClientInterface is the name of the gRPC client interface implemented
// by the service.
ClientInterface string
// ClientStream is the client stream data.
ClientStream *StreamData
}
// MetadataData describes a gRPC metadata field.
MetadataData struct {
// Name is the name of the metadata key.
Name string
// AttributeName is the name of the corresponding attribute.
AttributeName string
// Description is the metadata description.
Description string
// FieldName is the name of the struct field that holds the
// metadata value if any, empty string otherwise.
FieldName string
// FieldType is the type of the struct field.
FieldType expr.DataType
// VarName is the name of the Go variable used to read or
// convert the metadata value.
VarName string
// TypeName is the name of the type.
TypeName string
// TypeRef is the reference to the type.
TypeRef string
// Required is true if the metadata is required.
Required bool
// Pointer is true if and only the metadata variable is a pointer.
Pointer bool
// StringSlice is true if the metadata value type is array of strings.
StringSlice bool
// Slice is true if the metadata value type is an array.
Slice bool
// MapStringSlice is true if the metadata value type is a map of string
// slice.
MapStringSlice bool
// Map is true if the metadata value type is a map.
Map bool
// Type describes the datatype of the variable value. Mainly
// used for conversion.
Type expr.DataType
// Validate contains the validation code if any.
Validate string
// DefaultValue contains the default value if any.
DefaultValue interface{}
// Example is an example value.
Example interface{}
}
// ErrorData contains the error information required to generate the
// transport decode (client) and encode (server) code.
ErrorData struct {
// StatusCode is the response gRPC status code.
StatusCode string
// Name is the error name.
Name string
// Ref is a reference to the error type.
Ref string
// Response is the error response data.
Response *ResponseData
}
// RequestData describes a gRPC request.
RequestData struct {
// Description is the request description.
Description string
// Message is the gRPC request message.
Message *service.UserTypeData
// Metadata is the request metadata.
Metadata []*MetadataData
// ServerConvert is the request data with constructor function to
// initialize the method payload type from the generated payload type in
// *.pb.go.
ServerConvert *ConvertData
// ClientConvert is the request data with constructor function to
// initialize the generated payload type in *.pb.go from the
// method payload.
ClientConvert *ConvertData
// CLIArgs is the list of arguments for the command-line client.
// This is set only for the client side.
CLIArgs []*InitArgData
}
// ResponseData describes a gRPC success or error response.
ResponseData struct {
// StatusCode is the return code of the response.
StatusCode string
// Description is the response description.
Description string
// Message is the gRPC response message.
Message *service.UserTypeData
// Headers is the response header metadata.
Headers []*MetadataData
// Trailers is the response trailer metadata.
Trailers []*MetadataData
// ServerConvert is the type data with constructor function to
// initialize the generated response type in *.pb.go from the
// method result type or the projected result type.
ServerConvert *ConvertData
// ClientConvert is the type data with constructor function to
// initialize the method result type or the projected result type
// from the generated response type in *.pb.go.
ClientConvert *ConvertData
}
// ConvertData contains the data to convert source type to a target type.
// For request type, it contains data to transform gRPC request type to the
// corresponding payload type (server) and vice versa (client).
// For response type, it contains data to transform gRPC response type to the
// corresponding result type (client) and vice versa (server).
ConvertData struct {
// SrcName is the fully qualified name of the source type.
SrcName string
// SrcRef is the fully qualified reference to the source type.
SrcRef string
// TgtName is the fully qualified name of the target type.
TgtName string
// TgtRef is the fully qualified reference to the target type.
TgtRef string
// Inits contain the data required to render the constructor if any
// to transform the source type to a target type. If the source or target
// type is a goa result type, we generate one constructor for every view
// defined in the result type.
Init *InitData
// Validation contains the data required to render the validation function
// to validate the initialized type.
Validation *ValidationData
}
// ValidationData contains the data necessary to render the validation
// function.
ValidationData struct {
// Name is the validation function name.
Name string
// Def is the validation function definition.
Def string
// VarName is the name of the argument.
ArgName string
// SrcName is the fully qualified name of the type being validated.
SrcName string
// SrcRef is the fully qualified reference to the type being validated.
SrcRef string
// Kind indicates that the validation is for request (server-side),
// response (client-side), or both (server and client side) messages.
// It is used to generate validation code in the server and client packages.
Kind validateKind
}
// InitData contains the data required to render a constructor.
InitData struct {
// Name is the constructor function name.
Name string
// Description is the function description.
Description string
// Args is the list of constructor arguments.
Args []*InitArgData
// ReturnVarName is the name of the variable to be returned.
ReturnVarName string
// ReturnTypeRef is the qualified (including the package name)
// reference to the return type.
ReturnTypeRef string
// ReturnTypePkg is the package where the return type is present.
ReturnTypePkg string
// ReturnIsStruct is true if the return type is a struct.
ReturnIsStruct bool
// Code is the transformation code.
Code string
}
// InitArgData represents a single constructor argument.
InitArgData struct {
// Name is the argument name.
Name string
// Description is the argument description.
Description string
// Reference to the argument, e.g. "&body".
Ref string
// FieldName is the name of the data structure field that should
// be initialized with the argument if any.
FieldName string
// FieldType is the type of the data structure field that should be
// initialized with the argument if any.
FieldType expr.DataType
// TypeName is the argument type name.
TypeName string
// TypeRef is the argument type reference.
TypeRef string
// Type is the argument type. It is never an aliased user type.
Type expr.DataType
// Pointer is true if a pointer to the arg should be used.
Pointer bool
// Required is true if the arg is required to build the payload.
Required bool
// DefaultValue is the default value of the arg.
DefaultValue interface{}
// Validate contains the validation code for the argument
// value if any.
Validate string
// Example is a example value
Example interface{}
}
// StreamData contains data to render the stream struct type that implements
// the service stream interface.
StreamData struct {
// VarName is the name of the struct type.
VarName string
// Type is the stream type (client or server).
Type string
// ServiceInterface is the service interface that the struct implements.
ServiceInterface string
// Interface is the stream interface in *.pb.go stored in the struct.
Interface string
// Endpoint is the streaming endpoint data.
Endpoint *EndpointData
// SendName is the name of the send function.
SendName string
// SendDesc is the description for the send function.
SendDesc string
// SendRef is the fully qualified reference to the type sent across the
// stream.
SendRef string
// SendConvert is the type sent through the stream. It contains the
// constructor to convert the service send type to the type expected by
// the gRPC send type (in *.pb.go)
SendConvert *ConvertData
// RecvConvert is the type received through the stream. It contains the
// constructor to convert the gRPC type (in *.pb.go) to the service receive
// type.
RecvConvert *ConvertData
// RecvName is the name of the receive function.
RecvName string
// RecvDesc is the description for the recv function.
RecvDesc string
// RecvRef is the fully qualified reference to the type received from the
// stream.
RecvRef string
// MustClose indicates whether to generate the Close() function
// for the stream.
MustClose bool
}
// validateKind is a type to determine where the validation code is generated
// (server, client, or both)
validateKind int
)
const (
// pbPkgName is the directory name where the .proto file is generated and
// compiled.
pbPkgName = "pb"
)
const (
// validateServer generates the validation code for request messages in the
// server package.
validateServer validateKind = iota + 1
// validateClient generates the validation code for response messages in the
// client package.
validateClient
// validateBoth generates the validation code in both server and client
// packages.
validateBoth
)
// Get retrieves the transport 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) *ServiceData {
if data, ok := d[name]; ok {
return data
}
service := expr.Root.API.GRPC.Service(name)
if service == nil {
return nil
}
d[name] = d.analyze(service)
return d[name]
}
// Endpoint returns the endoint data for the endpoint with the given name, nil
// if there isn't one.
func (sd *ServiceData) Endpoint(name string) *EndpointData {
for _, ed := range sd.Endpoints {
if ed.Method.Name == name {
return ed
}
}
return nil
}
// HasUnaryEndpoint returns true if the service has at least one unary endpoint.
func (sd *ServiceData) HasUnaryEndpoint() bool {
for _, ed := range sd.Endpoints {
if ed.ServerStream == nil {
return true
}
}
return false
}
// HasStreamingEndpoint returns true if the service has at least one streaming
// endpoint.
func (sd *ServiceData) HasStreamingEndpoint() bool {
for _, ed := range sd.Endpoints {
if ed.ServerStream != nil {
return true
}
}
return false
}
// analyze creates the data necessary to render the code of the given service.
func (d ServicesData) analyze(gs *expr.GRPCServiceExpr) *ServiceData {
var (
sd *ServiceData
seen map[string]struct{}
svcVarN string
svc = service.Services.Get(gs.Name())
scope = codegen.NewNameScope()
pkg = codegen.SnakeCase(codegen.Goify(svc.Name, false)) + pbPkgName
)
{
svcVarN = scope.HashedUnique(gs.ServiceExpr, codegen.Goify(svc.Name, true))
sd = &ServiceData{
Service: svc,
Name: svcVarN,
Description: svc.Description,
PkgName: pkg,
ServerStruct: "Server",
ClientStruct: "Client",
ServerInit: "New",
ClientInit: "NewClient",
ServerInterface: svcVarN + "Server",
ClientInterface: svcVarN + "Client",
ClientInterfaceInit: fmt.Sprintf("%s.New%sClient", pkg, svcVarN),
Scope: scope,
}
seen = make(map[string]struct{})
}
for _, e := range gs.GRPCEndpoints {
// convert request and response types to protocol buffer message types
e.Request = makeProtoBufMessage(e.Request, protoBufify(e.Name()+"_request", true, true), sd)
if e.MethodExpr.StreamingPayload.Type != expr.Empty {
e.StreamingRequest = makeProtoBufMessage(e.StreamingRequest, protoBufify(e.Name()+"_streaming_request", true, true), sd)
}
e.Response.Message = makeProtoBufMessage(e.Response.Message, protoBufify(e.Name()+"_response", true, true), sd)
for _, er := range e.GRPCErrors {
if er.ErrorExpr.Type == expr.ErrorResult || !expr.IsObject(er.ErrorExpr.Type) {
continue
}
er.Response.Message = makeProtoBufMessage(er.Response.Message, protoBufify(e.Name()+"_"+er.Name+"_error", true, true), sd)
}
// collect all the nested messages and return the top-level message
collect := func(att *expr.AttributeExpr) *service.UserTypeData {
msgs := collectMessages(att, sd, seen)
if len(msgs) > 0 {
sd.Messages = append(sd.Messages, msgs...)
return msgs[0]
}
// lookup message in sd.Messages
if ut, ok := att.Type.(expr.UserType); ok {
for _, t := range sd.Messages {
if t.Name == ut.Name() {
return t
}
}
}
return nil
}
var (
payloadRef string
resultRef string
viewedResultRef string
errors []*ErrorData
md = svc.Method(e.Name())
)
{
if e.MethodExpr.Payload.Type != expr.Empty {
payloadRef = svc.Scope.GoFullTypeRef(e.MethodExpr.Payload, svc.PkgName)
}
if e.MethodExpr.Result.Type != expr.Empty {
resultRef = svc.Scope.GoFullTypeRef(e.MethodExpr.Result, svc.PkgName)
}
if md.ViewedResult != nil {
viewedResultRef = md.ViewedResult.FullRef
}
errors = buildErrorsData(e, sd)
for _, er := range e.GRPCErrors {
if er.ErrorExpr.Type == expr.ErrorResult || !expr.IsObject(er.ErrorExpr.Type) {
continue
}
collect(er.Response.Message)
}
}
// build request data
var (
request *RequestData
reqMD []*MetadataData
)
{
reqMD = extractMetadata(e.Metadata, e.MethodExpr.Payload, svc.Scope)
request = &RequestData{
Description: e.Request.Description,
Metadata: reqMD,
ServerConvert: buildRequestConvertData(e.Request, e.MethodExpr.Payload, reqMD, e, sd, true),
ClientConvert: buildRequestConvertData(e.Request, e.MethodExpr.Payload, reqMD, e, sd, false),
}
if obj := expr.AsObject(e.Request.Type); len(*obj) > 0 {
// add the request message as the first argument to the CLI
request.CLIArgs = append(request.CLIArgs, &InitArgData{
Name: "message",
Ref: "message",
TypeName: protoBufGoFullTypeName(e.Request, sd.PkgName, sd.Scope),
TypeRef: protoBufGoFullTypeRef(e.Request, sd.PkgName, sd.Scope),
Example: e.Request.Example(expr.Root.API.Random()),
})
}
// pass the metadata as arguments to client CLI args
for _, m := range reqMD {
request.CLIArgs = append(request.CLIArgs, &InitArgData{
Name: m.VarName,
Ref: m.VarName,
FieldName: m.FieldName,
FieldType: m.FieldType,
TypeName: m.TypeName,
TypeRef: m.TypeRef,
Type: m.Type,
Pointer: m.Pointer,
Required: m.Required,
Validate: m.Validate,
Example: m.Example,
})
}
if e.StreamingRequest.Type != expr.Empty {
request.Message = collect(e.StreamingRequest)
} else {
request.Message = collect(e.Request)
}
}
// build response data
var (
response *ResponseData
hdrs []*MetadataData
trlrs []*MetadataData
result, svcCtx = resultContext(e, sd)
)
{
hdrs = extractMetadata(e.Response.Headers, result, svc.Scope)
trlrs = extractMetadata(e.Response.Trailers, result, svc.Scope)
response = &ResponseData{
StatusCode: statusCodeToGRPCConst(e.Response.StatusCode),
Description: e.Response.Description,
Headers: hdrs,
Trailers: trlrs,
ServerConvert: buildResponseConvertData(e.Response.Message, result, svcCtx, hdrs, trlrs, e, sd, true),
ClientConvert: buildResponseConvertData(e.Response.Message, result, svcCtx, hdrs, trlrs, e, sd, false),
}
// If the endpoint is a streaming endpoint, no message is returned
// by gRPC. Hence, no need to set response message.
if e.Response.Message.Type != expr.Empty || !e.MethodExpr.IsStreaming() {
response.Message = collect(e.Response.Message)
}
}
// gather security requirements
var (
msgSch service.SchemesData
metSch service.SchemesData
)
{
for _, req := range e.Requirements {
for _, sch := range req.Schemes {
s := md.Requirements.Scheme(sch.SchemeName).Dup()
s.In = sch.In
switch s.In {
case "message":
msgSch = msgSch.Append(s)
default:
metSch = metSch.Append(s)
}
}
}
}
ed := &EndpointData{
ServiceName: svc.Name,
PkgName: sd.PkgName,
ServicePkgName: svc.PkgName,
Method: md,
PayloadType: e.MethodExpr.Payload.Type,
PayloadRef: payloadRef,
ResultRef: resultRef,
ViewedResultRef: viewedResultRef,
Request: request,
Response: response,
MessageSchemes: msgSch,
MetadataSchemes: metSch,
Errors: errors,
ServerStruct: sd.ServerStruct,
ServerInterface: sd.ServerInterface,
ClientMethodName: protoBufify(md.VarName, true, true),
ClientStruct: sd.ClientStruct,
ClientInterface: sd.ClientInterface,
}
sd.Endpoints = append(sd.Endpoints, ed)
if e.MethodExpr.IsStreaming() {
ed.ServerStream = buildStreamData(e, sd, true)
ed.ClientStream = buildStreamData(e, sd, false)
}
}
return sd
}
// collectMessages recurses through the attribute to gather all the messages.
func collectMessages(at *expr.AttributeExpr, sd *ServiceData, seen map[string]struct{}) (data []*service.UserTypeData) {
if at == nil || expr.IsPrimitive(at.Type) {
return
}
collect := func(at *expr.AttributeExpr) []*service.UserTypeData {
return collectMessages(at, sd, seen)
}
switch dt := at.Type.(type) {
case expr.UserType:
if _, ok := seen[dt.Name()]; ok {
return nil
}
att := dt.Attribute()
if rt, ok := dt.(*expr.ResultTypeExpr); ok {
if a := unwrapAttr(expr.DupAtt(rt.Attribute())); expr.IsArray(a.Type) && expr.IsObject(rt) {
// result type collection
att = &expr.AttributeExpr{Type: expr.AsObject(rt)}
}
}
data = append(data, &service.UserTypeData{
Name: dt.Name(),
VarName: protoBufMessageName(at, sd.Scope),
Description: dt.Attribute().Description,
Def: protoBufMessageDef(att, sd),
Ref: protoBufGoFullTypeRef(at, sd.PkgName, sd.Scope),
Type: dt,
})
seen[dt.Name()] = struct{}{}
data = append(data, collect(att)...)
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
}
// addValidation adds a validation function (if any) for the given user type
// and recurses through the user type adding other validation functions
// (if any).
//
// req if true indicates that the validation is generated for validating
// request (server-side) messages.
func addValidation(att *expr.AttributeExpr, sd *ServiceData, req bool) *ValidationData {
ut, ok := att.Type.(expr.UserType)
if !ok {
return nil
}
name := protoBufGoTypeName(att, sd.Scope)
ref := protoBufGoFullTypeRef(att, sd.PkgName, sd.Scope)
kind := validateClient
if req {
kind = validateServer
}
att = ut.Attribute()
if rt, ok := ut.(*expr.ResultTypeExpr); ok {
if a := unwrapAttr(expr.DupAtt(rt.Attribute())); expr.IsArray(a.Type) {
// result type collection
att = &expr.AttributeExpr{Type: expr.AsObject(rt)}
}
}
for _, n := range sd.validations {
if n.SrcName == name {
if n.Kind != kind {
n.Kind = validateBoth
ctx := protoBufTypeContext("", sd.Scope)
collectValidations(att, ctx, req, sd)
}
return n
}
}
ctx := protoBufTypeContext("", sd.Scope)
if def := codegen.RecursiveValidationCode(att, ctx, true, "message"); def != "" {
v := &ValidationData{
Name: "Validate" + name,
Def: def,
ArgName: "message",
SrcName: name,
SrcRef: ref,
Kind: kind,
}
sd.validations = append(sd.validations, v)
collectValidations(att, ctx, req, sd)
return v
}
return nil
}
// collectValidations recurses through the attribute and collects the
// validation functions.
//
// req if true indicates that the validations are generated for validating
// request messages.
func collectValidations(att *expr.AttributeExpr, ctx *codegen.AttributeContext, req bool, sd *ServiceData) {
switch dt := att.Type.(type) {
case expr.UserType:
name := protoBufMessageName(att, sd.Scope)
kind := validateClient
if req {
kind = validateServer
}
for _, n := range sd.validations {
if n.SrcName == name {
if n.Kind != validateBoth && n.Kind != kind {
n.Kind = validateBoth
goto collect
}
return
}
}
sd.validations = append(sd.validations, &ValidationData{
Name: "Validate" + name,
Def: codegen.RecursiveValidationCode(att, ctx, true, "message"),
ArgName: "message",
SrcName: name,
SrcRef: protoBufGoFullTypeRef(att, sd.PkgName, sd.Scope),
Kind: kind,
})
collect:
att := dt.Attribute()
if rt, ok := dt.(*expr.ResultTypeExpr); ok {
if a := unwrapAttr(expr.DupAtt(rt.Attribute())); expr.IsArray(a.Type) {
// result type collection
att = &expr.AttributeExpr{Type: expr.AsObject(rt)}
}
}
collectValidations(att, ctx, req, sd)
case *expr.Object:
for _, nat := range *dt {
collectValidations(nat.Attribute, ctx, req, sd)
}
case *expr.Array:
collectValidations(dt.ElemType, ctx, req, sd)
case *expr.Map:
collectValidations(dt.KeyType, ctx, req, sd)
collectValidations(dt.ElemType, ctx, req, sd)
}
}
// buildRequestConvertData builds the convert data for the server and client
// requests.
// * server side - converts generated gRPC request type in *.pb.go and the
// gRPC metadata to method payload type.
// * client side - converts method payload type to generated gRPC request
// type in *.pb.go.
//
// svr param indicates that the convert data is generated for server side.
func buildRequestConvertData(request, payload *expr.AttributeExpr, md []*MetadataData, e *expr.GRPCEndpointExpr, sd *ServiceData, svr bool) *ConvertData {
// Server-side: No need to build convert data if payload is empty or payload
// is not an object type and endpoint streams payload (the payload is
// encoded in metadata under "goa-payload" in this case).
if (svr && (isEmpty(payload.Type) || !expr.IsObject(payload.Type) && e.MethodExpr.IsPayloadStreaming())) ||
// Client-side: No need to build convert data if streaming payload since
// all attributes in method payload is encoded into request metadata.
(!svr && e.MethodExpr.IsPayloadStreaming()) {
return nil
}
var (
svc = sd.Service
svcCtx = serviceTypeContext(svc.PkgName, svc.Scope)
)
if svr {
// server side
var data *InitData
{
data = buildInitData(request, payload, "message", "v", svcCtx, false, sd)
data.Name = fmt.Sprintf("New%sPayload", codegen.Goify(e.Name(), true))
data.Description = fmt.Sprintf("%s builds the payload of the %q endpoint of the %q service from the gRPC request type.", data.Name, e.Name(), svc.Name)
for _, m := range md {
// pass the metadata as arguments to payload constructor in server
data.Args = append(data.Args, &InitArgData{
Name: m.VarName,
Ref: m.VarName,
FieldName: m.FieldName,
FieldType: m.FieldType,
TypeName: m.TypeName,
TypeRef: m.TypeRef,
Type: m.Type,
Pointer: m.Pointer,
Required: m.Required,
Validate: m.Validate,
Example: m.Example,
})
}
}
return &ConvertData{
SrcName: protoBufGoFullTypeName(request, sd.PkgName, sd.Scope),
SrcRef: protoBufGoFullTypeRef(request, sd.PkgName, sd.Scope),
TgtName: svc.Scope.GoFullTypeName(payload, svcCtx.Pkg),
TgtRef: svc.Scope.GoFullTypeRef(payload, svcCtx.Pkg),
Init: data,
Validation: addValidation(request, sd, true),
}
}
// client side
var (
data *InitData
)
{
data = buildInitData(payload, request, "payload", "message", svcCtx, true, sd)
data.Description = fmt.Sprintf("%s builds the gRPC request type from the payload of the %q endpoint of the %q service.", data.Name, e.Name(), svc.Name)
}
return &ConvertData{
SrcName: svc.Scope.GoFullTypeName(payload, svc.PkgName),
SrcRef: svc.Scope.GoFullTypeRef(payload, svc.PkgName),
TgtName: protoBufGoFullTypeName(request, sd.PkgName, sd.Scope),
TgtRef: protoBufGoFullTypeRef(request, sd.PkgName, sd.Scope),
Init: data,
}
}
// buildResponseConvertData builds the convert data for the server and client
// responses.
// * server side - converts method result type to generated gRPC response type
// in *.pb.go
// * client side - converts generated gRPC response type in *.pb.go and
// response metadata to method result type.
//
// svr param indicates that the convert data is generated for server side.
func buildResponseConvertData(response, result *expr.AttributeExpr, svcCtx *codegen.AttributeContext, hdrs, trlrs []*MetadataData, e *expr.GRPCEndpointExpr, sd *ServiceData, svr bool) *ConvertData {
if !svr && (e.MethodExpr.IsStreaming() || isEmpty(e.MethodExpr.Result.Type)) {
return nil
}
var (
svc = sd.Service
)
if svr {
// server side
var data *InitData
{
data = buildInitData(result, response, "result", "message", svcCtx, true, sd)
data.Description = fmt.Sprintf("%s builds the gRPC response type from the result of the %q endpoint of the %q service.", data.Name, e.Name(), svc.Name)
}
return &ConvertData{
SrcName: svcCtx.Scope.Name(result, svcCtx.Pkg, svcCtx.Pointer, svcCtx.UseDefault),
SrcRef: svcCtx.Scope.Ref(result, svcCtx.Pkg),
TgtName: protoBufGoFullTypeName(response, sd.PkgName, sd.Scope),
TgtRef: protoBufGoFullTypeRef(response, sd.PkgName, sd.Scope),
Init: data,
}
}
// client side
var data *InitData
{
data = buildInitData(response, result, "message", "result", svcCtx, false, sd)
data.Name = fmt.Sprintf("New%sResult", codegen.Goify(e.Name(), true))
data.Description = fmt.Sprintf("%s builds the result type of the %q endpoint of the %q service from the gRPC response type.", data.Name, e.Name(), svc.Name)
for _, m := range hdrs {
// pass the headers as arguments to result constructor in client
data.Args = append(data.Args, &InitArgData{
Name: m.VarName,
Ref: m.VarName,
FieldName: m.FieldName,
FieldType: m.FieldType,
TypeName: m.TypeName,
TypeRef: m.TypeRef,
Type: m.Type,
Pointer: m.Pointer,
Required: m.Required,
Validate: m.Validate,
Example: m.Example,
})
}
for _, m := range trlrs {
// pass the trailers as arguments to result constructor in client
data.Args = append(data.Args, &InitArgData{
Name: m.VarName,
Ref: m.VarName,
FieldName: m.FieldName,
FieldType: m.FieldType,
TypeName: m.TypeName,
TypeRef: m.TypeRef,
Type: m.Type,
Pointer: m.Pointer,
Required: m.Required,
Validate: m.Validate,
Example: m.Example,
})
}
}
return &ConvertData{
SrcName: protoBufGoFullTypeName(response, sd.PkgName, sd.Scope),
SrcRef: protoBufGoFullTypeRef(response, sd.PkgName, sd.Scope),
TgtName: svcCtx.Scope.Name(result, svcCtx.Pkg, svcCtx.Pointer, svcCtx.UseDefault),
TgtRef: svcCtx.Scope.Ref(result, svcCtx.Pkg),
Init: data,
Validation: addValidation(response, sd, false),
}
}
// buildInitData builds the transformation code to convert source to target.
//
// source, target are the source and target attributes used in the
// transformation
//
// sourceVar, targetVar are the source and target variable names used in the
// transformation
//
// svcCtx is the attribute context for service type
//
// proto if true indicates the target type is a protocol buffer type
//
func buildInitData(source, target *expr.AttributeExpr, sourceVar, targetVar string, svcCtx *codegen.AttributeContext, proto bool, sd *ServiceData) *InitData {
var (
name string
isStruct bool
code string
helpers []*codegen.TransformFunctionData
args []*InitArgData
err error
srcCtx *codegen.AttributeContext
tgtCtx *codegen.AttributeContext
pbCtx = protoBufTypeContext(sd.PkgName, sd.Scope)
)
{
isStruct = expr.IsObject(target.Type)
n := protoBufGoTypeName(target, sd.Scope)
if !isStruct {
// If target is array, map, or primitive the name will be suffixed with
// the definition (e.g int, []string, map[int]string) which is incorrect.
n = protoBufGoTypeName(source, sd.Scope)
}
name = "New" + n
srcCtx = pbCtx
tgtCtx = svcCtx
if proto {
srcCtx = svcCtx
tgtCtx = pbCtx
}
code, helpers, err = protoBufTransform(source, target, sourceVar, targetVar, srcCtx, tgtCtx, proto, true)
if err != nil {
fmt.Println(err.Error()) // TBD validate DSL so errors are not possible
return nil
}
sd.transformHelpers = codegen.AppendHelpers(sd.transformHelpers, helpers)
if (!proto && !isEmpty(source.Type)) || (proto && !isEmpty(target.Type)) {
args = []*InitArgData{{
Name: sourceVar,
Ref: sourceVar,
TypeName: srcCtx.Scope.Name(source, srcCtx.Pkg, srcCtx.Pointer, srcCtx.UseDefault),
TypeRef: srcCtx.Scope.Ref(source, srcCtx.Pkg),
Example: source.Example(expr.Root.API.Random()),
}}
}
}
return &InitData{
Name: name,
ReturnVarName: targetVar,
ReturnTypeRef: tgtCtx.Scope.Ref(target, tgtCtx.Pkg),
ReturnIsStruct: isStruct,
ReturnTypePkg: tgtCtx.Pkg,
Code: code,