1// 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	"path"
40	"strconv"
41	"strings"
42
43	pb "github.com/golang/protobuf/protoc-gen-go/descriptor"
44	"github.com/golang/protobuf/protoc-gen-go/generator"
45)
46
47// generatedCodeVersion indicates a version of the generated code.
48// It is incremented whenever an incompatibility between the generated code and
49// the grpc package is introduced; the generated code references
50// a constant, grpc.SupportPackageIsVersionN (where N is generatedCodeVersion).
51const generatedCodeVersion = 4
52
53// Paths for packages used by code generated in this file,
54// relative to the import_prefix of the generator.Generator.
55const (
56	contextPkgPath = "golang.org/x/net/context"
57	grpcPkgPath    = "google.golang.org/grpc"
58)
59
60func init() {
61	generator.RegisterPlugin(new(grpc))
62}
63
64// grpc is an implementation of the Go protocol buffer compiler's
65// plugin architecture.  It generates bindings for gRPC support.
66type grpc struct {
67	gen *generator.Generator
68}
69
70// Name returns the name of this plugin, "grpc".
71func (g *grpc) Name() string {
72	return "grpc"
73}
74
75// The names for packages imported in the generated code.
76// They may vary from the final path component of the import path
77// if the name is used by other packages.
78var (
79	contextPkg string
80	grpcPkg    string
81)
82
83// Init initializes the plugin.
84func (g *grpc) Init(gen *generator.Generator) {
85	g.gen = gen
86	contextPkg = generator.RegisterUniquePackageName("context", nil)
87	grpcPkg = generator.RegisterUniquePackageName("grpc", nil)
88}
89
90// Given a type name defined in a .proto, return its object.
91// Also record that we're using it, to guarantee the associated import.
92func (g *grpc) objectNamed(name string) generator.Object {
93	g.gen.RecordTypeUse(name)
94	return g.gen.ObjectNamed(name)
95}
96
97// Given a type name defined in a .proto, return its name as we will print it.
98func (g *grpc) typeName(str string) string {
99	return g.gen.TypeName(g.objectNamed(str))
100}
101
102// P forwards to g.gen.P.
103func (g *grpc) P(args ...interface{}) { g.gen.P(args...) }
104
105// Generate generates code for the services in the given file.
106func (g *grpc) Generate(file *generator.FileDescriptor) {
107	if len(file.FileDescriptorProto.Service) == 0 {
108		return
109	}
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	if len(file.FileDescriptorProto.Service) == 0 {
130		return
131	}
132	g.P("import (")
133	g.P(contextPkg, " ", generator.GoImportPath(path.Join(string(g.gen.ImportPrefix), contextPkgPath)))
134	g.P(grpcPkg, " ", generator.GoImportPath(path.Join(string(g.gen.ImportPrefix), grpcPkgPath)))
135	g.P(")")
136	g.P()
137}
138
139// reservedClientName records whether a client name is reserved on the client side.
140var reservedClientName = map[string]bool{
141	// TODO: do we need any in gRPC?
142}
143
144func unexport(s string) string { return strings.ToLower(s[:1]) + s[1:] }
145
146// deprecationComment is the standard comment added to deprecated
147// messages, fields, enums, and enum values.
148var deprecationComment = "// Deprecated: Do not use."
149
150// generateService generates all the code for the named service.
151func (g *grpc) generateService(file *generator.FileDescriptor, service *pb.ServiceDescriptorProto, index int) {
152	path := fmt.Sprintf("6,%d", index) // 6 means service.
153
154	origServName := service.GetName()
155	fullServName := origServName
156	if pkg := file.GetPackage(); pkg != "" {
157		fullServName = pkg + "." + fullServName
158	}
159	servName := generator.CamelCase(origServName)
160	deprecated := service.GetOptions().GetDeprecated()
161
162	g.P()
163	g.P(fmt.Sprintf(`// %sClient is the client API for %s service.
164//
165// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.`, servName, servName))
166
167	// Client interface.
168	if deprecated {
169		g.P("//")
170		g.P(deprecationComment)
171	}
172	g.P("type ", servName, "Client interface {")
173	for i, method := range service.Method {
174		g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service.
175		g.P(g.generateClientSignature(servName, method))
176	}
177	g.P("}")
178	g.P()
179
180	// Client structure.
181	g.P("type ", unexport(servName), "Client struct {")
182	g.P("cc *", grpcPkg, ".ClientConn")
183	g.P("}")
184	g.P()
185
186	// NewClient factory.
187	if deprecated {
188		g.P(deprecationComment)
189	}
190	g.P("func New", servName, "Client (cc *", grpcPkg, ".ClientConn) ", servName, "Client {")
191	g.P("return &", unexport(servName), "Client{cc}")
192	g.P("}")
193	g.P()
194
195	var methodIndex, streamIndex int
196	serviceDescVar := "_" + servName + "_serviceDesc"
197	// Client method implementations.
198	for _, method := range service.Method {
199		var descExpr string
200		if !method.GetServerStreaming() && !method.GetClientStreaming() {
201			// Unary RPC method
202			descExpr = fmt.Sprintf("&%s.Methods[%d]", serviceDescVar, methodIndex)
203			methodIndex++
204		} else {
205			// Streaming RPC method
206			descExpr = fmt.Sprintf("&%s.Streams[%d]", serviceDescVar, streamIndex)
207			streamIndex++
208		}
209		g.generateClientMethod(servName, fullServName, serviceDescVar, method, descExpr)
210	}
211
212	// Server interface.
213	serverType := servName + "Server"
214	g.P("// ", serverType, " is the server API for ", servName, " service.")
215	if deprecated {
216		g.P("//")
217		g.P(deprecationComment)
218	}
219	g.P("type ", serverType, " interface {")
220	for i, method := range service.Method {
221		g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service.
222		g.P(g.generateServerSignature(servName, method))
223	}
224	g.P("}")
225	g.P()
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// generateClientSignature returns the client-side signature for a method.
281func (g *grpc) generateClientSignature(servName string, method *pb.MethodDescriptorProto) string {
282	origMethName := method.GetName()
283	methName := generator.CamelCase(origMethName)
284	if reservedClientName[methName] {
285		methName += "_"
286	}
287	reqArg := ", in *" + g.typeName(method.GetInputType())
288	if method.GetClientStreaming() {
289		reqArg = ""
290	}
291	respName := "*" + g.typeName(method.GetOutputType())
292	if method.GetServerStreaming() || method.GetClientStreaming() {
293		respName = servName + "_" + generator.CamelCase(origMethName) + "Client"
294	}
295	return fmt.Sprintf("%s(ctx %s.Context%s, opts ...%s.CallOption) (%s, error)", methName, contextPkg, reqArg, grpcPkg, respName)
296}
297
298func (g *grpc) generateClientMethod(servName, fullServName, serviceDescVar string, method *pb.MethodDescriptorProto, descExpr string) {
299	sname := fmt.Sprintf("/%s/%s", fullServName, method.GetName())
300	methName := generator.CamelCase(method.GetName())
301	inType := g.typeName(method.GetInputType())
302	outType := g.typeName(method.GetOutputType())
303
304	if method.GetOptions().GetDeprecated() {
305		g.P(deprecationComment)
306	}
307	g.P("func (c *", unexport(servName), "Client) ", g.generateClientSignature(servName, method), "{")
308	if !method.GetServerStreaming() && !method.GetClientStreaming() {
309		g.P("out := new(", outType, ")")
310		// TODO: Pass descExpr to Invoke.
311		g.P(`err := c.cc.Invoke(ctx, "`, sname, `", in, out, opts...)`)
312		g.P("if err != nil { return nil, err }")
313		g.P("return out, nil")
314		g.P("}")
315		g.P()
316		return
317	}
318	streamType := unexport(servName) + methName + "Client"
319	g.P("stream, err := c.cc.NewStream(ctx, ", descExpr, `, "`, sname, `", opts...)`)
320	g.P("if err != nil { return nil, err }")
321	g.P("x := &", streamType, "{stream}")
322	if !method.GetClientStreaming() {
323		g.P("if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }")
324		g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }")
325	}
326	g.P("return x, nil")
327	g.P("}")
328	g.P()
329
330	genSend := method.GetClientStreaming()
331	genRecv := method.GetServerStreaming()
332	genCloseAndRecv := !method.GetServerStreaming()
333
334	// Stream auxiliary types and methods.
335	g.P("type ", servName, "_", methName, "Client interface {")
336	if genSend {
337		g.P("Send(*", inType, ") error")
338	}
339	if genRecv {
340		g.P("Recv() (*", outType, ", error)")
341	}
342	if genCloseAndRecv {
343		g.P("CloseAndRecv() (*", outType, ", error)")
344	}
345	g.P(grpcPkg, ".ClientStream")
346	g.P("}")
347	g.P()
348
349	g.P("type ", streamType, " struct {")
350	g.P(grpcPkg, ".ClientStream")
351	g.P("}")
352	g.P()
353
354	if genSend {
355		g.P("func (x *", streamType, ") Send(m *", inType, ") error {")
356		g.P("return x.ClientStream.SendMsg(m)")
357		g.P("}")
358		g.P()
359	}
360	if genRecv {
361		g.P("func (x *", streamType, ") Recv() (*", outType, ", error) {")
362		g.P("m := new(", outType, ")")
363		g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }")
364		g.P("return m, nil")
365		g.P("}")
366		g.P()
367	}
368	if genCloseAndRecv {
369		g.P("func (x *", streamType, ") CloseAndRecv() (*", outType, ", error) {")
370		g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }")
371		g.P("m := new(", outType, ")")
372		g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }")
373		g.P("return m, nil")
374		g.P("}")
375		g.P()
376	}
377}
378
379// generateServerSignature returns the server-side signature for a method.
380func (g *grpc) generateServerSignature(servName string, method *pb.MethodDescriptorProto) string {
381	origMethName := method.GetName()
382	methName := generator.CamelCase(origMethName)
383	if reservedClientName[methName] {
384		methName += "_"
385	}
386
387	var reqArgs []string
388	ret := "error"
389	if !method.GetServerStreaming() && !method.GetClientStreaming() {
390		reqArgs = append(reqArgs, contextPkg+".Context")
391		ret = "(*" + g.typeName(method.GetOutputType()) + ", error)"
392	}
393	if !method.GetClientStreaming() {
394		reqArgs = append(reqArgs, "*"+g.typeName(method.GetInputType()))
395	}
396	if method.GetServerStreaming() || method.GetClientStreaming() {
397		reqArgs = append(reqArgs, servName+"_"+generator.CamelCase(origMethName)+"Server")
398	}
399
400	return methName + "(" + strings.Join(reqArgs, ", ") + ") " + ret
401}
402
403func (g *grpc) generateServerMethod(servName, fullServName string, method *pb.MethodDescriptorProto) string {
404	methName := generator.CamelCase(method.GetName())
405	hname := fmt.Sprintf("_%s_%s_Handler", servName, methName)
406	inType := g.typeName(method.GetInputType())
407	outType := g.typeName(method.GetOutputType())
408
409	if !method.GetServerStreaming() && !method.GetClientStreaming() {
410		g.P("func ", hname, "(srv interface{}, ctx ", contextPkg, ".Context, dec func(interface{}) error, interceptor ", grpcPkg, ".UnaryServerInterceptor) (interface{}, error) {")
411		g.P("in := new(", inType, ")")
412		g.P("if err := dec(in); err != nil { return nil, err }")
413		g.P("if interceptor == nil { return srv.(", servName, "Server).", methName, "(ctx, in) }")
414		g.P("info := &", grpcPkg, ".UnaryServerInfo{")
415		g.P("Server: srv,")
416		g.P("FullMethod: ", strconv.Quote(fmt.Sprintf("/%s/%s", fullServName, methName)), ",")
417		g.P("}")
418		g.P("handler := func(ctx ", contextPkg, ".Context, req interface{}) (interface{}, error) {")
419		g.P("return srv.(", servName, "Server).", methName, "(ctx, req.(*", inType, "))")
420		g.P("}")
421		g.P("return interceptor(ctx, in, info, handler)")
422		g.P("}")
423		g.P()
424		return hname
425	}
426	streamType := unexport(servName) + methName + "Server"
427	g.P("func ", hname, "(srv interface{}, stream ", grpcPkg, ".ServerStream) error {")
428	if !method.GetClientStreaming() {
429		g.P("m := new(", inType, ")")
430		g.P("if err := stream.RecvMsg(m); err != nil { return err }")
431		g.P("return srv.(", servName, "Server).", methName, "(m, &", streamType, "{stream})")
432	} else {
433		g.P("return srv.(", servName, "Server).", methName, "(&", streamType, "{stream})")
434	}
435	g.P("}")
436	g.P()
437
438	genSend := method.GetServerStreaming()
439	genSendAndClose := !method.GetServerStreaming()
440	genRecv := method.GetClientStreaming()
441
442	// Stream auxiliary types and methods.
443	g.P("type ", servName, "_", methName, "Server interface {")
444	if genSend {
445		g.P("Send(*", outType, ") error")
446	}
447	if genSendAndClose {
448		g.P("SendAndClose(*", outType, ") error")
449	}
450	if genRecv {
451		g.P("Recv() (*", inType, ", error)")
452	}
453	g.P(grpcPkg, ".ServerStream")
454	g.P("}")
455	g.P()
456
457	g.P("type ", streamType, " struct {")
458	g.P(grpcPkg, ".ServerStream")
459	g.P("}")
460	g.P()
461
462	if genSend {
463		g.P("func (x *", streamType, ") Send(m *", outType, ") error {")
464		g.P("return x.ServerStream.SendMsg(m)")
465		g.P("}")
466		g.P()
467	}
468	if genSendAndClose {
469		g.P("func (x *", streamType, ") SendAndClose(m *", outType, ") error {")
470		g.P("return x.ServerStream.SendMsg(m)")
471		g.P("}")
472		g.P()
473	}
474	if genRecv {
475		g.P("func (x *", streamType, ") Recv() (*", inType, ", error) {")
476		g.P("m := new(", inType, ")")
477		g.P("if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }")
478		g.P("return m, nil")
479		g.P("}")
480		g.P()
481	}
482
483	return hname
484}
485