client.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. package internal
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "strings"
  7. "time"
  8. "github.com/wuntsong-org/go-zero-plus/zrpc/internal/balancer/p2c"
  9. "github.com/wuntsong-org/go-zero-plus/zrpc/internal/clientinterceptors"
  10. "github.com/wuntsong-org/go-zero-plus/zrpc/resolver"
  11. "google.golang.org/grpc"
  12. "google.golang.org/grpc/credentials"
  13. "google.golang.org/grpc/credentials/insecure"
  14. )
  15. const (
  16. dialTimeout = time.Second * 3
  17. separator = '/'
  18. )
  19. func init() {
  20. resolver.Register()
  21. }
  22. type (
  23. // Client interface wraps the Conn method.
  24. Client interface {
  25. Conn() *grpc.ClientConn
  26. }
  27. // A ClientOptions is a client options.
  28. ClientOptions struct {
  29. NonBlock bool
  30. Timeout time.Duration
  31. Secure bool
  32. DialOptions []grpc.DialOption
  33. }
  34. // ClientOption defines the method to customize a ClientOptions.
  35. ClientOption func(options *ClientOptions)
  36. client struct {
  37. conn *grpc.ClientConn
  38. middlewares ClientMiddlewaresConf
  39. }
  40. )
  41. // NewClient returns a Client.
  42. func NewClient(target string, middlewares ClientMiddlewaresConf, opts ...ClientOption) (Client, error) {
  43. cli := client{
  44. middlewares: middlewares,
  45. }
  46. svcCfg := fmt.Sprintf(`{"loadBalancingPolicy":"%s"}`, p2c.Name)
  47. balancerOpt := WithDialOption(grpc.WithDefaultServiceConfig(svcCfg))
  48. opts = append([]ClientOption{balancerOpt}, opts...)
  49. if err := cli.dial(target, opts...); err != nil {
  50. return nil, err
  51. }
  52. return &cli, nil
  53. }
  54. func (c *client) Conn() *grpc.ClientConn {
  55. return c.conn
  56. }
  57. func (c *client) buildDialOptions(opts ...ClientOption) []grpc.DialOption {
  58. var cliOpts ClientOptions
  59. for _, opt := range opts {
  60. opt(&cliOpts)
  61. }
  62. var options []grpc.DialOption
  63. if !cliOpts.Secure {
  64. options = append([]grpc.DialOption(nil),
  65. grpc.WithTransportCredentials(insecure.NewCredentials()))
  66. }
  67. if !cliOpts.NonBlock {
  68. options = append(options, grpc.WithBlock())
  69. }
  70. options = append(options,
  71. grpc.WithChainUnaryInterceptor(c.buildUnaryInterceptors(cliOpts.Timeout)...),
  72. grpc.WithChainStreamInterceptor(c.buildStreamInterceptors()...),
  73. )
  74. return append(options, cliOpts.DialOptions...)
  75. }
  76. func (c *client) buildStreamInterceptors() []grpc.StreamClientInterceptor {
  77. var interceptors []grpc.StreamClientInterceptor
  78. if c.middlewares.Trace {
  79. interceptors = append(interceptors, clientinterceptors.StreamTracingInterceptor)
  80. }
  81. return interceptors
  82. }
  83. func (c *client) buildUnaryInterceptors(timeout time.Duration) []grpc.UnaryClientInterceptor {
  84. var interceptors []grpc.UnaryClientInterceptor
  85. if c.middlewares.Trace {
  86. interceptors = append(interceptors, clientinterceptors.UnaryTracingInterceptor)
  87. }
  88. if c.middlewares.Duration {
  89. interceptors = append(interceptors, clientinterceptors.DurationInterceptor)
  90. }
  91. if c.middlewares.Prometheus {
  92. interceptors = append(interceptors, clientinterceptors.PrometheusInterceptor)
  93. }
  94. if c.middlewares.Breaker {
  95. interceptors = append(interceptors, clientinterceptors.BreakerInterceptor)
  96. }
  97. if c.middlewares.Timeout {
  98. interceptors = append(interceptors, clientinterceptors.TimeoutInterceptor(timeout))
  99. }
  100. return interceptors
  101. }
  102. func (c *client) dial(server string, opts ...ClientOption) error {
  103. options := c.buildDialOptions(opts...)
  104. timeCtx, cancel := context.WithTimeout(context.Background(), dialTimeout)
  105. defer cancel()
  106. conn, err := grpc.DialContext(timeCtx, server, options...)
  107. if err != nil {
  108. service := server
  109. if errors.Is(err, context.DeadlineExceeded) {
  110. pos := strings.LastIndexByte(server, separator)
  111. // len(server) - 1 is the index of last char
  112. if 0 < pos && pos < len(server)-1 {
  113. service = server[pos+1:]
  114. }
  115. }
  116. return fmt.Errorf("rpc dial: %s, error: %s, make sure rpc service %q is already started",
  117. server, err.Error(), service)
  118. }
  119. c.conn = conn
  120. return nil
  121. }
  122. // WithDialOption returns a func to customize a ClientOptions with given dial option.
  123. func WithDialOption(opt grpc.DialOption) ClientOption {
  124. return func(options *ClientOptions) {
  125. options.DialOptions = append(options.DialOptions, opt)
  126. }
  127. }
  128. // WithNonBlock sets the dialing to be nonblock.
  129. func WithNonBlock() ClientOption {
  130. return func(options *ClientOptions) {
  131. options.NonBlock = true
  132. }
  133. }
  134. // WithStreamClientInterceptor returns a func to customize a ClientOptions with given interceptor.
  135. func WithStreamClientInterceptor(interceptor grpc.StreamClientInterceptor) ClientOption {
  136. return func(options *ClientOptions) {
  137. options.DialOptions = append(options.DialOptions,
  138. grpc.WithChainStreamInterceptor(interceptor))
  139. }
  140. }
  141. // WithTimeout returns a func to customize a ClientOptions with given timeout.
  142. func WithTimeout(timeout time.Duration) ClientOption {
  143. return func(options *ClientOptions) {
  144. options.Timeout = timeout
  145. }
  146. }
  147. // WithTransportCredentials return a func to make the gRPC calls secured with given credentials.
  148. func WithTransportCredentials(creds credentials.TransportCredentials) ClientOption {
  149. return func(options *ClientOptions) {
  150. options.Secure = true
  151. options.DialOptions = append(options.DialOptions, grpc.WithTransportCredentials(creds))
  152. }
  153. }
  154. // WithUnaryClientInterceptor returns a func to customize a ClientOptions with given interceptor.
  155. func WithUnaryClientInterceptor(interceptor grpc.UnaryClientInterceptor) ClientOption {
  156. return func(options *ClientOptions) {
  157. options.DialOptions = append(options.DialOptions,
  158. grpc.WithChainUnaryInterceptor(interceptor))
  159. }
  160. }