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

Commit

Permalink
Merge pull request #280 from libp2p/constructor-error-return
Browse files Browse the repository at this point in the history
add an error return value to the constructor
  • Loading branch information
marten-seemann authored Sep 8, 2021
2 parents 2dca30d + 7a8208f commit bde78ea
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
16 changes: 10 additions & 6 deletions swarm.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,19 +41,21 @@ var ErrAddrFiltered = errors.New("address filtered")
// ErrDialTimeout is returned when one a dial times out due to the global timeout
var ErrDialTimeout = errors.New("dial timed out")

type Option func(*Swarm)
type Option func(*Swarm) error

// WithConnectionGater sets a connection gater
func WithConnectionGater(gater connmgr.ConnectionGater) Option {
return func(s *Swarm) {
return func(s *Swarm) error {
s.gater = gater
return nil
}
}

// WithMetrics sets a metrics reporter
func WithMetrics(reporter metrics.Reporter) Option {
return func(s *Swarm) {
return func(s *Swarm) error {
s.bwc = reporter
return nil
}
}

Expand Down Expand Up @@ -114,7 +116,7 @@ type Swarm struct {
}

// NewSwarm constructs a Swarm.
func NewSwarm(local peer.ID, peers peerstore.Peerstore, opts ...Option) *Swarm {
func NewSwarm(local peer.ID, peers peerstore.Peerstore, opts ...Option) (*Swarm, error) {
ctx, cancel := context.WithCancel(context.Background())
s := &Swarm{
local: local,
Expand All @@ -129,13 +131,15 @@ func NewSwarm(local peer.ID, peers peerstore.Peerstore, opts ...Option) *Swarm {
s.notifs.m = make(map[network.Notifiee]struct{})

for _, opt := range opts {
opt(s)
if err := opt(s); err != nil {
return nil, err
}
}

s.dsync = newDialSync(s.dialWorkerLoop)
s.limiter = newDialLimiter(s.dialAddr)
s.backf.init(s.ctx)
return s
return s, nil
}

func (s *Swarm) Close() error {
Expand Down
5 changes: 4 additions & 1 deletion testing/testing.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package testing
import (
"testing"

"github.com/stretchr/testify/require"

csms "github.com/libp2p/go-conn-security-multistream"
"github.com/libp2p/go-libp2p-core/connmgr"
"github.com/libp2p/go-libp2p-core/control"
Expand Down Expand Up @@ -117,7 +119,8 @@ func GenSwarm(t *testing.T, opts ...Option) *swarm.Swarm {
if cfg.connectionGater != nil {
swarmOpts = append(swarmOpts, swarm.WithConnectionGater(cfg.connectionGater))
}
s := swarm.NewSwarm(p.ID, ps, swarmOpts...)
s, err := swarm.NewSwarm(p.ID, ps, swarmOpts...)
require.NoError(t, err)

upgrader := GenUpgrader(s)
upgrader.ConnGater = cfg.connectionGater
Expand Down

0 comments on commit bde78ea

Please sign in to comment.