github.com/thanos-io/thanos@v0.32.5/pkg/targets/proxy_test.go (about)

     1  // Copyright (c) The Thanos Authors.
     2  // Licensed under the Apache License 2.0.
     3  
     4  package targets
     5  
     6  import (
     7  	"context"
     8  	"io"
     9  	"os"
    10  	"testing"
    11  
    12  	"github.com/go-kit/log"
    13  	"github.com/pkg/errors"
    14  	"google.golang.org/grpc"
    15  
    16  	"github.com/thanos-io/thanos/pkg/store/storepb"
    17  	"github.com/thanos-io/thanos/pkg/targets/targetspb"
    18  )
    19  
    20  type testTargetsClient struct {
    21  	grpc.ClientStream
    22  	targetsErr, recvErr error
    23  	response            *targetspb.TargetsResponse
    24  	sentResponse        bool
    25  }
    26  
    27  func (t *testTargetsClient) String() string {
    28  	return "test"
    29  }
    30  
    31  func (t *testTargetsClient) Recv() (*targetspb.TargetsResponse, error) {
    32  	// A simulation of underlying grpc Recv behavior as per https://github.com/grpc/grpc-go/blob/7f2581f910fc21497091c4109b56d310276fc943/stream.go#L117-L125.
    33  	if t.recvErr != nil {
    34  		return nil, t.recvErr
    35  	}
    36  
    37  	if t.sentResponse {
    38  		return nil, io.EOF
    39  	}
    40  	t.sentResponse = true
    41  
    42  	return t.response, nil
    43  }
    44  
    45  func (t *testTargetsClient) Targets(ctx context.Context, in *targetspb.TargetsRequest, opts ...grpc.CallOption) (targetspb.Targets_TargetsClient, error) {
    46  	return t, t.targetsErr
    47  }
    48  
    49  var _ targetspb.TargetsClient = &testTargetsClient{}
    50  
    51  // TestProxyDataRace find the concurrent data race bug ( go test -race -run TestProxyDataRace -v ).
    52  func TestProxyDataRace(t *testing.T) {
    53  	logger := log.NewLogfmtLogger(os.Stderr)
    54  	p := NewProxy(logger, func() []targetspb.TargetsClient {
    55  		es := &testTargetsClient{
    56  			recvErr: errors.New("err"),
    57  		}
    58  		size := 100
    59  		endpoints := make([]targetspb.TargetsClient, 0, size)
    60  		for i := 0; i < size; i++ {
    61  			endpoints = append(endpoints, es)
    62  		}
    63  		return endpoints
    64  	})
    65  	req := &targetspb.TargetsRequest{
    66  		State:                   targetspb.TargetsRequest_ANY,
    67  		PartialResponseStrategy: storepb.PartialResponseStrategy_WARN,
    68  	}
    69  	s := &targetsServer{
    70  		ctx: context.Background(),
    71  	}
    72  	_ = p.Targets(req, s)
    73  }