Skip to content

Commit

Permalink
Pay technical debt
Browse files Browse the repository at this point in the history
  • Loading branch information
mbobakov committed Mar 29, 2023
1 parent 1adaa17 commit 54e5702
Show file tree
Hide file tree
Showing 17 changed files with 2,022 additions and 242 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
.idea/
go.sum
bin
51 changes: 51 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
.DEFAULT_GOAL := help

BIN_DIR = ${PWD}/bin

.PHONY: clean download tools lint test generate test-integration terraform-fmt

RED=$(shell tput -T xterm setaf 1)
GREEN=$(shell tput -T xterm setaf 2)
YELLOW=$(shell tput -T xterm setaf 3)
RESET=$(shell tput -T xterm sgr0)

DOCKER_IMAGE ?= connectivity_controller


export GOPRIVATE=github.com/reemote/*
export PATH := ${BIN_DIR}:$(PATH)

tools: ## Installing tools from tools.go
- echo Installing tools from tools.go
- cat tools.go | grep _ | awk -F'"' '{print $$2}' | xargs -tI % env GOBIN=${BIN_DIR} go install %

.PHONY: clean
clean: ## run all cleanup tasks
go clean ./...
rm -rf $(BIN_DIR)
rm -rf ./builds

test: generate ## Run unit tests
go test -count=1 -v ./...
@echo ""
@echo "${GREEN} All tests passed ✅"
@echo "${RESET}"

test-integration: ## Integration test
test-integration:
go test -timeout 300s -tags integration -v ./...
@echo ""
@echo "${GREEN} All tests passed ✅"
@echo "${RESET}"

lint: tools ## Run linter
${BIN_DIR}/golangci-lint --color=always run ./... -v --timeout 15m

generate: tools
# Because go generate doesn't support subschell we need to call it directly
- ./bin/moq -pkg consul -out ./mocks_grpc_test.go $$(go list -f '{{.Dir}}' google.golang.org/grpc/resolver) ClientConn
- go generate -x ./...

help: ## Display help screen
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / \
{printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)
9 changes: 6 additions & 3 deletions consul.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ func (r *resolvr) Close() {
r.cancelFunc()
}

//go:generate mockgen -package mocks -destination internal/mocks/resolverClientConn.go google.golang.org/grpc/resolver ClientConn
//go:generate mockgen -package mocks -destination internal/mocks/servicer.go -source consul.go servicer
//go:generate ./bin/moq -out mocks_test.go . servicer
type servicer interface {
Service(string, string, bool, *api.QueryOptions) ([]*api.ServiceEntry, *api.QueryMeta, error)
}
Expand Down Expand Up @@ -138,7 +137,11 @@ func populateEndpoints(ctx context.Context, clientConn resolver.ClientConn, inpu
conns = append(conns, resolver.Address{Addr: c})
}
sort.Sort(byAddressString(conns)) // Don't replace the same address list in the balancer
clientConn.UpdateState(resolver.State{Addresses: conns})
err := clientConn.UpdateState(resolver.State{Addresses: conns})
if err != nil {
grpclog.Errorf("[Consul resolver] Couldn't update client connection. error={%v}", err)
continue
}
case <-ctx.Done():
grpclog.Info("[Consul resolver] Watch has been finished")
return
Expand Down
90 changes: 33 additions & 57 deletions consul_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,59 +5,51 @@ import (
"testing"
"time"

"github.com/golang/mock/gomock"
"github.com/hashicorp/consul/api"
"github.com/mbobakov/grpc-consul-resolver/internal/mocks"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/resolver"
)

func TestPopulateEndpoints(t *testing.T) {
tests := []struct {
name string
input [][]string
wantCalls [][]resolver.Address
name string
input []string
wantCall []resolver.Address
}{
{"one",
[][]string{{"127.0.0.1:50051"}},
[][]resolver.Address{
[]resolver.Address{
{Addr: "127.0.0.1:50051"},
},
[]string{"127.0.0.1:50051"},
[]resolver.Address{
{Addr: "127.0.0.1:50051"},
},
},
{"sorted",
[][]string{
{"227.0.0.1:50051", "127.0.0.1:50051"},
},
[][]resolver.Address{
[]resolver.Address{
{Addr: "127.0.0.1:50051"},
{Addr: "227.0.0.1:50051"},
},
[]string{"227.0.0.1:50051", "127.0.0.1:50051"},
[]resolver.Address{
{Addr: "127.0.0.1:50051"},
{Addr: "227.0.0.1:50051"},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
var (
in = make(chan []string, len(tt.input))
)

fcc := mocks.NewMockClientConn(ctrl)
for _, aa := range tt.wantCalls {
fcc.EXPECT().UpdateState(resolver.State{Addresses: aa}).Times(1)
fcc := &ClientConnMock{
UpdateStateFunc: func(state resolver.State) error {
require.Equal(t, tt.wantCall, state.Addresses)
return nil
},
}

ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go populateEndpoints(ctx, fcc, in)
for _, i := range tt.input {
in <- i
}
in <- tt.input
time.Sleep(time.Millisecond)

require.Equal(t, 1, len(fcc.UpdateStateCalls()))
})
}
}
Expand All @@ -72,7 +64,7 @@ func TestWatchConsulService(t *testing.T) {
}{
{"simple", target{Service: "svc", Wait: time.Second},
[]*api.ServiceEntry{
&api.ServiceEntry{
{
Service: &api.AgentService{Address: "127.0.0.1", Port: 1024},
},
},
Expand All @@ -85,8 +77,6 @@ func TestWatchConsulService(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ctrl := gomock.NewController(t)
defer ctrl.Finish()

var (
got []string
Expand All @@ -101,34 +91,20 @@ func TestWatchConsulService(t *testing.T) {
}
}
}()
fconsul := mocks.NewMockservicer(ctrl)
fconsul.EXPECT().Service(tt.tgt.Service, tt.tgt.Tag, tt.tgt.Healthy, &api.QueryOptions{
WaitIndex: 0,
Near: tt.tgt.Near,
WaitTime: tt.tgt.Wait,
Datacenter: tt.tgt.Dc,
AllowStale: tt.tgt.AllowStale,
RequireConsistent: tt.tgt.RequireConsistent,
}).
Times(1).
Return(tt.services, &api.QueryMeta{LastIndex: 1}, tt.errorFromService)
fconsul.EXPECT().Service(tt.tgt.Service, tt.tgt.Tag, tt.tgt.Healthy, &api.QueryOptions{
WaitIndex: 1,
Near: tt.tgt.Near,
WaitTime: tt.tgt.Wait,
Datacenter: tt.tgt.Dc,
AllowStale: tt.tgt.AllowStale,
RequireConsistent: tt.tgt.RequireConsistent,
}).
Do(
func(svc string, tag string, h bool, opt *api.QueryOptions) ([]*api.ServiceEntry, *api.QueryMeta, error) {
if opt.WaitIndex > 0 {
select {}
}
return tt.services, &api.QueryMeta{LastIndex: 1}, tt.errorFromService
},
).Times(1).
Return(tt.services, &api.QueryMeta{LastIndex: 1}, tt.errorFromService)
fconsul := &servicerMock{
ServiceFunc: func(s1, s2 string, b bool, queryOptions *api.QueryOptions) ([]*api.ServiceEntry, *api.QueryMeta, error) {
require.Equal(t, tt.tgt.Service, s1)
require.Equal(t, tt.tgt.Tag, s2)
require.Equal(t, tt.tgt.Healthy, b)
require.Equal(t, tt.tgt.Near, queryOptions.Near)
require.Equal(t, tt.tgt.Wait, queryOptions.WaitTime)
require.Equal(t, tt.tgt.Dc, queryOptions.Datacenter)
require.Equal(t, tt.tgt.AllowStale, queryOptions.AllowStale)
require.Equal(t, tt.tgt.RequireConsistent, queryOptions.RequireConsistent)

return tt.services, &api.QueryMeta{LastIndex: 1}, tt.errorFromService
},
}

go watchConsulService(ctx, fconsul, tt.tgt, out)
time.Sleep(5 * time.Millisecond)
Expand Down
8 changes: 8 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
version: "3.8"
services:
consul:
image: hashicorp/consul:1.13
ports:
- "127.0.0.1:8500:8500"
command: agent -ui -client 0.0.0.0 -dev

Loading

0 comments on commit 54e5702

Please sign in to comment.