Skip to content

host: use dependency injection (Fx) to construct services, and start and stop them #1993

@marten-seemann

Description

@marten-seemann

Now that we’ve started using Fx to construct our transports, muxers and security protocols, we should start using it to construct libp2p services like AutoNAT, Identify, the hole punching service etc.

Constructing, Starting and Stopping Services

These services might depend on each other. For example, the hole puncher needs the identity service. Currently, these interdependencies are hardcoded (and the host keeps references to particular services), but we could just have Fx take care of resolving this dependency tree.

We should also clearly define what a libp2p service is:

type Service interface {
     Start() error
     io.Closer
}

In general, service should not start any Go routines in their constructor, but wait for the explicit start signal provided with the Start method.

The host would then just have to keep track of a slice of services, so it can cleanly shut them down. Starting and stopping the services should also be done by Fx, so services are started in the right order. Maybe we won’t even need the slice of services, assuming that Fx keeps track the dependency tree for shutdown.

How to expose existing services to the Application

An application might want to be able to interact with particular services, once they’re constructed. We could add getter functions to the host, but this quickly gets messy, and doesn’t work with injected services at all.

Instead we could have users pass in a service struct that Fx would fill with concrete values, e.g.:

libp2p.FillHost(struct { *identify.Service, *autonat.Service }) (host.Host, error)

Metadata

Metadata

Assignees

No one assigned

    Labels

    effort/daysEstimated to take multiple days, but less than a weekexp/intermediatePrior experience is likely helpfulkind/enhancementA net-new feature or improvement to an existing feature

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions