@@ -25,14 +25,15 @@ type retryConfig struct {
2525 WaitTimeBetweenRetries time.Duration
2626}
2727
28- func retry (operationName string , operationFn func () error , cfg retryConfig ) error {
28+ func retry [ T any ] (operationName string , operationFn func () ( T , error ) , cfg retryConfig ) ( T , error ) {
2929 var lastErr error
30+ var zero T
3031 startTime := time .Now ()
3132 attempt := 1
3233
3334 for {
3435 if cfg .MaxRetryTime > 0 && time .Since (startTime ) > cfg .MaxRetryTime {
35- return fmt .Errorf (
36+ return zero , fmt .Errorf (
3637 "gave up retrying operation `%s` on reaching max retry time %v, last error: %w" ,
3738 operationName ,
3839 cfg .MaxRetryTime ,
@@ -41,17 +42,17 @@ func retry(operationName string, operationFn func() error, cfg retryConfig) erro
4142 }
4243
4344 if cfg .MaxAttempts > 0 && attempt > cfg .MaxAttempts {
44- return fmt .Errorf (
45+ return zero , fmt .Errorf (
4546 "gave up retrying operation `%s` on reaching max retry attempts %d, last error: %w" ,
4647 operationName ,
4748 cfg .MaxAttempts ,
4849 lastErr ,
4950 )
5051 }
5152
52- err := operationFn ()
53+ str , err := operationFn ()
5354 if err == nil {
54- return nil
55+ return str , nil
5556 }
5657
5758 lastErr = err
@@ -63,7 +64,7 @@ func retry(operationName string, operationFn func() error, cfg retryConfig) erro
6364}
6465
6566// UnlimitedRetry retries an operation forever.
66- func UnlimitedRetry (operationName string , operation func () error ) error {
67+ func UnlimitedRetry [ T any ] (operationName string , operation func () ( T , error )) ( T , error ) {
6768 return retry (operationName , operation , retryConfig {
6869 MaxRetryTime : 0 ,
6970 MaxAttempts : 0 ,
@@ -72,7 +73,7 @@ func UnlimitedRetry(operationName string, operation func() error) error {
7273}
7374
7475// LimitedRetry retries an operation until max retry time or until max attempts.
75- func LimitedRetry (operationName string , operation func () error ) error {
76+ func LimitedRetry [ T any ] (operationName string , operation func () ( T , error )) ( T , error ) {
7677 return retry (operationName , operation , retryConfig {
7778 MaxRetryTime : defaultMaxRetryTime ,
7879 MaxAttempts : defaultMaxRetries ,
0 commit comments