Skip to content
This repository has been archived by the owner on May 26, 2022. It is now read-only.

Commit

Permalink
add an option for the TCP connection timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
marten-seemann committed Sep 25, 2021
1 parent 77bb853 commit 6141597
Showing 1 changed file with 14 additions and 7 deletions.
21 changes: 14 additions & 7 deletions tcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@ import (
manet "github.com/multiformats/go-multiaddr/net"
)

// DefaultConnectTimeout is the (default) maximum amount of time the TCP
// transport will spend on the initial TCP connect before giving up.
var DefaultConnectTimeout = 5 * time.Second
const defaultConnectTimeout = 5 * time.Second

var log = logging.Logger("tcp-tpt")

Expand Down Expand Up @@ -97,6 +95,12 @@ func DisableReuseport() Option {
return nil
}
}
func WithConnectionTimeout(d time.Duration) Option {
return func(tr *TcpTransport) error {
tr.connectTimeout = d
return nil
}
}

// TcpTransport is the TCP transport.
type TcpTransport struct {
Expand All @@ -108,7 +112,7 @@ type TcpTransport struct {
disableReuseport bool

// TCP connect timeout
ConnectTimeout time.Duration
connectTimeout time.Duration

reuse rtpt.Transport
}
Expand All @@ -118,7 +122,10 @@ var _ transport.Transport = &TcpTransport{}
// NewTCPTransport creates a tcp transport object that tracks dialers and listeners
// created. It represents an entire TCP stack (though it might not necessarily be).
func NewTCPTransport(upgrader *tptu.Upgrader, opts ...Option) (*TcpTransport, error) {
tr := &TcpTransport{Upgrader: upgrader, ConnectTimeout: DefaultConnectTimeout}
tr := &TcpTransport{
Upgrader: upgrader,
connectTimeout: defaultConnectTimeout, // can be set by using the WithConnectionTimeout option
}
for _, o := range opts {
if err := o(tr); err != nil {
return nil, err
Expand All @@ -137,9 +144,9 @@ func (t *TcpTransport) CanDial(addr ma.Multiaddr) bool {

func (t *TcpTransport) maDial(ctx context.Context, raddr ma.Multiaddr) (manet.Conn, error) {
// Apply the deadline iff applicable
if t.ConnectTimeout > 0 {
if t.connectTimeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, t.ConnectTimeout)
ctx, cancel = context.WithTimeout(ctx, t.connectTimeout)
defer cancel()
}

Expand Down

0 comments on commit 6141597

Please sign in to comment.