forked from uber/zanzibar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
method.go
1588 lines (1387 loc) · 45.9 KB
/
method.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) 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 codegen
import (
"fmt"
"sort"
"strconv"
"strings"
"github.com/pkg/errors"
"go.uber.org/thriftrw/compile"
)
const (
antHTTPMethod = "%s.http.method"
antHTTPPath = "%s.http.path"
antHTTPStatus = "%s.http.status"
antHTTPReqHeaders = "%s.http.reqHeaders"
antHTTPResHeaders = "%s.http.resHeaders"
antHTTPRef = "%s.http.ref"
antMeta = "%s.meta"
antHandler = "%s.handler"
// AntHTTPReqDefBoxed annotates a method so that the genereted method takes
// generated argument directly instead of a struct that warps the argument.
// The annotated method should have one and only one argument.
AntHTTPReqDefBoxed = "%s.http.req.def"
antHTTPResNoBody = "%s.http.res.body.disallow"
)
const queryAnnotationPrefix = "query."
const headerAnnotationPrefix = "headers."
// PathSegment represents a part of the http path.
type PathSegment struct {
Type string
Text string
BodyIdentifier string
ParamName string
Required bool
}
// ExceptionSpec contains information about thrift exceptions
type ExceptionSpec struct {
StructSpec
StatusCode StatusCode
IsBodyDisallowed bool
}
// HeaderFieldInfo contains information about where to store
// the string from headers into the request/response body.
type HeaderFieldInfo struct {
FieldIdentifier string
IsPointer bool
}
// MethodSpec specifies all needed parts to generate code for a method in service.
type MethodSpec struct {
Name string
HTTPMethod string
// Used by edge gateway to generate endpoint.
EndpointName string
HTTPPath string
PathSegments []PathSegment
annotations annotations
IsEndpoint bool
// Statements for reading query parameters.
ParseQueryParamGoStatements []string
// Statements for writing query parameters
WriteQueryParamGoStatements []string
// Statements for reading request headers
ReqHeaderGoStatements []string
// Statements for reading request headers for clients
ReqClientHeaderGoStatements []string
// ResHeaderFields is a map of header name to a golang
// field accessor expression used to read fields out
// of the response body and place them into response headers
ResHeaderFields map[string]HeaderFieldInfo
// ReqHeaders needed, generated from "zanzibar.http.reqHeaders"
ReqHeaders []string
// ResHeaders needed, generated from "zanzibar.http.resHeaders"
ResHeaders []string
RequestType string
ShortRequestType string
ResponseType string
ShortResponseType string
OKStatusCode StatusCode
Exceptions []ExceptionSpec
ExceptionsByStatusCode map[int][]ExceptionSpec
ExceptionsIndex map[string]ExceptionSpec
ValidStatusCodes []int
// Fully qualified field type of the unboxed field
BoxedRequestType string
// Unboxed field name
BoxedRequestName string
// Additional struct generated from the bundle of request args.
RequestBoxed bool
// Thrift service name the method belongs to.
ThriftService string
// The thriftrw-generated go package name
GenCodePkgName string
// Whether the method needs annotation or not.
WantAnnot bool
// The thriftrw compiled spec, used to extract type information
CompiledThriftSpec *compile.FunctionSpec
// The downstream service method set by endpoint config
Downstream *ModuleSpec
// the downstream service name
DownstreamService string
// The downstream method spec for the endpoint
DownstreamMethod *MethodSpec
// Statements for converting request types
ConvertRequestGoStatements []string
// Statements for converting response types
ConvertResponseGoStatements []string
// Statements for converting Clientless request types
ConvertClientlessRequestGoStatements []string
// Statements for propagating headers to client requests
PropagateHeadersGoStatements []string
// Statements for reading data out of url params (server)
RequestParamGoStatements []string
}
type annotations struct {
HTTPMethod string
HTTPPath string
HTTPStatus string
HTTPReqHeaders string
HTTPResHeaders string
HTTPRef string
Meta string
Handler string
HTTPReqDefBoxed string
HTTPResNoBody string
}
// StructSpec specifies a Go struct to be generated.
type StructSpec struct {
Type string
Name string
Annotations map[string]string
}
// StatusCode is for http status code with exception message.
type StatusCode struct {
Code int
Message string
}
// NewMethod creates new method specification.
func NewMethod(
thriftFile string,
funcSpec *compile.FunctionSpec,
packageHelper *PackageHelper,
wantAnnot bool,
isEndpoint bool,
thriftService string,
) (*MethodSpec, error) {
var (
err error
ok bool
ant = packageHelper.annotationPrefix
method = &MethodSpec{}
)
method.CompiledThriftSpec = funcSpec
method.Name = funcSpec.MethodName()
method.IsEndpoint = isEndpoint
method.WantAnnot = wantAnnot
method.ThriftService = thriftService
method.annotations = annotations{
HTTPMethod: fmt.Sprintf(antHTTPMethod, ant),
HTTPPath: fmt.Sprintf(antHTTPPath, ant),
HTTPStatus: fmt.Sprintf(antHTTPStatus, ant),
HTTPReqHeaders: fmt.Sprintf(antHTTPReqHeaders, ant),
HTTPResHeaders: fmt.Sprintf(antHTTPResHeaders, ant),
HTTPRef: fmt.Sprintf(antHTTPRef, ant),
Meta: fmt.Sprintf(antMeta, ant),
Handler: fmt.Sprintf(antHandler, ant),
HTTPReqDefBoxed: fmt.Sprintf(AntHTTPReqDefBoxed, ant),
HTTPResNoBody: fmt.Sprintf(antHTTPResNoBody, ant),
}
method.GenCodePkgName, err = packageHelper.TypePackageName(thriftFile)
if err != nil {
return nil, err
}
err = method.setResponseType(thriftFile, funcSpec.ResultSpec, packageHelper)
if err != nil {
return nil, err
}
err = method.setRequestType(thriftFile, funcSpec, packageHelper)
if err != nil {
return nil, err
}
err = method.setExceptions(thriftFile, isEndpoint, funcSpec.ResultSpec, packageHelper)
if err != nil {
return nil, err
}
method.ReqHeaders = headers(funcSpec.Annotations[method.annotations.HTTPReqHeaders])
method.ResHeaders = headers(funcSpec.Annotations[method.annotations.HTTPResHeaders])
if !wantAnnot {
return method, nil
}
if method.HTTPMethod, ok = funcSpec.Annotations[method.annotations.HTTPMethod]; !ok {
return nil, errors.Errorf("missing annotation '%s' for HTTP method", method.annotations.HTTPMethod)
}
method.EndpointName = funcSpec.Annotations[method.annotations.Handler]
err = method.setOKStatusCode(funcSpec.Annotations[method.annotations.HTTPStatus])
if err != nil {
return nil, err
}
method.setValidStatusCodes()
if method.RequestType != "" {
hasNoBody := method.HTTPMethod == "GET"
if method.IsEndpoint {
err := method.setParseQueryParamStatements(funcSpec, packageHelper, hasNoBody)
if err != nil {
return nil, err
}
} else {
err := method.setWriteQueryParamStatements(funcSpec, packageHelper, hasNoBody)
if err != nil {
return nil, err
}
}
}
var httpPath string
if httpPath, ok = funcSpec.Annotations[method.annotations.HTTPPath]; !ok {
return nil, errors.Errorf(
"missing annotation '%s' for HTTP path", method.annotations.HTTPPath,
)
}
method.setHTTPPath(httpPath, funcSpec)
err = method.setRequestParamFields(funcSpec, packageHelper)
if err != nil {
return nil, err
}
err = method.setEndpointRequestHeaderFields(funcSpec, packageHelper)
if err != nil {
return nil, err
}
err = method.setClientRequestHeaderFields(funcSpec, packageHelper)
if err != nil {
return nil, err
}
method.setResponseHeaderFields(funcSpec)
return method, nil
}
// setRequestType sets the request type of the method specification. If the
// "zanzibar.http.req.def.boxed" is true, then the first parameter will be used as
// the request body; otherwise a new struct is generated to bundle the request
// parameters as http body and the name of the struct will be returned.
func (ms *MethodSpec) setRequestType(curThriftFile string, funcSpec *compile.FunctionSpec, packageHelper *PackageHelper) error {
if len(funcSpec.ArgsSpec) == 0 {
ms.RequestType = ""
return nil
}
var err error
if ms.isRequestBoxed(funcSpec) {
ms.RequestBoxed = true
ms.BoxedRequestType, err = packageHelper.TypeFullName(funcSpec.ArgsSpec[0].Type)
ms.BoxedRequestName = PascalCase(funcSpec.ArgsSpec[0].Name)
if err == nil && IsStructType(funcSpec.ArgsSpec[0].Type) {
ms.BoxedRequestType = "*" + ms.BoxedRequestType
}
}
goPackageName, err := packageHelper.TypePackageName(curThriftFile)
if err == nil {
ms.ShortRequestType = goPackageName + "." +
ms.ThriftService + "_" + strings.Title(ms.Name) + "_Args"
ms.RequestType = "*" + ms.ShortRequestType
}
if err != nil {
return errors.Wrap(err, "failed to set request type")
}
return nil
}
func (ms *MethodSpec) setResponseType(curThriftFile string, respSpec *compile.ResultSpec, packageHelper *PackageHelper) error {
if respSpec == nil {
ms.ResponseType = ""
return nil
}
typeName, err := packageHelper.TypeFullName(respSpec.ReturnType)
ms.ShortResponseType = typeName
if IsStructType(respSpec.ReturnType) {
typeName = "*" + typeName
}
if err != nil {
return errors.Wrap(err, "failed to get response type")
}
ms.ResponseType = typeName
return nil
}
// RefResponse prepends the response variable with '&' if it is not of reference type
// It is used to construct the `Success` field of the `$service_$method_Result` struct
// generated by thriftrw, which is always of reference type.
func (ms *MethodSpec) RefResponse(respVar string) string {
respSpec := ms.CompiledThriftSpec.ResultSpec
if respSpec == nil || respSpec.ReturnType == nil {
return respVar
}
switch compile.RootTypeSpec(respSpec.ReturnType).(type) {
case *compile.BoolSpec, *compile.I8Spec, *compile.I16Spec, *compile.I32Spec,
*compile.I64Spec, *compile.DoubleSpec, *compile.StringSpec, *compile.EnumSpec:
return "&" + respVar
default:
return respVar
}
}
func (ms *MethodSpec) setOKStatusCode(statusCode string) error {
if statusCode == "" {
return errors.Errorf("no http OK status code set by annotation '%s' ", ms.annotations.HTTPStatus)
}
code, err := strconv.Atoi(statusCode)
if err != nil {
return errors.Wrapf(err,
"Could not parse status code annotation (%s) for ok response",
statusCode,
)
}
ms.OKStatusCode = StatusCode{
Code: code,
}
return nil
}
func (ms *MethodSpec) setValidStatusCodes() {
ms.ValidStatusCodes = []int{
ms.OKStatusCode.Code,
}
for code := range ms.ExceptionsByStatusCode {
ms.ValidStatusCodes = append(ms.ValidStatusCodes, code)
}
// Prevents non-deterministic builds
sort.Ints(ms.ValidStatusCodes)
}
func (ms *MethodSpec) setExceptions(
curThriftFile string,
isEndpoint bool,
resultSpec *compile.ResultSpec,
h *PackageHelper,
) error {
ms.Exceptions = make([]ExceptionSpec, len(resultSpec.Exceptions))
ms.ExceptionsIndex = make(
map[string]ExceptionSpec, len(resultSpec.Exceptions),
)
ms.ExceptionsByStatusCode = map[int][]ExceptionSpec{}
for i, e := range resultSpec.Exceptions {
typeName, err := h.TypeFullName(e.Type)
if err != nil {
return errors.Wrapf(
err,
"cannot resolve type full name for %s for exception %s",
e.Type,
e.Name,
)
}
bodyDisallowed := ms.isBodyDisallowed(e)
if !ms.WantAnnot {
exception := ExceptionSpec{
StructSpec: StructSpec{
Type: typeName,
Name: e.Name,
},
IsBodyDisallowed: bodyDisallowed,
}
ms.Exceptions[i] = exception
ms.ExceptionsIndex[e.Name] = exception
if _, exists := ms.ExceptionsByStatusCode[exception.StatusCode.Code]; !exists {
ms.ExceptionsByStatusCode[exception.StatusCode.Code] = []ExceptionSpec{}
}
ms.ExceptionsByStatusCode[exception.StatusCode.Code] = append(
ms.ExceptionsByStatusCode[exception.StatusCode.Code],
exception,
)
continue
}
code, err := strconv.Atoi(e.Annotations[ms.annotations.HTTPStatus])
if err != nil {
return errors.Wrapf(
err,
"cannot parse the annotation %s for exception %s", ms.annotations.HTTPStatus, e.Name,
)
}
exception := ExceptionSpec{
StructSpec: StructSpec{
Type: typeName,
Name: e.Name,
Annotations: e.Annotations,
},
StatusCode: StatusCode{
Code: code,
Message: e.Name,
},
IsBodyDisallowed: bodyDisallowed,
}
ms.Exceptions[i] = exception
ms.ExceptionsIndex[e.Name] = exception
if _, exists := ms.ExceptionsByStatusCode[exception.StatusCode.Code]; !exists {
ms.ExceptionsByStatusCode[exception.StatusCode.Code] = []ExceptionSpec{}
}
ms.ExceptionsByStatusCode[exception.StatusCode.Code] = append(
ms.ExceptionsByStatusCode[exception.StatusCode.Code],
exception,
)
}
return nil
}
func (ms *MethodSpec) findParamsAnnotation(
fields compile.FieldGroup, paramName string,
) (string, bool, bool) {
var identifier string
var required bool
visitor := func(
goPrefix string, thriftPrefix string, field *compile.FieldSpec,
) bool {
if param, ok := field.Annotations[ms.annotations.HTTPRef]; ok {
if param == "params."+paramName[1:] {
identifier = goPrefix + "." + PascalCase(field.Name)
required = field.Required
return true
}
}
return false
}
walkFieldGroups(fields, visitor)
if identifier == "" {
return "", required, false
}
return identifier, required, true
}
func (ms *MethodSpec) setRequestParamFields(
funcSpec *compile.FunctionSpec, packageHelper *PackageHelper,
) error {
statements := LineBuilder{}
seenStructs, itrOrder, err := findStructs(funcSpec, packageHelper)
if err != nil {
return err
}
for _, segment := range ms.PathSegments {
if segment.Type != "param" {
continue
}
for _, seenStruct := range itrOrder {
if strings.HasPrefix(segment.BodyIdentifier, seenStruct) {
statements.appendf("if requestBody%s == nil {",
seenStruct,
)
statements.appendf("\trequestBody%s = &%s{}",
seenStruct, seenStructs[seenStruct],
)
statements.append("}")
}
}
if segment.Required {
statements.appendf("requestBody%s = req.Params.Get(%q)",
segment.BodyIdentifier, segment.ParamName,
)
} else {
statements.appendf(
"requestBody%s = ptr.String(req.Params.Get(%q))",
segment.BodyIdentifier,
segment.ParamName,
)
}
}
ms.RequestParamGoStatements = statements.GetLines()
return nil
}
func findStructs(
funcSpec *compile.FunctionSpec, packageHelper *PackageHelper,
) (map[string]string, []string, error) {
fields := compile.FieldGroup(funcSpec.ArgsSpec)
seenStructs := make(map[string]string)
itrOrder := make([]string, 0)
var finalError error
visitor := func(
goPrefix string, thriftPrefix string, field *compile.FieldSpec,
) bool {
realType := compile.RootTypeSpec(field.Type)
longFieldName := goPrefix + "." + PascalCase(field.Name)
if _, ok := realType.(*compile.StructSpec); ok {
typeName, err := GoType(packageHelper, realType)
if err != nil {
finalError = err
return true
}
seenStructs[longFieldName] = typeName
itrOrder = append(itrOrder, longFieldName)
}
return false
}
walkFieldGroups(fields, visitor)
if finalError != nil {
return nil, nil, finalError
}
return seenStructs, itrOrder, nil
}
func (ms *MethodSpec) setEndpointRequestHeaderFields(
funcSpec *compile.FunctionSpec, packageHelper *PackageHelper,
) error {
fields := compile.FieldGroup(funcSpec.ArgsSpec)
// ms.ReqHeaderFields = map[string]HeaderFieldInfo{}
statements := LineBuilder{}
var finalError error
var seenHeaders bool
var headersMap = map[string]int{}
var seenOptStructs = map[string]string{}
// Scan for all annotations
visitor := func(
goPrefix string, thriftPrefix string, field *compile.FieldSpec,
) bool {
realType := compile.RootTypeSpec(field.Type)
longFieldName := goPrefix + "." + PascalCase(field.Name)
// If the type is a struct then we cannot really do anything
if _, ok := realType.(*compile.StructSpec); ok {
// if a field is a struct then we must do a nil check
typeName, err := GoType(packageHelper, realType)
if err != nil {
finalError = err
return true
}
if field.Required {
statements.appendf("if requestBody%s == nil {", longFieldName)
statements.appendf("\trequestBody%s = &%s{}",
longFieldName, typeName,
)
statements.append("}")
} else {
seenOptStructs[longFieldName] = typeName
}
return false
}
if param, ok := field.Annotations[ms.annotations.HTTPRef]; ok {
if strings.HasPrefix(param, headerAnnotationPrefix) {
headerName := strings.TrimPrefix(param, headerAnnotationPrefix)
camelHeaderName := CamelCase(headerName)
fieldThriftType, err := GoType(packageHelper, field.Type)
if err != nil {
finalError = err
return true
}
bodyIdentifier := goPrefix + "." + PascalCase(field.Name)
seenCount := headersMap[camelHeaderName]
var variableName string
if seenCount > 0 {
variableName = camelHeaderName + "No" +
strconv.Itoa(seenCount) + "Value"
} else {
variableName = camelHeaderName + "Value"
}
headersMap[camelHeaderName] = seenCount + 1
if field.Required {
statements.appendf("%s, _ := req.Header.Get(%q)",
variableName, headerName,
)
for seenStruct, typeName := range seenOptStructs {
if strings.HasPrefix(longFieldName, seenStruct) {
statements.appendf("if requestBody%s == nil {",
seenStruct,
)
statements.appendf("\trequestBody%s = &%s{}",
seenStruct, typeName,
)
statements.append("}")
}
}
statements.appendf("requestBody%s = %s(%s)",
bodyIdentifier, fieldThriftType, variableName,
)
} else {
statements.appendf("%s, %sExists := req.Header.Get(%q)",
variableName, variableName, headerName,
)
statements.appendf("if %sExists {", variableName)
for seenStruct, typeName := range seenOptStructs {
if strings.HasPrefix(longFieldName, seenStruct) {
statements.appendf("\tif requestBody%s == nil {",
seenStruct,
)
statements.appendf("\t\trequestBody%s = &%s{}",
seenStruct, typeName,
)
statements.append("\t}")
}
}
switch fieldThriftType {
case "string":
statements.appendf("\trequestBody%s = ptr.String(%s)",
bodyIdentifier, variableName,
)
case "int64":
statements.appendf("body, _ := strconv.ParseInt(%s, 10, 64)",
variableName,
)
statements.appendf("requestBody%s = &body", bodyIdentifier)
case "bool":
statements.appendf("body, _ := strconv.ParseBool(%s)",
variableName,
)
statements.appendf("requestBody%s = &body", bodyIdentifier)
case "float64":
case "float32":
statements.appendf("body, _ := strconv.ParseFloat(%s, 64)",
variableName,
)
statements.appendf("requestBody%s = &body", bodyIdentifier)
default:
statements.appendf("body := %s(%s)",
fieldThriftType, variableName,
)
statements.appendf("requestBody%s = &body", bodyIdentifier)
}
statements.append("}")
}
seenHeaders = true
}
}
return false
}
walkFieldGroups(fields, visitor)
if finalError != nil {
return finalError
}
if seenHeaders {
ms.ReqHeaderGoStatements = statements.GetLines()
}
return nil
}
func (ms *MethodSpec) setResponseHeaderFields(
funcSpec *compile.FunctionSpec,
) {
structType, ok := funcSpec.ResultSpec.ReturnType.(*compile.StructSpec)
// If the result is not a struct then there are zero response header
// annotations.
if !ok {
return
}
fields := structType.Fields
ms.ResHeaderFields = map[string]HeaderFieldInfo{}
// Scan for all annotations
visitor := func(
goPrefix string, thriftPrefix string, field *compile.FieldSpec,
) bool {
if param, ok := field.Annotations[ms.annotations.HTTPRef]; ok {
if strings.HasPrefix(param, headerAnnotationPrefix) {
headerName := strings.TrimPrefix(param, headerAnnotationPrefix)
ms.ResHeaderFields[headerName] = HeaderFieldInfo{
FieldIdentifier: goPrefix + "." + PascalCase(field.Name),
IsPointer: !field.Required,
}
}
}
return false
}
walkFieldGroups(fields, visitor)
}
func (ms *MethodSpec) setClientRequestHeaderFields(
funcSpec *compile.FunctionSpec, packageHelper *PackageHelper,
) error {
fields := compile.FieldGroup(funcSpec.ArgsSpec)
statements := LineBuilder{}
var finalError error
seenOptStructs := make(map[string]string)
itrOrder := make([]string, 0)
// Scan for all annotations
visitor := func(
goPrefix string, thriftPrefix string, field *compile.FieldSpec,
) bool {
realType := compile.RootTypeSpec(field.Type)
longFieldName := goPrefix + "." + PascalCase(field.Name)
// If the type is a struct then we cannot really do anything
if _, ok := realType.(*compile.StructSpec); ok {
// if a field is a struct then we must do a nil check
typeName, err := GoType(packageHelper, realType)
if err != nil {
finalError = err
return true
}
seenOptStructs[longFieldName] = typeName
itrOrder = append(itrOrder, longFieldName)
return false
}
if param, ok := field.Annotations[ms.annotations.HTTPRef]; ok {
if strings.HasPrefix(param, headerAnnotationPrefix) {
headerName := strings.TrimPrefix(param, headerAnnotationPrefix)
bodyIdentifier := goPrefix + "." + PascalCase(field.Name)
var headerNameValuePair string
if field.Required {
// Note header values are always string
headerNameValuePair = "headers[%q]= string(r%s)"
} else {
headerNameValuePair = "headers[%q]= string(*r%s)"
}
if !field.Required {
closeFunction := ""
for _, seenStruct := range itrOrder {
if strings.HasPrefix(longFieldName, seenStruct) {
statements.appendf("if r%s != nil {", seenStruct)
closeFunction = closeFunction + "}"
}
}
statements.appendf("if r%s != nil {", bodyIdentifier)
statements.appendf(headerNameValuePair, headerName, bodyIdentifier)
statements.append("}")
statements.append(closeFunction)
} else {
statements.appendf(headerNameValuePair,
headerName, bodyIdentifier,
)
}
}
}
return false
}
walkFieldGroups(fields, visitor)
if finalError != nil {
return finalError
}
ms.ReqClientHeaderGoStatements = statements.GetLines()
return nil
}
func (ms *MethodSpec) setHTTPPath(httpPath string, funcSpec *compile.FunctionSpec) {
ms.HTTPPath = httpPath
segments := strings.Split(httpPath[1:], "/")
ms.PathSegments = make([]PathSegment, len(segments))
for i := 0; i < len(segments); i++ {
segment := segments[i]
if segment == "" || segment[0] != ':' {
ms.PathSegments[i].Type = "static"
ms.PathSegments[i].Text = segment
} else {
ms.PathSegments[i].Type = "param"
var fieldSelect string
var required bool
var ok bool
fieldSelect, required, ok = ms.findParamsAnnotation(
compile.FieldGroup(funcSpec.ArgsSpec), segment,
)
if !ok {
panic(fmt.Sprintf("cannot find params: %s for http path %s", segment, httpPath))
}
ms.PathSegments[i].BodyIdentifier = fieldSelect
ms.PathSegments[i].ParamName = segment[1:]
ms.PathSegments[i].Required = required
}
}
}
func (ms *MethodSpec) setDownstream(
clientModule *ModuleSpec, clientThriftService, clientThriftMethod string,
) error {
var downstreamService *ServiceSpec
for _, service := range clientModule.Services {
if service.Name == clientThriftService {
downstreamService = service
break
}
}
if downstreamService == nil {
return errors.Errorf(
"Downstream service '%s' is not found in '%s'",
clientThriftService, clientModule.ThriftFile,
)
}
var downstreamMethod *MethodSpec
for _, method := range downstreamService.Methods {
if method.Name == clientThriftMethod {
downstreamMethod = method
break
}
}
if downstreamMethod == nil {
return errors.Errorf(
"\n Downstream method '%s' is not found in '%s'",
clientThriftMethod, clientModule.ThriftFile,
)
}
// Remove irrelevant services and methods.
ms.Downstream = clientModule
ms.DownstreamService = clientThriftService
ms.DownstreamMethod = downstreamMethod
return nil
}
func (ms *MethodSpec) setHeaderPropagator(
reqHeaders []string,
downstreamSpec *compile.FunctionSpec,
headersPropagate map[string]FieldMapperEntry,
h *PackageHelper,
downstreamMethod *MethodSpec,
) error {
downstreamStructType := compile.FieldGroup(downstreamSpec.ArgsSpec)
hp := NewHeaderPropagator(h)
hp.append(
"func propagateHeaders",
PascalCase(ms.Name),
"ClientRequests(in ",
downstreamMethod.RequestType,
", headers zanzibar.Header) ",
downstreamMethod.RequestType,
"{",
)
hp.append("if in == nil {")
hp.append(fmt.Sprintf(`in = %s{}`, strings.Replace(downstreamMethod.RequestType, "*", "&", 1)))
hp.append("}")
err := hp.Propagate(reqHeaders, downstreamStructType, headersPropagate)
if err != nil {
return err
}
hp.append("return in")
hp.append("}")
ms.PropagateHeadersGoStatements = hp.GetLines()
return nil
}
func (ms *MethodSpec) setTypeConverters(
funcSpec *compile.FunctionSpec,
downstreamSpec *compile.FunctionSpec,
reqTransforms map[string]FieldMapperEntry,
headersPropagate map[string]FieldMapperEntry,
respTransforms map[string]FieldMapperEntry,
h *PackageHelper,
downstreamMethod *MethodSpec,
) error {
// TODO(sindelar): Iterate over fields that are structs (for foo/bar examples).
// Add type checking and conversion, custom mapping
structType := compile.FieldGroup(funcSpec.ArgsSpec)
downstreamStructType := compile.FieldGroup(downstreamSpec.ArgsSpec)
typeConverter := NewTypeConverter(h, headersPropagate)
typeConverter.append(
"func convertTo",
PascalCase(ms.Name),
"ClientRequest(in ", ms.RequestType, ") ", downstreamMethod.RequestType, "{")
typeConverter.append("out := &", downstreamMethod.ShortRequestType, "{}\n")
err := typeConverter.GenStructConverter(structType, downstreamStructType, reqTransforms)
if err != nil {
return err
}
typeConverter.append("\nreturn out")
typeConverter.append("}")
ms.ConvertRequestGoStatements = typeConverter.GetLines()
// TODO: support non-struct return types
respType := funcSpec.ResultSpec.ReturnType
downstreamRespType := downstreamMethod.CompiledThriftSpec.ResultSpec.ReturnType
if respType == nil || downstreamRespType == nil {
return nil
}
respConverter := NewTypeConverter(h, nil)
respConverter.append(
"func convert",
PascalCase(ms.DownstreamService), PascalCase(ms.Name),
"ClientResponse(in ", downstreamMethod.ResponseType, ") ", ms.ResponseType, "{")
var respFields, downstreamRespFields []*compile.FieldSpec
switch respType.(type) {
case
*compile.BoolSpec,
*compile.I8Spec,
*compile.I16Spec,
*compile.I32Spec,
*compile.EnumSpec,
*compile.I64Spec,
*compile.DoubleSpec,
*compile.StringSpec:
respConverter.append("out", " := in\t\n")
default:
// default as struct
respFields = respType.(*compile.StructSpec).Fields
downstreamRespFields = downstreamRespType.(*compile.StructSpec).Fields