Skip to content

Commit 3c72a7c

Browse files
authored
Merge pull request #351 from libp2p/fix/hanging-provide
Add timeout
2 parents 874e3d3 + 49ccd21 commit 3c72a7c

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

lookup.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"context"
55
"fmt"
66
"strings"
7+
"time"
78

89
"github.com/libp2p/go-libp2p-core/peer"
910

@@ -93,8 +94,10 @@ func (dht *IpfsDHT) GetClosestPeers(ctx context.Context, key string) (<-chan pee
9394
go func() {
9495
defer close(out)
9596
defer e.Done()
97+
timedCtx, cancel := context.WithTimeout(ctx, time.Minute)
98+
defer cancel()
9699
// run it!
97-
res, err := query.Run(ctx, tablepeers)
100+
res, err := query.Run(timedCtx, tablepeers)
98101
if err != nil {
99102
logger.Debugf("closestPeers query run error: %s", err)
100103
}

routing.go

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -408,7 +408,28 @@ func (dht *IpfsDHT) Provide(ctx context.Context, key cid.Cid, brdcst bool) (err
408408
return nil
409409
}
410410

411-
peers, err := dht.GetClosestPeers(ctx, key.KeyString())
411+
closerCtx := ctx
412+
if deadline, ok := ctx.Deadline(); ok {
413+
now := time.Now()
414+
timeout := deadline.Sub(now)
415+
416+
if timeout < 0 {
417+
// timed out
418+
return context.DeadlineExceeded
419+
} else if timeout < 10*time.Second {
420+
// Reserve 10% for the final put.
421+
deadline = deadline.Add(timeout / 10)
422+
} else {
423+
// Otherwise, reserve a second (we'll already be
424+
// connected so this should be fast).
425+
deadline = deadline.Add(-time.Second)
426+
}
427+
var cancel context.CancelFunc
428+
closerCtx, cancel = context.WithDeadline(ctx, deadline)
429+
defer cancel()
430+
}
431+
432+
peers, err := dht.GetClosestPeers(closerCtx, key.KeyString())
412433
if err != nil {
413434
return err
414435
}

0 commit comments

Comments
 (0)