goresilience icon indicating copy to clipboard operation
goresilience copied to clipboard

Retries with context cancelled will continue to retry without calling user's function

Open csueiras opened this issue 3 years ago • 0 comments

The retry middleware will continue to retry even in the event of the context being cancelled.

r := retry.New(retry.Config{ Times: math.MaxInt32 })
ctx, cancel := context.WithCancel(context.TODO())
cancel() // context is now cancelled
// this will run forever even though the context is cancelled
r.Run(ctx, func(ctx context.Context) error {
  fmt.Println("Running user's function")
  return fmt.Errorf("error")
})

I realize that this might be a design choice, where the command under execution can decide to stop throwing errors if the context is cancelled, but the issue is that once the context is cancelled the command wrapper will no longer call the user's function:

// command is the unit of execution.
type command struct{}

// Run satisfies Runner interface.
func (command) Run(ctx context.Context, f Func) error {
	// Only execute if we reached to the execution and the context has not been cancelled.
	select {
	case <-ctx.Done():
		return errors.ErrContextCanceled
	default:
		return f(ctx)
	}
}

It will just continuously return errors.ErrContextCanceled which is unhandled in any special way in the retry middleware.

csueiras avatar Apr 11 '21 14:04 csueiras