From bd035e9840c7f73b7218bf3e51ec610dc331ec44 Mon Sep 17 00:00:00 2001 From: Simone Gotti Date: Thu, 25 Jul 2019 15:55:52 +0200 Subject: [PATCH] util: use context in backoff --- internal/services/gateway/action/run.go | 6 +++--- internal/util/backoff.go | 10 ++++++++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/internal/services/gateway/action/run.go b/internal/services/gateway/action/run.go index 2f674d9..534a3c7 100644 --- a/internal/services/gateway/action/run.go +++ b/internal/services/gateway/action/run.go @@ -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)) } @@ -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)) diff --git a/internal/util/backoff.go b/internal/util/backoff.go index 0fe238a..2892b37 100644 --- a/internal/util/backoff.go +++ b/internal/util/backoff.go @@ -15,6 +15,7 @@ package util import ( + "context" "errors" "math/rand" "time" @@ -87,7 +88,7 @@ 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 { @@ -95,7 +96,12 @@ func ExponentialBackoff(backoff Backoff, condition ConditionFunc) error { 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 {