grpc.go 16 KB

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