blob: 5d1e3f0f6193138f3c9adb6431606c90556e1322 [file] [log] [blame]
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -07001// Go support for Protocol Buffers - Google's data interchange format
2//
3// Copyright 2015 The Go Authors. All rights reserved.
4// https://github.com/golang/protobuf
5//
6// Redistribution and use in source and binary forms, with or without
7// modification, are permitted provided that the following conditions are
8// met:
9//
10// * Redistributions of source code must retain the above copyright
11// notice, this list of conditions and the following disclaimer.
12// * Redistributions in binary form must reproduce the above
13// copyright notice, this list of conditions and the following disclaimer
14// in the documentation and/or other materials provided with the
15// distribution.
16// * Neither the name of Google Inc. nor the names of its
17// contributors may be used to endorse or promote products derived from
18// this software without specific prior written permission.
19//
20// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32// Package grpc outputs gRPC service descriptions in Go code.
33// It runs as a plugin for the Go protocol buffer compiler plugin.
34// It is linked in to protoc-gen-go.
35package grpc
36
37import (
38 "fmt"
39 "strconv"
40 "strings"
41
42 pb "github.com/golang/protobuf/protoc-gen-go/descriptor"
43 "github.com/golang/protobuf/protoc-gen-go/generator"
44)
45
46// generatedCodeVersion indicates a version of the generated code.
47// It is incremented whenever an incompatibility between the generated code and
48// the grpc package is introduced; the generated code references
49// a constant, grpc.SupportPackageIsVersionN (where N is generatedCodeVersion).
50const generatedCodeVersion = 4
51
52// Paths for packages used by code generated in this file,
53// relative to the import_prefix of the generator.Generator.
54const (
55 contextPkgPath = "context"
56 grpcPkgPath = "google.golang.org/grpc"
57 codePkgPath = "google.golang.org/grpc/codes"
58 statusPkgPath = "google.golang.org/grpc/status"
59)
60
61func init() {
62 generator.RegisterPlugin(new(grpc))
63}
64
65// grpc is an implementation of the Go protocol buffer compiler's
66// plugin architecture. It generates bindings for gRPC support.
67type grpc struct {
68 gen *generator.Generator
69}
70
71// Name returns the name of this plugin, "grpc".
72func (g *grpc) Name() string {
73 return "grpc"
74}
75
76// The names for packages imported in the generated code.
77// They may vary from the final path component of the import path
78// if the name is used by other packages.
79var (
80 contextPkg string
81 grpcPkg string
82)
83
84// Init initializes the plugin.
85func (g *grpc) Init(gen *generator.Generator) {
86 g.gen = gen
87}
88
89// Given a type name defined in a .proto, return its object.
90// Also record that we're using it, to guarantee the associated import.
91func (g *grpc) objectNamed(name string) generator.Object {
92 g.gen.RecordTypeUse(name)
93 return g.gen.ObjectNamed(name)
94}
95
96// Given a type name defined in a .proto, return its name as we will print it.
97func (g *grpc) typeName(str string) string {
98 return g.gen.TypeName(g.objectNamed(str))
99}
100
101// P forwards to g.gen.P.
102func (g *grpc) P(args ...interface{}) { g.gen.P(args...) }
103
104// Generate generates code for the services in the given file.
105func (g *grpc) Generate(file *generator.FileDescriptor) {
106 if len(file.FileDescriptorProto.Service) == 0 {
107 return
108 }
109
110 contextPkg = string(g.gen.AddImport(contextPkgPath))
111 grpcPkg = string(g.gen.AddImport(grpcPkgPath))
112
113 g.P("// Reference imports to suppress errors if they are not otherwise used.")
114 g.P("var _ ", contextPkg, ".Context")
115 g.P("var _ ", grpcPkg, ".ClientConn")
116 g.P()
117
118 // Assert version compatibility.
119 g.P("// This is a compile-time assertion to ensure that this generated file")
120 g.P("// is compatible with the grpc package it is being compiled against.")
121 g.P("const _ = ", grpcPkg, ".SupportPackageIsVersion", generatedCodeVersion)
122 g.P()
123
124 for i, service := range file.FileDescriptorProto.Service {
125 g.generateService(file, service, i)
126 }
127}
128
129// GenerateImports generates the import declaration for this file.
130func (g *grpc) GenerateImports(file *generator.FileDescriptor) {
131}
132
133// reservedClientName records whether a client name is reserved on the client side.
134var reservedClientName = map[string]bool{
135 // TODO: do we need any in gRPC?
136}
137
138func unexport(s string) string { return strings.ToLower(s[:1]) + s[1:] }
139
140// deprecationComment is the standard comment added to deprecated
141// messages, fields, enums, and enum values.
142var deprecationComment = "// Deprecated: Do not use."
143
144// generateService generates all the code for the named service.
145func (g *grpc) generateService(file *generator.FileDescriptor, service *pb.ServiceDescriptorProto, index int) {
146 path := fmt.Sprintf("6,%d", index) // 6 means service.
147
148 origServName := service.GetName()
149 fullServName := origServName
150 if pkg := file.GetPackage(); pkg != "" {
151 fullServName = pkg + "." + fullServName
152 }
153 servName := generator.CamelCase(origServName)
154 deprecated := service.GetOptions().GetDeprecated()
155
156 g.P()
157 g.P(fmt.Sprintf(`// %sClient is the client API for %s service.
158//
159// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.`, servName, servName))
160
161 // Client interface.
162 if deprecated {
163 g.P("//")
164 g.P(deprecationComment)
165 }
166 g.P("type ", servName, "Client interface {")
167 for i, method := range service.Method {
168 g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service.
169 g.P(g.generateClientSignature(servName, method))
170 }
171 g.P("}")
172 g.P()
173
174 // Client structure.
175 g.P("type ", unexport(servName), "Client struct {")
176 g.P("cc *", grpcPkg, ".ClientConn")
177 g.P("}")
178 g.P()
179
180 // NewClient factory.
181 if deprecated {
182 g.P(deprecationComment)
183 }
184 g.P("func New", servName, "Client (cc *", grpcPkg, ".ClientConn) ", servName, "Client {")
185 g.P("return &", unexport(servName), "Client{cc}")
186 g.P("}")
187 g.P()
188
189 var methodIndex, streamIndex int
190 serviceDescVar := "_" + servName + "_serviceDesc"
191 // Client method implementations.
192 for _, method := range service.Method {
193 var descExpr string
194 if !method.GetServerStreaming() && !method.GetClientStreaming() {
195 // Unary RPC method
196 descExpr = fmt.Sprintf("&%s.Methods[%d]", serviceDescVar, methodIndex)
197 methodIndex++
198 } else {
199 // Streaming RPC method
200 descExpr = fmt.Sprintf("&%s.Streams[%d]", serviceDescVar, streamIndex)
201 streamIndex++
202 }
203 g.generateClientMethod(servName, fullServName, serviceDescVar, method, descExpr)
204 }
205
206 // Server interface.
207 serverType := servName + "Server"
208 g.P("// ", serverType, " is the server API for ", servName, " service.")
209 if deprecated {
210 g.P("//")
211 g.P(deprecationComment)
212 }
213 g.P("type ", serverType, " interface {")
214 for i, method := range service.Method {
215 g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service.
216 g.P(g.generateServerSignature(servName, method))
217 }
218 g.P("}")
219 g.P()
220
221 // Server Unimplemented struct for forward compatability.
222 if deprecated {
223 g.P(deprecationComment)
224 }
225 g.generateUnimplementedServer(servName, service)
226
227 // Server registration.
228 if deprecated {
229 g.P(deprecationComment)
230 }
231 g.P("func Register", servName, "Server(s *", grpcPkg, ".Server, srv ", serverType, ") {")
232 g.P("s.RegisterService(&", serviceDescVar, `, srv)`)
233 g.P("}")
234 g.P()
235
236 // Server handler implementations.
237 var handlerNames []string
238 for _, method := range service.Method {
239 hname := g.generateServerMethod(servName, fullServName, method)
240 handlerNames = append(handlerNames, hname)
241 }
242
243 // Service descriptor.
244 g.P("var ", serviceDescVar, " = ", grpcPkg, ".ServiceDesc {")
245 g.P("ServiceName: ", strconv.Quote(fullServName), ",")
246 g.P("HandlerType: (*", serverType, ")(nil),")
247 g.P("Methods: []", grpcPkg, ".MethodDesc{")
248 for i, method := range service.Method {
249 if method.GetServerStreaming() || method.GetClientStreaming() {
250 continue
251 }
252 g.P("{")
253 g.P("MethodName: ", strconv.Quote(method.GetName()), ",")
254 g.P("Handler: ", handlerNames[i], ",")
255 g.P("},")
256 }
257 g.P("},")
258 g.P("Streams: []", grpcPkg, ".StreamDesc{")
259 for i, method := range service.Method {
260 if !method.GetServerStreaming() && !method.GetClientStreaming() {
261 continue
262 }
263 g.P("{")
264 g.P("StreamName: ", strconv.Quote(method.GetName()), ",")
265 g.P("Handler: ", handlerNames[i], ",")
266 if method.GetServerStreaming() {
267 g.P("ServerStreams: true,")
268 }
269 if method.GetClientStreaming() {
270 g.P("ClientStreams: true,")
271 }
272 g.P("},")
273 }
274 g.P("},")
275 g.P("Metadata: \"", file.GetName(), "\",")
276 g.P("}")
277 g.P()
278}
279
280// generateUnimplementedServer creates the unimplemented server struct
281func (g *grpc) generateUnimplementedServer(servName string, service *pb.ServiceDescriptorProto) {
282 serverType := servName + "Server"
283 g.P("// Unimplemented", serverType, " can be embedded to have forward compatible implementations.")
284 g.P("type Unimplemented", serverType, " struct {")
285 g.P("}")
286 g.P()
287 // Unimplemented<service_name>Server's concrete methods
288 for _, method := range service.Method {
289 g.generateServerMethodConcrete(servName, method)
290 }
291 g.P()
292}
293
294// generateServerMethodConcrete returns unimplemented methods which ensure forward compatibility
295func (g *grpc) generateServerMethodConcrete(servName string, method *pb.MethodDescriptorProto) {
296 header := g.generateServerSignatureWithParamNames(servName, method)
297 g.P("func (*Unimplemented", servName, "Server) ", header, " {")
298 var nilArg string
299 if !method.GetServerStreaming() && !method.GetClientStreaming() {
300 nilArg = "nil, "
301 }
302 methName := generator.CamelCase(method.GetName())
303 statusPkg := string(g.gen.AddImport(statusPkgPath))
304 codePkg := string(g.gen.AddImport(codePkgPath))
305 g.P("return ", nilArg, statusPkg, `.Errorf(`, codePkg, `.Unimplemented, "method `, methName, ` not implemented")`)
306 g.P("}")
307}
308
309// generateClientSignature returns the client-side signature for a method.
310func (g *grpc) generateClientSignature(servName string, method *pb.MethodDescriptorProto) string {
311 origMethName := method.GetName()
312 methName := generator.CamelCase(origMethName)
313 if reservedClientName[methName] {
314 methName += "_"
315 }
316 reqArg := ", in *" + g.typeName(method.GetInputType())
317 if method.GetClientStreaming() {
318 reqArg = ""
319 }
320 respName := "*" + g.typeName(method.GetOutputType())
321 if method.GetServerStreaming() || method.GetClientStreaming() {
322 respName = servName + "_" + generator.CamelCase(origMethName) + "Client"
323 }
324 return fmt.Sprintf("%s(ctx %s.Context%s, opts ...%s.CallOption) (%s, error)", methName, contextPkg, reqArg, grpcPkg, respName)
325}
326
327func (g *grpc) generateClientMethod(servName, fullServName, serviceDescVar string, method *pb.MethodDescriptorProto, descExpr string) {
328 sname := fmt.Sprintf("/%s/%s", fullServName, method.GetName())
329 methName := generator.CamelCase(method.GetName())
330 inType := g.typeName(method.GetInputType())
331 outType := g.typeName(method.GetOutputType())
332
333 if method.GetOptions().GetDeprecated() {
334 g.P(deprecationComment)
335 }
336 g.P("func (c *", unexport(servName), "Client) ", g.generateClientSignature(servName, method), "{")
337 if !method.GetServerStreaming() && !method.GetClientStreaming() {
338 g.P("out := new(", outType, ")")
339 // TODO: Pass descExpr to Invoke.
340 g.P(`err := c.cc.Invoke(ctx, "`, sname, `", in, out, opts...)`)
341 g.P("if err != nil { return nil, err }")
342 g.P("return out, nil")
343 g.P("}")
344 g.P()
345 return
346 }
347 streamType := unexport(servName) + methName + "Client"
348 g.P("stream, err := c.cc.NewStream(ctx, ", descExpr, `, "`, sname, `", opts...)`)
349 g.P("if err != nil { return nil, err }")
350 g.P("x := &", streamType, "{stream}")
351 if !method.GetClientStreaming() {
352 g.P("if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }")
353 g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }")
354 }
355 g.P("return x, nil")
356 g.P("}")
357 g.P()
358
359 genSend := method.GetClientStreaming()
360 genRecv := method.GetServerStreaming()
361 genCloseAndRecv := !method.GetServerStreaming()
362
363 // Stream auxiliary types and methods.
364 g.P("type ", servName, "_", methName, "Client interface {")
365 if genSend {
366 g.P("Send(*", inType, ") error")
367 }
368 if genRecv {
369 g.P("Recv() (*", outType, ", error)")
370 }
371 if genCloseAndRecv {
372 g.P("CloseAndRecv() (*", outType, ", error)")
373 }
374 g.P(grpcPkg, ".ClientStream")
375 g.P("}")
376 g.P()
377
378 g.P("type ", streamType, " struct {")
379 g.P(grpcPkg, ".ClientStream")
380 g.P("}")
381 g.P()
382
383 if genSend {
384 g.P("func (x *", streamType, ") Send(m *", inType, ") error {")
385 g.P("return x.ClientStream.SendMsg(m)")
386 g.P("}")
387 g.P()
388 }
389 if genRecv {
390 g.P("func (x *", streamType, ") Recv() (*", outType, ", error) {")
391 g.P("m := new(", outType, ")")
392 g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }")
393 g.P("return m, nil")
394 g.P("}")
395 g.P()
396 }
397 if genCloseAndRecv {
398 g.P("func (x *", streamType, ") CloseAndRecv() (*", outType, ", error) {")
399 g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }")
400 g.P("m := new(", outType, ")")
401 g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }")
402 g.P("return m, nil")
403 g.P("}")
404 g.P()
405 }
406}
407
408// generateServerSignatureWithParamNames returns the server-side signature for a method with parameter names.
409func (g *grpc) generateServerSignatureWithParamNames(servName string, method *pb.MethodDescriptorProto) string {
410 origMethName := method.GetName()
411 methName := generator.CamelCase(origMethName)
412 if reservedClientName[methName] {
413 methName += "_"
414 }
415
416 var reqArgs []string
417 ret := "error"
418 if !method.GetServerStreaming() && !method.GetClientStreaming() {
419 reqArgs = append(reqArgs, "ctx "+contextPkg+".Context")
420 ret = "(*" + g.typeName(method.GetOutputType()) + ", error)"
421 }
422 if !method.GetClientStreaming() {
423 reqArgs = append(reqArgs, "req *"+g.typeName(method.GetInputType()))
424 }
425 if method.GetServerStreaming() || method.GetClientStreaming() {
426 reqArgs = append(reqArgs, "srv "+servName+"_"+generator.CamelCase(origMethName)+"Server")
427 }
428
429 return methName + "(" + strings.Join(reqArgs, ", ") + ") " + ret
430}
431
432// generateServerSignature returns the server-side signature for a method.
433func (g *grpc) generateServerSignature(servName string, method *pb.MethodDescriptorProto) string {
434 origMethName := method.GetName()
435 methName := generator.CamelCase(origMethName)
436 if reservedClientName[methName] {
437 methName += "_"
438 }
439
440 var reqArgs []string
441 ret := "error"
442 if !method.GetServerStreaming() && !method.GetClientStreaming() {
443 reqArgs = append(reqArgs, contextPkg+".Context")
444 ret = "(*" + g.typeName(method.GetOutputType()) + ", error)"
445 }
446 if !method.GetClientStreaming() {
447 reqArgs = append(reqArgs, "*"+g.typeName(method.GetInputType()))
448 }
449 if method.GetServerStreaming() || method.GetClientStreaming() {
450 reqArgs = append(reqArgs, servName+"_"+generator.CamelCase(origMethName)+"Server")
451 }
452
453 return methName + "(" + strings.Join(reqArgs, ", ") + ") " + ret
454}
455
456func (g *grpc) generateServerMethod(servName, fullServName string, method *pb.MethodDescriptorProto) string {
457 methName := generator.CamelCase(method.GetName())
458 hname := fmt.Sprintf("_%s_%s_Handler", servName, methName)
459 inType := g.typeName(method.GetInputType())
460 outType := g.typeName(method.GetOutputType())
461
462 if !method.GetServerStreaming() && !method.GetClientStreaming() {
463 g.P("func ", hname, "(srv interface{}, ctx ", contextPkg, ".Context, dec func(interface{}) error, interceptor ", grpcPkg, ".UnaryServerInterceptor) (interface{}, error) {")
464 g.P("in := new(", inType, ")")
465 g.P("if err := dec(in); err != nil { return nil, err }")
466 g.P("if interceptor == nil { return srv.(", servName, "Server).", methName, "(ctx, in) }")
467 g.P("info := &", grpcPkg, ".UnaryServerInfo{")
468 g.P("Server: srv,")
469 g.P("FullMethod: ", strconv.Quote(fmt.Sprintf("/%s/%s", fullServName, methName)), ",")
470 g.P("}")
471 g.P("handler := func(ctx ", contextPkg, ".Context, req interface{}) (interface{}, error) {")
472 g.P("return srv.(", servName, "Server).", methName, "(ctx, req.(*", inType, "))")
473 g.P("}")
474 g.P("return interceptor(ctx, in, info, handler)")
475 g.P("}")
476 g.P()
477 return hname
478 }
479 streamType := unexport(servName) + methName + "Server"
480 g.P("func ", hname, "(srv interface{}, stream ", grpcPkg, ".ServerStream) error {")
481 if !method.GetClientStreaming() {
482 g.P("m := new(", inType, ")")
483 g.P("if err := stream.RecvMsg(m); err != nil { return err }")
484 g.P("return srv.(", servName, "Server).", methName, "(m, &", streamType, "{stream})")
485 } else {
486 g.P("return srv.(", servName, "Server).", methName, "(&", streamType, "{stream})")
487 }
488 g.P("}")
489 g.P()
490
491 genSend := method.GetServerStreaming()
492 genSendAndClose := !method.GetServerStreaming()
493 genRecv := method.GetClientStreaming()
494
495 // Stream auxiliary types and methods.
496 g.P("type ", servName, "_", methName, "Server interface {")
497 if genSend {
498 g.P("Send(*", outType, ") error")
499 }
500 if genSendAndClose {
501 g.P("SendAndClose(*", outType, ") error")
502 }
503 if genRecv {
504 g.P("Recv() (*", inType, ", error)")
505 }
506 g.P(grpcPkg, ".ServerStream")
507 g.P("}")
508 g.P()
509
510 g.P("type ", streamType, " struct {")
511 g.P(grpcPkg, ".ServerStream")
512 g.P("}")
513 g.P()
514
515 if genSend {
516 g.P("func (x *", streamType, ") Send(m *", outType, ") error {")
517 g.P("return x.ServerStream.SendMsg(m)")
518 g.P("}")
519 g.P()
520 }
521 if genSendAndClose {
522 g.P("func (x *", streamType, ") SendAndClose(m *", outType, ") error {")
523 g.P("return x.ServerStream.SendMsg(m)")
524 g.P("}")
525 g.P()
526 }
527 if genRecv {
528 g.P("func (x *", streamType, ") Recv() (*", inType, ", error) {")
529 g.P("m := new(", inType, ")")
530 g.P("if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }")
531 g.P("return m, nil")
532 g.P("}")
533 g.P()
534 }
535
536 return hname
537}