Skip to content

Commit

Permalink
minor backoff refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
arriven committed Mar 28, 2022
1 parent 8b7da01 commit a805c4a
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 17 deletions.
3 changes: 2 additions & 1 deletion src/jobs/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,9 +158,10 @@ func fastHTTPJob(ctx context.Context, logger *zap.Logger, globalConfig *GlobalCo

if err := sendFastHTTPRequest(client, req, nil); err != nil {
logger.Debug("error sending request", zap.Error(err), zap.Any("args", args))
backoffController.Handle(ctx, err)
utils.Sleep(ctx, backoffController.Increment().GetTimeout())
} else {
processedTrafficMonitor.Add(uint64(dataSize))
backoffController.Reset()
}
}

Expand Down
6 changes: 5 additions & 1 deletion src/jobs/rawnet.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,11 @@ func tcpJob(ctx context.Context, logger *zap.Logger, globalConfig *GlobalConfig,

for jobConfig.Next(ctx) {
err = sendTCP(ctx, logger, jobConfig, trafficMonitor, processedTrafficMonitor)
backoffController.Handle(ctx, err)
if err != nil {
utils.Sleep(ctx, backoffController.Increment().GetTimeout())
} else {
backoffController.Reset()
}
}

return nil, nil
Expand Down
20 changes: 6 additions & 14 deletions src/utils/backoff.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func NewBackoffController(c *BackoffConfig) BackoffController {
return BackoffController{BackoffConfig: DefaultBackoffConfig()}
}

func (c BackoffController) getTimeout() time.Duration {
func (c BackoffController) GetTimeout() time.Duration {
result := c.Timeout
for i := 0; i < c.count; i++ {
result *= time.Duration(c.Multiplier)
Expand All @@ -51,25 +51,17 @@ func (c BackoffController) getTimeout() time.Duration {
return result
}

func (c *BackoffController) increment() {
func (c *BackoffController) Increment() *BackoffController {
if c.count < c.Limit {
c.count++
}
}

func (c *BackoffController) reset() {
c.count = 0
// return pointer to itself for usability
return c
}

func (c *BackoffController) Handle(ctx context.Context, err error) {
if err == nil {
c.reset()

return
}

c.increment()
Sleep(ctx, c.getTimeout())
func (c *BackoffController) Reset() {
c.count = 0
}

type Counter struct {
Expand Down
2 changes: 1 addition & 1 deletion src/utils/countrychecker.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func CheckCountry(countriesToAvoid []string, strictCountryCheck bool) (bool, str
log.Printf("Checking IP address, attempt #%d", counter.iter)

if country, ip, err = fetchLocationInfo(); err != nil {
backoffController.Handle(context.Background(), err)
Sleep(context.Background(), backoffController.Increment().GetTimeout())
}
}

Expand Down

0 comments on commit a805c4a

Please sign in to comment.