]> Sergey Matveev's repositories - btrtrc.git/blob - conn_stats.go
Merge a bunch of stuff into ConnStats and refactor connection.upload
[btrtrc.git] / conn_stats.go
1 package torrent
2
3 import (
4         "io"
5         "sync"
6
7         pp "github.com/anacrolix/torrent/peer_protocol"
8 )
9
10 // Various connection-level metrics. At the Torrent level these are
11 // aggregates. Chunks are messages with data payloads. Data is actual torrent
12 // content without any overhead. Useful is something we needed locally.
13 // Unwanted is something we didn't ask for (but may still be useful). Written
14 // is things sent to the peer, and Read is stuff received from them.
15 type ConnStats struct {
16         // Total bytes on the wire. Includes handshakes and encryption.
17         BytesWritten int64
18         BytesRead    int64
19
20         // The rest of the stats only occur on connections after handshakes.
21
22         ChunksWritten int64
23
24         ChunksRead         int64
25         ChunksReadUseful   int64
26         ChunksReadUnwanted int64
27
28         DataBytesWritten    int64
29         DataBytesRead       int64
30         UsefulDataBytesRead int64
31
32         // Number of pieces data was written to, that subsequently passed verification.
33         GoodPiecesDirtied int64
34         // Number of pieces data was written to, that subsequently failed
35         // verification. Note that a connection may not have been the sole dirtier
36         // of a piece.
37         BadPiecesDirtied int64
38 }
39
40 func (cs *ConnStats) wroteMsg(msg *pp.Message) {
41         switch msg.Type {
42         case pp.Piece:
43                 cs.ChunksWritten++
44                 cs.DataBytesWritten += int64(len(msg.Piece))
45         }
46 }
47
48 func (cs *ConnStats) readMsg(msg *pp.Message) {
49         switch msg.Type {
50         case pp.Piece:
51                 cs.ChunksRead++
52                 cs.DataBytesRead += int64(len(msg.Piece))
53         }
54 }
55
56 func (cs *ConnStats) wroteBytes(n int64) {
57         cs.BytesWritten += n
58 }
59
60 func (cs *ConnStats) readBytes(n int64) {
61         cs.BytesRead += n
62 }
63
64 type connStatsReadWriter struct {
65         rw io.ReadWriter
66         l  sync.Locker
67         c  *connection
68 }
69
70 func (me connStatsReadWriter) Write(b []byte) (n int, err error) {
71         n, err = me.rw.Write(b)
72         me.l.Lock()
73         me.c.wroteBytes(int64(n))
74         me.l.Unlock()
75         return
76 }
77
78 func (me connStatsReadWriter) Read(b []byte) (n int, err error) {
79         n, err = me.rw.Read(b)
80         me.l.Lock()
81         me.c.readBytes(int64(n))
82         me.l.Unlock()
83         return
84 }