Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 82084fe

Browse files
committedOct 6, 2015
rate limit concurrent peer dials
License: MIT Signed-off-by: Jeromy <jeromyj@gmail.com>
1 parent bb8e231 commit 82084fe

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed
 

‎p2p/net/swarm/swarm_dial.go

+13
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,9 @@ var (
4444
// add loop back in Dial(.)
4545
const dialAttempts = 1
4646

47+
// dial at most 12 peers concurrently
48+
const concurrentPeerDials = 12
49+
4750
// DialTimeout is the amount of time each dial attempt has. We can think about making
4851
// this larger down the road, or putting more granular timeouts (i.e. within each
4952
// subcomponent of Dial)
@@ -77,6 +80,8 @@ type dialsync struct {
7780
// this way, we dont kick off N dials simultaneously.
7881
ongoing map[peer.ID]chan struct{}
7982
lock sync.Mutex
83+
84+
ratelimit chan struct{}
8085
}
8186

8287
// Lock governs the beginning of a dial attempt.
@@ -92,6 +97,7 @@ func (ds *dialsync) Lock(dst peer.ID) (bool, chan struct{}) {
9297
ds.lock.Lock()
9398
if ds.ongoing == nil { // init if not ready
9499
ds.ongoing = make(map[peer.ID]chan struct{})
100+
ds.ratelimit = make(chan struct{}, concurrentPeerDials)
95101
}
96102
wait, found := ds.ongoing[dst]
97103
if !found {
@@ -103,6 +109,9 @@ func (ds *dialsync) Lock(dst peer.ID) (bool, chan struct{}) {
103109
return false, wait
104110
}
105111

112+
// consume rate limiting token
113+
ds.ratelimit <- struct{}{}
114+
106115
// ok! you're signed up to dial!
107116
return true, nil
108117
}
@@ -115,6 +124,10 @@ func (ds *dialsync) Unlock(dst peer.ID) {
115124
if !found {
116125
panic("called dialDone with no ongoing dials to peer: " + dst.Pretty())
117126
}
127+
128+
// replace token for rate limiting
129+
<-ds.ratelimit
130+
118131
delete(ds.ongoing, dst) // remove ongoing dial
119132
close(wait) // release everyone else
120133
ds.lock.Unlock()

0 commit comments

Comments
 (0)
Please sign in to comment.