host.go 2.03 KB
Newer Older
tavit ohanian's avatar
tavit ohanian committed
1
package dms3p2p
2 3 4 5

import (
	"context"

tavit ohanian's avatar
tavit ohanian committed
6 7 8 9 10 11 12
	"gitlab.dms3.io/p2p/go-p2p"
	host "gitlab.dms3.io/p2p/go-p2p-core/host"
	peer "gitlab.dms3.io/p2p/go-p2p-core/peer"
	peerstore "gitlab.dms3.io/p2p/go-p2p-core/peerstore"
	routing "gitlab.dms3.io/p2p/go-p2p-core/routing"
	record "gitlab.dms3.io/p2p/go-p2p-record"
	routedhost "gitlab.dms3.io/p2p/go-p2p/p2p/host/routed"
13

tavit ohanian's avatar
tavit ohanian committed
14 15
	"gitlab.dms3.io/dms3/go-dms3/core/node/helpers"
	"gitlab.dms3.io/dms3/go-dms3/repo"
16 17

	"go.uber.org/fx"
18 19 20 21 22 23 24 25 26 27 28 29
)

type P2PHostIn struct {
	fx.In

	Repo          repo.Repo
	Validator     record.Validator
	HostOption    HostOption
	RoutingOption RoutingOption
	ID            peer.ID
	Peerstore     peerstore.Peerstore

tavit ohanian's avatar
tavit ohanian committed
30
	Opts [][]p2p.Option `group:"p2p"`
31 32 33 34 35 36
}

type P2PHostOut struct {
	fx.Out

	Host    host.Host
tavit ohanian's avatar
tavit ohanian committed
37
	Routing BaseDms3Routing
38 39 40
}

func Host(mctx helpers.MetricsCtx, lc fx.Lifecycle, params P2PHostIn) (out P2PHostOut, err error) {
tavit ohanian's avatar
tavit ohanian committed
41
	opts := []p2p.Option{p2p.NoListenAddrs}
42 43 44 45 46
	for _, o := range params.Opts {
		opts = append(opts, o...)
	}

	ctx := helpers.LifecycleCtx(mctx, lc)
47 48 49 50 51 52 53 54
	cfg, err := params.Repo.Config()
	if err != nil {
		return out, err
	}
	bootstrappers, err := cfg.BootstrapPeers()
	if err != nil {
		return out, err
	}
55

tavit ohanian's avatar
tavit ohanian committed
56
	opts = append(opts, p2p.Routing(func(h host.Host) (routing.PeerRouting, error) {
57 58 59 60 61 62
		r, err := params.RoutingOption(
			ctx, h,
			params.Repo.Datastore(),
			params.Validator,
			bootstrappers...,
		)
63 64 65 66 67 68 69 70 71 72
		out.Routing = r
		return r, err
	}))

	out.Host, err = params.HostOption(ctx, params.ID, params.Peerstore, opts...)
	if err != nil {
		return P2PHostOut{}, err
	}

	// this code is necessary just for tests: mock network constructions
tavit ohanian's avatar
tavit ohanian committed
73
	// ignore the p2p constructor options that actually construct the routing!
74
	if out.Routing == nil {
75
		r, err := params.RoutingOption(ctx, out.Host, params.Repo.Datastore(), params.Validator, bootstrappers...)
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
		if err != nil {
			return P2PHostOut{}, err
		}
		out.Routing = r
		out.Host = routedhost.Wrap(out.Host, out.Routing)
	}

	lc.Append(fx.Hook{
		OnStop: func(ctx context.Context) error {
			return out.Host.Close()
		},
	})

	return out, err
}