Skip to content

Commit

Permalink
swarm: add a default timeout to conn.NewStream (#2907)
Browse files Browse the repository at this point in the history
  • Loading branch information
sukunrt committed Aug 5, 2024
1 parent e2e0d29 commit a7939fa
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
2 changes: 2 additions & 0 deletions p2p/net/swarm/swarm.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ const (
// This includes the time between dialing the raw network connection,
// protocol selection as well the handshake, if applicable.
defaultDialTimeoutLocal = 5 * time.Second

defaultNewStreamTimeout = 15 * time.Second
)

var log = logging.Logger("swarm2")
Expand Down
9 changes: 9 additions & 0 deletions p2p/net/swarm/swarm_conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,9 +209,18 @@ func (c *Conn) NewStream(ctx context.Context) (network.Stream, error) {
return nil, err
}

if _, ok := ctx.Deadline(); !ok {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, defaultNewStreamTimeout)
defer cancel()
}

s, err := c.openAndAddStream(ctx, scope)
if err != nil {
scope.Done()
if errors.Is(err, context.DeadlineExceeded) {
err = fmt.Errorf("timed out: %w", err)
}
return nil, err
}
return s, nil
Expand Down

0 comments on commit a7939fa

Please sign in to comment.