forked from libp2p/go-libp2p-kad-dht
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dht_net.go
169 lines (145 loc) · 4.74 KB
/
dht_net.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
package dht
import (
"io"
"time"
"github.com/libp2p/go-libp2p/core/network"
"github.com/daotl/go-libp2p-kad-dht/internal/net"
"github.com/daotl/go-libp2p-kad-dht/metrics"
pb "github.com/daotl/go-libp2p-kad-dht/pb"
"github.com/libp2p/go-msgio"
"go.opencensus.io/stats"
"go.opencensus.io/tag"
"go.uber.org/zap"
)
var dhtStreamIdleTimeout = 1 * time.Minute
// ErrReadTimeout is an error that occurs when no message is read within the timeout period.
var ErrReadTimeout = net.ErrReadTimeout
// handleNewStream implements the network.StreamHandler
func (dht *IpfsDHT) handleNewStream(s network.Stream) {
if dht.handleNewMessage(s) {
// If we exited without error, close gracefully.
_ = s.Close()
} else {
// otherwise, send an error.
_ = s.Reset()
}
}
// Returns true on orderly completion of writes (so we can Close the stream).
func (dht *IpfsDHT) handleNewMessage(s network.Stream) bool {
ctx := dht.ctx
r := msgio.NewVarintReaderSize(s, network.MessageSizeMax)
mPeer := s.Conn().RemotePeer()
timer := time.AfterFunc(dhtStreamIdleTimeout, func() { _ = s.Reset() })
defer timer.Stop()
for {
if dht.getMode() != modeServer {
logger.Errorf("ignoring incoming dht message while not in server mode")
return false
}
var req pb.Message
msgbytes, err := r.ReadMsg()
msgLen := len(msgbytes)
if err != nil {
r.ReleaseMsg(msgbytes)
if err == io.EOF {
return true
}
// This string test is necessary because there isn't a single stream reset error
// instance in use.
if c := baseLogger.Check(zap.DebugLevel, "error reading message"); c != nil && err.Error() != "stream reset" {
c.Write(zap.String("from", mPeer.String()),
zap.Error(err))
}
if msgLen > 0 {
_ = stats.RecordWithTags(ctx,
[]tag.Mutator{tag.Upsert(metrics.KeyMessageType, "UNKNOWN")},
metrics.ReceivedMessages.M(1),
metrics.ReceivedMessageErrors.M(1),
metrics.ReceivedBytes.M(int64(msgLen)),
)
}
return false
}
err = req.Unmarshal(msgbytes)
r.ReleaseMsg(msgbytes)
if err != nil {
if c := baseLogger.Check(zap.DebugLevel, "error unmarshaling message"); c != nil {
c.Write(zap.String("from", mPeer.String()),
zap.Error(err))
}
_ = stats.RecordWithTags(ctx,
[]tag.Mutator{tag.Upsert(metrics.KeyMessageType, "UNKNOWN")},
metrics.ReceivedMessages.M(1),
metrics.ReceivedMessageErrors.M(1),
metrics.ReceivedBytes.M(int64(msgLen)),
)
return false
}
timer.Reset(dhtStreamIdleTimeout)
startTime := time.Now()
ctx, _ := tag.New(ctx,
tag.Upsert(metrics.KeyMessageType, req.GetType().String()),
)
stats.Record(ctx,
metrics.ReceivedMessages.M(1),
metrics.ReceivedBytes.M(int64(msgLen)),
)
handler := dht.handlerForMsgType(req.GetType())
if handler == nil {
stats.Record(ctx, metrics.ReceivedMessageErrors.M(1))
if c := baseLogger.Check(zap.DebugLevel, "can't handle received message"); c != nil {
c.Write(zap.String("from", mPeer.String()),
zap.Int32("type", int32(req.GetType())))
}
return false
}
// a peer has queried us, let's add it to RT
dht.peerFound(dht.ctx, mPeer, true)
if c := baseLogger.Check(zap.DebugLevel, "handling message"); c != nil {
c.Write(zap.String("from", mPeer.String()),
zap.Int32("type", int32(req.GetType())),
zap.Binary("key", req.GetKey()))
}
resp, err := handler(ctx, mPeer, &req)
if err != nil {
stats.Record(ctx, metrics.ReceivedMessageErrors.M(1))
if c := baseLogger.Check(zap.DebugLevel, "error handling message"); c != nil {
c.Write(zap.String("from", mPeer.String()),
zap.Int32("type", int32(req.GetType())),
zap.Binary("key", req.GetKey()),
zap.Error(err))
}
return false
}
if c := baseLogger.Check(zap.DebugLevel, "handled message"); c != nil {
c.Write(zap.String("from", mPeer.String()),
zap.Int32("type", int32(req.GetType())),
zap.Binary("key", req.GetKey()),
zap.Duration("time", time.Since(startTime)))
}
if resp == nil {
continue
}
// send out response msg
err = net.WriteMsg(s, resp)
if err != nil {
stats.Record(ctx, metrics.ReceivedMessageErrors.M(1))
if c := baseLogger.Check(zap.DebugLevel, "error writing response"); c != nil {
c.Write(zap.String("from", mPeer.String()),
zap.Int32("type", int32(req.GetType())),
zap.Binary("key", req.GetKey()),
zap.Error(err))
}
return false
}
elapsedTime := time.Since(startTime)
if c := baseLogger.Check(zap.DebugLevel, "responded to message"); c != nil {
c.Write(zap.String("from", mPeer.String()),
zap.Int32("type", int32(req.GetType())),
zap.Binary("key", req.GetKey()),
zap.Duration("time", elapsedTime))
}
latencyMillis := float64(elapsedTime) / float64(time.Millisecond)
stats.Record(ctx, metrics.InboundRequestLatency.M(latencyMillis))
}
}