conn.go 817 Bytes
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1
2
3
package meterconn

import (
Jeromy's avatar
Jeromy committed
4
5
	metrics "github.com/ipfs/go-libp2p/p2p/metrics"
	transport "github.com/ipfs/go-libp2p/p2p/net/transport"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6
7
8
9
10
11
)

type MeteredConn struct {
	mesRecv metrics.MeterCallback
	mesSent metrics.MeterCallback

Jeromy's avatar
Jeromy committed
12
	transport.Conn
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
13
14
}

Jeromy's avatar
Jeromy committed
15
func WrapConn(bwc metrics.Reporter, c transport.Conn) transport.Conn {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
16
17
18
	return newMeteredConn(c, bwc.LogRecvMessage, bwc.LogSentMessage)
}

Jeromy's avatar
Jeromy committed
19
func newMeteredConn(base transport.Conn, rcb metrics.MeterCallback, scb metrics.MeterCallback) transport.Conn {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
	return &MeteredConn{
		Conn:    base,
		mesRecv: rcb,
		mesSent: scb,
	}
}

func (mc *MeteredConn) Read(b []byte) (int, error) {
	n, err := mc.Conn.Read(b)

	mc.mesRecv(int64(n))
	return n, err
}

func (mc *MeteredConn) Write(b []byte) (int, error) {
	n, err := mc.Conn.Write(b)

	mc.mesSent(int64(n))
	return n, err
}