From 8cae78cbf1222656e480b94128af64bb33ff89ed Mon Sep 17 00:00:00 2001 From: Matt Joiner Date: Mon, 17 Nov 2014 18:04:09 -0600 Subject: [PATCH] Reduce dial timeouts when there are lots of peers in the backlog --- client.go | 5 +++++ client_test.go | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/client.go b/client.go index c3e99d0c..d1d25288 100644 --- a/client.go +++ b/client.go @@ -387,6 +387,10 @@ func doDial(dial func() (net.Conn, error), ch chan dialResult, utp bool) { } } +func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) time.Duration { + return max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit) +} + // Start the process of connecting to the given peer for the given torrent if // appropriate. func (me *Client) initiateConn(peer Peer, t *torrent) { @@ -405,6 +409,7 @@ func (me *Client) initiateConn(peer Peer, t *torrent) { // this address so that peers associate our local address with our // listen address. + dialTimeout := reducedDialTimeout(dialTimeout, me.halfOpenLimit, len(t.Peers)) // Initiate connections via TCP and UTP simultaneously. Use the first // one that succeeds. left := 2 diff --git a/client_test.go b/client_test.go index 3dcb6c34..05d08e69 100644 --- a/client_test.go +++ b/client_test.go @@ -3,6 +3,7 @@ package torrent import ( "os" "testing" + "time" "bitbucket.org/anacrolix/go.torrent/testutil" "bitbucket.org/anacrolix/go.torrent/util" @@ -75,3 +76,24 @@ func TestUnmarshalPEXMsg(t *testing.T) { t.FailNow() } } + +func TestReducedDialTimeout(t *testing.T) { + for _, _case := range []struct { + Max time.Duration + HalfOpenLimit int + PendingPeers int + ExpectedReduced time.Duration + }{ + {dialTimeout, 40, 0, dialTimeout}, + {dialTimeout, 40, 1, dialTimeout}, + {dialTimeout, 40, 39, dialTimeout}, + {dialTimeout, 40, 40, dialTimeout / 2}, + {dialTimeout, 40, 80, dialTimeout / 3}, + {dialTimeout, 40, 4000, dialTimeout / 101}, + } { + reduced := reducedDialTimeout(_case.Max, _case.HalfOpenLimit, _case.PendingPeers) + if reduced != _case.ExpectedReduced { + t.Fatalf("expected %s, got %s", _case.ExpectedReduced, reduced) + } + } +} -- 2.48.1