kubo/core/node/libp2p/routing.go
Łukasz Magiera e133058487 constructor: break down libp2p logic
License: MIT
Signed-off-by: Łukasz Magiera <magik6k@gmail.com>
2019-04-30 00:09:42 +02:00

109 lines
2.2 KiB
Go

package libp2p
import (
"context"
"sort"
host "github.com/libp2p/go-libp2p-host"
dht "github.com/libp2p/go-libp2p-kad-dht"
"github.com/libp2p/go-libp2p-pubsub"
namesys "github.com/libp2p/go-libp2p-pubsub-router"
record "github.com/libp2p/go-libp2p-record"
routing "github.com/libp2p/go-libp2p-routing"
routinghelpers "github.com/libp2p/go-libp2p-routing-helpers"
"go.uber.org/fx"
"github.com/ipfs/go-ipfs/core/node/helpers"
"github.com/ipfs/go-ipfs/repo"
)
type BaseIpfsRouting routing.IpfsRouting
type Router struct {
routing.IpfsRouting
Priority int // less = more important
}
type p2pRouterOut struct {
fx.Out
Router Router `group:"routers"`
}
func BaseRouting(lc fx.Lifecycle, in BaseIpfsRouting) (out p2pRouterOut, dr *dht.IpfsDHT) {
if dht, ok := in.(*dht.IpfsDHT); ok {
dr = dht
lc.Append(fx.Hook{
OnStop: func(ctx context.Context) error {
return dr.Close()
},
})
}
return p2pRouterOut{
Router: Router{
Priority: 1000,
IpfsRouting: in,
},
}, dr
}
type p2pOnlineRoutingIn struct {
fx.In
Routers []Router `group:"routers"`
Validator record.Validator
}
func Routing(in p2pOnlineRoutingIn) routing.IpfsRouting {
routers := in.Routers
sort.SliceStable(routers, func(i, j int) bool {
return routers[i].Priority < routers[j].Priority
})
irouters := make([]routing.IpfsRouting, len(routers))
for i, v := range routers {
irouters[i] = v.IpfsRouting
}
return routinghelpers.Tiered{
Routers: irouters,
Validator: in.Validator,
}
}
type p2pPSRoutingIn struct {
fx.In
BaseRouting BaseIpfsRouting
Repo repo.Repo
Validator record.Validator
Host host.Host
PubSub *pubsub.PubSub `optional:"true"`
}
func PubsubRouter(mctx helpers.MetricsCtx, lc fx.Lifecycle, in p2pPSRoutingIn) (p2pRouterOut, *namesys.PubsubValueStore) {
psRouter := namesys.NewPubsubValueStore(
helpers.LifecycleCtx(mctx, lc),
in.Host,
in.BaseRouting,
in.PubSub,
in.Validator,
)
return p2pRouterOut{
Router: Router{
IpfsRouting: &routinghelpers.Compose{
ValueStore: &routinghelpers.LimitedValueStore{
ValueStore: psRouter,
Namespaces: []string{"ipns"},
},
},
Priority: 100,
},
}, psRouter
}