istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/backoff/exponential.go (about)

     1  // Copyright Istio Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package backoff is a wrapper of `github.com/cenkalti/backoff/v4`.
    16  // It is to prevent misuse of `github.com/cenkalti/backoff/v4`,
    17  // thus application could fall into dead loop.
    18  package backoff
    19  
    20  import (
    21  	"context"
    22  	"fmt"
    23  	"time"
    24  
    25  	"github.com/cenkalti/backoff/v4"
    26  )
    27  
    28  // BackOff is a backoff policy for retrying an operation.
    29  type BackOff interface {
    30  	// NextBackOff returns the duration to wait before retrying the next operation.
    31  	NextBackOff() time.Duration
    32  	// Reset to initial state.
    33  	Reset()
    34  	// RetryWithContext tries the operation until it does not return error,
    35  	// or when the context expires, whichever happens first.
    36  	RetryWithContext(ctx context.Context, operation func() error) error
    37  }
    38  
    39  type Option struct {
    40  	InitialInterval time.Duration
    41  	MaxInterval     time.Duration
    42  }
    43  
    44  // ExponentialBackOff is a wrapper of backoff.ExponentialBackOff to override its NextBackOff().
    45  type ExponentialBackOff struct {
    46  	exponentialBackOff *backoff.ExponentialBackOff
    47  }
    48  
    49  // Default values for ExponentialBackOff.
    50  const (
    51  	defaultInitialInterval = 500 * time.Millisecond
    52  	defaultMaxInterval     = 60 * time.Second
    53  )
    54  
    55  func DefaultOption() Option {
    56  	return Option{
    57  		InitialInterval: defaultInitialInterval,
    58  		MaxInterval:     defaultMaxInterval,
    59  	}
    60  }
    61  
    62  // NewExponentialBackOff creates an istio wrapped ExponentialBackOff.
    63  // By default, it never stops.
    64  func NewExponentialBackOff(o Option) BackOff {
    65  	b := ExponentialBackOff{}
    66  	b.exponentialBackOff = backoff.NewExponentialBackOff()
    67  	b.exponentialBackOff.InitialInterval = o.InitialInterval
    68  	b.exponentialBackOff.MaxInterval = o.MaxInterval
    69  	b.Reset()
    70  	return b
    71  }
    72  
    73  func (b ExponentialBackOff) NextBackOff() time.Duration {
    74  	duration := b.exponentialBackOff.NextBackOff()
    75  	// always return maxInterval after it reaches MaxElapsedTime
    76  	if duration == b.exponentialBackOff.Stop {
    77  		return b.exponentialBackOff.MaxInterval
    78  	}
    79  	return duration
    80  }
    81  
    82  func (b ExponentialBackOff) Reset() {
    83  	b.exponentialBackOff.Reset()
    84  }
    85  
    86  // RetryWithContext tries the operation until it does not return error,
    87  // or when the context expires, whichever happens first.
    88  // o is guaranteed to be run at least once.
    89  // RetryWithContext sleeps the goroutine for the duration returned by BackOff after a
    90  // failed operation returns.
    91  func (b ExponentialBackOff) RetryWithContext(ctx context.Context, operation func() error) error {
    92  	b.Reset()
    93  	for {
    94  		err := operation()
    95  		if err == nil {
    96  			return nil
    97  		}
    98  		next := b.NextBackOff()
    99  		select {
   100  		case <-ctx.Done():
   101  			return fmt.Errorf("%v with last error: %v", context.DeadlineExceeded, err)
   102  		case <-time.After(next):
   103  		}
   104  	}
   105  }