diff --git a/config/config.go b/config/config.go index d0a71664f7..b33a4a5d64 100644 --- a/config/config.go +++ b/config/config.go @@ -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) { @@ -556,6 +558,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 diff --git a/fx_options_test.go b/fx_options_test.go new file mode 100644 index 0000000000..0c96f0c02e --- /dev/null +++ b/fx_options_test.go @@ -0,0 +1,61 @@ +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.Invoke( + func(myid peer.ID) { + id = myid + }))) + 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.Invoke( + func(e event.Bus) { + eb = e + }, + ), + ), + ) + 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.Invoke( + func(hostFromInvoke host.Host) { + h = hostFromInvoke + }, + ), + ), + ) + require.NoError(t, err) + defer host.Close() + + require.NotNil(t, h) +} diff --git a/options.go b/options.go index 1a8bc5dd55..2a34d13b2a 100644 --- a/options.go +++ b/options.go @@ -635,3 +635,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 + } +}