Repository navigation
feat(task): add resumable retry #228
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| package task_test | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "github.com/flanksource/clicky/task" | ||
| ) | ||
|
|
||
| func ExampleRetryMessage() { | ||
| config := task.RetryConfig{OnError: func(ctx context.Context, request task.RetryRequest) (task.RetryDecision, error) { | ||
| // A terminal, approval broker, or web host can await the operator here. | ||
| return task.RetryDecision{Action: task.RetryResume, Message: "use the corrected configuration"}, nil | ||
| }} | ||
| err := task.Retry(context.Background(), config, func(ctx context.Context, attempt int) error { | ||
| if attempt == 1 { | ||
| return errors.New("invalid configuration") | ||
| } | ||
| fmt.Println(task.RetryMessage(ctx)) | ||
| return nil | ||
| }) | ||
| fmt.Println(err) | ||
| // Output: | ||
| // use the corrected configuration | ||
| // <nil> | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| package task | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "time" | ||
| ) | ||
|
|
||
| type RetryAction string | ||
|
|
||
| // RetryResume can resume after MaxRetries; RetryAutomatic keeps the bounded policy. | ||
| const ( | ||
| RetryAutomatic RetryAction = "automatic" | ||
| RetryResume RetryAction = "retry" | ||
| RetryFail RetryAction = "fail" | ||
| ) | ||
|
|
||
| type RetryRequest struct { | ||
| Attempt int `json:"attempt"` | ||
| Error string `json:"error"` | ||
| Automatic bool `json:"automatic"` | ||
| RemainingRetries int `json:"remainingRetries"` | ||
| Cause error `json:"-"` | ||
| } | ||
|
|
||
| type RetryDecision struct { | ||
| Action RetryAction `json:"action"` | ||
| Message string `json:"message,omitempty"` | ||
| } | ||
|
|
||
| type retryMessageKey struct{} | ||
|
|
||
| // RetryMessage is the user's message for the resumed attempt. It is never | ||
| // logged or included in snapshots; the operation decides how to use it. | ||
| func RetryMessage(ctx context.Context) string { | ||
| message, _ := ctx.Value(retryMessageKey{}).(string) | ||
| return message | ||
| } | ||
|
|
||
| func retryAfterError(ctx context.Context, config RetryConfig, attempt int, cause error) (context.Context, bool, error) { | ||
| if ctx.Err() != nil { | ||
| return ctx, false, errors.Join(cause, context.Cause(ctx)) | ||
| } | ||
| retryable := shouldRetryError(cause, config) | ||
| automatic := retryable && attempt <= config.MaxRetries | ||
| if config.OnError != nil { | ||
| decision, err := config.OnError(ctx, RetryRequest{Attempt: attempt, Error: cause.Error(), Cause: cause, Automatic: automatic, RemainingRetries: max(0, config.MaxRetries-attempt+1)}) | ||
| if err != nil { | ||
| return ctx, false, errors.Join(cause, fmt.Errorf("retry decision: %w", err)) | ||
| } | ||
| if ctx.Err() != nil { | ||
| return ctx, false, errors.Join(cause, context.Cause(ctx)) | ||
| } | ||
| switch decision.Action { | ||
| case RetryResume: | ||
| return context.WithValue(ctx, retryMessageKey{}, decision.Message), true, nil | ||
| case RetryFail: | ||
| return ctx, false, cause | ||
| case RetryAutomatic: | ||
| default: | ||
| return ctx, false, errors.Join(cause, fmt.Errorf("invalid retry decision %q", decision.Action)) | ||
| } | ||
| } | ||
| if !automatic { | ||
| if retryable && attempt > config.MaxRetries { | ||
| cause = fmt.Errorf("failed after %d attempts: %w", attempt, cause) | ||
| } | ||
| return ctx, false, cause | ||
| } | ||
| timer := time.NewTimer(config.Delay(attempt)) | ||
| defer timer.Stop() | ||
| select { | ||
| case <-timer.C: | ||
| return ctx, true, nil | ||
| case <-ctx.Done(): | ||
| return ctx, false, errors.Join(cause, context.Cause(ctx)) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| package task_test | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "sync/atomic" | ||
|
|
||
| "github.com/flanksource/clicky/task" | ||
| commonscontext "github.com/flanksource/commons/context" | ||
| . "github.com/onsi/ginkgo/v2" | ||
| . "github.com/onsi/gomega" | ||
| ) | ||
|
|
||
| var _ = Describe("Resumable retry", func() { | ||
| It("exposes the cause and passes user input to a resumed attempt after automatic retries are exhausted", func() { | ||
| cause := errors.New("the selected configuration is invalid") | ||
| message := "The configuration has been corrected; use the new settings." | ||
| var requests []task.RetryRequest | ||
| config := task.RetryConfig{MaxRetries: 0, OnError: func(_ context.Context, request task.RetryRequest) (task.RetryDecision, error) { | ||
| requests = append(requests, request) | ||
| return task.RetryDecision{Action: task.RetryResume, Message: message}, nil | ||
| }} | ||
| calls := 0 | ||
| err := task.Retry(context.Background(), config, func(ctx context.Context, attempt int) error { | ||
| calls++ | ||
| if attempt == 1 { | ||
| return cause | ||
| } | ||
| Expect(task.RetryMessage(ctx)).To(Equal(message)) | ||
| return nil | ||
| }) | ||
| Expect(err).NotTo(HaveOccurred()) | ||
| Expect(calls).To(Equal(2)) | ||
| Expect(requests).To(HaveLen(1)) | ||
| Expect(errors.Is(requests[0].Cause, cause)).To(BeTrue()) | ||
| Expect(requests[0].Error).To(Equal(cause.Error())) | ||
| Expect(requests[0].Automatic).To(BeFalse()) | ||
| }) | ||
| It("uses the same response seam for tracked tasks", func() { | ||
| var calls atomic.Int32 | ||
| config := task.RetryConfig{OnError: func(context.Context, task.RetryRequest) (task.RetryDecision, error) { | ||
| return task.RetryDecision{Action: task.RetryResume, Message: "continue"}, nil | ||
| }} | ||
| handle := task.StartTask("Resumable operation", func(ctx commonscontext.Context, _ *task.Task) (string, error) { | ||
| if calls.Add(1) == 1 { | ||
| return "", errors.New("operator input required") | ||
| } | ||
| return task.RetryMessage(ctx), nil | ||
| }, task.WithRetryConfig(config)) | ||
| result, err := handle.GetResult() | ||
| Expect(err).NotTo(HaveOccurred()) | ||
| Expect(result).To(Equal("continue")) | ||
| Expect(calls.Load()).To(Equal(int32(2))) | ||
| }) | ||
| It("preserves the original cause when the operator declines to retry", func() { | ||
| cause := errors.New("invalid project settings") | ||
| config := task.RetryConfig{OnError: func(context.Context, task.RetryRequest) (task.RetryDecision, error) { | ||
| return task.RetryDecision{Action: task.RetryFail}, nil | ||
| }} | ||
| Expect(task.Retry(context.Background(), config, func(context.Context, int) error { return cause })).To(MatchError(cause)) | ||
| }) | ||
| It("publishes the pending error and cancels a task waiting for an operator", func() { | ||
| waiting := make(chan struct{}) | ||
| cause := errors.New("credentials need attention") | ||
| config := task.RetryConfig{OnError: func(ctx context.Context, request task.RetryRequest) (task.RetryDecision, error) { | ||
| close(waiting) | ||
| <-ctx.Done() | ||
| return task.RetryDecision{}, context.Cause(ctx) | ||
| }} | ||
| handle := task.StartTask("Waiting operation", func(commonscontext.Context, *task.Task) (bool, error) { return false, cause }, task.WithRetryConfig(config), task.WithCancellationDrain()) | ||
| Eventually(waiting).Should(BeClosed()) | ||
| snapshot := task.SnapshotTask(handle.GetTask(), nil) | ||
| Expect(snapshot.Error).To(Equal(cause.Error())) | ||
| Expect(snapshot.Retry).NotTo(BeNil()) | ||
| Expect(snapshot.Retry.Error).To(Equal(cause.Error())) | ||
| handle.Cancel() | ||
| _, err := handle.GetResult() | ||
| Expect(err).To(HaveOccurred()) | ||
| Expect(handle.GetTask().Status()).To(Equal(task.StatusCancelled)) | ||
| Expect(task.SnapshotTask(handle.GetTask(), nil).Retry).To(BeNil()) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Script executed:
Repository: flanksource/clicky
Length of output: 6434
Script executed:
Repository: flanksource/clicky
Length of output: 18029
Script executed:
Repository: flanksource/clicky
Length of output: 3790
Web query:
github.com/flanksource/commons v1.59.0 context.Context Value method sourceResult:
Clear the resume message before an explicit automatic retry.
RetryResumestores the operator message in the context for the resumed attempt. If that attempt fails andOnErrorselectsRetryAutomatic,retryAfterErrorreturns the same context after the delay. The next attempt can therefore read the old message throughRetryMessage(ctx), although the message is documented for the resumed attempt only.Proposed fix
Committable suggestion