package grpc

import (
	"io"
	"net"
	"strings"
	"testing"
	"time"

	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/examples/route_guide/routeguide"
)

// TestGRPCGoIssue632 tests for a regression of the flow control bug described
// in grpc/grpc-go issue #632. https://github.com/grpc/grpc-go/issues/632
func TestGRPCGoIssue632(t *testing.T) {
	t.Skip("flaky test, see https://git-aws.internal.justin.tv/release/trace/issues/57")

	const (
		itemCount    = 100
		itemSize     = 1 << 10
		requestCount = 10000
		recvCount    = 2
	)

	errs := make(chan error, 1)

	lis, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatalf("Listen; err = %q", err)
	}
	defer lis.Close()

	s := grpc.NewServer()
	routeguide.RegisterRouteGuideServer(s, &guide{
		itemCount: itemCount,
		itemSize:  itemSize,
	})
	defer s.Stop()

	go func() {
		err = s.Serve(lis)
		if err != nil {
			select {
			case errs <- err:
			default:
			}
		}
	}()

	ctx := context.Background()
	ctx, _ = context.WithTimeout(ctx, 30*time.Second)
	defer func() {
		if ctx.Err() == context.DeadlineExceeded {
			t.Fatalf("test timed out")
		}
	}()

	cc, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure())
	if err != nil {
		t.Fatalf("Dial; err = %q", err)
	}
	cl := routeguide.NewRouteGuideClient(cc)

	for i := 0; i < requestCount; i++ {
		ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
		features, err := cl.ListFeatures(ctx, &routeguide.Rectangle{})
		if err != nil {
			t.Fatalf("ListFeatures; err = %q", err)
		}

		j := 0
	loop:
		for ; j < recvCount; j++ {
			_, err := features.Recv()
			if err != nil {
				if err == io.EOF {
					break loop
				}
				switch grpc.Code(err) {
				case codes.DeadlineExceeded:
					break loop
				default:
					t.Fatalf("Recv; err = %q", err)
				}
			}
		}
		cancel()
		<-ctx.Done()

		if j < recvCount {
			t.Errorf("got %d responses to request %d", j, i)
			break
		}
	}

	select {
	case err = <-errs:
	default:
	}
	if err != nil {
		t.Fatalf("err = %q", err)
	}
}

type guide struct {
	routeguide.RouteGuideServer

	itemSize  int
	itemCount int
}

func (s *guide) ListFeatures(req *routeguide.Rectangle, srv routeguide.RouteGuide_ListFeaturesServer) error {
	for i := 0; i < s.itemCount; i++ {
		err := srv.Send(&routeguide.Feature{
			Name: strings.Repeat("a", s.itemSize),
		})
		if err != nil {
			return err
		}
	}
	return nil
}
