123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452 |
- // Copyright 2015 The Go Authors. All rights reserved.
- // Use of this source code is governed by a BSD-style
- // license that can be found in the LICENSE file.
- // Package grpc is deprecated.
- //
- // This package is excluded from the Go protocol buffer compatibility guarantee
- // and may be deleted at some point in the future.
- //
- // Deprecated: Do not use.
- package grpc
- import (
- "fmt"
- "strconv"
- "strings"
- pb "github.com/golang/protobuf/protoc-gen-go/descriptor"
- "github.com/golang/protobuf/protoc-gen-go/generator"
- )
- // generatedCodeVersion indicates a version of the generated code.
- // It is incremented whenever an incompatibility between the generated code and
- // the grpc package is introduced; the generated code references
- // a constant, grpc.SupportPackageIsVersionN (where N is generatedCodeVersion).
- const generatedCodeVersion = 4
- // Paths for packages used by code generated in this file,
- // relative to the import_prefix of the generator.Generator.
- const (
- contextPkgPath = "context"
- grpcPkgPath = "google.golang.org/grpc"
- )
- func init() {
- generator.RegisterPlugin(new(grpc))
- }
- // grpc is an implementation of the Go protocol buffer compiler's
- // plugin architecture. It generates bindings for gRPC support.
- type grpc struct {
- gen *generator.Generator
- }
- // Name returns the name of this plugin, "grpc".
- func (g *grpc) Name() string {
- return "grpc"
- }
- // The names for packages imported in the generated code.
- // They may vary from the final path component of the import path
- // if the name is used by other packages.
- var (
- contextPkg string
- grpcPkg string
- )
- // Init initializes the plugin.
- func (g *grpc) Init(gen *generator.Generator) {
- g.gen = gen
- }
- // Given a type name defined in a .proto, return its object.
- // Also record that we're using it, to guarantee the associated import.
- func (g *grpc) objectNamed(name string) generator.Object {
- g.gen.RecordTypeUse(name)
- return g.gen.ObjectNamed(name)
- }
- // Given a type name defined in a .proto, return its name as we will print it.
- func (g *grpc) typeName(str string) string {
- return g.gen.TypeName(g.objectNamed(str))
- }
- // P forwards to g.gen.P.
- func (g *grpc) P(args ...interface{}) { g.gen.P(args...) }
- // Generate generates code for the services in the given file.
- func (g *grpc) Generate(file *generator.FileDescriptor) {
- if len(file.FileDescriptorProto.Service) == 0 {
- return
- }
- contextPkg = string(g.gen.AddImport(contextPkgPath))
- grpcPkg = string(g.gen.AddImport(grpcPkgPath))
- g.P("// Reference imports to suppress errors if they are not otherwise used.")
- g.P("var _ ", contextPkg, ".Context")
- g.P("var _ ", grpcPkg, ".ClientConn")
- g.P()
- // Assert version compatibility.
- g.P("// This is a compile-time assertion to ensure that this generated file")
- g.P("// is compatible with the grpc package it is being compiled against.")
- g.P("const _ = ", grpcPkg, ".SupportPackageIsVersion", generatedCodeVersion)
- g.P()
- for i, service := range file.FileDescriptorProto.Service {
- g.generateService(file, service, i)
- }
- }
- // GenerateImports generates the import declaration for this file.
- func (g *grpc) GenerateImports(file *generator.FileDescriptor) {
- }
- // reservedClientName records whether a client name is reserved on the client side.
- var reservedClientName = map[string]bool{
- // TODO: do we need any in gRPC?
- }
- func unexport(s string) string { return strings.ToLower(s[:1]) + s[1:] }
- // deprecationComment is the standard comment added to deprecated
- // messages, fields, enums, and enum values.
- var deprecationComment = "// Deprecated: Do not use."
- // generateService generates all the code for the named service.
- func (g *grpc) generateService(file *generator.FileDescriptor, service *pb.ServiceDescriptorProto, index int) {
- path := fmt.Sprintf("6,%d", index) // 6 means service.
- origServName := service.GetName()
- fullServName := origServName
- if pkg := file.GetPackage(); pkg != "" {
- fullServName = pkg + "." + fullServName
- }
- servName := generator.CamelCase(origServName)
- deprecated := service.GetOptions().GetDeprecated()
- g.P()
- g.P(fmt.Sprintf(`// %sClient is the client API for %s service.
- //
- // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.`, servName, servName))
- // Client interface.
- if deprecated {
- g.P("//")
- g.P(deprecationComment)
- }
- g.P("type ", servName, "Client interface {")
- for i, method := range service.Method {
- g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service.
- g.P(g.generateClientSignature(servName, method))
- }
- g.P("}")
- g.P()
- // Client structure.
- g.P("type ", unexport(servName), "Client struct {")
- g.P("cc *", grpcPkg, ".ClientConn")
- g.P("}")
- g.P()
- // NewClient factory.
- if deprecated {
- g.P(deprecationComment)
- }
- g.P("func New", servName, "Client (cc *", grpcPkg, ".ClientConn) ", servName, "Client {")
- g.P("return &", unexport(servName), "Client{cc}")
- g.P("}")
- g.P()
- var methodIndex, streamIndex int
- serviceDescVar := "_" + servName + "_serviceDesc"
- // Client method implementations.
- for _, method := range service.Method {
- var descExpr string
- if !method.GetServerStreaming() && !method.GetClientStreaming() {
- // Unary RPC method
- descExpr = fmt.Sprintf("&%s.Methods[%d]", serviceDescVar, methodIndex)
- methodIndex++
- } else {
- // Streaming RPC method
- descExpr = fmt.Sprintf("&%s.Streams[%d]", serviceDescVar, streamIndex)
- streamIndex++
- }
- g.generateClientMethod(servName, fullServName, serviceDescVar, method, descExpr)
- }
- // Server interface.
- serverType := servName + "Server"
- g.P("// ", serverType, " is the server API for ", servName, " service.")
- if deprecated {
- g.P("//")
- g.P(deprecationComment)
- }
- g.P("type ", serverType, " interface {")
- for i, method := range service.Method {
- g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service.
- g.P(g.generateServerSignature(servName, method))
- }
- g.P("}")
- g.P()
- // Server registration.
- if deprecated {
- g.P(deprecationComment)
- }
- g.P("func Register", servName, "Server(s *", grpcPkg, ".Server, srv ", serverType, ") {")
- g.P("s.RegisterService(&", serviceDescVar, `, srv)`)
- g.P("}")
- g.P()
- // Server handler implementations.
- var handlerNames []string
- for _, method := range service.Method {
- hname := g.generateServerMethod(servName, fullServName, method)
- handlerNames = append(handlerNames, hname)
- }
- // Service descriptor.
- g.P("var ", serviceDescVar, " = ", grpcPkg, ".ServiceDesc {")
- g.P("ServiceName: ", strconv.Quote(fullServName), ",")
- g.P("HandlerType: (*", serverType, ")(nil),")
- g.P("Methods: []", grpcPkg, ".MethodDesc{")
- for i, method := range service.Method {
- if method.GetServerStreaming() || method.GetClientStreaming() {
- continue
- }
- g.P("{")
- g.P("MethodName: ", strconv.Quote(method.GetName()), ",")
- g.P("Handler: ", handlerNames[i], ",")
- g.P("},")
- }
- g.P("},")
- g.P("Streams: []", grpcPkg, ".StreamDesc{")
- for i, method := range service.Method {
- if !method.GetServerStreaming() && !method.GetClientStreaming() {
- continue
- }
- g.P("{")
- g.P("StreamName: ", strconv.Quote(method.GetName()), ",")
- g.P("Handler: ", handlerNames[i], ",")
- if method.GetServerStreaming() {
- g.P("ServerStreams: true,")
- }
- if method.GetClientStreaming() {
- g.P("ClientStreams: true,")
- }
- g.P("},")
- }
- g.P("},")
- g.P("Metadata: \"", file.GetName(), "\",")
- g.P("}")
- g.P()
- }
- // generateClientSignature returns the client-side signature for a method.
- func (g *grpc) generateClientSignature(servName string, method *pb.MethodDescriptorProto) string {
- origMethName := method.GetName()
- methName := generator.CamelCase(origMethName)
- if reservedClientName[methName] {
- methName += "_"
- }
- reqArg := ", in *" + g.typeName(method.GetInputType())
- if method.GetClientStreaming() {
- reqArg = ""
- }
- respName := "*" + g.typeName(method.GetOutputType())
- if method.GetServerStreaming() || method.GetClientStreaming() {
- respName = servName + "_" + generator.CamelCase(origMethName) + "Client"
- }
- return fmt.Sprintf("%s(ctx %s.Context%s, opts ...%s.CallOption) (%s, error)", methName, contextPkg, reqArg, grpcPkg, respName)
- }
- func (g *grpc) generateClientMethod(servName, fullServName, serviceDescVar string, method *pb.MethodDescriptorProto, descExpr string) {
- sname := fmt.Sprintf("/%s/%s", fullServName, method.GetName())
- methName := generator.CamelCase(method.GetName())
- inType := g.typeName(method.GetInputType())
- outType := g.typeName(method.GetOutputType())
- if method.GetOptions().GetDeprecated() {
- g.P(deprecationComment)
- }
- g.P("func (c *", unexport(servName), "Client) ", g.generateClientSignature(servName, method), "{")
- if !method.GetServerStreaming() && !method.GetClientStreaming() {
- g.P("out := new(", outType, ")")
- // TODO: Pass descExpr to Invoke.
- g.P(`err := c.cc.Invoke(ctx, "`, sname, `", in, out, opts...)`)
- g.P("if err != nil { return nil, err }")
- g.P("return out, nil")
- g.P("}")
- g.P()
- return
- }
- streamType := unexport(servName) + methName + "Client"
- g.P("stream, err := c.cc.NewStream(ctx, ", descExpr, `, "`, sname, `", opts...)`)
- g.P("if err != nil { return nil, err }")
- g.P("x := &", streamType, "{stream}")
- if !method.GetClientStreaming() {
- g.P("if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }")
- g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }")
- }
- g.P("return x, nil")
- g.P("}")
- g.P()
- genSend := method.GetClientStreaming()
- genRecv := method.GetServerStreaming()
- genCloseAndRecv := !method.GetServerStreaming()
- // Stream auxiliary types and methods.
- g.P("type ", servName, "_", methName, "Client interface {")
- if genSend {
- g.P("Send(*", inType, ") error")
- }
- if genRecv {
- g.P("Recv() (*", outType, ", error)")
- }
- if genCloseAndRecv {
- g.P("CloseAndRecv() (*", outType, ", error)")
- }
- g.P(grpcPkg, ".ClientStream")
- g.P("}")
- g.P()
- g.P("type ", streamType, " struct {")
- g.P(grpcPkg, ".ClientStream")
- g.P("}")
- g.P()
- if genSend {
- g.P("func (x *", streamType, ") Send(m *", inType, ") error {")
- g.P("return x.ClientStream.SendMsg(m)")
- g.P("}")
- g.P()
- }
- if genRecv {
- g.P("func (x *", streamType, ") Recv() (*", outType, ", error) {")
- g.P("m := new(", outType, ")")
- g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }")
- g.P("return m, nil")
- g.P("}")
- g.P()
- }
- if genCloseAndRecv {
- g.P("func (x *", streamType, ") CloseAndRecv() (*", outType, ", error) {")
- g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }")
- g.P("m := new(", outType, ")")
- g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }")
- g.P("return m, nil")
- g.P("}")
- g.P()
- }
- }
- // generateServerSignature returns the server-side signature for a method.
- func (g *grpc) generateServerSignature(servName string, method *pb.MethodDescriptorProto) string {
- origMethName := method.GetName()
- methName := generator.CamelCase(origMethName)
- if reservedClientName[methName] {
- methName += "_"
- }
- var reqArgs []string
- ret := "error"
- if !method.GetServerStreaming() && !method.GetClientStreaming() {
- reqArgs = append(reqArgs, contextPkg+".Context")
- ret = "(*" + g.typeName(method.GetOutputType()) + ", error)"
- }
- if !method.GetClientStreaming() {
- reqArgs = append(reqArgs, "*"+g.typeName(method.GetInputType()))
- }
- if method.GetServerStreaming() || method.GetClientStreaming() {
- reqArgs = append(reqArgs, servName+"_"+generator.CamelCase(origMethName)+"Server")
- }
- return methName + "(" + strings.Join(reqArgs, ", ") + ") " + ret
- }
- func (g *grpc) generateServerMethod(servName, fullServName string, method *pb.MethodDescriptorProto) string {
- methName := generator.CamelCase(method.GetName())
- hname := fmt.Sprintf("_%s_%s_Handler", servName, methName)
- inType := g.typeName(method.GetInputType())
- outType := g.typeName(method.GetOutputType())
- if !method.GetServerStreaming() && !method.GetClientStreaming() {
- g.P("func ", hname, "(srv interface{}, ctx ", contextPkg, ".Context, dec func(interface{}) error, interceptor ", grpcPkg, ".UnaryServerInterceptor) (interface{}, error) {")
- g.P("in := new(", inType, ")")
- g.P("if err := dec(in); err != nil { return nil, err }")
- g.P("if interceptor == nil { return srv.(", servName, "Server).", methName, "(ctx, in) }")
- g.P("info := &", grpcPkg, ".UnaryServerInfo{")
- g.P("Server: srv,")
- g.P("FullMethod: ", strconv.Quote(fmt.Sprintf("/%s/%s", fullServName, methName)), ",")
- g.P("}")
- g.P("handler := func(ctx ", contextPkg, ".Context, req interface{}) (interface{}, error) {")
- g.P("return srv.(", servName, "Server).", methName, "(ctx, req.(*", inType, "))")
- g.P("}")
- g.P("return interceptor(ctx, in, info, handler)")
- g.P("}")
- g.P()
- return hname
- }
- streamType := unexport(servName) + methName + "Server"
- g.P("func ", hname, "(srv interface{}, stream ", grpcPkg, ".ServerStream) error {")
- if !method.GetClientStreaming() {
- g.P("m := new(", inType, ")")
- g.P("if err := stream.RecvMsg(m); err != nil { return err }")
- g.P("return srv.(", servName, "Server).", methName, "(m, &", streamType, "{stream})")
- } else {
- g.P("return srv.(", servName, "Server).", methName, "(&", streamType, "{stream})")
- }
- g.P("}")
- g.P()
- genSend := method.GetServerStreaming()
- genSendAndClose := !method.GetServerStreaming()
- genRecv := method.GetClientStreaming()
- // Stream auxiliary types and methods.
- g.P("type ", servName, "_", methName, "Server interface {")
- if genSend {
- g.P("Send(*", outType, ") error")
- }
- if genSendAndClose {
- g.P("SendAndClose(*", outType, ") error")
- }
- if genRecv {
- g.P("Recv() (*", inType, ", error)")
- }
- g.P(grpcPkg, ".ServerStream")
- g.P("}")
- g.P()
- g.P("type ", streamType, " struct {")
- g.P(grpcPkg, ".ServerStream")
- g.P("}")
- g.P()
- if genSend {
- g.P("func (x *", streamType, ") Send(m *", outType, ") error {")
- g.P("return x.ServerStream.SendMsg(m)")
- g.P("}")
- g.P()
- }
- if genSendAndClose {
- g.P("func (x *", streamType, ") SendAndClose(m *", outType, ") error {")
- g.P("return x.ServerStream.SendMsg(m)")
- g.P("}")
- g.P()
- }
- if genRecv {
- g.P("func (x *", streamType, ") Recv() (*", inType, ", error) {")
- g.P("m := new(", inType, ")")
- g.P("if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }")
- g.P("return m, nil")
- g.P("}")
- g.P()
- }
- return hname
- }
|