Skip to content

Commit 91817e0

Browse files
authored
Merge pull request #21 from renaynay/retries
feat(p2p): Implement retries for requests
2 parents e40362f + b853f60 commit 91817e0

File tree

2 files changed

+40
-10
lines changed

2 files changed

+40
-10
lines changed

p2p/exchange.go

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -119,23 +119,50 @@ func (ex *Exchange[H]) Head(ctx context.Context) (H, error) {
119119
}
120120

121121
var (
122-
zero H
123-
headerCh = make(chan H)
122+
zero H
123+
124+
trustedPeers = ex.trustedPeers()
125+
headerCh = make(chan H, len(trustedPeers))
126+
// refers to number of times one trusted peer can be retried for
127+
// their head
128+
headRequestRetries = 5
129+
timeout = time.Millisecond * 150
124130
)
125131

126-
trustedPeers := ex.trustedPeers()
127132
// request head from each trusted peer
128133
for _, from := range trustedPeers {
129134
go func(from peer.ID) {
130-
// request ensures that the result slice will have at least one Header
131-
headers, err := ex.request(ctx, from, req)
135+
var err error
136+
137+
timer := time.NewTimer(timeout)
138+
defer timer.Stop()
139+
140+
for i := 0; i < headRequestRetries; i++ {
141+
// request ensures that the result slice will have at least one header
142+
headers, err := ex.request(ctx, from, req)
143+
if err == nil {
144+
headerCh <- headers[0]
145+
return
146+
}
147+
if !timer.Stop() {
148+
break
149+
}
150+
timer.Reset(timeout)
151+
152+
select {
153+
case <-ex.ctx.Done():
154+
return
155+
case <-ctx.Done():
156+
return
157+
case <-timer.C:
158+
}
159+
}
132160
if err != nil {
133161
log.Errorw("head request to trusted peer failed", "trustedPeer", from, "err", err)
134162
var zero H
135163
headerCh <- zero
136164
return
137165
}
138-
headerCh <- headers[0]
139166
}(from)
140167
}
141168

p2p/exchange_test.go

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -319,15 +319,18 @@ func TestExchange_HandleHeaderWithDifferentChainID(t *testing.T) {
319319
exchg, store := createP2PExAndServer(t, hosts[0], hosts[1])
320320
exchg.Params.chainID = "test"
321321

322-
_, err := exchg.Head(context.Background())
322+
ctx, cancel := context.WithTimeout(context.Background(), time.Second*1)
323+
t.Cleanup(cancel)
324+
325+
_, err := exchg.Head(ctx)
323326
require.Error(t, err)
324327

325-
_, err = exchg.GetByHeight(context.Background(), 1)
328+
_, err = exchg.GetByHeight(ctx, 1)
326329
require.Error(t, err)
327330

328-
h, err := store.GetByHeight(context.Background(), 1)
331+
h, err := store.GetByHeight(ctx, 1)
329332
require.NoError(t, err)
330-
_, err = exchg.Get(context.Background(), h.Hash())
333+
_, err = exchg.Get(ctx, h.Hash())
331334
require.Error(t, err)
332335
}
333336

0 commit comments

Comments
 (0)