github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/module/retrymiddleware/after_consecutive_failures.go (about)

     1  package retrymiddleware
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/sethvargo/go-retry"
     7  )
     8  
     9  // OnMaxConsecutiveFailures func that gets invoked when max consecutive failures has been reached
    10  type OnMaxConsecutiveFailures func(currentAttempt int)
    11  
    12  // AfterConsecutiveFailures returns a retry middleware will invoke the OnMaxConsecutiveFailures callback when ever maxConsecutiveFailures
    13  // has been reached for a retry operation
    14  func AfterConsecutiveFailures(maxConsecutiveFailures int, next retry.Backoff, f OnMaxConsecutiveFailures) retry.Backoff {
    15  	var attempt int
    16  
    17  	return retry.BackoffFunc(func() (time.Duration, bool) {
    18  		attempt++
    19  
    20  		// if we have reached maxConsecutiveFailures failures update client index
    21  		if attempt%maxConsecutiveFailures == 0 {
    22  			//invoke f with current attempt
    23  			f(attempt)
    24  		}
    25  
    26  		val, stop := next.Next()
    27  		if stop {
    28  			return 0, true
    29  		}
    30  
    31  		return val, false
    32  	})
    33  }