client.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. package internal
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "strings"
  7. "time"
  8. "github.com/tal-tech/go-zero/zrpc/internal/balancer/p2c"
  9. "github.com/tal-tech/go-zero/zrpc/internal/clientinterceptors"
  10. "github.com/tal-tech/go-zero/zrpc/internal/resolver"
  11. "google.golang.org/grpc"
  12. "google.golang.org/grpc/credentials"
  13. )
  14. const (
  15. dialTimeout = time.Second * 3
  16. separator = '/'
  17. )
  18. func init() {
  19. resolver.RegisterResolver()
  20. }
  21. type (
  22. // Client interface wraps the Conn method.
  23. Client interface {
  24. Conn() *grpc.ClientConn
  25. }
  26. // A ClientOptions is a client options.
  27. ClientOptions struct {
  28. NonBlock bool
  29. Timeout time.Duration
  30. Secure bool
  31. Retry 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. }
  39. )
  40. // NewClient returns a Client.
  41. func NewClient(target string, opts ...ClientOption) (Client, error) {
  42. var cli client
  43. opts = append([]ClientOption{WithDialOption(grpc.WithBalancerName(p2c.Name))}, opts...)
  44. if err := cli.dial(target, opts...); err != nil {
  45. return nil, err
  46. }
  47. return &cli, nil
  48. }
  49. func (c *client) Conn() *grpc.ClientConn {
  50. return c.conn
  51. }
  52. func (c *client) buildDialOptions(opts ...ClientOption) []grpc.DialOption {
  53. var cliOpts ClientOptions
  54. for _, opt := range opts {
  55. opt(&cliOpts)
  56. }
  57. var options []grpc.DialOption
  58. if !cliOpts.Secure {
  59. options = append([]grpc.DialOption(nil), grpc.WithInsecure())
  60. }
  61. if !cliOpts.NonBlock {
  62. options = append(options, grpc.WithBlock())
  63. }
  64. options = append(options,
  65. WithUnaryClientInterceptors(
  66. clientinterceptors.UnaryTracingInterceptor,
  67. clientinterceptors.DurationInterceptor,
  68. clientinterceptors.PrometheusInterceptor,
  69. clientinterceptors.BreakerInterceptor,
  70. clientinterceptors.TimeoutInterceptor(cliOpts.Timeout),
  71. clientinterceptors.RetryInterceptor(cliOpts.Retry),
  72. ),
  73. WithStreamClientInterceptors(
  74. clientinterceptors.StreamTracingInterceptor,
  75. ),
  76. )
  77. return append(options, cliOpts.DialOptions...)
  78. }
  79. func (c *client) dial(server string, opts ...ClientOption) error {
  80. options := c.buildDialOptions(opts...)
  81. timeCtx, cancel := context.WithTimeout(context.Background(), dialTimeout)
  82. defer cancel()
  83. conn, err := grpc.DialContext(timeCtx, server, options...)
  84. if err != nil {
  85. service := server
  86. if errors.Is(err, context.DeadlineExceeded) {
  87. pos := strings.LastIndexByte(server, separator)
  88. // len(server) - 1 is the index of last char
  89. if 0 < pos && pos < len(server)-1 {
  90. service = server[pos+1:]
  91. }
  92. }
  93. return fmt.Errorf("rpc dial: %s, error: %s, make sure rpc service %q is already started",
  94. server, err.Error(), service)
  95. }
  96. c.conn = conn
  97. return nil
  98. }
  99. // WithDialOption returns a func to customize a ClientOptions with given dial option.
  100. func WithDialOption(opt grpc.DialOption) ClientOption {
  101. return func(options *ClientOptions) {
  102. options.DialOptions = append(options.DialOptions, opt)
  103. }
  104. }
  105. // WithNonBlock sets the dialing to be nonblock.
  106. func WithNonBlock() ClientOption {
  107. return func(options *ClientOptions) {
  108. options.NonBlock = true
  109. }
  110. }
  111. // WithTimeout returns a func to customize a ClientOptions with given timeout.
  112. func WithTimeout(timeout time.Duration) ClientOption {
  113. return func(options *ClientOptions) {
  114. options.Timeout = timeout
  115. }
  116. }
  117. // WithRetry returns a func to customize a ClientOptions with auto retry.
  118. func WithRetry() ClientOption {
  119. return func(options *ClientOptions) {
  120. options.Retry = true
  121. }
  122. }
  123. // WithTransportCredentials return a func to make the gRPC calls secured with given credentials.
  124. func WithTransportCredentials(creds credentials.TransportCredentials) ClientOption {
  125. return func(options *ClientOptions) {
  126. options.Secure = true
  127. options.DialOptions = append(options.DialOptions, grpc.WithTransportCredentials(creds))
  128. }
  129. }
  130. // WithUnaryClientInterceptor returns a func to customize a ClientOptions with given interceptor.
  131. func WithUnaryClientInterceptor(interceptor grpc.UnaryClientInterceptor) ClientOption {
  132. return func(options *ClientOptions) {
  133. options.DialOptions = append(options.DialOptions, WithUnaryClientInterceptors(interceptor))
  134. }
  135. }