grpc.go 14 KB

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