grpc.go 18 KB

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