-
Notifications
You must be signed in to change notification settings - Fork 325
/
generator.go
1747 lines (1611 loc) · 61.3 KB
/
generator.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 2018 Twitch Interactive, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may not
// use this file except in compliance with the License. A copy of the License is
// located at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// or in the "license" file accompanying this file. This file is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
package main
import (
"bufio"
"bytes"
"compress/gzip"
"fmt"
"go/parser"
"go/printer"
"go/token"
"path"
"strconv"
"strings"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/protoc-gen-go/descriptor"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
"github.com/pkg/errors"
"github.com/twitchtv/twirp/internal/gen"
"github.com/twitchtv/twirp/internal/gen/stringutils"
"github.com/twitchtv/twirp/internal/gen/typemap"
)
type twirp struct {
filesHandled int
currentPackage string // Go name of current package we're working on
reg *typemap.Registry
// Map to record whether we've built each package
pkgs map[string]string
pkgNamesInUse map[string]bool
// Map to record whether we've generated Stream types for request and response
// types.
streamTypes map[string]bool
// Package naming:
genPkgName string // Name of the package that we're generating
fileToGoPackageName map[*descriptor.FileDescriptorProto]string
// List of files that were inputs to the generator. We need to hold this in
// the struct so we can write a header for the file that lists its inputs.
genFiles []*descriptor.FileDescriptorProto
// Output buffer that holds the bytes we want to write out for a single file.
// Gets reset after working on a file.
output *bytes.Buffer
}
func newGenerator() *twirp {
t := &twirp{
pkgs: make(map[string]string),
pkgNamesInUse: make(map[string]bool),
streamTypes: make(map[string]bool),
fileToGoPackageName: make(map[*descriptor.FileDescriptorProto]string),
output: bytes.NewBuffer(nil),
}
return t
}
func (t *twirp) Generate(in *plugin.CodeGeneratorRequest) *plugin.CodeGeneratorResponse {
t.genFiles = gen.FilesToGenerate(in)
// Collect information on types.
t.reg = typemap.New(in.ProtoFile)
// Register names of packages that we import.
t.registerPackageName("bufio")
t.registerPackageName("binary")
t.registerPackageName("bytes")
t.registerPackageName("strings")
t.registerPackageName("ctxsetters")
t.registerPackageName("context")
t.registerPackageName("http")
t.registerPackageName("io")
t.registerPackageName("ioutil")
t.registerPackageName("json")
t.registerPackageName("jsonpb")
t.registerPackageName("proto")
t.registerPackageName("strconv")
t.registerPackageName("twirp")
t.registerPackageName("url")
t.registerPackageName("fmt")
// Time to figure out package names of objects defined in protobuf. First,
// we'll figure out the name for the package we're generating.
genPkgName, err := deduceGenPkgName(t.genFiles)
if err != nil {
gen.Fail(err.Error())
}
t.genPkgName = genPkgName
// Next, we need to pick names for all the files that are dependencies.
for _, f := range in.ProtoFile {
if fileDescSliceContains(t.genFiles, f) {
// This is a file we are generating. It gets the shared package name.
t.fileToGoPackageName[f] = t.genPkgName
} else {
// This is a dependency. Use its package name.
name := f.GetPackage()
if name == "" {
name = stringutils.BaseName(f.GetName())
}
name = stringutils.CleanIdentifier(name)
t.fileToGoPackageName[f] = name
t.registerPackageName(name)
}
}
// Showtime! Generate the response.
resp := new(plugin.CodeGeneratorResponse)
for _, f := range t.genFiles {
respFile := t.generate(f)
if respFile != nil {
resp.File = append(resp.File, respFile)
}
}
return resp
}
func (t *twirp) registerPackageName(name string) (alias string) {
alias = name
i := 1
for t.pkgNamesInUse[alias] {
alias = name + strconv.Itoa(i)
i++
}
t.pkgNamesInUse[alias] = true
t.pkgs[name] = alias
return alias
}
// deduceGenPkgName figures out the go package name to use for generated code.
// Will try to use the explicit go_package setting in a file (if set, must be
// consistent in all files). If no files have go_package set, then use the
// protobuf package name (must be consistent in all files)
func deduceGenPkgName(genFiles []*descriptor.FileDescriptorProto) (string, error) {
var genPkgName string
for _, f := range genFiles {
name, explicit := goPackageName(f)
if explicit {
name = stringutils.CleanIdentifier(name)
if genPkgName != "" && genPkgName != name {
// Make sure they're all set consistently.
return "", errors.Errorf("files have conflicting go_package settings, must be the same: %q and %q", genPkgName, name)
}
genPkgName = name
}
}
if genPkgName != "" {
return genPkgName, nil
}
// If there is no explicit setting, then check the implicit package name
// (derived from the protobuf package name) of the files and make sure it's
// consistent.
for _, f := range genFiles {
name, _ := goPackageName(f)
name = stringutils.CleanIdentifier(name)
if genPkgName != "" && genPkgName != name {
return "", errors.Errorf("files have conflicting package names, must be the same or overridden with go_package: %q and %q", genPkgName, name)
}
genPkgName = name
}
// All the files have the same name, so we're good.
return genPkgName, nil
}
func (t *twirp) generate(file *descriptor.FileDescriptorProto) *plugin.CodeGeneratorResponse_File {
resp := new(plugin.CodeGeneratorResponse_File)
if len(file.Service) == 0 {
return nil
}
t.generateFileHeader(file)
t.generateImports(file)
if t.filesHandled == 0 {
t.generateUtilImports()
}
// For each service, generate client stubs and server
for i, service := range file.Service {
t.generateService(file, service, i)
// For streaming RPCs, we need to define Stream types. This won't do
// anything if the service has no streaming RPCs.
t.generateStreamTypesForService(service)
}
// Util functions only generated once per package
if t.filesHandled == 0 {
t.generateUtils()
if t.genFilesIncludeStreams() {
t.generateStreamUtils()
}
}
t.generateFileDescriptor(file)
resp.Name = proto.String(goFileName(file))
resp.Content = proto.String(t.formattedOutput())
t.output.Reset()
t.filesHandled++
return resp
}
func (t *twirp) generateFileHeader(file *descriptor.FileDescriptorProto) {
t.P("// Code generated by protoc-gen-twirp ", gen.Version, ", DO NOT EDIT.")
t.P("// source: ", file.GetName())
t.P()
if t.filesHandled == 0 {
t.P("/*")
t.P("Package ", t.genPkgName, " is a generated twirp stub package.")
t.P("This code was generated with github.com/twitchtv/twirp/protoc-gen-twirp ", gen.Version, ".")
t.P()
comment, err := t.reg.FileComments(file)
if err == nil && comment.Leading != "" {
for _, line := range strings.Split(comment.Leading, "\n") {
line = strings.TrimPrefix(line, " ")
// ensure we don't escape from the block comment
line = strings.Replace(line, "*/", "* /", -1)
t.P(line)
}
t.P()
}
t.P("It is generated from these files:")
for _, f := range t.genFiles {
t.P("\t", f.GetName())
}
t.P("*/")
}
t.P(`package `, t.genPkgName)
t.P()
}
func (t *twirp) generateImports(file *descriptor.FileDescriptorProto) {
if len(file.Service) == 0 {
return
}
t.P(`import `, t.pkgs["bytes"], ` "bytes"`)
t.P(`import `, t.pkgs["strings"], ` "strings"`)
t.P(`import `, t.pkgs["context"], ` "context"`)
t.P(`import `, t.pkgs["fmt"], ` "fmt"`)
t.P(`import `, t.pkgs["ioutil"], ` "io/ioutil"`)
t.P(`import `, t.pkgs["http"], ` "net/http"`)
t.P()
t.P(`import `, t.pkgs["jsonpb"], ` "github.com/golang/protobuf/jsonpb"`)
t.P(`import `, t.pkgs["proto"], ` "github.com/golang/protobuf/proto"`)
t.P(`import `, t.pkgs["twirp"], ` "github.com/twitchtv/twirp"`)
t.P(`import `, t.pkgs["ctxsetters"], ` "github.com/twitchtv/twirp/ctxsetters"`)
t.P()
// It's legal to import a message and use it as an input or output for a
// method. Make sure to import the package of any such message. First, dedupe
// them.
deps := make(map[string]string) // Map of package name to quoted import path.
ourImportPath := path.Dir(goFileName(file))
for _, s := range file.Service {
for _, m := range s.Method {
defs := []*typemap.MessageDefinition{
t.reg.MethodInputDefinition(m),
t.reg.MethodOutputDefinition(m),
}
for _, def := range defs {
importPath := path.Dir(goFileName(def.File))
if importPath != ourImportPath {
pkg := t.goPackageName(def.File)
deps[pkg] = strconv.Quote(importPath)
}
}
}
}
for pkg, importPath := range deps {
t.P(`import `, pkg, ` `, importPath)
}
if len(deps) > 0 {
t.P()
}
}
func (t *twirp) generateUtilImports() {
t.P("// Imports only used by utility functions:")
t.P(`import `, t.pkgs["io"], ` "io"`)
t.P(`import `, t.pkgs["strconv"], ` "strconv"`)
t.P(`import `, t.pkgs["json"], ` "encoding/json"`)
t.P(`import `, t.pkgs["url"], ` "net/url"`)
if t.genFilesIncludeStreams() {
t.P(`import `, t.pkgs["bufio"], ` "bufio"`)
t.P(`import `, t.pkgs["binary"], ` "encoding/binary"`)
}
}
// Generate utility functions used in Twirp code.
// These should be generated just once per package.
func (t *twirp) generateUtils() {
t.sectionComment(`Utils`)
t.P(`// HTTPClient is the interface used by generated clients to send HTTP requests.`)
t.P(`// It is fulfilled by *(net/http).Client, which is sufficient for most users.`)
t.P(`// Users can provide their own implementation for special retry policies.`)
t.P(`// `)
t.P(`// HTTPClient implementations should not follow redirects. Redirects are`)
t.P(`// automatically disabled if *(net/http).Client is passed to client`)
t.P(`// constructors. See the withoutRedirects function in this file for more`)
t.P(`// details.`)
t.P(`type HTTPClient interface {`)
t.P(` Do(req *`, t.pkgs["http"], `.Request) (*`, t.pkgs["http"], `.Response, error)`)
t.P(`}`)
t.P()
t.P(`// TwirpServer is the interface generated server structs will support: they're`)
t.P(`// HTTP handlers with additional methods for accessing metadata about the`)
t.P(`// service. Those accessors are a low-level API for building reflection tools.`)
t.P(`// Most people can think of TwirpServers as just http.Handlers.`)
t.P(`type TwirpServer interface {`)
t.P(` `, t.pkgs["http"], `.Handler`)
t.P(` // ServiceDescriptor returns gzipped bytes describing the .proto file that`)
t.P(` // this service was generated from. Once unzipped, the bytes can be`)
t.P(` // unmarshalled as a`)
t.P(` // github.com/golang/protobuf/protoc-gen-go/descriptor.FileDescriptorProto.`)
t.P(` //`)
t.P(` // The returned integer is the index of this particular service within that`)
t.P(` // FileDescriptorProto's 'Service' slice of ServiceDescriptorProtos. This is a`)
t.P(` // low-level field, expected to be used for reflection.`)
t.P(` ServiceDescriptor() ([]byte, int)`)
t.P(` // ProtocGenTwirpVersion is the semantic version string of the version of`)
t.P(` // twirp used to generate this file.`)
t.P(` ProtocGenTwirpVersion() string`)
t.P(`}`)
t.P()
t.P(`// WriteError writes an HTTP response with a valid Twirp error format.`)
t.P(`// If err is not a twirp.Error, it will get wrapped with twirp.InternalErrorWith(err)`)
t.P(`func WriteError(resp `, t.pkgs["http"], `.ResponseWriter, err error) {`)
t.P(` writeError(`, t.pkgs["context"], `.Background(), resp, err, nil)`)
t.P(`}`)
t.P()
t.P(`// writeError writes Twirp errors in the response and triggers hooks.`)
t.P(`func writeError(ctx `, t.pkgs["context"], `.Context, resp `, t.pkgs["http"], `.ResponseWriter, err error, hooks *`, t.pkgs["twirp"], `.ServerHooks) {`)
t.P(` // Non-twirp errors are wrapped as Internal (default)`)
t.P(` twerr, ok := err.(`, t.pkgs["twirp"], `.Error)`)
t.P(` if !ok {`)
t.P(` twerr = `, t.pkgs["twirp"], `.InternalErrorWith(err)`)
t.P(` }`)
t.P(``)
t.P(` statusCode := `, t.pkgs["twirp"], `.ServerHTTPStatusFromErrorCode(twerr.Code())`)
t.P(` ctx = `, t.pkgs["ctxsetters"], `.WithStatusCode(ctx, statusCode)`)
t.P(` ctx = callError(ctx, hooks, twerr)`)
t.P(``)
t.P(` resp.Header().Set("Content-Type", "application/json") // Error responses are always JSON (instead of protobuf)`)
t.P(` resp.WriteHeader(statusCode) // HTTP response status code`)
t.P(``)
t.P(` respBody := marshalErrorToJSON(twerr)`)
t.P(` _, writeErr := resp.Write(respBody)`)
t.P(` if writeErr != nil {`)
t.P(` // We have three options here. We could log the error, call the Error`)
t.P(` // hook, or just silently ignore the error.`)
t.P(` //`)
t.P(` // Logging is unacceptable because we don't have a user-controlled `)
t.P(` // logger; writing out to stderr without permission is too rude.`)
t.P(` //`)
t.P(` // Calling the Error hook would confuse users: it would mean the Error`)
t.P(` // hook got called twice for one request, which is likely to lead to`)
t.P(` // duplicated log messages and metrics, no matter how well we document`)
t.P(` // the behavior.`)
t.P(` //`)
t.P(` // Silently ignoring the error is our least-bad option. It's highly`)
t.P(` // likely that the connection is broken and the original 'err' says`)
t.P(` // so anyway.`)
t.P(` _ = writeErr`)
t.P(` }`)
t.P(``)
t.P(` callResponseSent(ctx, hooks)`)
t.P(`}`)
t.P()
t.P(`// urlBase helps ensure that addr specifies a scheme. If it is unparsable`)
t.P(`// as a URL, it returns addr unchanged.`)
t.P(`func urlBase(addr string) string {`)
t.P(` // If the addr specifies a scheme, use it. If not, default to`)
t.P(` // http. If url.Parse fails on it, return it unchanged.`)
t.P(` url, err := `, t.pkgs["url"], `.Parse(addr)`)
t.P(` if err != nil {`)
t.P(` return addr`)
t.P(` }`)
t.P(` if url.Scheme == "" {`)
t.P(` url.Scheme = "http"`)
t.P(` }`)
t.P(` return url.String()`)
t.P(`}`)
t.P()
t.P(`// getCustomHTTPReqHeaders retrieves a copy of any headers that are set in`)
t.P(`// a context through the twirp.WithHTTPRequestHeaders function.`)
t.P(`// If there are no headers set, or if they have the wrong type, nil is returned.`)
t.P(`func getCustomHTTPReqHeaders(ctx `, t.pkgs["context"], `.Context) `, t.pkgs["http"], `.Header {`)
t.P(` header, ok := `, t.pkgs["twirp"], `.HTTPRequestHeaders(ctx)`)
t.P(` if !ok || header == nil {`)
t.P(` return nil`)
t.P(` }`)
t.P(` copied := make(`, t.pkgs["http"], `.Header)`)
t.P(` for k, vv := range header {`)
t.P(` if vv == nil {`)
t.P(` copied[k] = nil`)
t.P(` continue`)
t.P(` }`)
t.P(` copied[k] = make([]string, len(vv))`)
t.P(` copy(copied[k], vv)`)
t.P(` }`)
t.P(` return copied`)
t.P(`}`)
t.P()
t.P(`// newRequest makes an http.Request from a client, adding common headers.`)
t.P(`func newRequest(ctx `, t.pkgs["context"], `.Context, url string, reqBody io.Reader, contentType string) (*`, t.pkgs["http"], `.Request, error) {`)
t.P(` req, err := `, t.pkgs["http"], `.NewRequest("POST", url, reqBody)`)
t.P(` if err != nil {`)
t.P(` return nil, err`)
t.P(` }`)
t.P(` req = req.WithContext(ctx)`)
t.P(` if customHeader := getCustomHTTPReqHeaders(ctx); customHeader != nil {`)
t.P(` req.Header = customHeader`)
t.P(` }`)
t.P(` req.Header.Set("Accept", contentType)`)
t.P(` req.Header.Set("Content-Type", contentType)`)
t.P(` req.Header.Set("Twirp-Version", "`, gen.Version, `")`)
t.P(` return req, nil`)
t.P(`}`)
t.P(`// JSON serialization for errors`)
t.P(`type twerrJSON struct {`)
t.P(" Code string `json:\"code\"`")
t.P(" Msg string `json:\"msg\"`")
t.P(" Meta map[string]string `json:\"meta,omitempty\"`")
t.P(`}`)
t.P()
t.P(`func (tj twerrJSON) toTwirpError() `, t.pkgs["twirp"], `.Error {`)
t.P(` errorCode := `, t.pkgs["twirp"], `.ErrorCode(tj.Code)`)
t.P(` if !`, t.pkgs["twirp"], `.IsValidErrorCode(errorCode) {`)
t.P(` msg := "invalid type returned from server error response: " + tj.Code`)
t.P(` return `, t.pkgs["twirp"], `.InternalError(msg)`)
t.P(` }`)
t.P(``)
t.P(` twerr := `, t.pkgs["twirp"], `.NewError(errorCode, tj.Msg)`)
t.P(` for k, v := range tj.Meta {`)
t.P(` twerr = twerr.WithMeta(k, v)`)
t.P(` }`)
t.P(` return twerr`)
t.P(`}`)
t.P(`// marshalErrorToJSON returns JSON from a twirp.Error, that can be used as HTTP error response body.`)
t.P(`// If serialization fails, it will use a descriptive Internal error instead.`)
t.P(`func marshalErrorToJSON(twerr `, t.pkgs["twirp"], `.Error) []byte {`)
t.P(` // make sure that msg is not too large`)
t.P(` msg := twerr.Msg()`)
t.P(` if len(msg) > 1e6 {`)
t.P(` msg = msg[:1e6]`)
t.P(` }`)
t.P(``)
t.P(` tj := twerrJSON{`)
t.P(` Code: string(twerr.Code()),`)
t.P(` Msg: msg,`)
t.P(` Meta: twerr.MetaMap(),`)
t.P(` }`)
t.P(``)
t.P(` buf, err := `, t.pkgs["json"], `.Marshal(&tj)`)
t.P(` if err != nil {`)
t.P(` buf = []byte("{\"type\": \"" + `, t.pkgs["twirp"], `.Internal +"\", \"msg\": \"There was an error but it could not be serialized into JSON\"}") // fallback`)
t.P(` }`)
t.P(``)
t.P(` return buf`)
t.P(`}`)
t.P()
t.P(`// errorFromResponse builds a twirp.Error from a non-200 HTTP response.`)
t.P(`// If the response has a valid serialized Twirp error, then it's returned.`)
t.P(`// If not, the response status code is used to generate a similar twirp`)
t.P(`// error. See twirpErrorFromIntermediary for more info on intermediary errors.`)
t.P(`func errorFromResponse(resp *`, t.pkgs["http"], `.Response) `, t.pkgs["twirp"], `.Error {`)
t.P(` statusCode := resp.StatusCode`)
t.P(` statusText := `, t.pkgs["http"], `.StatusText(statusCode)`)
t.P(``)
t.P(` if isHTTPRedirect(statusCode) {`)
t.P(` // Unexpected redirect: it must be an error from an intermediary.`)
t.P(` // Twirp clients don't follow redirects automatically, Twirp only handles`)
t.P(` // POST requests, redirects should only happen on GET and HEAD requests.`)
t.P(` location := resp.Header.Get("Location")`)
t.P(` msg := `, t.pkgs["fmt"], `.Sprintf("unexpected HTTP status code %d %q received, Location=%q", statusCode, statusText, location)`)
t.P(` return twirpErrorFromIntermediary(statusCode, msg, location)`)
t.P(` }`)
t.P(``)
t.P(` respBodyBytes, err := `, t.pkgs["ioutil"], `.ReadAll(resp.Body)`)
t.P(` if err != nil {`)
t.P(` return clientError("failed to read server error response body", err)`)
t.P(` }`)
t.P(` var tj twerrJSON`)
t.P(` if err := `, t.pkgs["json"], `.Unmarshal(respBodyBytes, &tj); err != nil {`)
t.P(` // Invalid JSON response; it must be an error from an intermediary.`)
t.P(` msg := `, t.pkgs["fmt"], `.Sprintf("Error from intermediary with HTTP status code %d %q", statusCode, statusText)`)
t.P(` return twirpErrorFromIntermediary(statusCode, msg, string(respBodyBytes))`)
t.P(` }`)
t.P(``)
t.P(` return tj.toTwirpError()`)
t.P(`}`)
t.P()
t.P(`// twirpErrorFromIntermediary maps HTTP errors from non-twirp sources to twirp errors.`)
t.P(`// The mapping is similar to gRPC: https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md.`)
t.P(`// Returned twirp Errors have some additional metadata for inspection.`)
t.P(`func twirpErrorFromIntermediary(status int, msg string, bodyOrLocation string) `, t.pkgs["twirp"], `.Error {`)
t.P(` var code `, t.pkgs["twirp"], `.ErrorCode`)
t.P(` if isHTTPRedirect(status) { // 3xx`)
t.P(` code = `, t.pkgs["twirp"], `.Internal`)
t.P(` } else {`)
t.P(` switch status {`)
t.P(` case 400: // Bad Request`)
t.P(` code = `, t.pkgs["twirp"], `.Internal`)
t.P(` case 401: // Unauthorized`)
t.P(` code = `, t.pkgs["twirp"], `.Unauthenticated`)
t.P(` case 403: // Forbidden`)
t.P(` code = `, t.pkgs["twirp"], `.PermissionDenied`)
t.P(` case 404: // Not Found`)
t.P(` code = `, t.pkgs["twirp"], `.BadRoute`)
t.P(` case 429, 502, 503, 504: // Too Many Requests, Bad Gateway, Service Unavailable, Gateway Timeout`)
t.P(` code = `, t.pkgs["twirp"], `.Unavailable`)
t.P(` default: // All other codes`)
t.P(` code = `, t.pkgs["twirp"], `.Unknown`)
t.P(` }`)
t.P(` }`)
t.P(``)
t.P(` twerr := `, t.pkgs["twirp"], `.NewError(code, msg)`)
t.P(` twerr = twerr.WithMeta("http_error_from_intermediary", "true") // to easily know if this error was from intermediary`)
t.P(` twerr = twerr.WithMeta("status_code", `, t.pkgs["strconv"], `.Itoa(status))`)
t.P(` if isHTTPRedirect(status) {`)
t.P(` twerr = twerr.WithMeta("location", bodyOrLocation)`)
t.P(` } else {`)
t.P(` twerr = twerr.WithMeta("body", bodyOrLocation)`)
t.P(` }`)
t.P(` return twerr`)
t.P(`}`)
t.P(`func isHTTPRedirect(status int) bool {`)
t.P(` return status >= 300 && status <= 399`)
t.P(`}`)
t.P(`// wrappedError implements the github.com/pkg/errors.Causer interface, allowing errors to be`)
t.P(`// examined for their root cause.`)
t.P(`type wrappedError struct {`)
t.P(` msg string`)
t.P(` cause error`)
t.P(`}`)
t.P()
t.P(`func wrapErr(err error, msg string) error { return &wrappedError{msg: msg, cause: err} }`)
t.P(`func (e *wrappedError) Cause() error { return e.cause }`)
t.P(`func (e *wrappedError) Error() string { return e.msg + ": " + e.cause.Error() }`)
t.P()
t.P(`// clientError adds consistency to errors generated in the client`)
t.P(`func clientError(desc string, err error) `, t.pkgs["twirp"], `.Error {`)
t.P(` return `, t.pkgs["twirp"], `.InternalErrorWith(wrapErr(err, desc))`)
t.P(`}`)
t.P()
t.P(`// badRouteError is used when the twirp server cannot route a request`)
t.P(`func badRouteError(msg string, method, url string) `, t.pkgs["twirp"], `.Error {`)
t.P(` err := `, t.pkgs["twirp"], `.NewError(`, t.pkgs["twirp"], `.BadRoute, msg)`)
t.P(` err = err.WithMeta("twirp_invalid_route", method+" "+url)`)
t.P(` return err`)
t.P(`}`)
t.P()
t.P(`// The standard library will, by default, redirect requests (including POSTs) if it gets a 302 or`)
t.P(`// 303 response, and also 301s in go1.8. It redirects by making a second request, changing the`)
t.P(`// method to GET and removing the body. This produces very confusing error messages, so instead we`)
t.P(`// set a redirect policy that always errors. This stops Go from executing the redirect.`)
t.P(`//`)
t.P(`// We have to be a little careful in case the user-provided http.Client has its own CheckRedirect`)
t.P(`// policy - if so, we'll run through that policy first.`)
t.P(`//`)
t.P(`// Because this requires modifying the http.Client, we make a new copy of the client and return it.`)
t.P(`func withoutRedirects(in *`, t.pkgs["http"], `.Client) *`, t.pkgs["http"], `.Client {`)
t.P(` copy := *in`)
t.P(` copy.CheckRedirect = func(req *`, t.pkgs["http"], `.Request, via []*`, t.pkgs["http"], `.Request) error {`)
t.P(` if in.CheckRedirect != nil {`)
t.P(` // Run the input's redirect if it exists, in case it has side effects, but ignore any error it`)
t.P(` // returns, since we want to use ErrUseLastResponse.`)
t.P(` err := in.CheckRedirect(req, via)`)
t.P(` _ = err // Silly, but this makes sure generated code passes errcheck -blank, which some people use.`)
t.P(` }`)
t.P(` return `, t.pkgs["http"], `.ErrUseLastResponse`)
t.P(` }`)
t.P(` return ©`)
t.P(`}`)
t.P()
t.P(`// doProtobufRequest is common code to make a request to the remote twirp service.`)
t.P(`func doProtobufRequest(ctx `, t.pkgs["context"], `.Context, client HTTPClient, url string, in, out `, t.pkgs["proto"], `.Message) (err error) {`)
t.P(` reqBodyBytes, err := `, t.pkgs["proto"], `.Marshal(in)`)
t.P(` if err != nil {`)
t.P(` return clientError("failed to marshal proto request", err)`)
t.P(` }`)
t.P(` reqBody := `, t.pkgs["bytes"], `.NewBuffer(reqBodyBytes)`)
t.P(` if err = ctx.Err(); err != nil {`)
t.P(` return clientError("aborted because context was done", err)`)
t.P(` }`)
t.P()
t.P(` req, err := newRequest(ctx, url, reqBody, "application/protobuf")`)
t.P(` if err != nil {`)
t.P(` return clientError("could not build request", err)`)
t.P(` }`)
t.P(` resp, err := client.Do(req)`)
t.P(` if err != nil {`)
t.P(` return clientError("failed to do request", err)`)
t.P(` }`)
t.P()
t.P(` defer func() {`)
t.P(` cerr := resp.Body.Close()`)
t.P(` if err == nil && cerr != nil {`)
t.P(` err = clientError("failed to close response body", cerr)`)
t.P(` }`)
t.P(` }()`)
t.P()
t.P(` if err = ctx.Err(); err != nil {`)
t.P(` return clientError("aborted because context was done", err)`)
t.P(` }`)
t.P()
t.P(` if resp.StatusCode != 200 {`)
t.P(` return errorFromResponse(resp)`)
t.P(` }`)
t.P()
t.P(` respBodyBytes, err := `, t.pkgs["ioutil"], `.ReadAll(resp.Body)`)
t.P(` if err != nil {`)
t.P(` return clientError("failed to read response body", err)`)
t.P(` }`)
t.P(` if err = ctx.Err(); err != nil {`)
t.P(` return clientError("aborted because context was done", err)`)
t.P(` }`)
t.P()
t.P(` if err = `, t.pkgs["proto"], `.Unmarshal(respBodyBytes, out); err != nil {`)
t.P(` return clientError("failed to unmarshal proto response", err)`)
t.P(` }`)
t.P(` return nil`)
t.P(`}`)
t.P()
t.P(`// doJSONRequest is common code to make a request to the remote twirp service.`)
t.P(`func doJSONRequest(ctx `, t.pkgs["context"], `.Context, client HTTPClient, url string, in, out `, t.pkgs["proto"], `.Message) (err error) {`)
t.P(` reqBody := `, t.pkgs["bytes"], `.NewBuffer(nil)`)
t.P(` marshaler := &`, t.pkgs["jsonpb"], `.Marshaler{OrigName: true}`)
t.P(` if err = marshaler.Marshal(reqBody, in); err != nil {`)
t.P(` return clientError("failed to marshal json request", err)`)
t.P(` }`)
t.P(` if err = ctx.Err(); err != nil {`)
t.P(` return clientError("aborted because context was done", err)`)
t.P(` }`)
t.P()
t.P(` req, err := newRequest(ctx, url, reqBody, "application/json")`)
t.P(` if err != nil {`)
t.P(` return clientError("could not build request", err)`)
t.P(` }`)
t.P(` resp, err := client.Do(req)`)
t.P(` if err != nil {`)
t.P(` return clientError("failed to do request", err)`)
t.P(` }`)
t.P()
t.P(` defer func() {`)
t.P(` cerr := resp.Body.Close()`)
t.P(` if err == nil && cerr != nil {`)
t.P(` err = clientError("failed to close response body", cerr)`)
t.P(` }`)
t.P(` }()`)
t.P()
t.P(` if err = ctx.Err(); err != nil {`)
t.P(` return clientError("aborted because context was done", err)`)
t.P(` }`)
t.P()
t.P(` if resp.StatusCode != 200 {`)
t.P(` return errorFromResponse(resp)`)
t.P(` }`)
t.P()
t.P(` unmarshaler := `, t.pkgs["jsonpb"], `.Unmarshaler{AllowUnknownFields: true}`)
t.P(` if err = unmarshaler.Unmarshal(resp.Body, out); err != nil {`)
t.P(` return clientError("failed to unmarshal json response", err)`)
t.P(` }`)
t.P(` if err = ctx.Err(); err != nil {`)
t.P(` return clientError("aborted because context was done", err)`)
t.P(` }`)
t.P(` return nil`)
t.P(`}`)
t.P()
t.P(`// Call twirp.ServerHooks.RequestReceived if the hook is available`)
t.P(`func callRequestReceived(ctx `, t.pkgs["context"], `.Context, h *`, t.pkgs["twirp"], `.ServerHooks) (`, t.pkgs["context"], `.Context, error) {`)
t.P(` if h == nil || h.RequestReceived == nil {`)
t.P(` return ctx, nil`)
t.P(` }`)
t.P(` return h.RequestReceived(ctx)`)
t.P(`}`)
t.P()
t.P(`// Call twirp.ServerHooks.RequestRouted if the hook is available`)
t.P(`func callRequestRouted(ctx `, t.pkgs["context"], `.Context, h *`, t.pkgs["twirp"], `.ServerHooks) (`, t.pkgs["context"], `.Context, error) {`)
t.P(` if h == nil || h.RequestRouted == nil {`)
t.P(` return ctx, nil`)
t.P(` }`)
t.P(` return h.RequestRouted(ctx)`)
t.P(`}`)
t.P()
t.P(`// Call twirp.ServerHooks.ResponsePrepared if the hook is available`)
t.P(`func callResponsePrepared(ctx `, t.pkgs["context"], `.Context, h *`, t.pkgs["twirp"], `.ServerHooks) `, t.pkgs["context"], `.Context {`)
t.P(` if h == nil || h.ResponsePrepared == nil {`)
t.P(` return ctx`)
t.P(` }`)
t.P(` return h.ResponsePrepared(ctx)`)
t.P(`}`)
t.P()
t.P(`// Call twirp.ServerHooks.ResponseSent if the hook is available`)
t.P(`func callResponseSent(ctx `, t.pkgs["context"], `.Context, h *`, t.pkgs["twirp"], `.ServerHooks) {`)
t.P(` if h == nil || h.ResponseSent == nil {`)
t.P(` return`)
t.P(` }`)
t.P(` h.ResponseSent(ctx)`)
t.P(`}`)
t.P()
t.P(`// Call twirp.ServerHooks.Error if the hook is available`)
t.P(`func callError(ctx `, t.pkgs["context"], `.Context, h *`, t.pkgs["twirp"], `.ServerHooks, err `, t.pkgs["twirp"], `.Error) `, t.pkgs["context"], `.Context {`)
t.P(` if h == nil || h.Error == nil {`)
t.P(` return ctx`)
t.P(` }`)
t.P(` return h.Error(ctx, err)`)
t.P(`}`)
t.P()
}
func (t *twirp) generateStreamUtils() {
t.P(`type protoStreamReader struct {`)
t.P(` r *`, t.pkgs["bufio"], `.Reader`)
t.P(` pb *`, t.pkgs["proto"], `.Buffer`)
t.P(` maxSize int`)
t.P(`}`)
t.P(``)
t.P(`func (r protoStreamReader) Read(msg `, t.pkgs["proto"], `.Message) error {`)
t.P(` // Get next field tag.`)
t.P(` tag, err := `, t.pkgs["binary"], `.ReadUvarint(r.r)`)
t.P(` if err != nil {`)
t.P(` return err`)
t.P(` }`)
t.P(``)
t.P(` const (`)
t.P(` msgTag = (1 << 3) | 2`)
t.P(` trailerTag = (2 << 3) | 2`)
t.P(` )`)
t.P(``)
t.P(` if tag == trailerTag { // Received a json twirp error or "EOF"`)
t.P(` // Read the length delimiter`)
t.P(` l, err := binary.ReadUvarint(r.r)`)
t.P(` if err != nil {`)
t.P(` return clientError("unable to read trailer's length delimiter", err)`)
t.P(` }`)
t.P(` sb := new(`, t.pkgs["bytes"], `.Buffer)`)
t.P(` sb.Grow(int(l))`)
t.P(` _, err = `, t.pkgs["io"], `.Copy(sb, r.r)`)
t.P(` if err != nil {`)
t.P(` return clientError("unable to read trailer", err)`)
t.P(` }`)
t.P(` if sb.String() == "EOF" {`)
t.P(` return `, t.pkgs["io"], `.EOF`)
t.P(` }`)
t.P(` var tj twerrJSON`)
t.P(` if err = `, t.pkgs["json"], `.Unmarshal([]byte(sb.String()), &tj); err != nil {`)
t.P(` return clientError("unable to decode trailer", err)`)
t.P(` }`)
t.P(` return tj.toTwirpError()`)
t.P(` }`)
t.P(``)
t.P(` if tag != msgTag {`)
t.P(` return `, t.pkgs["fmt"], `.Errorf("invalid field tag: %v", tag)`)
t.P(` }`)
t.P(``)
t.P(` // This is a real message. How long is it?`)
t.P(` l, err := `, t.pkgs["binary"], `.ReadUvarint(r.r)`)
t.P(` if err != nil {`)
t.P(` return err`)
t.P(` }`)
t.P(` if int(l) < 0 || int(l) > r.maxSize {`)
t.P(` return `, t.pkgs["io"], `.ErrShortBuffer`)
t.P(` }`)
t.P()
t.P(` // Go ahead and read a message.`)
t.P(` buf := make([]byte, int(l))`)
t.P(` if _, err = `, t.pkgs["io"], `.ReadFull(r.r, buf); err != nil {`)
t.P(` return err`)
t.P(` }`)
t.P(` r.pb.SetBuf(buf)`)
t.P(` if err = r.pb.Unmarshal(msg); err != nil {`)
t.P(` return err`)
t.P(` }`)
t.P(` return nil`)
t.P(`}`)
t.P()
t.P(`type jsonStreamReader struct {`)
t.P(` dec *`, t.pkgs["json"], `.Decoder`)
t.P(` unmarshaler *`, t.pkgs["jsonpb"], `.Unmarshaler`)
t.P(` messageStreamDone bool`)
t.P(`}`)
t.P()
t.P(`func newJSONStreamReader(r `, t.pkgs["io"], `.Reader) (*jsonStreamReader, error) {`)
t.P(` // stream should start with {"messages":[`)
t.P(` dec := `, t.pkgs["json"], `.NewDecoder(r)`)
t.P(` t, err := dec.Token()`)
t.P(` if err != nil {`)
t.P(` return nil, err`)
t.P(` }`)
t.P(` delim, ok := t.(`, t.pkgs["json"], `.Delim)`)
t.P(` if !ok || delim != '{' {`)
t.P(` return nil, fmt.Errorf("missing leading { in JSON stream, found %q", t)`)
t.P(` }`)
t.P(``)
t.P(` t, err = dec.Token()`)
t.P(` if err != nil {`)
t.P(` return nil, err`)
t.P(` }`)
t.P(` key, ok := t.(string)`)
t.P(` if !ok || key != "messages" {`)
t.P(` return nil, fmt.Errorf("missing \"messages\" key in JSON stream, found %q", t)`)
t.P(` }`)
t.P(``)
t.P(` t, err = dec.Token()`)
t.P(` if err != nil {`)
t.P(` return nil, err`)
t.P(` }`)
t.P(` delim, ok = t.(`, t.pkgs["json"], `.Delim)`)
t.P(` if !ok || delim != '[' {`)
t.P(` return nil, fmt.Errorf("missing [ to open messages array in JSON stream, found %q", t)`)
t.P(` }`)
t.P(``)
t.P(` return &jsonStreamReader{`)
t.P(` dec: dec,`)
t.P(` unmarshaler: &`, t.pkgs["jsonpb"], `.Unmarshaler{AllowUnknownFields: true},`)
t.P(` }, nil`)
t.P(`}`)
t.P(``)
t.P(`func (r *jsonStreamReader) Read(msg proto.Message) error {`)
t.P(` if !r.messageStreamDone && r.dec.More() {`)
t.P(` return r.unmarshaler.UnmarshalNext(r.dec, msg)`)
t.P(` }`)
t.P(``)
t.P(` // else, we hit the end of the message stream. finish up the array, and then read the trailer.`)
t.P(` r.messageStreamDone = true`)
t.P(` t, err := r.dec.Token()`)
t.P(` if err != nil {`)
t.P(` return err`)
t.P(` }`)
t.P(` delim, ok := t.(json.Delim)`)
t.P(` if !ok || delim != ']' {`)
t.P(` return fmt.Errorf("missing end of message array in JSON stream, found %q", t)`)
t.P(` }`)
t.P(``)
t.P(` t, err = r.dec.Token()`)
t.P(` if err != nil {`)
t.P(` return err`)
t.P(` }`)
t.P(` key, ok := t.(string)`)
t.P(` if !ok || key != "trailer" {`)
t.P(` return fmt.Errorf("missing trailer after messages in JSON stream, found %q", t)`)
t.P(` }`)
t.P(``)
t.P(` var tj twerrJSON`)
t.P(` err = r.dec.Decode(&tj)`)
t.P(` if err != nil {`)
t.P(` var eof string`)
t.P(` if _ = r.dec.Decode(&eof); eof == "EOF" {`)
t.P(` return io.EOF`)
t.P(` }`)
t.P(` return err`)
t.P(` }`)
t.P(``)
t.P(` return tj.toTwirpError()`)
t.P(`}`)
t.P()
}
// P forwards to g.gen.P, which prints output.
func (t *twirp) P(args ...string) {
for _, v := range args {
t.output.WriteString(v)
}
t.output.WriteByte('\n')
}
// Big header comments to makes it easier to visually parse a generated file.
func (t *twirp) sectionComment(sectionTitle string) {
t.P()
t.P(`// `, strings.Repeat("=", len(sectionTitle)))
t.P(`// `, sectionTitle)
t.P(`// `, strings.Repeat("=", len(sectionTitle)))
t.P()
}
func (t *twirp) generateService(file *descriptor.FileDescriptorProto, service *descriptor.ServiceDescriptorProto, index int) {
servName := serviceName(service)
t.sectionComment(servName + ` Interface`)
t.generateTwirpInterface(file, service)
t.sectionComment(servName + ` Protobuf Client`)
t.generateClient("Protobuf", file, service)
t.sectionComment(servName + ` JSON Client`)
t.generateClient("JSON", file, service)
// Server
t.sectionComment(servName + ` Server Handler`)
t.generateServer(file, service)
}
func (t *twirp) generateTwirpInterface(file *descriptor.FileDescriptorProto, service *descriptor.ServiceDescriptorProto) {
servName := serviceName(service)
comments, err := t.reg.ServiceComments(file, service)
if err == nil {
t.printComments(comments)
}
t.P(`type `, servName, ` interface {`)
for _, method := range service.Method {
comments, err = t.reg.MethodComments(file, service, method)
if err == nil {
t.printComments(comments)
}
t.P(t.signature(method))
t.P()
}
t.P(`}`)
}
type rpcType string
const (
unary rpcType = "unary"
download rpcType = "download"
upload rpcType = "upload"
bidirectional rpcType = "bidirectional"
)
func methodRPCType(method *descriptor.MethodDescriptorProto) rpcType {
var (
streamInput = method.GetClientStreaming()
streamOutput = method.GetServerStreaming()
)
switch {
case !streamInput && !streamOutput:
return unary
case streamInput && !streamOutput:
return upload
case !streamInput && streamOutput:
return download
case streamInput && streamOutput:
return bidirectional
}
return ""
}
func (t *twirp) signature(method *descriptor.MethodDescriptorProto) string {
methName := methodName(method)
inputType := t.methodInputType(method)
outputType := t.methodOutputType(method)
switch methodRPCType(method) {
case unary:
inputType = "*" + inputType
outputType = "*" + outputType
case upload:
outputType = "*" + outputType
case download:
inputType = "*" + inputType
case bidirectional:
}
return fmt.Sprintf(`%s(ctx %s.Context, in %s) (%s, error)`, methName, t.pkgs["context"], inputType, outputType)
}