client.go 3.9 KB

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