server.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. package gateway
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "github.com/fullstorydev/grpcurl"
  8. "github.com/golang/protobuf/jsonpb"
  9. "github.com/jhump/protoreflect/grpcreflect"
  10. "github.com/wuntsong-org/go-zero-plus/core/logx"
  11. "github.com/wuntsong-org/go-zero-plus/core/mr"
  12. "github.com/wuntsong-org/go-zero-plus/gateway/internal"
  13. "github.com/wuntsong-org/go-zero-plus/rest"
  14. "github.com/wuntsong-org/go-zero-plus/rest/httpx"
  15. "github.com/wuntsong-org/go-zero-plus/zrpc"
  16. "google.golang.org/grpc/codes"
  17. )
  18. type (
  19. // Server is a gateway server.
  20. Server struct {
  21. *rest.Server
  22. upstreams []Upstream
  23. processHeader func(http.Header) []string
  24. dialer func(conf zrpc.RpcClientConf) zrpc.Client
  25. }
  26. // Option defines the method to customize Server.
  27. Option func(svr *Server)
  28. )
  29. // MustNewServer creates a new gateway server.
  30. func MustNewServer(c GatewayConf, opts ...Option) *Server {
  31. svr := &Server{
  32. upstreams: c.Upstreams,
  33. Server: rest.MustNewServer(c.RestConf),
  34. }
  35. for _, opt := range opts {
  36. opt(svr)
  37. }
  38. return svr
  39. }
  40. // Start starts the gateway server.
  41. func (s *Server) Start() {
  42. logx.Must(s.build())
  43. s.Server.Start()
  44. }
  45. // Stop stops the gateway server.
  46. func (s *Server) Stop() {
  47. s.Server.Stop()
  48. }
  49. func (s *Server) build() error {
  50. if err := s.ensureUpstreamNames(); err != nil {
  51. return err
  52. }
  53. return mr.MapReduceVoid(func(source chan<- Upstream) {
  54. for _, up := range s.upstreams {
  55. source <- up
  56. }
  57. }, func(up Upstream, writer mr.Writer[rest.Route], cancel func(error)) {
  58. var cli zrpc.Client
  59. if s.dialer != nil {
  60. cli = s.dialer(up.Grpc)
  61. } else {
  62. cli = zrpc.MustNewClient(up.Grpc)
  63. }
  64. source, err := s.createDescriptorSource(cli, up)
  65. if err != nil {
  66. cancel(fmt.Errorf("%s: %w", up.Name, err))
  67. return
  68. }
  69. methods, err := internal.GetMethods(source)
  70. if err != nil {
  71. cancel(fmt.Errorf("%s: %w", up.Name, err))
  72. return
  73. }
  74. resolver := grpcurl.AnyResolverFromDescriptorSource(source)
  75. for _, m := range methods {
  76. if len(m.HttpMethod) > 0 && len(m.HttpPath) > 0 {
  77. writer.Write(rest.Route{
  78. Method: m.HttpMethod,
  79. Path: m.HttpPath,
  80. Handler: s.buildHandler(source, resolver, cli, m.RpcPath),
  81. })
  82. }
  83. }
  84. methodSet := make(map[string]struct{})
  85. for _, m := range methods {
  86. methodSet[m.RpcPath] = struct{}{}
  87. }
  88. for _, m := range up.Mappings {
  89. if _, ok := methodSet[m.RpcPath]; !ok {
  90. cancel(fmt.Errorf("%s: rpc method %s not found", up.Name, m.RpcPath))
  91. return
  92. }
  93. writer.Write(rest.Route{
  94. Method: strings.ToUpper(m.Method),
  95. Path: m.Path,
  96. Handler: s.buildHandler(source, resolver, cli, m.RpcPath),
  97. })
  98. }
  99. }, func(pipe <-chan rest.Route, cancel func(error)) {
  100. for route := range pipe {
  101. s.Server.AddRoute(route)
  102. }
  103. })
  104. }
  105. func (s *Server) buildHandler(source grpcurl.DescriptorSource, resolver jsonpb.AnyResolver,
  106. cli zrpc.Client, rpcPath string) func(http.ResponseWriter, *http.Request) {
  107. return func(w http.ResponseWriter, r *http.Request) {
  108. parser, err := internal.NewRequestParser(r, resolver)
  109. if err != nil {
  110. httpx.ErrorCtx(r.Context(), w, err)
  111. return
  112. }
  113. w.Header().Set(httpx.ContentType, httpx.JsonContentType)
  114. handler := internal.NewEventHandler(w, resolver)
  115. if err := grpcurl.InvokeRPC(r.Context(), source, cli.Conn(), rpcPath, s.prepareMetadata(r.Header),
  116. handler, parser.Next); err != nil {
  117. httpx.ErrorCtx(r.Context(), w, err)
  118. }
  119. st := handler.Status
  120. if st.Code() != codes.OK {
  121. httpx.ErrorCtx(r.Context(), w, st.Err())
  122. }
  123. }
  124. }
  125. func (s *Server) createDescriptorSource(cli zrpc.Client, up Upstream) (grpcurl.DescriptorSource, error) {
  126. var source grpcurl.DescriptorSource
  127. var err error
  128. if len(up.ProtoSets) > 0 {
  129. source, err = grpcurl.DescriptorSourceFromProtoSets(up.ProtoSets...)
  130. if err != nil {
  131. return nil, err
  132. }
  133. } else {
  134. client := grpcreflect.NewClientAuto(context.Background(), cli.Conn())
  135. source = grpcurl.DescriptorSourceFromServer(context.Background(), client)
  136. }
  137. return source, nil
  138. }
  139. func (s *Server) ensureUpstreamNames() error {
  140. for i := 0; i < len(s.upstreams); i++ {
  141. target, err := s.upstreams[i].Grpc.BuildTarget()
  142. if err != nil {
  143. return err
  144. }
  145. s.upstreams[i].Name = target
  146. }
  147. return nil
  148. }
  149. func (s *Server) prepareMetadata(header http.Header) []string {
  150. vals := internal.ProcessHeaders(header)
  151. if s.processHeader != nil {
  152. vals = append(vals, s.processHeader(header)...)
  153. }
  154. return vals
  155. }
  156. // WithHeaderProcessor sets a processor to process request headers.
  157. // The returned headers are used as metadata to invoke the RPC.
  158. func WithHeaderProcessor(processHeader func(http.Header) []string) func(*Server) {
  159. return func(s *Server) {
  160. s.processHeader = processHeader
  161. }
  162. }
  163. // withDialer sets a dialer to create a gRPC client.
  164. func withDialer(dialer func(conf zrpc.RpcClientConf) zrpc.Client) func(*Server) {
  165. return func(s *Server) {
  166. s.dialer = dialer
  167. }
  168. }