|
| 1 | +package jobs |
| 2 | + |
| 3 | +import ( |
| 4 | + "time" |
| 5 | + |
| 6 | + "github.com/scaleway/scaleway-sdk-go/internal/async" |
| 7 | + "github.com/scaleway/scaleway-sdk-go/internal/errors" |
| 8 | + "github.com/scaleway/scaleway-sdk-go/scw" |
| 9 | +) |
| 10 | + |
| 11 | +const ( |
| 12 | + defaultRetryInterval = 15 * time.Second |
| 13 | + defaultTimeout = 15 * time.Minute |
| 14 | +) |
| 15 | + |
| 16 | +type WaitForJobRunRequest struct { |
| 17 | + JobRunID string |
| 18 | + Region scw.Region |
| 19 | + Timeout *time.Duration |
| 20 | + RetryInterval *time.Duration |
| 21 | +} |
| 22 | + |
| 23 | +// WaitForJobRun waits for the job run to be in a "terminal state" before returning. |
| 24 | +// This function can be used to wait for a job run to fail for example. |
| 25 | +func (s *API) WaitForJobRun(req *WaitForJobRunRequest, opts ...scw.RequestOption) (*JobRun, error) { |
| 26 | + timeout := defaultTimeout |
| 27 | + if req.Timeout != nil { |
| 28 | + timeout = *req.Timeout |
| 29 | + } |
| 30 | + retryInterval := defaultRetryInterval |
| 31 | + if req.RetryInterval != nil { |
| 32 | + retryInterval = *req.RetryInterval |
| 33 | + } |
| 34 | + |
| 35 | + terminalStatus := map[JobRunState]struct{}{ |
| 36 | + JobRunStateSucceeded: {}, |
| 37 | + JobRunStateFailed: {}, |
| 38 | + JobRunStateCanceled: {}, |
| 39 | + } |
| 40 | + |
| 41 | + jobRun, err := async.WaitSync(&async.WaitSyncConfig{ |
| 42 | + Get: func() (interface{}, bool, error) { |
| 43 | + res, err := s.GetJobRun(&GetJobRunRequest{ |
| 44 | + JobRunID: req.JobRunID, |
| 45 | + Region: req.Region, |
| 46 | + }, opts...) |
| 47 | + |
| 48 | + if err != nil { |
| 49 | + return nil, false, err |
| 50 | + } |
| 51 | + _, isTerminal := terminalStatus[res.State] |
| 52 | + |
| 53 | + return res, isTerminal, nil |
| 54 | + }, |
| 55 | + Timeout: timeout, |
| 56 | + IntervalStrategy: async.LinearIntervalStrategy(retryInterval), |
| 57 | + }) |
| 58 | + if err != nil { |
| 59 | + return nil, errors.Wrap(err, "waiting for job run failed") |
| 60 | + } |
| 61 | + |
| 62 | + return jobRun.(*JobRun), nil |
| 63 | +} |
0 commit comments