Skip to content

Commit

Permalink
Add global options swarm.WithPerPeerLimit, swarm.WithFDLimit to contr…
Browse files Browse the repository at this point in the history
…ol dialLimiter
  • Loading branch information
millken committed Jun 6, 2022
1 parent 093adc2 commit 8085166
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 19 deletions.
18 changes: 0 additions & 18 deletions p2p/net/swarm/limiter.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ package swarm

import (
"context"
"os"
"strconv"
"sync"
"time"

Expand Down Expand Up @@ -47,22 +45,6 @@ type dialLimiter struct {

type dialfunc func(context.Context, peer.ID, ma.Multiaddr) (transport.CapableConn, error)

func newDialLimiter(df dialfunc) *dialLimiter {
fd := ConcurrentFdDials
if env := os.Getenv("LIBP2P_SWARM_FD_LIMIT"); env != "" {
if n, err := strconv.ParseInt(env, 10, 32); err == nil {
fd = int(n)
}
}
perPeerRateLimit := DefaultPerPeerRateLimit
if env := os.Getenv("LIBP2P_SWARM_PEER_RATE_LIMIT"); env != "" {
if n, err := strconv.ParseInt(env, 10, 32); err == nil {
perPeerRateLimit = int(n)
}
}
return newDialLimiterWithParams(df, fd, perPeerRateLimit)
}

func newDialLimiterWithParams(df dialfunc, fdLimit, perPeerLimit int) *dialLimiter {
return &dialLimiter{
fdLimit: fdLimit,
Expand Down
22 changes: 21 additions & 1 deletion p2p/net/swarm/swarm.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,20 @@ func WithResourceManager(m network.ResourceManager) Option {
}
}

func WithPerPeerLimit(perPeerLimit int) Option {
return func(s *Swarm) error {
s.perPeerLimit = perPeerLimit
return nil
}
}

func WithFDLimit(fdLimit int) Option {
return func(s *Swarm) error {
s.fdLimit = fdLimit
return nil
}
}

// Swarm is a connection muxer, allowing connections to other peers to
// be opened and closed, while still using the same Chan for all
// communication. The Chan sends/receives Messages, which note the
Expand Down Expand Up @@ -141,6 +155,10 @@ type Swarm struct {
ctxCancel context.CancelFunc

bwc metrics.Reporter

// dial limiter
perPeerLimit int
fdLimit int
}

// NewSwarm constructs a Swarm.
Expand All @@ -153,6 +171,8 @@ func NewSwarm(local peer.ID, peers peerstore.Peerstore, opts ...Option) (*Swarm,
ctxCancel: cancel,
dialTimeout: defaultDialTimeout,
dialTimeoutLocal: defaultDialTimeoutLocal,
perPeerLimit: DefaultPerPeerRateLimit,
fdLimit: ConcurrentFdDials,
}

s.conns.m = make(map[peer.ID][]*Conn)
Expand All @@ -170,7 +190,7 @@ func NewSwarm(local peer.ID, peers peerstore.Peerstore, opts ...Option) (*Swarm,
}

s.dsync = newDialSync(s.dialWorkerLoop)
s.limiter = newDialLimiter(s.dialAddr)
s.limiter = newDialLimiterWithParams(s.dialAddr, s.fdLimit, s.perPeerLimit)
s.backf.init(s.ctx)
return s, nil
}
Expand Down

0 comments on commit 8085166

Please sign in to comment.