@@ -62,6 +62,57 @@ function decode(buf, offset = 0) {
62
62
}
63
63
throw new RangeError ( "malformed or overflow varint" ) ;
64
64
}
65
+ class AssertionError extends Error {
66
+ name = "AssertionError" ;
67
+ constructor ( message ) {
68
+ super ( message ) ;
69
+ }
70
+ }
71
+ function assert ( expr , msg = "" ) {
72
+ if ( ! expr ) {
73
+ throw new AssertionError ( msg ) ;
74
+ }
75
+ }
76
+ class RetryError extends Error {
77
+ constructor ( cause , attempts ) {
78
+ super ( `Retrying exceeded the maxAttempts (${ attempts } ).` ) ;
79
+ this . name = "RetryError" ;
80
+ this . cause = cause ;
81
+ }
82
+ }
83
+ const defaultRetryOptions = {
84
+ multiplier : 2 ,
85
+ maxTimeout : 60000 ,
86
+ maxAttempts : 5 ,
87
+ minTimeout : 1000 ,
88
+ jitter : 1
89
+ } ;
90
+ async function retry ( fn , opts ) {
91
+ const options = {
92
+ ...defaultRetryOptions ,
93
+ ...opts
94
+ } ;
95
+ assert ( options . maxTimeout >= 0 , "maxTimeout is less than 0" ) ;
96
+ assert ( options . minTimeout <= options . maxTimeout , "minTimeout is greater than maxTimeout" ) ;
97
+ assert ( options . jitter <= 1 , "jitter is greater than 1" ) ;
98
+ let attempt = 0 ;
99
+ while ( true ) {
100
+ try {
101
+ return await fn ( ) ;
102
+ } catch ( error ) {
103
+ if ( attempt + 1 >= options . maxAttempts ) {
104
+ throw new RetryError ( error , options . maxAttempts ) ;
105
+ }
106
+ const timeout = _exponentialBackoffWithJitter ( options . maxTimeout , options . minTimeout , attempt , options . multiplier , options . jitter ) ;
107
+ await new Promise ( ( r ) => setTimeout ( r , timeout ) ) ;
108
+ }
109
+ attempt ++ ;
110
+ }
111
+ }
112
+ function _exponentialBackoffWithJitter ( cap , base , attempt , multiplier , jitter ) {
113
+ const exp = Math . min ( cap , base * multiplier ** attempt ) ;
114
+ return ( 1 - jitter * Math . random ( ) ) * exp ;
115
+ }
65
116
const typeofs = [
66
117
"string" ,
67
118
"number" ,
@@ -11692,6 +11743,7 @@ var $t = o4.FastestNodeClient, Vt = o4.HttpCachingChain, qt = o4.HttpChain, zt =
11692
11743
export { encodeHex as encodeHex } ;
11693
11744
export { decodeBase64 as decodeBase64 } ;
11694
11745
export { decode as decodeVarint } ;
11746
+ export { retry as retry } ;
11695
11747
export { CarBlockIterator as CarBlockIterator } ;
11696
11748
export { UnsupportedHashError as UnsupportedHashError , HashMismatchError as HashMismatchError , validateBlock as validateBlock } ;
11697
11749
export { ne1 as fetchBeaconByTime , zt as HttpChainClient , Vt as HttpCachingChain } ;
0 commit comments