Skip to content

Commit

Permalink
Merge pull request agola-io#66 from sgotti/util_backoff_use_context
Browse files Browse the repository at this point in the history
util: use context in backoff
  • Loading branch information
sgotti authored Jul 26, 2019
2 parents 49d883b + 22debeb commit ef4c87c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
6 changes: 3 additions & 3 deletions internal/services/gateway/action/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,7 @@ func (h *ActionHandler) CreateRuns(ctx context.Context, req *CreateRunRequest) e
cacheGroup = req.User.ID + "-" + req.UserRunRepoUUID
}

data, filename, err := h.fetchConfigFiles(req.GitSource, req.RepoPath, req.CommitSHA)
data, filename, err := h.fetchConfigFiles(ctx, req.GitSource, req.RepoPath, req.CommitSHA)
if err != nil {
return util.NewErrInternal(errors.Errorf("failed to fetch config file: %w", err))
}
Expand Down Expand Up @@ -498,10 +498,10 @@ func (h *ActionHandler) CreateRuns(ctx context.Context, req *CreateRunRequest) e
return nil
}

func (h *ActionHandler) fetchConfigFiles(gitSource gitsource.GitSource, repopath, commitSHA string) ([]byte, string, error) {
func (h *ActionHandler) fetchConfigFiles(ctx context.Context, gitSource gitsource.GitSource, repopath, commitSHA string) ([]byte, string, error) {
var data []byte
var filename string
err := util.ExponentialBackoff(util.FetchFileBackoff, func() (bool, error) {
err := util.ExponentialBackoff(ctx, util.FetchFileBackoff, func() (bool, error) {
for _, filename = range []string{agolaDefaultJsonnetConfigFile, agolaDefaultJsonConfigFile, agolaDefaultYamlConfigFile} {
var err error
data, err = gitSource.GetFile(repopath, commitSHA, path.Join(agolaDefaultConfigDir, filename))
Expand Down
10 changes: 8 additions & 2 deletions internal/util/backoff.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package util

import (
"context"
"errors"
"math/rand"
"time"
Expand Down Expand Up @@ -87,15 +88,20 @@ type Backoff struct {
//
// If the condition never returns true, ErrWaitTimeout is returned. All other
// errors terminate immediately.
func ExponentialBackoff(backoff Backoff, condition ConditionFunc) error {
func ExponentialBackoff(ctx context.Context,backoff Backoff, condition ConditionFunc) error {
duration := backoff.Duration
for i := 0; i < backoff.Steps; i++ {
if i != 0 {
adjusted := duration
if backoff.Jitter > 0.0 {
adjusted = Jitter(duration, backoff.Jitter)
}
time.Sleep(adjusted)
sleepCh := time.NewTimer(adjusted).C
select {
case <-ctx.Done():
return nil
case <-sleepCh:
}
duration = time.Duration(float64(duration) * backoff.Factor)
}
if ok, err := condition(); err != nil || ok {
Expand Down

0 comments on commit ef4c87c

Please # to comment.