github.com/safedep/dry@v0.0.0-20241016050132-a15651f0548b/retry/retry.go (about) 1 package retry 2 3 import ( 4 "errors" 5 "time" 6 ) 7 8 var ( 9 errInvalidRetryCount = errors.New("invalid retry count") 10 errInvalidSleepDuration = errors.New("must have a valid sleep") 11 ) 12 13 type RetryFuncArg struct { 14 // Total retries to be executed 15 Total int 16 17 // Current try count starting with 1 18 Current int 19 } 20 21 type RetriableFunc func(arg RetryFuncArg) error 22 23 type RetryConfig struct { 24 Count int 25 Sleep time.Duration 26 } 27 28 func InvokeWithRetry(config RetryConfig, f RetriableFunc) error { 29 if config.Count <= 0 { 30 return errInvalidRetryCount 31 } 32 33 now := time.Now() 34 if now.Add(config.Sleep) == now { 35 return errInvalidSleepDuration 36 } 37 38 var err error 39 for i := 0; i < config.Count; i += 1 { 40 err = f(RetryFuncArg{Total: config.Count, Current: (i + 1)}) 41 if err == nil { 42 break 43 } 44 45 time.Sleep(config.Sleep) 46 } 47 48 return err 49 }