avoid sleep to ctx done during retry (#27992)

Signed-off-by: Wei Liu <wei.liu@zilliz.com>
pull/28083/head
wei liu 2023-11-01 18:52:24 +08:00 committed by GitHub
parent a1033604d7
commit 3b8fbbd91d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 0 deletions

View File

@ -53,6 +53,12 @@ func Do(ctx context.Context, fn func() error, opts ...Option) error {
return el
}
deadline, ok := ctx.Deadline()
if ok && time.Until(deadline) < c.sleep {
// to avoid sleep until ctx done
return el
}
select {
case <-time.After(c.sleep):
case <-ctx.Done():

View File

@ -63,6 +63,12 @@ func TestMaxSleepTime(t *testing.T) {
err := Do(ctx, testFn, Attempts(3), MaxSleepTime(200*time.Millisecond))
assert.Error(t, err)
t.Log(err)
ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
defer cancel()
err = Do(ctx, testFn, Attempts(10), MaxSleepTime(200*time.Millisecond))
assert.Error(t, err)
assert.Nil(t, ctx.Err())
}
func TestSleep(t *testing.T) {