refactor: move bytecounting conn in bytecounter pkg (#392)

* refactor: move bytecounting conn in bytecounter pkg

This enables other pieces of code to request bytecounting without
depending on netx or on the perverse using-the-context-to-configure-
byte-counting mechanism.

Also occurred when working on https://github.com/ooni/probe/issues/1687

* fix: add missing docs
This commit is contained in:
Simone Basso
2021-06-22 13:44:36 +02:00
committed by GitHub
parent 23bc261464
commit 760ac905d6
4 changed files with 104 additions and 33 deletions
+26
View File
@@ -0,0 +1,26 @@
package bytecounter
import "net"
// Conn wraps a network connection and counts bytes.
type Conn struct {
// net.Conn is the underlying net.Conn.
net.Conn
// Counter is the byte counter.
Counter *Counter
}
// Read implements net.Conn.Read.
func (c *Conn) Read(p []byte) (int, error) {
count, err := c.Conn.Read(p)
c.Counter.CountBytesReceived(count)
return count, err
}
// Write implements net.Conn.Write.
func (c *Conn) Write(p []byte) (int, error) {
count, err := c.Conn.Write(p)
c.Counter.CountBytesSent(count)
return count, err
}
+66
View File
@@ -0,0 +1,66 @@
package bytecounter
import (
"errors"
"testing"
"github.com/ooni/probe-cli/v3/internal/engine/netx/mockablex"
)
func TestConnWorksOnSuccess(t *testing.T) {
counter := New()
underlying := &mockablex.Conn{
MockRead: func(b []byte) (int, error) {
return 10, nil
},
MockWrite: func(b []byte) (int, error) {
return 4, nil
},
}
conn := &Conn{
Conn: underlying,
Counter: counter,
}
if _, err := conn.Read(make([]byte, 128)); err != nil {
t.Fatal(err)
}
if _, err := conn.Write(make([]byte, 1024)); err != nil {
t.Fatal(err)
}
if counter.BytesReceived() != 10 {
t.Fatal("unexpected number of bytes received")
}
if counter.BytesSent() != 4 {
t.Fatal("unexpected number of bytes sent")
}
}
func TestConnWorksOnFailure(t *testing.T) {
readError := errors.New("read error")
writeError := errors.New("write error")
counter := New()
underlying := &mockablex.Conn{
MockRead: func(b []byte) (int, error) {
return 0, readError
},
MockWrite: func(b []byte) (int, error) {
return 0, writeError
},
}
conn := &Conn{
Conn: underlying,
Counter: counter,
}
if _, err := conn.Read(make([]byte, 128)); !errors.Is(err, readError) {
t.Fatal("not the error we expected", err)
}
if _, err := conn.Write(make([]byte, 1024)); !errors.Is(err, writeError) {
t.Fatal("not the error we expected", err)
}
if counter.BytesReceived() != 0 {
t.Fatal("unexpected number of bytes received")
}
if counter.BytesSent() != 0 {
t.Fatal("unexpected number of bytes sent")
}
}