forked from ipfs/kubo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
metered.go
52 lines (40 loc) · 1.2 KB
/
metered.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
package meterstream
import (
metrics "github.com/ipfs/go-ipfs/metrics"
inet "github.com/ipfs/go-ipfs/p2p/net"
peer "github.com/ipfs/go-ipfs/p2p/peer"
protocol "github.com/ipfs/go-ipfs/p2p/protocol"
)
type meteredStream struct {
// keys for accessing metrics data
protoKey protocol.ID
peerKey peer.ID
inet.Stream
// callbacks for reporting bandwidth usage
mesSent metrics.StreamMeterCallback
mesRecv metrics.StreamMeterCallback
}
func newMeteredStream(base inet.Stream, pid protocol.ID, p peer.ID, recvCB, sentCB metrics.StreamMeterCallback) inet.Stream {
return &meteredStream{
Stream: base,
mesSent: sentCB,
mesRecv: recvCB,
protoKey: pid,
peerKey: p,
}
}
func WrapStream(base inet.Stream, pid protocol.ID, bwc metrics.Reporter) inet.Stream {
return newMeteredStream(base, pid, base.Conn().RemotePeer(), bwc.LogRecvMessageStream, bwc.LogSentMessageStream)
}
func (s *meteredStream) Read(b []byte) (int, error) {
n, err := s.Stream.Read(b)
// Log bytes read
s.mesRecv(int64(n), s.protoKey, s.peerKey)
return n, err
}
func (s *meteredStream) Write(b []byte) (int, error) {
n, err := s.Stream.Write(b)
// Log bytes written
s.mesSent(int64(n), s.protoKey, s.peerKey)
return n, err
}