blob: 1ddfe836f4d4ea06b0de95ffd05a3499a2705fb5 [file] [log] [blame]
Scott Bakere7144bc2019-10-01 14:16:47 -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)
58
59func init() {
60 generator.RegisterPlugin(new(grpc))
61}
62
63// grpc is an implementation of the Go protocol buffer compiler's
64// plugin architecture. It generates bindings for gRPC support.
65type grpc struct {
66 gen *generator.Generator
67}
68
69// Name returns the name of this plugin, "grpc".
70func (g *grpc) Name() string {
71 return "grpc"
72}
73
74// The names for packages imported in the generated code.
75// They may vary from the final path component of the import path
76// if the name is used by other packages.
77var (
78 contextPkg string
79 grpcPkg string
80)
81
82// Init initializes the plugin.
83func (g *grpc) Init(gen *generator.Generator) {
84 g.gen = gen
85}
86
87// Given a type name defined in a .proto, return its object.
88// Also record that we're using it, to guarantee the associated import.
89func (g *grpc) objectNamed(name string) generator.Object {
90 g.gen.RecordTypeUse(name)
91 return g.gen.ObjectNamed(name)
92}
93
94// Given a type name defined in a .proto, return its name as we will print it.
95func (g *grpc) typeName(str string) string {
96 return g.gen.TypeName(g.objectNamed(str))
97}
98
99// P forwards to g.gen.P.
100func (g *grpc) P(args ...interface{}) { g.gen.P(args...) }
101
102// Generate generates code for the services in the given file.
103func (g *grpc) Generate(file *generator.FileDescriptor) {
104 if len(file.FileDescriptorProto.Service) == 0 {
105 return
106 }
107
108 contextPkg = string(g.gen.AddImport(contextPkgPath))
109 grpcPkg = string(g.gen.AddImport(grpcPkgPath))
110
111 g.P("// Reference imports to suppress errors if they are not otherwise used.")
112 g.P("var _ ", contextPkg, ".Context")
113 g.P("var _ ", grpcPkg, ".ClientConn")
114 g.P()
115
116 // Assert version compatibility.
117 g.P("// This is a compile-time assertion to ensure that this generated file")
118 g.P("// is compatible with the grpc package it is being compiled against.")
119 g.P("const _ = ", grpcPkg, ".SupportPackageIsVersion", generatedCodeVersion)
120 g.P()
121
122 for i, service := range file.FileDescriptorProto.Service {
123 g.generateService(file, service, i)
124 }
125}
126
127// GenerateImports generates the import declaration for this file.
128func (g *grpc) GenerateImports(file *generator.FileDescriptor) {
129}
130
131// reservedClientName records whether a client name is reserved on the client side.
132var reservedClientName = map[string]bool{
133 // TODO: do we need any in gRPC?
134}
135
136func unexport(s string) string { return strings.ToLower(s[:1]) + s[1:] }
137
138// deprecationComment is the standard comment added to deprecated
139// messages, fields, enums, and enum values.
140var deprecationComment = "// Deprecated: Do not use."
141
142// generateService generates all the code for the named service.
143func (g *grpc) generateService(file *generator.FileDescriptor, service *pb.ServiceDescriptorProto, index int) {
144 path := fmt.Sprintf("6,%d", index) // 6 means service.
145
146 origServName := service.GetName()
147 fullServName := origServName
148 if pkg := file.GetPackage(); pkg != "" {
149 fullServName = pkg + "." + fullServName
150 }
151 servName := generator.CamelCase(origServName)
152 deprecated := service.GetOptions().GetDeprecated()
153
154 g.P()
155 g.P(fmt.Sprintf(`// %sClient is the client API for %s service.
156//
157// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.`, servName, servName))
158
159 // Client interface.
160 if deprecated {
161 g.P("//")
162 g.P(deprecationComment)
163 }
164 g.P("type ", servName, "Client interface {")
165 for i, method := range service.Method {
166 g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service.
167 g.P(g.generateClientSignature(servName, method))
168 }
169 g.P("}")
170 g.P()
171
172 // Client structure.
173 g.P("type ", unexport(servName), "Client struct {")
174 g.P("cc *", grpcPkg, ".ClientConn")
175 g.P("}")
176 g.P()
177
178 // NewClient factory.
179 if deprecated {
180 g.P(deprecationComment)
181 }
182 g.P("func New", servName, "Client (cc *", grpcPkg, ".ClientConn) ", servName, "Client {")
183 g.P("return &", unexport(servName), "Client{cc}")
184 g.P("}")
185 g.P()
186
187 var methodIndex, streamIndex int
188 serviceDescVar := "_" + servName + "_serviceDesc"
189 // Client method implementations.
190 for _, method := range service.Method {
191 var descExpr string
192 if !method.GetServerStreaming() && !method.GetClientStreaming() {
193 // Unary RPC method
194 descExpr = fmt.Sprintf("&%s.Methods[%d]", serviceDescVar, methodIndex)
195 methodIndex++
196 } else {
197 // Streaming RPC method
198 descExpr = fmt.Sprintf("&%s.Streams[%d]", serviceDescVar, streamIndex)
199 streamIndex++
200 }
201 g.generateClientMethod(servName, fullServName, serviceDescVar, method, descExpr)
202 }
203
204 // Server interface.
205 serverType := servName + "Server"
206 g.P("// ", serverType, " is the server API for ", servName, " service.")
207 if deprecated {
208 g.P("//")
209 g.P(deprecationComment)
210 }
211 g.P("type ", serverType, " interface {")
212 for i, method := range service.Method {
213 g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service.
214 g.P(g.generateServerSignature(servName, method))
215 }
216 g.P("}")
217 g.P()
218
219 // Server registration.
220 if deprecated {
221 g.P(deprecationComment)
222 }
223 g.P("func Register", servName, "Server(s *", grpcPkg, ".Server, srv ", serverType, ") {")
224 g.P("s.RegisterService(&", serviceDescVar, `, srv)`)
225 g.P("}")
226 g.P()
227
228 // Server handler implementations.
229 var handlerNames []string
230 for _, method := range service.Method {
231 hname := g.generateServerMethod(servName, fullServName, method)
232 handlerNames = append(handlerNames, hname)
233 }
234
235 // Service descriptor.
236 g.P("var ", serviceDescVar, " = ", grpcPkg, ".ServiceDesc {")
237 g.P("ServiceName: ", strconv.Quote(fullServName), ",")
238 g.P("HandlerType: (*", serverType, ")(nil),")
239 g.P("Methods: []", grpcPkg, ".MethodDesc{")
240 for i, method := range service.Method {
241 if method.GetServerStreaming() || method.GetClientStreaming() {
242 continue
243 }
244 g.P("{")
245 g.P("MethodName: ", strconv.Quote(method.GetName()), ",")
246 g.P("Handler: ", handlerNames[i], ",")
247 g.P("},")
248 }
249 g.P("},")
250 g.P("Streams: []", grpcPkg, ".StreamDesc{")
251 for i, method := range service.Method {
252 if !method.GetServerStreaming() && !method.GetClientStreaming() {
253 continue
254 }
255 g.P("{")
256 g.P("StreamName: ", strconv.Quote(method.GetName()), ",")
257 g.P("Handler: ", handlerNames[i], ",")
258 if method.GetServerStreaming() {
259 g.P("ServerStreams: true,")
260 }
261 if method.GetClientStreaming() {
262 g.P("ClientStreams: true,")
263 }
264 g.P("},")
265 }
266 g.P("},")
267 g.P("Metadata: \"", file.GetName(), "\",")
268 g.P("}")
269 g.P()
270}
271
272// generateClientSignature returns the client-side signature for a method.
273func (g *grpc) generateClientSignature(servName string, method *pb.MethodDescriptorProto) string {
274 origMethName := method.GetName()
275 methName := generator.CamelCase(origMethName)
276 if reservedClientName[methName] {
277 methName += "_"
278 }
279 reqArg := ", in *" + g.typeName(method.GetInputType())
280 if method.GetClientStreaming() {
281 reqArg = ""
282 }
283 respName := "*" + g.typeName(method.GetOutputType())
284 if method.GetServerStreaming() || method.GetClientStreaming() {
285 respName = servName + "_" + generator.CamelCase(origMethName) + "Client"
286 }
287 return fmt.Sprintf("%s(ctx %s.Context%s, opts ...%s.CallOption) (%s, error)", methName, contextPkg, reqArg, grpcPkg, respName)
288}
289
290func (g *grpc) generateClientMethod(servName, fullServName, serviceDescVar string, method *pb.MethodDescriptorProto, descExpr string) {
291 sname := fmt.Sprintf("/%s/%s", fullServName, method.GetName())
292 methName := generator.CamelCase(method.GetName())
293 inType := g.typeName(method.GetInputType())
294 outType := g.typeName(method.GetOutputType())
295
296 if method.GetOptions().GetDeprecated() {
297 g.P(deprecationComment)
298 }
299 g.P("func (c *", unexport(servName), "Client) ", g.generateClientSignature(servName, method), "{")
300 if !method.GetServerStreaming() && !method.GetClientStreaming() {
301 g.P("out := new(", outType, ")")
302 // TODO: Pass descExpr to Invoke.
303 g.P(`err := c.cc.Invoke(ctx, "`, sname, `", in, out, opts...)`)
304 g.P("if err != nil { return nil, err }")
305 g.P("return out, nil")
306 g.P("}")
307 g.P()
308 return
309 }
310 streamType := unexport(servName) + methName + "Client"
311 g.P("stream, err := c.cc.NewStream(ctx, ", descExpr, `, "`, sname, `", opts...)`)
312 g.P("if err != nil { return nil, err }")
313 g.P("x := &", streamType, "{stream}")
314 if !method.GetClientStreaming() {
315 g.P("if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }")
316 g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }")
317 }
318 g.P("return x, nil")
319 g.P("}")
320 g.P()
321
322 genSend := method.GetClientStreaming()
323 genRecv := method.GetServerStreaming()
324 genCloseAndRecv := !method.GetServerStreaming()
325
326 // Stream auxiliary types and methods.
327 g.P("type ", servName, "_", methName, "Client interface {")
328 if genSend {
329 g.P("Send(*", inType, ") error")
330 }
331 if genRecv {
332 g.P("Recv() (*", outType, ", error)")
333 }
334 if genCloseAndRecv {
335 g.P("CloseAndRecv() (*", outType, ", error)")
336 }
337 g.P(grpcPkg, ".ClientStream")
338 g.P("}")
339 g.P()
340
341 g.P("type ", streamType, " struct {")
342 g.P(grpcPkg, ".ClientStream")
343 g.P("}")
344 g.P()
345
346 if genSend {
347 g.P("func (x *", streamType, ") Send(m *", inType, ") error {")
348 g.P("return x.ClientStream.SendMsg(m)")
349 g.P("}")
350 g.P()
351 }
352 if genRecv {
353 g.P("func (x *", streamType, ") Recv() (*", outType, ", error) {")
354 g.P("m := new(", outType, ")")
355 g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }")
356 g.P("return m, nil")
357 g.P("}")
358 g.P()
359 }
360 if genCloseAndRecv {
361 g.P("func (x *", streamType, ") CloseAndRecv() (*", outType, ", error) {")
362 g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }")
363 g.P("m := new(", outType, ")")
364 g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }")
365 g.P("return m, nil")
366 g.P("}")
367 g.P()
368 }
369}
370
371// generateServerSignature returns the server-side signature for a method.
372func (g *grpc) generateServerSignature(servName string, method *pb.MethodDescriptorProto) string {
373 origMethName := method.GetName()
374 methName := generator.CamelCase(origMethName)
375 if reservedClientName[methName] {
376 methName += "_"
377 }
378
379 var reqArgs []string
380 ret := "error"
381 if !method.GetServerStreaming() && !method.GetClientStreaming() {
382 reqArgs = append(reqArgs, contextPkg+".Context")
383 ret = "(*" + g.typeName(method.GetOutputType()) + ", error)"
384 }
385 if !method.GetClientStreaming() {
386 reqArgs = append(reqArgs, "*"+g.typeName(method.GetInputType()))
387 }
388 if method.GetServerStreaming() || method.GetClientStreaming() {
389 reqArgs = append(reqArgs, servName+"_"+generator.CamelCase(origMethName)+"Server")
390 }
391
392 return methName + "(" + strings.Join(reqArgs, ", ") + ") " + ret
393}
394
395func (g *grpc) generateServerMethod(servName, fullServName string, method *pb.MethodDescriptorProto) string {
396 methName := generator.CamelCase(method.GetName())
397 hname := fmt.Sprintf("_%s_%s_Handler", servName, methName)
398 inType := g.typeName(method.GetInputType())
399 outType := g.typeName(method.GetOutputType())
400
401 if !method.GetServerStreaming() && !method.GetClientStreaming() {
402 g.P("func ", hname, "(srv interface{}, ctx ", contextPkg, ".Context, dec func(interface{}) error, interceptor ", grpcPkg, ".UnaryServerInterceptor) (interface{}, error) {")
403 g.P("in := new(", inType, ")")
404 g.P("if err := dec(in); err != nil { return nil, err }")
405 g.P("if interceptor == nil { return srv.(", servName, "Server).", methName, "(ctx, in) }")
406 g.P("info := &", grpcPkg, ".UnaryServerInfo{")
407 g.P("Server: srv,")
408 g.P("FullMethod: ", strconv.Quote(fmt.Sprintf("/%s/%s", fullServName, methName)), ",")
409 g.P("}")
410 g.P("handler := func(ctx ", contextPkg, ".Context, req interface{}) (interface{}, error) {")
411 g.P("return srv.(", servName, "Server).", methName, "(ctx, req.(*", inType, "))")
412 g.P("}")
413 g.P("return interceptor(ctx, in, info, handler)")
414 g.P("}")
415 g.P()
416 return hname
417 }
418 streamType := unexport(servName) + methName + "Server"
419 g.P("func ", hname, "(srv interface{}, stream ", grpcPkg, ".ServerStream) error {")
420 if !method.GetClientStreaming() {
421 g.P("m := new(", inType, ")")
422 g.P("if err := stream.RecvMsg(m); err != nil { return err }")
423 g.P("return srv.(", servName, "Server).", methName, "(m, &", streamType, "{stream})")
424 } else {
425 g.P("return srv.(", servName, "Server).", methName, "(&", streamType, "{stream})")
426 }
427 g.P("}")
428 g.P()
429
430 genSend := method.GetServerStreaming()
431 genSendAndClose := !method.GetServerStreaming()
432 genRecv := method.GetClientStreaming()
433
434 // Stream auxiliary types and methods.
435 g.P("type ", servName, "_", methName, "Server interface {")
436 if genSend {
437 g.P("Send(*", outType, ") error")
438 }
439 if genSendAndClose {
440 g.P("SendAndClose(*", outType, ") error")
441 }
442 if genRecv {
443 g.P("Recv() (*", inType, ", error)")
444 }
445 g.P(grpcPkg, ".ServerStream")
446 g.P("}")
447 g.P()
448
449 g.P("type ", streamType, " struct {")
450 g.P(grpcPkg, ".ServerStream")
451 g.P("}")
452 g.P()
453
454 if genSend {
455 g.P("func (x *", streamType, ") Send(m *", outType, ") error {")
456 g.P("return x.ServerStream.SendMsg(m)")
457 g.P("}")
458 g.P()
459 }
460 if genSendAndClose {
461 g.P("func (x *", streamType, ") SendAndClose(m *", outType, ") error {")
462 g.P("return x.ServerStream.SendMsg(m)")
463 g.P("}")
464 g.P()
465 }
466 if genRecv {
467 g.P("func (x *", streamType, ") Recv() (*", inType, ", error) {")
468 g.P("m := new(", inType, ")")
469 g.P("if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }")
470 g.P("return m, nil")
471 g.P("}")
472 g.P()
473 }
474
475 return hname
476}