-
-
Notifications
You must be signed in to change notification settings - Fork 66
/
transaction.go
48 lines (41 loc) · 848 Bytes
/
transaction.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
package dht
import (
"context"
"errors"
"fmt"
"time"
"github.com/anacrolix/dht/v2/krpc"
)
var TransactionTimeout = errors.New("transaction timed out")
// Transaction keeps track of a message exchange between nodes, such as a
// query message and a response message.
type transaction struct {
onResponse func(krpc.Msg)
}
func (t *transaction) handleResponse(m krpc.Msg) {
t.onResponse(m)
}
const defaultMaxQuerySends = 1
func transactionSender(
ctx context.Context,
send func() error,
resendDelay func() time.Duration,
maxSends int,
) error {
var delay time.Duration
sends := 0
for sends < maxSends {
select {
case <-time.After(delay):
err := send()
sends++
if err != nil {
return fmt.Errorf("send %d: %w", sends, err)
}
delay = resendDelay()
case <-ctx.Done():
return ctx.Err()
}
}
return nil
}