2018-07-04 10:51:47 +00:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
2019-06-09 07:24:20 +00:00
|
|
|
"github.com/libp2p/go-libp2p-core/host"
|
|
|
|
"github.com/libp2p/go-libp2p-core/mux"
|
|
|
|
msmux "github.com/libp2p/go-stream-muxer-multistream"
|
2018-07-04 10:51:47 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// MuxC is a stream multiplex transport constructor
|
2019-06-09 07:24:20 +00:00
|
|
|
type MuxC func(h host.Host) (mux.Multiplexer, error)
|
2018-07-04 10:51:47 +00:00
|
|
|
|
|
|
|
// MsMuxC is a tuple containing a multiplex transport constructor and a protocol
|
|
|
|
// ID.
|
|
|
|
type MsMuxC struct {
|
|
|
|
MuxC
|
|
|
|
ID string
|
|
|
|
}
|
|
|
|
|
|
|
|
var muxArgTypes = newArgTypeSet(hostType, networkType, peerIDType, pstoreType)
|
|
|
|
|
|
|
|
// MuxerConstructor creates a multiplex constructor from the passed parameter
|
|
|
|
// using reflection.
|
|
|
|
func MuxerConstructor(m interface{}) (MuxC, error) {
|
|
|
|
// Already constructed?
|
2019-06-09 07:24:20 +00:00
|
|
|
if t, ok := m.(mux.Multiplexer); ok {
|
|
|
|
return func(_ host.Host) (mux.Multiplexer, error) {
|
2018-07-04 10:51:47 +00:00
|
|
|
return t, nil
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
ctor, err := makeConstructor(m, muxType, muxArgTypes)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-06-09 07:24:20 +00:00
|
|
|
return func(h host.Host) (mux.Multiplexer, error) {
|
2018-07-04 10:51:47 +00:00
|
|
|
t, err := ctor(h, nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-06-09 07:24:20 +00:00
|
|
|
return t.(mux.Multiplexer), nil
|
2018-07-04 10:51:47 +00:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2019-06-09 07:24:20 +00:00
|
|
|
func makeMuxer(h host.Host, tpts []MsMuxC) (mux.Multiplexer, error) {
|
2018-07-04 10:51:47 +00:00
|
|
|
muxMuxer := msmux.NewBlankTransport()
|
|
|
|
transportSet := make(map[string]struct{}, len(tpts))
|
|
|
|
for _, tptC := range tpts {
|
|
|
|
if _, ok := transportSet[tptC.ID]; ok {
|
|
|
|
return nil, fmt.Errorf("duplicate muxer transport: %s", tptC.ID)
|
|
|
|
}
|
2019-06-09 07:24:20 +00:00
|
|
|
transportSet[tptC.ID] = struct{}{}
|
2018-07-04 10:51:47 +00:00
|
|
|
}
|
|
|
|
for _, tptC := range tpts {
|
|
|
|
tpt, err := tptC.MuxC(h)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
muxMuxer.AddTransport(tptC.ID, tpt)
|
|
|
|
}
|
|
|
|
return muxMuxer, nil
|
|
|
|
}
|