Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add timeout #351

Merged
merged 2 commits into from
Jun 30, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion lookup.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"strings"
"time"

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

Expand Down Expand Up @@ -93,8 +94,10 @@ func (dht *IpfsDHT) GetClosestPeers(ctx context.Context, key string) (<-chan pee
go func() {
defer close(out)
defer e.Done()
timedCtx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
// run it!
res, err := query.Run(ctx, tablepeers)
res, err := query.Run(timedCtx, tablepeers)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Stebalien is this what you're talking about?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Exactly! If we want to get fancy, we could even get the deadline from the context and subtract 1(?) second (we should be connected to the closest peers when this command returns.

Yay for arbitrary constants!

if err != nil {
logger.Debugf("closestPeers query run error: %s", err)
}
Expand Down
23 changes: 22 additions & 1 deletion routing.go
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,28 @@ func (dht *IpfsDHT) Provide(ctx context.Context, key cid.Cid, brdcst bool) (err
return nil
}

peers, err := dht.GetClosestPeers(ctx, key.KeyString())
closerCtx := ctx
if deadline, ok := ctx.Deadline(); ok {
now := time.Now()
timeout := deadline.Sub(now)

if timeout < 0 {
// timed out
return context.DeadlineExceeded
} else if timeout < 10*time.Second {
// Reserve 10% for the final put.
deadline = deadline.Add(timeout / 10)
} else {
// Otherwise, reserve a second (we'll already be
// connected so this should be fast).
deadline = deadline.Add(-time.Second)
}
var cancel context.CancelFunc
closerCtx, cancel = context.WithDeadline(ctx, deadline)
defer cancel()
}

peers, err := dht.GetClosestPeers(closerCtx, key.KeyString())
if err != nil {
return err
}
Expand Down