-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpc.go
120 lines (106 loc) · 2.45 KB
/
grpc.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package node
import (
"context"
"net"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/network"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p-core/protocol"
manet "github.com/multiformats/go-multiaddr-net"
)
func newStreamListener(ctx context.Context, h host.Host, proto protocol.ID) *streamListener {
ctx, cancel := context.WithCancel(ctx)
l := &streamListener{
host: h,
streams: make(chan network.Stream),
ctx: ctx,
cancel: cancel,
}
if proto == "" {
proto = "/grpc/0.1"
}
h.SetStreamHandler(proto, l.streamHandler)
return l
}
// GRPCDialer creates a dialer function for use as a grpc.DialOption.
// A stream creator can be a host.Host from libp2p
//
// Use with the grpc.WithContextDialer dialer option
func GRPCDialer(h host.Host, proto ...protocol.ID) func(context.Context, string) (net.Conn, error) {
return func(ctx context.Context, addr string) (net.Conn, error) {
pid, err := peer.Decode(addr)
if err != nil {
return nil, err
}
s, err := h.NewStream(ctx, pid, proto...)
if err != nil {
return nil, err
}
return newStreamConn(s)
}
}
type streamListener struct {
host host.Host
streams chan network.Stream
ctx context.Context
cancel context.CancelFunc
}
func (sl *streamListener) streamHandler(s network.Stream) {
select {
case <-sl.ctx.Done():
return
case sl.streams <- s:
}
}
func (sl *streamListener) Accept() (net.Conn, error) {
select {
case <-sl.ctx.Done():
sl.cancel()
return nil, sl.ctx.Err()
case s := <-sl.streams:
return newStreamConn(s)
}
}
func (sl *streamListener) Close() error {
return sl.host.Close()
}
func (sl *streamListener) Addr() net.Addr {
addrs := sl.host.Network().ListenAddresses()
for _, maaddr := range addrs {
addr, err := manet.ToNetAddr(maaddr)
if err == nil {
return addr
}
}
return nil
}
func newStreamConn(s network.Stream) (*streamConn, error) {
local, err := manet.ToNetAddr(s.Conn().LocalMultiaddr())
if err != nil {
return nil, err
}
remote, err := manet.ToNetAddr(s.Conn().RemoteMultiaddr())
if err != nil {
return nil, err
}
return &streamConn{
Stream: s,
local: local,
remote: remote,
}, nil
}
type streamConn struct {
network.Stream
local net.Addr
remote net.Addr
}
func (sc *streamConn) LocalAddr() net.Addr {
return sc.local
}
func (sc *streamConn) RemoteAddr() net.Addr {
return sc.remote
}
var (
_ net.Conn = (*streamConn)(nil)
_ net.Listener = (*streamListener)(nil)
)