-
Notifications
You must be signed in to change notification settings - Fork 99
/
retry.go
89 lines (73 loc) · 2.39 KB
/
retry.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package sender
import (
"crypto/rand"
"math/big"
"sync"
"time"
goutils "github.com/berachain/go-utils/utils"
"github.com/ethereum/go-ethereum/common"
coretypes "github.com/ethereum/go-ethereum/core/types"
)
const (
maxRetriesPerTx = 3 // TODO: read from config.
backoffStart = 500 * time.Millisecond // TODO: read from config.
backoffMultiplier = 2 // TODO: read from config.
maxBackoff = 3 * time.Second // TODO: read from config.
jitterRange = 1000 // TODO: read from config.
)
var (
_ retryPolicy = (*noRetryPolicy)(nil)
_ retryPolicy = (*expoRetryPolicy)(nil)
)
// noRetryPolicy does not retry transactions.
type noRetryPolicy struct{}
func (*noRetryPolicy) Get(*coretypes.Transaction, error) (bool, time.Duration) {
return false, 0
}
func (*noRetryPolicy) UpdateTxModified(common.Hash, common.Hash) {}
// expoRetryPolicy is a RetryPolicy that does an exponential backoff until maxRetries is
// reached. This does not assume anything about whether the specifc tx should be retried.
type expoRetryPolicy struct {
retries sync.Map
}
func (erp *expoRetryPolicy) Get(tx *coretypes.Transaction, err error) (bool, time.Duration) {
var (
txHash = tx.Hash()
tri *txRetryInfo
jitter time.Duration
)
// If the retry error is nil, the transaction was retried successfully.
if err == nil {
erp.retries.Delete(txHash)
return false, 0
}
txri, found := erp.retries.Load(txHash)
if !found {
tri = &txRetryInfo{backoff: backoffStart}
erp.retries.Store(txHash, tri)
} else if tri = goutils.MustGetAs[*txRetryInfo](txri); tri.numRetries >= maxRetriesPerTx {
erp.retries.Delete(txHash)
return false, 0
}
tri.numRetries++
// Exponential backoff with jitter.
if random, _ := rand.Int(rand.Reader, big.NewInt(jitterRange)); random != nil {
jitter = time.Duration(random.Int64()) * time.Millisecond
}
waitTime := tri.backoff + jitter
if tri.backoff *= backoffMultiplier; tri.backoff > maxBackoff {
tri.backoff = maxBackoff
}
return true, waitTime
}
func (erp *expoRetryPolicy) UpdateTxModified(oldTx, newTx common.Hash) {
if txri, found := erp.retries.Load(oldTx); found {
erp.retries.Delete(oldTx)
erp.retries.Store(newTx, txri)
}
}
// txRetryInfo contains the necessary information to determine if a transaction should be retried.
type txRetryInfo struct {
numRetries int
backoff time.Duration
}