client.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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. 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.WithTransportCredentials(insecure.NewCredentials()))
  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. ),
  72. WithStreamClientInterceptors(
  73. clientinterceptors.StreamTracingInterceptor,
  74. ),
  75. )
  76. return append(options, cliOpts.DialOptions...)
  77. }
  78. func (c *client) dial(server string, opts ...ClientOption) error {
  79. options := c.buildDialOptions(opts...)
  80. timeCtx, cancel := context.WithTimeout(context.Background(), dialTimeout)
  81. defer cancel()
  82. conn, err := grpc.DialContext(timeCtx, server, options...)
  83. if err != nil {
  84. service := server
  85. if errors.Is(err, context.DeadlineExceeded) {
  86. pos := strings.LastIndexByte(server, separator)
  87. // len(server) - 1 is the index of last char
  88. if 0 < pos && pos < len(server)-1 {
  89. service = server[pos+1:]
  90. }
  91. }
  92. return fmt.Errorf("rpc dial: %s, error: %s, make sure rpc service %q is already started",
  93. server, err.Error(), service)
  94. }
  95. c.conn = conn
  96. return nil
  97. }
  98. // WithDialOption returns a func to customize a ClientOptions with given dial option.
  99. func WithDialOption(opt grpc.DialOption) ClientOption {
  100. return func(options *ClientOptions) {
  101. options.DialOptions = append(options.DialOptions, opt)
  102. }
  103. }
  104. // WithNonBlock sets the dialing to be nonblock.
  105. func WithNonBlock() ClientOption {
  106. return func(options *ClientOptions) {
  107. options.NonBlock = true
  108. }
  109. }
  110. // WithTimeout returns a func to customize a ClientOptions with given timeout.
  111. func WithTimeout(timeout time.Duration) ClientOption {
  112. return func(options *ClientOptions) {
  113. options.Timeout = timeout
  114. }
  115. }
  116. // WithTransportCredentials return a func to make the gRPC calls secured with given credentials.
  117. func WithTransportCredentials(creds credentials.TransportCredentials) ClientOption {
  118. return func(options *ClientOptions) {
  119. options.Secure = true
  120. options.DialOptions = append(options.DialOptions, grpc.WithTransportCredentials(creds))
  121. }
  122. }
  123. // WithUnaryClientInterceptor returns a func to customize a ClientOptions with given interceptor.
  124. func WithUnaryClientInterceptor(interceptor grpc.UnaryClientInterceptor) ClientOption {
  125. return func(options *ClientOptions) {
  126. options.DialOptions = append(options.DialOptions, WithUnaryClientInterceptors(interceptor))
  127. }
  128. }