client.go 5.2 KB

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