Skip to content

Commit

Permalink
Fix race condition (#426)
Browse files Browse the repository at this point in the history
  • Loading branch information
zacharyfox authored Aug 3, 2023
1 parent a14bfaf commit cd2141b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
8 changes: 8 additions & 0 deletions partition_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package goka
import (
"context"
"fmt"
"sync"
"time"

"github.com/Shopify/sarama"
Expand Down Expand Up @@ -137,27 +138,34 @@ func (p *PartitionTable) loadRestarting(ctx context.Context, stopAfterCatchup bo
var (
resetTimer *time.Timer
retries int
retryMux sync.Mutex
)

for {
err := p.load(ctx, stopAfterCatchup)
if err != nil {
p.log.Printf("Error while starting up: %v", err)

retryMux.Lock()
retries++
retryMux.Unlock()
if resetTimer != nil {
resetTimer.Stop()
}
resetTimer = time.AfterFunc(p.backoffResetTimeout, func() {
p.backoff.Reset()
retryMux.Lock()
retries = 0
retryMux.Unlock()
})
} else {
return nil
}

retryDuration := p.backoff.Duration()
retryMux.Lock()
p.log.Printf("Will retry in %.0f seconds (retried %d times so far)", retryDuration.Seconds(), retries)
retryMux.Unlock()
select {
case <-ctx.Done():
return nil
Expand Down
11 changes: 10 additions & 1 deletion simple_backoff.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package goka

import "time"
import (
"sync"
"time"
)

// NewSimpleBackoff returns a simple backoff waiting the
// specified duration longer each iteration until reset.
Expand All @@ -12,16 +15,22 @@ func NewSimpleBackoff(step time.Duration, max time.Duration) Backoff {
}

type simpleBackoff struct {
sync.Mutex

current time.Duration
step time.Duration
max time.Duration
}

func (b *simpleBackoff) Reset() {
b.Lock()
defer b.Unlock()
b.current = time.Duration(0)
}

func (b *simpleBackoff) Duration() time.Duration {
b.Lock()
defer b.Unlock()
value := b.current

if (b.current + b.step) <= b.max {
Expand Down

0 comments on commit cd2141b

Please sign in to comment.