From 9199a4c25bdd119372f5a02f2c8dec4853d5a42d Mon Sep 17 00:00:00 2001 From: ICHINOSE Shogo Date: Fri, 29 Dec 2023 17:26:34 +0900 Subject: [PATCH] use global rand functions --- .github/workflows/test.yml | 3 ++- rand.go | 21 +++++++++++++++++++++ rand_v2.go | 21 +++++++++++++++++++++ retry.go | 30 ------------------------------ 4 files changed, 44 insertions(+), 31 deletions(-) create mode 100644 rand.go create mode 100644 rand_v2.go diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 2fcc24a..daab423 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -10,7 +10,8 @@ jobs: strategy: matrix: go: - - "1" + - "stable" + - "1.22.0-rc.1" - "1.21" - "1.20" - "1.19" diff --git a/rand.go b/rand.go new file mode 100644 index 0000000..95f562d --- /dev/null +++ b/rand.go @@ -0,0 +1,21 @@ +//go:build !go1.22 +// +build !go1.22 + +package retry + +import ( + "math/rand" + "time" +) + +func (p *Policy) randomJitter() time.Duration { + jitter := int64(p.Jitter) + if jitter == 0 { + return 0 + } + + if jitter < 0 { + return -time.Duration(rand.Int63n(-jitter)) + } + return time.Duration(rand.Int63n(jitter)) +} diff --git a/rand_v2.go b/rand_v2.go new file mode 100644 index 0000000..39f2ee3 --- /dev/null +++ b/rand_v2.go @@ -0,0 +1,21 @@ +//go:build go1.22 +// +build go1.22 + +package retry + +import ( + "math/rand/v2" + "time" +) + +func (p *Policy) randomJitter() time.Duration { + jitter := p.Jitter + if jitter == 0 { + return 0 + } + + if jitter < 0 { + return -rand.N(-jitter) + } + return rand.N(jitter) +} diff --git a/retry.go b/retry.go index 233dbe7..a40e0df 100644 --- a/retry.go +++ b/retry.go @@ -2,11 +2,7 @@ package retry import ( "context" - crand "crypto/rand" - "encoding/binary" "errors" - "math/rand" - "sync" "time" ) @@ -28,9 +24,6 @@ type Policy struct { // Zero means no jitter. // Negative value shorten the delay. Jitter time.Duration - - mu sync.Mutex - rand *rand.Rand } // Retrier handles retrying. @@ -122,29 +115,6 @@ func MarkPermanent(err error) error { return &permanentError{err} } -func (p *Policy) randomJitter() time.Duration { - jitter := int64(p.Jitter) - if jitter == 0 { - return 0 - } - - p.mu.Lock() - defer p.mu.Unlock() - - if p.rand == nil { - // initialize rand using crypto/rand - var seed int64 - if err := binary.Read(crand.Reader, binary.LittleEndian, &seed); err != nil { - seed = time.Now().UnixNano() // fall back to timestamp - } - p.rand = rand.New(rand.NewSource(seed)) - } - if jitter < 0 { - return -time.Duration(p.rand.Int63n(-jitter)) - } - return time.Duration(p.rand.Int63n(jitter)) -} - // Continue returns whether retrying should be continued. func (r *Retrier) Continue() bool { r.count++