Skip to content

Commit

Permalink
feat: Add WithFxOption
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoPolo committed Oct 22, 2024
1 parent 3d63fd6 commit 0e76f3d
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
4 changes: 4 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,8 @@ type Config struct {
CustomUDPBlackHoleSuccessCounter bool
IPv6BlackHoleSuccessCounter *swarm.BlackHoleSuccessCounter
CustomIPv6BlackHoleSuccessCounter bool

UserFxOptions []fx.Option
}

func (cfg *Config) makeSwarm(eventBus event.Bus, enableMetrics bool) (*swarm.Swarm, error) {
Expand Down Expand Up @@ -536,6 +538,8 @@ func (cfg *Config) NewNode() (host.Host, error) {
fxopts = append(fxopts, fx.Invoke(func(bho *routed.RoutedHost) { rh = bho }))
}

fxopts = append(fxopts, cfg.UserFxOptions...)

app := fx.New(fxopts...)
if err := app.Start(context.Background()); err != nil {
return nil, err
Expand Down
47 changes: 47 additions & 0 deletions fx_options_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package libp2p

import (
"testing"

"github.com/libp2p/go-libp2p/core/event"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/stretchr/testify/require"
"go.uber.org/fx"
)

func TestGetPeerID(t *testing.T) {
var id peer.ID
host, err := New(
WithFxOption(fx.Populate(&id)),
)
require.NoError(t, err)
defer host.Close()

require.Equal(t, host.ID(), id)

}

func TestGetEventBus(t *testing.T) {
var eb event.Bus
host, err := New(
NoTransports,
WithFxOption(fx.Populate(&eb)),
)
require.NoError(t, err)
defer host.Close()

require.NotNil(t, eb)
}

func TestGetHost(t *testing.T) {
var h host.Host
host, err := New(
NoTransports,
WithFxOption(fx.Populate(&h)),
)
require.NoError(t, err)
defer host.Close()

require.NotNil(t, h)
}
9 changes: 9 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -634,3 +634,12 @@ func IPv6BlackHoleSuccessCounter(f *swarm.BlackHoleSuccessCounter) Option {
return nil
}
}

// WithFxOption adds a user provided fx.Option to the libp2p constructor.
// Experimental: This option is subject to change or removal.
func WithFxOption(opts ...fx.Option) Option {
return func(cfg *Config) error {
cfg.UserFxOptions = append(cfg.UserFxOptions, opts...)
return nil
}
}

0 comments on commit 0e76f3d

Please sign in to comment.