Skip to content

Commit

Permalink
Fix: handle invalid endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
mtojek committed Nov 25, 2018
1 parent 3c40934 commit 1b4d62a
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 2 deletions.
9 changes: 7 additions & 2 deletions closest/regions.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import (
const measureRepeats = 5

var (
errEndpointsUnavailable = errors.New("service endpoints are unavailable")
errAllEndpointsUnavailable = errors.New("all service endpoints are unavailable")
errRegionalServiceEndpointUnavailable = errors.New("regional service endpoint is unavailable")

httpClient = http.Client{Timeout: 30 * time.Second}
)
Expand All @@ -38,7 +39,7 @@ func (r *Regions) FindClosest(endpoints Endpoints) (string, error) {
}

if len(latencies) == 0 {
return "", errEndpointsUnavailable
return "", errAllEndpointsUnavailable
}

theRegion, theLatency := r.regionWithLowestLatency(latencies)
Expand All @@ -65,6 +66,10 @@ func (r *Regions) measureLatency(endpoint string) (time.Duration, error) {
response.Body.Close()
}
}

if c == 0 {
return -1, errRegionalServiceEndpointUnavailable
}
return time.Duration(sum / c), nil
}

Expand Down
52 changes: 52 additions & 0 deletions closest/regions_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package closest

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestRegions_FindClosest_ValidEndpoints(t *testing.T) {
// given
regions := new(Regions)
endpoints := Endpoints{}
endpoints["slower_endpoint"] = "http://httpbin.org/delay/3"
endpoints["slow_endpoint"] = "http://httpbin.org/delay/1"
endpoints["slowest_endpoint"] = "http://httpbin.org/delay/5"

// when
region, err := regions.FindClosest(endpoints)

// then
assert.Equal(t, "slow_endpoint", region, "faster region should be reported")
assert.Nil(t, err, "no error should be returned")
}

func TestRegions_FindClosest_BothValidInvalidEndpoints(t *testing.T) {
// given
regions := new(Regions)
endpoints := Endpoints{}
endpoints["slow_endpoint"] = "http://httpbin.org/delay/1"
endpoints["wrong_endpoint"] = "http://localhost:57585"

// when
region, err := regions.FindClosest(endpoints)

// then
assert.Equal(t, "slow_endpoint", region, "faster region should be reported")
assert.Nil(t, err, "no error should be returned")
}

func TestRegions_FindClosest_InvalidEndpoints(t *testing.T) {
// given
regions := new(Regions)
endpoints := Endpoints{}
endpoints["wrong_endpoint"] = "http://localhost:69695"

// when
region, err := regions.FindClosest(endpoints)

// then
assert.NotNil(t, err, "an error should be returned")
assert.Empty(t, region, "no endpoint should be returned")
}

0 comments on commit 1b4d62a

Please sign in to comment.