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 "strconv" 40 "strings" 41 42 pb "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" 43 "github.com/gogo/protobuf/protoc-gen-gogo/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// reservedClientName records whether a client name is reserved on the client side. 131var reservedClientName = map[string]bool{ 132 // TODO: do we need any in gRPC? 133} 134 135func unexport(s string) string { return strings.ToLower(s[:1]) + s[1:] } 136 137// deprecationComment is the standard comment added to deprecated 138// messages, fields, enums, and enum values. 139var deprecationComment = "// Deprecated: Do not use." 140 141// generateService generates all the code for the named service. 142func (g *grpc) generateService(file *generator.FileDescriptor, service *pb.ServiceDescriptorProto, index int) { 143 path := fmt.Sprintf("6,%d", index) // 6 means service. 144 145 origServName := service.GetName() 146 fullServName := origServName 147 if pkg := file.GetPackage(); pkg != "" { 148 fullServName = pkg + "." + fullServName 149 } 150 servName := generator.CamelCase(origServName) 151 deprecated := service.GetOptions().GetDeprecated() 152 153 g.P() 154 g.P(fmt.Sprintf(`// %sClient is the client API for %s service. 155// 156// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.`, servName, servName)) 157 158 // Client interface. 159 if deprecated { 160 g.P("//") 161 g.P(deprecationComment) 162 } 163 g.P("type ", servName, "Client interface {") 164 for i, method := range service.Method { 165 g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service. 166 g.P(g.generateClientSignature(servName, method)) 167 } 168 g.P("}") 169 g.P() 170 171 // Client structure. 172 g.P("type ", unexport(servName), "Client struct {") 173 g.P("cc *", grpcPkg, ".ClientConn") 174 g.P("}") 175 g.P() 176 177 // NewClient factory. 178 if deprecated { 179 g.P(deprecationComment) 180 } 181 g.P("func New", servName, "Client (cc *", grpcPkg, ".ClientConn) ", servName, "Client {") 182 g.P("return &", unexport(servName), "Client{cc}") 183 g.P("}") 184 g.P() 185 186 var methodIndex, streamIndex int 187 serviceDescVar := "_" + servName + "_serviceDesc" 188 // Client method implementations. 189 for _, method := range service.Method { 190 var descExpr string 191 if !method.GetServerStreaming() && !method.GetClientStreaming() { 192 // Unary RPC method 193 descExpr = fmt.Sprintf("&%s.Methods[%d]", serviceDescVar, methodIndex) 194 methodIndex++ 195 } else { 196 // Streaming RPC method 197 descExpr = fmt.Sprintf("&%s.Streams[%d]", serviceDescVar, streamIndex) 198 streamIndex++ 199 } 200 g.generateClientMethod(servName, fullServName, serviceDescVar, method, descExpr) 201 } 202 203 // Server interface. 204 serverType := servName + "Server" 205 g.P("// ", serverType, " is the server API for ", servName, " service.") 206 if deprecated { 207 g.P("//") 208 g.P(deprecationComment) 209 } 210 g.P("type ", serverType, " interface {") 211 for i, method := range service.Method { 212 g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service. 213 g.P(g.generateServerSignature(servName, method)) 214 } 215 g.P("}") 216 g.P() 217 218 // Server registration. 219 if deprecated { 220 g.P(deprecationComment) 221 } 222 g.P("func Register", servName, "Server(s *", grpcPkg, ".Server, srv ", serverType, ") {") 223 g.P("s.RegisterService(&", serviceDescVar, `, srv)`) 224 g.P("}") 225 g.P() 226 227 // Server handler implementations. 228 var handlerNames []string 229 for _, method := range service.Method { 230 hname := g.generateServerMethod(servName, fullServName, method) 231 handlerNames = append(handlerNames, hname) 232 } 233 234 // Service descriptor. 235 g.P("var ", serviceDescVar, " = ", grpcPkg, ".ServiceDesc {") 236 g.P("ServiceName: ", strconv.Quote(fullServName), ",") 237 g.P("HandlerType: (*", serverType, ")(nil),") 238 g.P("Methods: []", grpcPkg, ".MethodDesc{") 239 for i, method := range service.Method { 240 if method.GetServerStreaming() || method.GetClientStreaming() { 241 continue 242 } 243 g.P("{") 244 g.P("MethodName: ", strconv.Quote(method.GetName()), ",") 245 g.P("Handler: ", handlerNames[i], ",") 246 g.P("},") 247 } 248 g.P("},") 249 g.P("Streams: []", grpcPkg, ".StreamDesc{") 250 for i, method := range service.Method { 251 if !method.GetServerStreaming() && !method.GetClientStreaming() { 252 continue 253 } 254 g.P("{") 255 g.P("StreamName: ", strconv.Quote(method.GetName()), ",") 256 g.P("Handler: ", handlerNames[i], ",") 257 if method.GetServerStreaming() { 258 g.P("ServerStreams: true,") 259 } 260 if method.GetClientStreaming() { 261 g.P("ClientStreams: true,") 262 } 263 g.P("},") 264 } 265 g.P("},") 266 g.P("Metadata: \"", file.GetName(), "\",") 267 g.P("}") 268 g.P() 269} 270 271// generateClientSignature returns the client-side signature for a method. 272func (g *grpc) generateClientSignature(servName string, method *pb.MethodDescriptorProto) string { 273 origMethName := method.GetName() 274 methName := generator.CamelCase(origMethName) 275 if reservedClientName[methName] { 276 methName += "_" 277 } 278 reqArg := ", in *" + g.typeName(method.GetInputType()) 279 if method.GetClientStreaming() { 280 reqArg = "" 281 } 282 respName := "*" + g.typeName(method.GetOutputType()) 283 if method.GetServerStreaming() || method.GetClientStreaming() { 284 respName = servName + "_" + generator.CamelCase(origMethName) + "Client" 285 } 286 return fmt.Sprintf("%s(ctx %s.Context%s, opts ...%s.CallOption) (%s, error)", methName, contextPkg, reqArg, grpcPkg, respName) 287} 288 289func (g *grpc) generateClientMethod(servName, fullServName, serviceDescVar string, method *pb.MethodDescriptorProto, descExpr string) { 290 sname := fmt.Sprintf("/%s/%s", fullServName, method.GetName()) 291 methName := generator.CamelCase(method.GetName()) 292 inType := g.typeName(method.GetInputType()) 293 outType := g.typeName(method.GetOutputType()) 294 295 if method.GetOptions().GetDeprecated() { 296 g.P(deprecationComment) 297 } 298 g.P("func (c *", unexport(servName), "Client) ", g.generateClientSignature(servName, method), "{") 299 if !method.GetServerStreaming() && !method.GetClientStreaming() { 300 g.P("out := new(", outType, ")") 301 // TODO: Pass descExpr to Invoke. 302 g.P(`err := c.cc.Invoke(ctx, "`, sname, `", in, out, opts...)`) 303 g.P("if err != nil { return nil, err }") 304 g.P("return out, nil") 305 g.P("}") 306 g.P() 307 return 308 } 309 streamType := unexport(servName) + methName + "Client" 310 g.P("stream, err := c.cc.NewStream(ctx, ", descExpr, `, "`, sname, `", opts...)`) 311 g.P("if err != nil { return nil, err }") 312 g.P("x := &", streamType, "{stream}") 313 if !method.GetClientStreaming() { 314 g.P("if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }") 315 g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }") 316 } 317 g.P("return x, nil") 318 g.P("}") 319 g.P() 320 321 genSend := method.GetClientStreaming() 322 genRecv := method.GetServerStreaming() 323 genCloseAndRecv := !method.GetServerStreaming() 324 325 // Stream auxiliary types and methods. 326 g.P("type ", servName, "_", methName, "Client interface {") 327 if genSend { 328 g.P("Send(*", inType, ") error") 329 } 330 if genRecv { 331 g.P("Recv() (*", outType, ", error)") 332 } 333 if genCloseAndRecv { 334 g.P("CloseAndRecv() (*", outType, ", error)") 335 } 336 g.P(grpcPkg, ".ClientStream") 337 g.P("}") 338 g.P() 339 340 g.P("type ", streamType, " struct {") 341 g.P(grpcPkg, ".ClientStream") 342 g.P("}") 343 g.P() 344 345 if genSend { 346 g.P("func (x *", streamType, ") Send(m *", inType, ") error {") 347 g.P("return x.ClientStream.SendMsg(m)") 348 g.P("}") 349 g.P() 350 } 351 if genRecv { 352 g.P("func (x *", streamType, ") Recv() (*", outType, ", error) {") 353 g.P("m := new(", outType, ")") 354 g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }") 355 g.P("return m, nil") 356 g.P("}") 357 g.P() 358 } 359 if genCloseAndRecv { 360 g.P("func (x *", streamType, ") CloseAndRecv() (*", outType, ", error) {") 361 g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }") 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} 369 370// generateServerSignature returns the server-side signature for a method. 371func (g *grpc) generateServerSignature(servName string, method *pb.MethodDescriptorProto) string { 372 origMethName := method.GetName() 373 methName := generator.CamelCase(origMethName) 374 if reservedClientName[methName] { 375 methName += "_" 376 } 377 378 var reqArgs []string 379 ret := "error" 380 if !method.GetServerStreaming() && !method.GetClientStreaming() { 381 reqArgs = append(reqArgs, contextPkg+".Context") 382 ret = "(*" + g.typeName(method.GetOutputType()) + ", error)" 383 } 384 if !method.GetClientStreaming() { 385 reqArgs = append(reqArgs, "*"+g.typeName(method.GetInputType())) 386 } 387 if method.GetServerStreaming() || method.GetClientStreaming() { 388 reqArgs = append(reqArgs, servName+"_"+generator.CamelCase(origMethName)+"Server") 389 } 390 391 return methName + "(" + strings.Join(reqArgs, ", ") + ") " + ret 392} 393 394func (g *grpc) generateServerMethod(servName, fullServName string, method *pb.MethodDescriptorProto) string { 395 methName := generator.CamelCase(method.GetName()) 396 hname := fmt.Sprintf("_%s_%s_Handler", servName, methName) 397 inType := g.typeName(method.GetInputType()) 398 outType := g.typeName(method.GetOutputType()) 399 400 if !method.GetServerStreaming() && !method.GetClientStreaming() { 401 g.P("func ", hname, "(srv interface{}, ctx ", contextPkg, ".Context, dec func(interface{}) error, interceptor ", grpcPkg, ".UnaryServerInterceptor) (interface{}, error) {") 402 g.P("in := new(", inType, ")") 403 g.P("if err := dec(in); err != nil { return nil, err }") 404 g.P("if interceptor == nil { return srv.(", servName, "Server).", methName, "(ctx, in) }") 405 g.P("info := &", grpcPkg, ".UnaryServerInfo{") 406 g.P("Server: srv,") 407 g.P("FullMethod: ", strconv.Quote(fmt.Sprintf("/%s/%s", fullServName, methName)), ",") 408 g.P("}") 409 g.P("handler := func(ctx ", contextPkg, ".Context, req interface{}) (interface{}, error) {") 410 g.P("return srv.(", servName, "Server).", methName, "(ctx, req.(*", inType, "))") 411 g.P("}") 412 g.P("return interceptor(ctx, in, info, handler)") 413 g.P("}") 414 g.P() 415 return hname 416 } 417 streamType := unexport(servName) + methName + "Server" 418 g.P("func ", hname, "(srv interface{}, stream ", grpcPkg, ".ServerStream) error {") 419 if !method.GetClientStreaming() { 420 g.P("m := new(", inType, ")") 421 g.P("if err := stream.RecvMsg(m); err != nil { return err }") 422 g.P("return srv.(", servName, "Server).", methName, "(m, &", streamType, "{stream})") 423 } else { 424 g.P("return srv.(", servName, "Server).", methName, "(&", streamType, "{stream})") 425 } 426 g.P("}") 427 g.P() 428 429 genSend := method.GetServerStreaming() 430 genSendAndClose := !method.GetServerStreaming() 431 genRecv := method.GetClientStreaming() 432 433 // Stream auxiliary types and methods. 434 g.P("type ", servName, "_", methName, "Server interface {") 435 if genSend { 436 g.P("Send(*", outType, ") error") 437 } 438 if genSendAndClose { 439 g.P("SendAndClose(*", outType, ") error") 440 } 441 if genRecv { 442 g.P("Recv() (*", inType, ", error)") 443 } 444 g.P(grpcPkg, ".ServerStream") 445 g.P("}") 446 g.P() 447 448 g.P("type ", streamType, " struct {") 449 g.P(grpcPkg, ".ServerStream") 450 g.P("}") 451 g.P() 452 453 if genSend { 454 g.P("func (x *", streamType, ") Send(m *", outType, ") error {") 455 g.P("return x.ServerStream.SendMsg(m)") 456 g.P("}") 457 g.P() 458 } 459 if genSendAndClose { 460 g.P("func (x *", streamType, ") SendAndClose(m *", outType, ") error {") 461 g.P("return x.ServerStream.SendMsg(m)") 462 g.P("}") 463 g.P() 464 } 465 if genRecv { 466 g.P("func (x *", streamType, ") Recv() (*", inType, ", error) {") 467 g.P("m := new(", inType, ")") 468 g.P("if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }") 469 g.P("return m, nil") 470 g.P("}") 471 g.P() 472 } 473 474 return hname 475} 476