github.com/kaydxh/golang@v0.0.131/go/net/grpc/grpc_client.repository.factory.go (about)

     1  /*
     2   *Copyright (c) 2022, kaydxh
     3   *
     4   *Permission is hereby granted, free of charge, to any person obtaining a copy
     5   *of this software and associated documentation files (the "Software"), to deal
     6   *in the Software without restriction, including without limitation the rights
     7   *to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     8   *copies of the Software, and to permit persons to whom the Software is
     9   *furnished to do so, subject to the following conditions:
    10   *
    11   *The above copyright notice and this permission notice shall be included in all
    12   *copies or substantial portions of the Software.
    13   *
    14   *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    15   *IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    16   *FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    17   *AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    18   *LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    19   *OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    20   *SOFTWARE.
    21   */
    22  package grpc
    23  
    24  import (
    25  	"context"
    26  	"fmt"
    27  	"time"
    28  
    29  	"github.com/go-playground/validator/v10"
    30  	resolve_ "github.com/kaydxh/golang/go/net/resolver/resolve"
    31  	"google.golang.org/grpc"
    32  )
    33  
    34  type FactoryConfigFunc[T any] func(c *FactoryConfig[T]) error
    35  
    36  type FactoryConfig[T any] struct {
    37  	Validator        *validator.Validate
    38  	Addr             string
    39  	Timeout          time.Duration //接口处理超时时间
    40  	NewServiceClient func(*grpc.ClientConn) T
    41  
    42  	// not include the first call
    43  	RetryTimes    int
    44  	RetryInterval time.Duration
    45  
    46  	DisablePrintInoutMethods []string
    47  }
    48  
    49  func (fc *FactoryConfig[T]) ApplyOptions(configFuncs ...FactoryConfigFunc[T]) error {
    50  
    51  	for _, f := range configFuncs {
    52  		err := f(fc)
    53  		if err != nil {
    54  			return fmt.Errorf("failed to apply factory config, err: %v", err)
    55  		}
    56  	}
    57  
    58  	return nil
    59  }
    60  
    61  func (fc FactoryConfig[T]) Validate() error {
    62  	valid := fc.Validator
    63  	if valid == nil {
    64  		valid = validator.New()
    65  	}
    66  	return valid.Struct(fc)
    67  }
    68  
    69  type Repository[T any] struct {
    70  	Timeout time.Duration
    71  
    72  	Addr             string
    73  	NewServiceClient func(*grpc.ClientConn) T
    74  	Conn             *grpc.ClientConn
    75  	Client           T
    76  
    77  	// not include the first call
    78  	RetryTimes    int
    79  	RetryInterval time.Duration
    80  
    81  	DisablePrintInoutMethods []string
    82  }
    83  
    84  func (r *Repository[T]) NewConnect(ctx context.Context) (client T, conn *grpc.ClientConn, err error) {
    85  
    86  	var zeroClient T
    87  
    88  	addr := r.Addr
    89  	address, err := resolve_.ResolveOne(ctx, addr)
    90  	if err != nil {
    91  		return zeroClient, nil, err
    92  	}
    93  	if address.Addr != "" {
    94  		addr = address.Addr
    95  	}
    96  
    97  	conn, err = GetGrpcClientConn(addr, r.Timeout)
    98  	if err != nil {
    99  		return zeroClient, nil, err
   100  	}
   101  
   102  	return r.NewServiceClient(conn), conn, nil
   103  }
   104  
   105  func (r *Repository[T]) Close(conn *grpc.ClientConn) (err error) {
   106  	return conn.Close()
   107  }
   108  
   109  func newRepository[T any](ctx context.Context, fc FactoryConfig[T]) (Repository[T], error) {
   110  	conn, err := GetGrpcClientConn(fc.Addr, fc.Timeout, fc.DisablePrintInoutMethods...)
   111  	if err != nil {
   112  		return Repository[T]{}, err
   113  	}
   114  
   115  	repo := Repository[T]{
   116  		Timeout:                  fc.Timeout,
   117  		Addr:                     fc.Addr,
   118  		NewServiceClient:         fc.NewServiceClient,
   119  		Conn:                     conn,
   120  		Client:                   fc.NewServiceClient(conn),
   121  		RetryTimes:               fc.RetryTimes,
   122  		RetryInterval:            fc.RetryInterval,
   123  		DisablePrintInoutMethods: fc.DisablePrintInoutMethods,
   124  	}
   125  
   126  	return repo, nil
   127  }
   128  
   129  type Factory[T any] struct {
   130  	fc FactoryConfig[T]
   131  }
   132  
   133  func NewFactory[T any](fc FactoryConfig[T], configFuncs ...FactoryConfigFunc[T]) (Factory[T], error) {
   134  	err := fc.ApplyOptions(configFuncs...)
   135  	if err != nil {
   136  		return Factory[T]{}, err
   137  	}
   138  
   139  	err = fc.Validate()
   140  	if err != nil {
   141  		return Factory[T]{}, err
   142  	}
   143  
   144  	return Factory[T]{fc: fc}, nil
   145  }
   146  
   147  func (f Factory[T]) NewClient(ctx context.Context) (Repository[T], error) {
   148  	return newRepository(ctx, f.fc)
   149  }