Skip to content

Commit

Permalink
Fix bad Next behaviour (#53)
Browse files Browse the repository at this point in the history
  • Loading branch information
cristaloleg committed Sep 15, 2023
1 parent 021644b commit a7cd913
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
6 changes: 5 additions & 1 deletion hedged.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,9 +174,13 @@ func (ht *hedgedTransport) RoundTrip(req *http.Request) (*http.Response, error)
}

// no hedged requests, just a regular one.
if upto == 0 {
if upto <= 0 {
return ht.rt.RoundTrip(req)
}
// rollback to default timeout.
if timeout < 0 {
timeout = ht.timeout
}

errOverall := &MultiError{}
resultCh := make(chan indexedResp, upto)
Expand Down
60 changes: 60 additions & 0 deletions hedged_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,66 @@ func TestClient(t *testing.T) {
mustTrue(t, took >= handlerSleep && took < (handlerSleep+10*time.Millisecond))
}

func TestClientBadNextUpto(t *testing.T) {
const handlerSleep = 100 * time.Millisecond
url := testServerURL(t, func(w http.ResponseWriter, r *http.Request) {
time.Sleep(handlerSleep)
})

cfg := hedgedhttp.Config{
Transport: http.DefaultTransport,
Upto: 2,
Delay: 50 * time.Millisecond,
Next: func() (upto int, delay time.Duration) {
return -1, 10 * time.Millisecond
},
}
client, err := hedgedhttp.New(cfg)
mustOk(t, err)

start := time.Now()
resp, err := client.Do(newGetReq(url))
took := time.Since(start)
mustOk(t, err)
defer resp.Body.Close()
mustTrue(t, resp != nil)
mustEqual(t, resp.StatusCode, http.StatusOK)

stats := client.Stats()
mustEqual(t, stats.ActualRoundTrips(), uint64(0))
mustTrue(t, took >= handlerSleep && took < (handlerSleep+10*time.Millisecond))
}

func TestClientBadNextDelay(t *testing.T) {
const handlerSleep = 100 * time.Millisecond
url := testServerURL(t, func(w http.ResponseWriter, r *http.Request) {
time.Sleep(handlerSleep)
})

cfg := hedgedhttp.Config{
Transport: http.DefaultTransport,
Upto: 2,
Delay: 150 * time.Millisecond,
Next: func() (upto int, delay time.Duration) {
return 2, -10 * time.Millisecond
},
}
client, err := hedgedhttp.New(cfg)
mustOk(t, err)

start := time.Now()
resp, err := client.Do(newGetReq(url))
took := time.Since(start)
mustOk(t, err)
defer resp.Body.Close()
mustTrue(t, resp != nil)
mustEqual(t, resp.StatusCode, http.StatusOK)

stats := client.Stats()
mustEqual(t, stats.ActualRoundTrips(), uint64(1))
mustTrue(t, took >= handlerSleep && took < (handlerSleep+10*time.Millisecond))
}

func TestValidateInput(t *testing.T) {
var err error
_, err = hedgedhttp.New(hedgedhttp.Config{
Expand Down

0 comments on commit a7cd913

Please sign in to comment.