grpc.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. // Copyright 2018 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 internal_gengogrpc is internal to the protobuf module.
  5. package internal_gengogrpc
  6. import (
  7. "fmt"
  8. "strconv"
  9. "strings"
  10. "google.golang.org/protobuf/compiler/protogen"
  11. "google.golang.org/protobuf/types/descriptorpb"
  12. )
  13. const (
  14. contextPackage = protogen.GoImportPath("context")
  15. grpcPackage = protogen.GoImportPath("google.golang.org/grpc")
  16. )
  17. // GenerateFile generates a _grpc.pb.go file containing gRPC service definitions.
  18. func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {
  19. if len(file.Services) == 0 {
  20. return nil
  21. }
  22. filename := file.GeneratedFilenamePrefix + "_grpc.pb.go"
  23. g := gen.NewGeneratedFile(filename, file.GoImportPath)
  24. g.P("// Code generated by protoc-gen-go-grpc. DO NOT EDIT.")
  25. g.P()
  26. g.P("package ", file.GoPackageName)
  27. g.P()
  28. GenerateFileContent(gen, file, g)
  29. return g
  30. }
  31. // GenerateFileContent generates the gRPC service definitions, excluding the package statement.
  32. func GenerateFileContent(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile) {
  33. if len(file.Services) == 0 {
  34. return
  35. }
  36. // TODO: Remove this. We don't need to include these references any more.
  37. g.P("// Reference imports to suppress errors if they are not otherwise used.")
  38. g.P("var _ ", contextPackage.Ident("Context"))
  39. g.P("var _ ", grpcPackage.Ident("ClientConn"))
  40. g.P()
  41. g.P("// This is a compile-time assertion to ensure that this generated file")
  42. g.P("// is compatible with the grpc package it is being compiled against.")
  43. g.P("const _ = ", grpcPackage.Ident("SupportPackageIsVersion4"))
  44. g.P()
  45. for _, service := range file.Services {
  46. genService(gen, file, g, service)
  47. }
  48. }
  49. func genService(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) {
  50. clientName := service.GoName + "Client"
  51. g.P("// ", clientName, " is the client API for ", service.GoName, " service.")
  52. g.P("//")
  53. g.P("// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.")
  54. // Client interface.
  55. if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() {
  56. g.P("//")
  57. g.P(deprecationComment)
  58. }
  59. g.Annotate(clientName, service.Location)
  60. g.P("type ", clientName, " interface {")
  61. for _, method := range service.Methods {
  62. g.Annotate(clientName+"."+method.GoName, method.Location)
  63. g.P(method.Comments.Leading,
  64. clientSignature(g, method))
  65. }
  66. g.P("}")
  67. g.P()
  68. // Client structure.
  69. g.P("type ", unexport(clientName), " struct {")
  70. g.P("cc *", grpcPackage.Ident("ClientConn"))
  71. g.P("}")
  72. g.P()
  73. // NewClient factory.
  74. if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() {
  75. g.P(deprecationComment)
  76. }
  77. g.P("func New", clientName, " (cc *", grpcPackage.Ident("ClientConn"), ") ", clientName, " {")
  78. g.P("return &", unexport(clientName), "{cc}")
  79. g.P("}")
  80. g.P()
  81. var methodIndex, streamIndex int
  82. // Client method implementations.
  83. for _, method := range service.Methods {
  84. if !method.Desc.IsStreamingServer() && !method.Desc.IsStreamingClient() {
  85. // Unary RPC method
  86. genClientMethod(gen, file, g, method, methodIndex)
  87. methodIndex++
  88. } else {
  89. // Streaming RPC method
  90. genClientMethod(gen, file, g, method, streamIndex)
  91. streamIndex++
  92. }
  93. }
  94. // Server interface.
  95. serverType := service.GoName + "Server"
  96. g.P("// ", serverType, " is the server API for ", service.GoName, " service.")
  97. if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() {
  98. g.P("//")
  99. g.P(deprecationComment)
  100. }
  101. g.Annotate(serverType, service.Location)
  102. g.P("type ", serverType, " interface {")
  103. for _, method := range service.Methods {
  104. g.Annotate(serverType+"."+method.GoName, method.Location)
  105. g.P(method.Comments.Leading,
  106. serverSignature(g, method))
  107. }
  108. g.P("}")
  109. g.P()
  110. // Server registration.
  111. if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() {
  112. g.P(deprecationComment)
  113. }
  114. serviceDescVar := "_" + service.GoName + "_serviceDesc"
  115. g.P("func Register", service.GoName, "Server(s *", grpcPackage.Ident("Server"), ", srv ", serverType, ") {")
  116. g.P("s.RegisterService(&", serviceDescVar, `, srv)`)
  117. g.P("}")
  118. g.P()
  119. // Server handler implementations.
  120. var handlerNames []string
  121. for _, method := range service.Methods {
  122. hname := genServerMethod(gen, file, g, method)
  123. handlerNames = append(handlerNames, hname)
  124. }
  125. // Service descriptor.
  126. g.P("var ", serviceDescVar, " = ", grpcPackage.Ident("ServiceDesc"), " {")
  127. g.P("ServiceName: ", strconv.Quote(string(service.Desc.FullName())), ",")
  128. g.P("HandlerType: (*", serverType, ")(nil),")
  129. g.P("Methods: []", grpcPackage.Ident("MethodDesc"), "{")
  130. for i, method := range service.Methods {
  131. if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() {
  132. continue
  133. }
  134. g.P("{")
  135. g.P("MethodName: ", strconv.Quote(string(method.Desc.Name())), ",")
  136. g.P("Handler: ", handlerNames[i], ",")
  137. g.P("},")
  138. }
  139. g.P("},")
  140. g.P("Streams: []", grpcPackage.Ident("StreamDesc"), "{")
  141. for i, method := range service.Methods {
  142. if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
  143. continue
  144. }
  145. g.P("{")
  146. g.P("StreamName: ", strconv.Quote(string(method.Desc.Name())), ",")
  147. g.P("Handler: ", handlerNames[i], ",")
  148. if method.Desc.IsStreamingServer() {
  149. g.P("ServerStreams: true,")
  150. }
  151. if method.Desc.IsStreamingClient() {
  152. g.P("ClientStreams: true,")
  153. }
  154. g.P("},")
  155. }
  156. g.P("},")
  157. g.P("Metadata: \"", file.Desc.Path(), "\",")
  158. g.P("}")
  159. g.P()
  160. }
  161. func clientSignature(g *protogen.GeneratedFile, method *protogen.Method) string {
  162. s := method.GoName + "(ctx " + g.QualifiedGoIdent(contextPackage.Ident("Context"))
  163. if !method.Desc.IsStreamingClient() {
  164. s += ", in *" + g.QualifiedGoIdent(method.Input.GoIdent)
  165. }
  166. s += ", opts ..." + g.QualifiedGoIdent(grpcPackage.Ident("CallOption")) + ") ("
  167. if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
  168. s += "*" + g.QualifiedGoIdent(method.Output.GoIdent)
  169. } else {
  170. s += method.Parent.GoName + "_" + method.GoName + "Client"
  171. }
  172. s += ", error)"
  173. return s
  174. }
  175. func genClientMethod(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, method *protogen.Method, index int) {
  176. service := method.Parent
  177. sname := fmt.Sprintf("/%s/%s", service.Desc.FullName(), method.Desc.Name())
  178. if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() {
  179. g.P(deprecationComment)
  180. }
  181. g.P("func (c *", unexport(service.GoName), "Client) ", clientSignature(g, method), "{")
  182. if !method.Desc.IsStreamingServer() && !method.Desc.IsStreamingClient() {
  183. g.P("out := new(", method.Output.GoIdent, ")")
  184. g.P(`err := c.cc.Invoke(ctx, "`, sname, `", in, out, opts...)`)
  185. g.P("if err != nil { return nil, err }")
  186. g.P("return out, nil")
  187. g.P("}")
  188. g.P()
  189. return
  190. }
  191. streamType := unexport(service.GoName) + method.GoName + "Client"
  192. serviceDescVar := "_" + service.GoName + "_serviceDesc"
  193. g.P("stream, err := c.cc.NewStream(ctx, &", serviceDescVar, ".Streams[", index, `], "`, sname, `", opts...)`)
  194. g.P("if err != nil { return nil, err }")
  195. g.P("x := &", streamType, "{stream}")
  196. if !method.Desc.IsStreamingClient() {
  197. g.P("if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }")
  198. g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }")
  199. }
  200. g.P("return x, nil")
  201. g.P("}")
  202. g.P()
  203. genSend := method.Desc.IsStreamingClient()
  204. genRecv := method.Desc.IsStreamingServer()
  205. genCloseAndRecv := !method.Desc.IsStreamingServer()
  206. // Stream auxiliary types and methods.
  207. g.P("type ", service.GoName, "_", method.GoName, "Client interface {")
  208. if genSend {
  209. g.P("Send(*", method.Input.GoIdent, ") error")
  210. }
  211. if genRecv {
  212. g.P("Recv() (*", method.Output.GoIdent, ", error)")
  213. }
  214. if genCloseAndRecv {
  215. g.P("CloseAndRecv() (*", method.Output.GoIdent, ", error)")
  216. }
  217. g.P(grpcPackage.Ident("ClientStream"))
  218. g.P("}")
  219. g.P()
  220. g.P("type ", streamType, " struct {")
  221. g.P(grpcPackage.Ident("ClientStream"))
  222. g.P("}")
  223. g.P()
  224. if genSend {
  225. g.P("func (x *", streamType, ") Send(m *", method.Input.GoIdent, ") error {")
  226. g.P("return x.ClientStream.SendMsg(m)")
  227. g.P("}")
  228. g.P()
  229. }
  230. if genRecv {
  231. g.P("func (x *", streamType, ") Recv() (*", method.Output.GoIdent, ", error) {")
  232. g.P("m := new(", method.Output.GoIdent, ")")
  233. g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }")
  234. g.P("return m, nil")
  235. g.P("}")
  236. g.P()
  237. }
  238. if genCloseAndRecv {
  239. g.P("func (x *", streamType, ") CloseAndRecv() (*", method.Output.GoIdent, ", error) {")
  240. g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }")
  241. g.P("m := new(", method.Output.GoIdent, ")")
  242. g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }")
  243. g.P("return m, nil")
  244. g.P("}")
  245. g.P()
  246. }
  247. }
  248. func serverSignature(g *protogen.GeneratedFile, method *protogen.Method) string {
  249. var reqArgs []string
  250. ret := "error"
  251. if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
  252. reqArgs = append(reqArgs, g.QualifiedGoIdent(contextPackage.Ident("Context")))
  253. ret = "(*" + g.QualifiedGoIdent(method.Output.GoIdent) + ", error)"
  254. }
  255. if !method.Desc.IsStreamingClient() {
  256. reqArgs = append(reqArgs, "*"+g.QualifiedGoIdent(method.Input.GoIdent))
  257. }
  258. if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() {
  259. reqArgs = append(reqArgs, method.Parent.GoName+"_"+method.GoName+"Server")
  260. }
  261. return method.GoName + "(" + strings.Join(reqArgs, ", ") + ") " + ret
  262. }
  263. func genServerMethod(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, method *protogen.Method) string {
  264. service := method.Parent
  265. hname := fmt.Sprintf("_%s_%s_Handler", service.GoName, method.GoName)
  266. if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
  267. g.P("func ", hname, "(srv interface{}, ctx ", contextPackage.Ident("Context"), ", dec func(interface{}) error, interceptor ", grpcPackage.Ident("UnaryServerInterceptor"), ") (interface{}, error) {")
  268. g.P("in := new(", method.Input.GoIdent, ")")
  269. g.P("if err := dec(in); err != nil { return nil, err }")
  270. g.P("if interceptor == nil { return srv.(", service.GoName, "Server).", method.GoName, "(ctx, in) }")
  271. g.P("info := &", grpcPackage.Ident("UnaryServerInfo"), "{")
  272. g.P("Server: srv,")
  273. g.P("FullMethod: ", strconv.Quote(fmt.Sprintf("/%s/%s", service.Desc.FullName(), method.GoName)), ",")
  274. g.P("}")
  275. g.P("handler := func(ctx ", contextPackage.Ident("Context"), ", req interface{}) (interface{}, error) {")
  276. g.P("return srv.(", service.GoName, "Server).", method.GoName, "(ctx, req.(*", method.Input.GoIdent, "))")
  277. g.P("}")
  278. g.P("return interceptor(ctx, in, info, handler)")
  279. g.P("}")
  280. g.P()
  281. return hname
  282. }
  283. streamType := unexport(service.GoName) + method.GoName + "Server"
  284. g.P("func ", hname, "(srv interface{}, stream ", grpcPackage.Ident("ServerStream"), ") error {")
  285. if !method.Desc.IsStreamingClient() {
  286. g.P("m := new(", method.Input.GoIdent, ")")
  287. g.P("if err := stream.RecvMsg(m); err != nil { return err }")
  288. g.P("return srv.(", service.GoName, "Server).", method.GoName, "(m, &", streamType, "{stream})")
  289. } else {
  290. g.P("return srv.(", service.GoName, "Server).", method.GoName, "(&", streamType, "{stream})")
  291. }
  292. g.P("}")
  293. g.P()
  294. genSend := method.Desc.IsStreamingServer()
  295. genSendAndClose := !method.Desc.IsStreamingServer()
  296. genRecv := method.Desc.IsStreamingClient()
  297. // Stream auxiliary types and methods.
  298. g.P("type ", service.GoName, "_", method.GoName, "Server interface {")
  299. if genSend {
  300. g.P("Send(*", method.Output.GoIdent, ") error")
  301. }
  302. if genSendAndClose {
  303. g.P("SendAndClose(*", method.Output.GoIdent, ") error")
  304. }
  305. if genRecv {
  306. g.P("Recv() (*", method.Input.GoIdent, ", error)")
  307. }
  308. g.P(grpcPackage.Ident("ServerStream"))
  309. g.P("}")
  310. g.P()
  311. g.P("type ", streamType, " struct {")
  312. g.P(grpcPackage.Ident("ServerStream"))
  313. g.P("}")
  314. g.P()
  315. if genSend {
  316. g.P("func (x *", streamType, ") Send(m *", method.Output.GoIdent, ") error {")
  317. g.P("return x.ServerStream.SendMsg(m)")
  318. g.P("}")
  319. g.P()
  320. }
  321. if genSendAndClose {
  322. g.P("func (x *", streamType, ") SendAndClose(m *", method.Output.GoIdent, ") error {")
  323. g.P("return x.ServerStream.SendMsg(m)")
  324. g.P("}")
  325. g.P()
  326. }
  327. if genRecv {
  328. g.P("func (x *", streamType, ") Recv() (*", method.Input.GoIdent, ", error) {")
  329. g.P("m := new(", method.Input.GoIdent, ")")
  330. g.P("if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }")
  331. g.P("return m, nil")
  332. g.P("}")
  333. g.P()
  334. }
  335. return hname
  336. }
  337. const deprecationComment = "// Deprecated: Do not use."
  338. func unexport(s string) string { return strings.ToLower(s[:1]) + s[1:] }