]> Sergey Matveev's repositories - btrtrc.git/blob - conn_stats.go
TODOs and comments
[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         BytesWrittenData int64
19
20         BytesRead           int64
21         BytesReadData       int64
22         BytesReadUsefulData int64
23
24         ChunksWritten int64
25
26         ChunksRead         int64
27         ChunksReadUseful   int64
28         ChunksReadUnwanted int64
29
30         // Number of pieces data was written to, that subsequently passed verification.
31         PiecesDirtiedGood int64
32         // Number of pieces data was written to, that subsequently failed
33         // verification. Note that a connection may not have been the sole dirtier
34         // of a piece.
35         PiecesDirtiedBad int64
36 }
37
38 func (cs *ConnStats) wroteMsg(msg *pp.Message) {
39         // TODO: Track messages and not just chunks.
40         switch msg.Type {
41         case pp.Piece:
42                 cs.ChunksWritten++
43                 cs.BytesWrittenData += int64(len(msg.Piece))
44         }
45 }
46
47 func (cs *ConnStats) readMsg(msg *pp.Message) {
48         switch msg.Type {
49         case pp.Piece:
50                 cs.ChunksRead++
51                 cs.BytesReadData += int64(len(msg.Piece))
52         }
53 }
54
55 func (cs *ConnStats) wroteBytes(n int64) {
56         cs.BytesWritten += n
57 }
58
59 func (cs *ConnStats) readBytes(n int64) {
60         cs.BytesRead += n
61 }
62
63 type connStatsReadWriter struct {
64         rw io.ReadWriter
65         l  sync.Locker
66         c  *connection
67 }
68
69 func (me connStatsReadWriter) Write(b []byte) (n int, err error) {
70         n, err = me.rw.Write(b)
71         me.l.Lock()
72         me.c.wroteBytes(int64(n))
73         me.l.Unlock()
74         return
75 }
76
77 func (me connStatsReadWriter) Read(b []byte) (n int, err error) {
78         n, err = me.rw.Read(b)
79         me.l.Lock()
80         me.c.readBytes(int64(n))
81         me.l.Unlock()
82         return
83 }