generated from RTradeLtd/repo-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
multistream.go
75 lines (60 loc) · 1.55 KB
/
multistream.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// package multistream implements a peerstream transport using
// go-multistream to select the underlying stream muxer
package multistream
import (
"fmt"
"net"
"time"
"github.com/RTradeLtd/libp2px-core/mux"
mss "github.com/multiformats/go-multistream"
)
var DefaultNegotiateTimeout = time.Second * 60
type Transport struct {
mux *mss.MultistreamMuxer
tpts map[string]mux.Multiplexer
NegotiateTimeout time.Duration
OrderPreference []string
}
func NewBlankTransport() *Transport {
return &Transport{
mux: mss.NewMultistreamMuxer(),
tpts: make(map[string]mux.Multiplexer),
NegotiateTimeout: DefaultNegotiateTimeout,
}
}
func (t *Transport) AddTransport(path string, tpt mux.Multiplexer) {
t.mux.AddHandler(path, nil)
t.tpts[path] = tpt
t.OrderPreference = append(t.OrderPreference, path)
}
func (t *Transport) NewConn(nc net.Conn, isServer bool) (mux.MuxedConn, error) {
if t.NegotiateTimeout != 0 {
if err := nc.SetDeadline(time.Now().Add(t.NegotiateTimeout)); err != nil {
return nil, err
}
}
var proto string
if isServer {
selected, _, err := t.mux.Negotiate(nc)
if err != nil {
return nil, err
}
proto = selected
} else {
selected, err := mss.SelectOneOf(t.OrderPreference, nc)
if err != nil {
return nil, err
}
proto = selected
}
if t.NegotiateTimeout != 0 {
if err := nc.SetDeadline(time.Time{}); err != nil {
return nil, err
}
}
tpt, ok := t.tpts[proto]
if !ok {
return nil, fmt.Errorf("selected protocol we don't have a transport for")
}
return tpt.NewConn(nc, isServer)
}