client.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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. }
  39. )
  40. // NewClient returns a Client.
  41. func NewClient(target string, opts ...ClientOption) (Client, error) {
  42. var cli client
  43. svcCfg := fmt.Sprintf(`{"loadBalancingPolicy":"%s"}`, p2c.Name)
  44. balancerOpt := WithDialOption(grpc.WithDefaultServiceConfig(svcCfg))
  45. opts = append([]ClientOption{balancerOpt}, opts...)
  46. if err := cli.dial(target, opts...); err != nil {
  47. return nil, err
  48. }
  49. return &cli, nil
  50. }
  51. func (c *client) Conn() *grpc.ClientConn {
  52. return c.conn
  53. }
  54. func (c *client) buildDialOptions(opts ...ClientOption) []grpc.DialOption {
  55. var cliOpts ClientOptions
  56. for _, opt := range opts {
  57. opt(&cliOpts)
  58. }
  59. var options []grpc.DialOption
  60. if !cliOpts.Secure {
  61. options = append([]grpc.DialOption(nil), grpc.WithTransportCredentials(insecure.NewCredentials()))
  62. }
  63. if !cliOpts.NonBlock {
  64. options = append(options, grpc.WithBlock())
  65. }
  66. options = append(options,
  67. WithUnaryClientInterceptors(
  68. clientinterceptors.UnaryTracingInterceptor,
  69. clientinterceptors.DurationInterceptor,
  70. clientinterceptors.PrometheusInterceptor,
  71. clientinterceptors.BreakerInterceptor,
  72. clientinterceptors.TimeoutInterceptor(cliOpts.Timeout),
  73. ),
  74. WithStreamClientInterceptors(
  75. clientinterceptors.StreamTracingInterceptor,
  76. ),
  77. )
  78. return append(options, cliOpts.DialOptions...)
  79. }
  80. func (c *client) dial(server string, opts ...ClientOption) error {
  81. options := c.buildDialOptions(opts...)
  82. timeCtx, cancel := context.WithTimeout(context.Background(), dialTimeout)
  83. defer cancel()
  84. conn, err := grpc.DialContext(timeCtx, server, options...)
  85. if err != nil {
  86. service := server
  87. if errors.Is(err, context.DeadlineExceeded) {
  88. pos := strings.LastIndexByte(server, separator)
  89. // len(server) - 1 is the index of last char
  90. if 0 < pos && pos < len(server)-1 {
  91. service = server[pos+1:]
  92. }
  93. }
  94. return fmt.Errorf("rpc dial: %s, error: %s, make sure rpc service %q is already started",
  95. server, err.Error(), service)
  96. }
  97. c.conn = conn
  98. return nil
  99. }
  100. // WithDialOption returns a func to customize a ClientOptions with given dial option.
  101. func WithDialOption(opt grpc.DialOption) ClientOption {
  102. return func(options *ClientOptions) {
  103. options.DialOptions = append(options.DialOptions, opt)
  104. }
  105. }
  106. // WithNonBlock sets the dialing to be nonblock.
  107. func WithNonBlock() ClientOption {
  108. return func(options *ClientOptions) {
  109. options.NonBlock = true
  110. }
  111. }
  112. // WithTimeout returns a func to customize a ClientOptions with given timeout.
  113. func WithTimeout(timeout time.Duration) ClientOption {
  114. return func(options *ClientOptions) {
  115. options.Timeout = timeout
  116. }
  117. }
  118. // WithTransportCredentials return a func to make the gRPC calls secured with given credentials.
  119. func WithTransportCredentials(creds credentials.TransportCredentials) ClientOption {
  120. return func(options *ClientOptions) {
  121. options.Secure = true
  122. options.DialOptions = append(options.DialOptions, grpc.WithTransportCredentials(creds))
  123. }
  124. }
  125. // WithUnaryClientInterceptor returns a func to customize a ClientOptions with given interceptor.
  126. func WithUnaryClientInterceptor(interceptor grpc.UnaryClientInterceptor) ClientOption {
  127. return func(options *ClientOptions) {
  128. options.DialOptions = append(options.DialOptions, WithUnaryClientInterceptors(interceptor))
  129. }
  130. }