refactor: вынести stats, netadapt, bond в internal/
- internal/stats: throughputStats/countingConn/форматтеры, общие для клиента и сервера - internal/netadapt: DirectNet, ConnectedUDPConn, SplitFirstWriteConn - internal/bond: wire-кодек (Frame/Hello, Read/Write, CloseWrite) Убирает дублирование между client/main.go и server/main.go. Wire-формат и поведение CLI не изменены; round-trip кодека покрыт тестами.
This commit is contained in:
1 parent
948108a33a
commit
ada0c746aa
8 files changed
+817
-580
No files matched your search
@@ -0,0 +1,133 @@
|
||||
// Package bond contains the wire format used by the VLESS bond multi-lane
|
||||
// transport (hello + framed data/FIN). Both the client (initiator) and the
|
||||
// server (acceptor) speak the same encoding.
|
||||
package bond
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
Version uint8 = 1
|
||||
Magic = "VLB1"
|
||||
|
||||
FrameData byte = 1
|
||||
FrameFIN byte = 2
|
||||
|
||||
MaxChunk = 16 * 1024
|
||||
|
||||
LaneAttachTimeout = 300 * time.Millisecond
|
||||
)
|
||||
|
||||
// Hello is the per-lane handshake header sent right after a smux stream opens.
|
||||
type Hello struct {
|
||||
ConnID uint64
|
||||
LaneIndex uint16
|
||||
LaneCount uint16
|
||||
}
|
||||
|
||||
// Frame is a single bonded data or FIN unit, identified by Seq within a ConnID.
|
||||
type Frame struct {
|
||||
Type byte
|
||||
Seq uint64
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// WriteHello encodes and writes a Hello to w using the bond wire format.
|
||||
func WriteHello(w io.Writer, connID uint64, laneIndex, laneCount uint16) error {
|
||||
var hdr [17]byte
|
||||
copy(hdr[0:4], Magic)
|
||||
hdr[4] = Version
|
||||
binary.BigEndian.PutUint64(hdr[5:13], connID)
|
||||
binary.BigEndian.PutUint16(hdr[13:15], laneIndex)
|
||||
binary.BigEndian.PutUint16(hdr[15:17], laneCount)
|
||||
_, err := w.Write(hdr[:])
|
||||
return err
|
||||
}
|
||||
|
||||
// ReadHelloAfterMagic finishes reading a Hello whose first 4 magic bytes have
|
||||
// already been consumed (server pre-peeks the magic to multiplex protocols).
|
||||
func ReadHelloAfterMagic(r io.Reader, magic [4]byte) (Hello, error) {
|
||||
var hdr [17]byte
|
||||
copy(hdr[0:4], magic[:])
|
||||
if _, err := io.ReadFull(r, hdr[4:]); err != nil {
|
||||
return Hello{}, err
|
||||
}
|
||||
return ParseHelloHeader(hdr[:])
|
||||
}
|
||||
|
||||
// ParseHelloHeader decodes a 17-byte Hello header from hdr.
|
||||
func ParseHelloHeader(hdr []byte) (Hello, error) {
|
||||
if len(hdr) != 17 {
|
||||
return Hello{}, fmt.Errorf("bad bond hello size: %d", len(hdr))
|
||||
}
|
||||
if string(hdr[0:4]) != Magic {
|
||||
return Hello{}, fmt.Errorf("bad bond magic")
|
||||
}
|
||||
if hdr[4] != Version {
|
||||
return Hello{}, fmt.Errorf("unsupported bond version: %d", hdr[4])
|
||||
}
|
||||
return Hello{
|
||||
ConnID: binary.BigEndian.Uint64(hdr[5:13]),
|
||||
LaneIndex: binary.BigEndian.Uint16(hdr[13:15]),
|
||||
LaneCount: binary.BigEndian.Uint16(hdr[15:17]),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// WriteFrame writes a single Frame to w (header + payload).
|
||||
func WriteFrame(w io.Writer, typ byte, seq uint64, data []byte) error {
|
||||
var hdr [13]byte
|
||||
hdr[0] = typ
|
||||
binary.BigEndian.PutUint64(hdr[1:9], seq)
|
||||
binary.BigEndian.PutUint32(hdr[9:13], uint32(len(data)))
|
||||
if _, err := w.Write(hdr[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return nil
|
||||
}
|
||||
_, err := w.Write(data)
|
||||
return err
|
||||
}
|
||||
|
||||
// ReadFrame reads one Frame from r. Payloads over 4 MiB are rejected.
|
||||
func ReadFrame(r io.Reader) (Frame, error) {
|
||||
var hdr [13]byte
|
||||
if _, err := io.ReadFull(r, hdr[:]); err != nil {
|
||||
return Frame{}, err
|
||||
}
|
||||
size := binary.BigEndian.Uint32(hdr[9:13])
|
||||
if size > 4*1024*1024 {
|
||||
return Frame{}, fmt.Errorf("bond frame too large: %d", size)
|
||||
}
|
||||
f := Frame{
|
||||
Type: hdr[0],
|
||||
Seq: binary.BigEndian.Uint64(hdr[1:9]),
|
||||
}
|
||||
if size > 0 {
|
||||
f.Data = make([]byte, size)
|
||||
if _, err := io.ReadFull(r, f.Data); err != nil {
|
||||
return Frame{}, err
|
||||
}
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// CloseWrite half-closes the write side of conn if the underlying type
|
||||
// supports it (TCPConn, smux.Stream, …); otherwise it is a no-op. errf is
|
||||
// invoked with the error if CloseWrite fails; callers typically pass a
|
||||
// debug-gated log func.
|
||||
func CloseWrite(conn net.Conn, errf func(format string, v ...any)) {
|
||||
type closeWriter interface {
|
||||
CloseWrite() error
|
||||
}
|
||||
if cw, ok := conn.(closeWriter); ok {
|
||||
if err := cw.CloseWrite(); err != nil && errf != nil {
|
||||
errf("CloseWrite failed: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package bond
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHelloRoundTrip(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := WriteHello(&buf, 0xCAFEBABEDEADBEEF, 3, 7); err != nil {
|
||||
t.Fatalf("WriteHello: %v", err)
|
||||
}
|
||||
if buf.Len() != 17 {
|
||||
t.Fatalf("hello size = %d, want 17", buf.Len())
|
||||
}
|
||||
|
||||
var magic [4]byte
|
||||
copy(magic[:], buf.Bytes()[:4])
|
||||
if string(magic[:]) != Magic {
|
||||
t.Fatalf("magic = %q, want %q", magic, Magic)
|
||||
}
|
||||
|
||||
// Consume magic to simulate the server pre-peek path.
|
||||
buf.Next(4)
|
||||
got, err := ReadHelloAfterMagic(&buf, magic)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadHelloAfterMagic: %v", err)
|
||||
}
|
||||
want := Hello{ConnID: 0xCAFEBABEDEADBEEF, LaneIndex: 3, LaneCount: 7}
|
||||
if got != want {
|
||||
t.Fatalf("hello = %+v, want %+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseHelloHeader_BadInputs(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if _, err := ParseHelloHeader(make([]byte, 16)); err == nil {
|
||||
t.Errorf("short header should fail")
|
||||
}
|
||||
|
||||
bad := make([]byte, 17)
|
||||
copy(bad[0:4], "XXXX")
|
||||
if _, err := ParseHelloHeader(bad); err == nil {
|
||||
t.Errorf("bad magic should fail")
|
||||
}
|
||||
|
||||
bad = make([]byte, 17)
|
||||
copy(bad[0:4], Magic)
|
||||
bad[4] = 99
|
||||
if _, err := ParseHelloHeader(bad); err == nil {
|
||||
t.Errorf("unsupported version should fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFrameRoundTrip(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cases := []Frame{
|
||||
{Type: FrameData, Seq: 0, Data: []byte("hello")},
|
||||
{Type: FrameData, Seq: 0xFFFFFFFFFFFFFFFF, Data: bytes.Repeat([]byte{0xAB}, 1500)},
|
||||
{Type: FrameFIN, Seq: 42, Data: nil},
|
||||
}
|
||||
for _, want := range cases {
|
||||
var buf bytes.Buffer
|
||||
if err := WriteFrame(&buf, want.Type, want.Seq, want.Data); err != nil {
|
||||
t.Fatalf("WriteFrame: %v", err)
|
||||
}
|
||||
got, err := ReadFrame(&buf)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadFrame: %v", err)
|
||||
}
|
||||
if got.Type != want.Type || got.Seq != want.Seq || !bytes.Equal(got.Data, want.Data) {
|
||||
t.Fatalf("frame = %+v, want %+v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadFrame_RejectsOversize(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var buf bytes.Buffer
|
||||
var hdr [13]byte
|
||||
hdr[0] = FrameData
|
||||
binary.BigEndian.PutUint32(hdr[9:13], 4*1024*1024+1)
|
||||
buf.Write(hdr[:])
|
||||
if _, err := ReadFrame(&buf); err == nil {
|
||||
t.Fatalf("oversize frame should be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadFrame_TruncatedHeader(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
buf := bytes.NewReader([]byte{1, 2, 3})
|
||||
_, err := ReadFrame(buf)
|
||||
if err == nil {
|
||||
t.Fatalf("truncated header should fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadFrame_TruncatedPayload(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := WriteFrame(&buf, FrameData, 1, []byte("hello world")); err != nil {
|
||||
t.Fatalf("WriteFrame: %v", err)
|
||||
}
|
||||
truncated := buf.Bytes()[:13+5] // header + 5 of 11 payload bytes
|
||||
if _, err := ReadFrame(bytes.NewReader(truncated)); err == nil {
|
||||
t.Fatalf("truncated payload should fail")
|
||||
}
|
||||
}
|
||||
|
||||
// Sanity: ReadHelloAfterMagic surfaces underlying EOF, not a silent zero.
|
||||
func TestReadHelloAfterMagic_EOF(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var magic [4]byte
|
||||
copy(magic[:], Magic)
|
||||
if _, err := ReadHelloAfterMagic(bytes.NewReader(nil), magic); err == nil || err == io.ErrShortBuffer {
|
||||
t.Fatalf("expected EOF-like error, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
// Package netadapt holds small net.Conn / transport.Net adapters used by both
|
||||
// client and server: a passthrough transport.Net (for pion turn),
|
||||
// ConnectedUDPConn (Write-only WriteTo on a dialed UDPConn), and
|
||||
// SplitFirstWriteConn (DPI evasion via first-segment split).
|
||||
package netadapt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/pion/transport/v4"
|
||||
)
|
||||
|
||||
// DirectNet implements transport.Net by delegating to the std net package.
|
||||
type DirectNet struct{}
|
||||
|
||||
// New returns a transport.Net that delegates to the standard net package.
|
||||
func New() transport.Net {
|
||||
return DirectNet{}
|
||||
}
|
||||
|
||||
type directDialer struct {
|
||||
*net.Dialer
|
||||
}
|
||||
|
||||
type directListenConfig struct {
|
||||
*net.ListenConfig
|
||||
}
|
||||
|
||||
type directTCPListener struct {
|
||||
*net.TCPListener
|
||||
}
|
||||
|
||||
func (DirectNet) ListenPacket(network string, address string) (net.PacketConn, error) {
|
||||
return net.ListenPacket(network, address)
|
||||
}
|
||||
|
||||
func (DirectNet) ListenUDP(network string, locAddr *net.UDPAddr) (transport.UDPConn, error) {
|
||||
return net.ListenUDP(network, locAddr)
|
||||
}
|
||||
|
||||
func (DirectNet) ListenTCP(network string, laddr *net.TCPAddr) (transport.TCPListener, error) {
|
||||
listener, err := net.ListenTCP(network, laddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return directTCPListener{listener}, nil
|
||||
}
|
||||
|
||||
func (DirectNet) Dial(network, address string) (net.Conn, error) {
|
||||
return net.Dial(network, address)
|
||||
}
|
||||
|
||||
func (DirectNet) DialUDP(network string, laddr, raddr *net.UDPAddr) (transport.UDPConn, error) {
|
||||
return net.DialUDP(network, laddr, raddr)
|
||||
}
|
||||
|
||||
func (DirectNet) DialTCP(network string, laddr, raddr *net.TCPAddr) (transport.TCPConn, error) {
|
||||
return net.DialTCP(network, laddr, raddr)
|
||||
}
|
||||
|
||||
func (DirectNet) ResolveIPAddr(network, address string) (*net.IPAddr, error) {
|
||||
return net.ResolveIPAddr(network, address)
|
||||
}
|
||||
|
||||
func (DirectNet) ResolveUDPAddr(network, address string) (*net.UDPAddr, error) {
|
||||
return net.ResolveUDPAddr(network, address)
|
||||
}
|
||||
|
||||
func (DirectNet) ResolveTCPAddr(network, address string) (*net.TCPAddr, error) {
|
||||
return net.ResolveTCPAddr(network, address)
|
||||
}
|
||||
|
||||
func (DirectNet) Interfaces() ([]*transport.Interface, error) {
|
||||
return nil, transport.ErrNotSupported
|
||||
}
|
||||
|
||||
func (DirectNet) InterfaceByIndex(index int) (*transport.Interface, error) {
|
||||
return nil, fmt.Errorf("%w: index=%d", transport.ErrInterfaceNotFound, index)
|
||||
}
|
||||
|
||||
func (DirectNet) InterfaceByName(name string) (*transport.Interface, error) {
|
||||
return nil, fmt.Errorf("%w: %s", transport.ErrInterfaceNotFound, name)
|
||||
}
|
||||
|
||||
func (DirectNet) CreateDialer(dialer *net.Dialer) transport.Dialer {
|
||||
return directDialer{Dialer: dialer}
|
||||
}
|
||||
|
||||
func (DirectNet) CreateListenConfig(listenerConfig *net.ListenConfig) transport.ListenConfig {
|
||||
return directListenConfig{ListenConfig: listenerConfig}
|
||||
}
|
||||
|
||||
func (d directDialer) Dial(network, address string) (net.Conn, error) {
|
||||
return d.Dialer.Dial(network, address)
|
||||
}
|
||||
|
||||
func (d directListenConfig) Listen(ctx context.Context, network, address string) (net.Listener, error) {
|
||||
return d.ListenConfig.Listen(ctx, network, address)
|
||||
}
|
||||
|
||||
func (d directListenConfig) ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error) {
|
||||
return d.ListenConfig.ListenPacket(ctx, network, address)
|
||||
}
|
||||
|
||||
func (l directTCPListener) AcceptTCP() (transport.TCPConn, error) {
|
||||
return l.TCPListener.AcceptTCP()
|
||||
}
|
||||
|
||||
// ConnectedUDPConn lets a dialed (connected) *net.UDPConn satisfy
|
||||
// net.PacketConn semantics: WriteTo ignores the destination since the kernel
|
||||
// already has it from connect().
|
||||
type ConnectedUDPConn struct {
|
||||
*net.UDPConn
|
||||
}
|
||||
|
||||
// WriteTo discards the addr (UDP is already connected) and writes p.
|
||||
func (c *ConnectedUDPConn) WriteTo(p []byte, _ net.Addr) (int, error) {
|
||||
return c.Write(p)
|
||||
}
|
||||
|
||||
// SplitFirstWriteConn wraps a TCP net.Conn and splits the very first Write
|
||||
// into two segments (SplitAt bytes + remainder) with an optional Delay between
|
||||
// them. This breaks DPI rules that match a fixed offset in the first segment
|
||||
// without TCP reassembly (e.g. the STUN magic cookie at offset 4-7).
|
||||
type SplitFirstWriteConn struct {
|
||||
net.Conn
|
||||
SplitAt int
|
||||
Delay time.Duration
|
||||
done atomic.Bool
|
||||
}
|
||||
|
||||
// Write performs the one-shot split on the first call, then forwards directly.
|
||||
func (s *SplitFirstWriteConn) Write(b []byte) (int, error) {
|
||||
if s.done.CompareAndSwap(false, true) && len(b) > s.SplitAt {
|
||||
n1, err := s.Conn.Write(b[:s.SplitAt])
|
||||
if err != nil {
|
||||
return n1, err
|
||||
}
|
||||
if s.Delay > 0 {
|
||||
time.Sleep(s.Delay)
|
||||
}
|
||||
n2, err := s.Conn.Write(b[s.SplitAt:])
|
||||
return n1 + n2, err
|
||||
}
|
||||
return s.Conn.Write(b)
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package netadapt
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// pipeRecorder is a net.Conn that records the slice handed to each Write.
|
||||
type pipeRecorder struct {
|
||||
net.Conn
|
||||
mu sync.Mutex
|
||||
writes [][]byte
|
||||
}
|
||||
|
||||
func (p *pipeRecorder) Write(b []byte) (int, error) {
|
||||
p.mu.Lock()
|
||||
cp := make([]byte, len(b))
|
||||
copy(cp, b)
|
||||
p.writes = append(p.writes, cp)
|
||||
p.mu.Unlock()
|
||||
return len(b), nil
|
||||
}
|
||||
|
||||
func newRecorder() *pipeRecorder {
|
||||
a, b := net.Pipe()
|
||||
go func() { _ = b.Close() }()
|
||||
_ = a
|
||||
return &pipeRecorder{Conn: dummyConn{}}
|
||||
}
|
||||
|
||||
type dummyConn struct{ net.Conn }
|
||||
|
||||
func (dummyConn) Close() error { return nil }
|
||||
func (dummyConn) LocalAddr() net.Addr { return nil }
|
||||
func (dummyConn) RemoteAddr() net.Addr { return nil }
|
||||
func (dummyConn) SetDeadline(time.Time) error { return nil }
|
||||
func (dummyConn) SetReadDeadline(time.Time) error { return nil }
|
||||
func (dummyConn) SetWriteDeadline(time.Time) error { return nil }
|
||||
func (dummyConn) Read(b []byte) (int, error) { return 0, nil }
|
||||
|
||||
func TestSplitFirstWriteConn_SplitsFirstWrite(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
rec := newRecorder()
|
||||
c := &SplitFirstWriteConn{Conn: rec, SplitAt: 6}
|
||||
payload := []byte("ABCDEF01234567")
|
||||
n, err := c.Write(payload)
|
||||
if err != nil {
|
||||
t.Fatalf("Write err: %v", err)
|
||||
}
|
||||
if n != len(payload) {
|
||||
t.Fatalf("Write n=%d want %d", n, len(payload))
|
||||
}
|
||||
if len(rec.writes) != 2 {
|
||||
t.Fatalf("expected 2 underlying writes, got %d", len(rec.writes))
|
||||
}
|
||||
if !bytes.Equal(rec.writes[0], payload[:6]) {
|
||||
t.Fatalf("first segment = %q, want %q", rec.writes[0], payload[:6])
|
||||
}
|
||||
if !bytes.Equal(rec.writes[1], payload[6:]) {
|
||||
t.Fatalf("second segment = %q, want %q", rec.writes[1], payload[6:])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitFirstWriteConn_SubsequentWritesPassThrough(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
rec := newRecorder()
|
||||
c := &SplitFirstWriteConn{Conn: rec, SplitAt: 6}
|
||||
if _, err := c.Write([]byte("ABCDEF01234567")); err != nil {
|
||||
t.Fatalf("first Write: %v", err)
|
||||
}
|
||||
if _, err := c.Write([]byte("XYZXYZ")); err != nil {
|
||||
t.Fatalf("second Write: %v", err)
|
||||
}
|
||||
if len(rec.writes) != 3 {
|
||||
t.Fatalf("expected 3 underlying writes after second call (2+1), got %d", len(rec.writes))
|
||||
}
|
||||
if !bytes.Equal(rec.writes[2], []byte("XYZXYZ")) {
|
||||
t.Fatalf("third write = %q, want XYZXYZ", rec.writes[2])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitFirstWriteConn_ShortFirstWriteNoSplit(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
rec := newRecorder()
|
||||
c := &SplitFirstWriteConn{Conn: rec, SplitAt: 6}
|
||||
if _, err := c.Write([]byte("ABC")); err != nil { // len < SplitAt
|
||||
t.Fatalf("Write: %v", err)
|
||||
}
|
||||
if len(rec.writes) != 1 {
|
||||
t.Fatalf("expected single underlying write, got %d", len(rec.writes))
|
||||
}
|
||||
if !bytes.Equal(rec.writes[0], []byte("ABC")) {
|
||||
t.Fatalf("write = %q, want ABC", rec.writes[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitFirstWriteConn_DelayApplied(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
rec := newRecorder()
|
||||
c := &SplitFirstWriteConn{Conn: rec, SplitAt: 4, Delay: 25 * time.Millisecond}
|
||||
start := time.Now()
|
||||
if _, err := c.Write([]byte("ABCDEFGH")); err != nil {
|
||||
t.Fatalf("Write: %v", err)
|
||||
}
|
||||
elapsed := time.Since(start)
|
||||
if elapsed < 20*time.Millisecond {
|
||||
t.Fatalf("expected delay >= 20ms, got %v", elapsed)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// Package stats provides throughput counters and a counting net.Conn wrapper
|
||||
// shared between the client and server binaries.
|
||||
package stats
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Stats tracks tx/rx byte counters. When Enabled is false, Add* are no-ops and
|
||||
// LogEvery returns immediately, matching the original isDebug-gated behavior.
|
||||
type Stats struct {
|
||||
tx atomic.Uint64
|
||||
rx atomic.Uint64
|
||||
enabled bool
|
||||
}
|
||||
|
||||
// New returns a Stats with the given enabled flag.
|
||||
func New(enabled bool) *Stats {
|
||||
return &Stats{enabled: enabled}
|
||||
}
|
||||
|
||||
// AddTx records n bytes sent.
|
||||
func (s *Stats) AddTx(n int) {
|
||||
if !s.enabled || n <= 0 {
|
||||
return
|
||||
}
|
||||
s.tx.Add(uint64(n))
|
||||
}
|
||||
|
||||
// AddRx records n bytes received.
|
||||
func (s *Stats) AddRx(n int) {
|
||||
if !s.enabled || n <= 0 {
|
||||
return
|
||||
}
|
||||
s.rx.Add(uint64(n))
|
||||
}
|
||||
|
||||
// LogEvery emits a throughput summary every 5s via logf until ctx is canceled.
|
||||
// No-op if Stats is disabled.
|
||||
func (s *Stats) LogEvery(ctx context.Context, logf func(string, ...any), label, txName, rxName string) {
|
||||
if !s.enabled {
|
||||
return
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(5 * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
var prevTx, prevRx uint64
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
tx := s.tx.Load()
|
||||
rx := s.rx.Load()
|
||||
deltaTx := tx - prevTx
|
||||
deltaRx := rx - prevRx
|
||||
prevTx = tx
|
||||
prevRx = rx
|
||||
|
||||
if deltaTx == 0 && deltaRx == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
logf(
|
||||
"%s throughput: %s=%s %s=%s total_%s=%s total_%s=%s",
|
||||
label,
|
||||
txName,
|
||||
FormatBitsPerSecond(deltaTx, 5*time.Second),
|
||||
rxName,
|
||||
FormatBitsPerSecond(deltaRx, 5*time.Second),
|
||||
txName,
|
||||
FormatByteCount(tx),
|
||||
rxName,
|
||||
FormatByteCount(rx),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// FormatBitsPerSecond renders a bandwidth value from a byte count and interval.
|
||||
func FormatBitsPerSecond(bytes uint64, interval time.Duration) string {
|
||||
if interval <= 0 {
|
||||
interval = time.Second
|
||||
}
|
||||
|
||||
bps := float64(bytes*8) / interval.Seconds()
|
||||
if bps >= 1_000_000 {
|
||||
return fmt.Sprintf("%.2f Mbit/s", bps/1_000_000)
|
||||
}
|
||||
if bps >= 1_000 {
|
||||
return fmt.Sprintf("%.1f kbit/s", bps/1_000)
|
||||
}
|
||||
return fmt.Sprintf("%.0f bit/s", bps)
|
||||
}
|
||||
|
||||
// FormatByteCount renders a human-readable byte count.
|
||||
func FormatByteCount(bytes uint64) string {
|
||||
if bytes >= 1024*1024 {
|
||||
return fmt.Sprintf("%.2f MiB", float64(bytes)/(1024*1024))
|
||||
}
|
||||
if bytes >= 1024 {
|
||||
return fmt.Sprintf("%.1f KiB", float64(bytes)/1024)
|
||||
}
|
||||
return fmt.Sprintf("%d B", bytes)
|
||||
}
|
||||
|
||||
// CountingConn wraps a net.Conn and accumulates rx/tx byte counters in Stats.
|
||||
type CountingConn struct {
|
||||
net.Conn
|
||||
Stats *Stats
|
||||
}
|
||||
|
||||
// Read reads from the underlying conn and updates rx counter.
|
||||
func (c *CountingConn) Read(p []byte) (int, error) {
|
||||
n, err := c.Conn.Read(p)
|
||||
c.Stats.AddRx(n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// Write writes to the underlying conn and updates tx counter.
|
||||
func (c *CountingConn) Write(p []byte) (int, error) {
|
||||
n, err := c.Conn.Write(p)
|
||||
c.Stats.AddTx(n)
|
||||
return n, err
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package stats
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestFormatBitsPerSecond(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cases := []struct {
|
||||
bytes uint64
|
||||
interval time.Duration
|
||||
want string
|
||||
}{
|
||||
{0, time.Second, "0 bit/s"},
|
||||
{125, time.Second, "1.0 kbit/s"}, // 1000 bit/s
|
||||
{125_000, time.Second, "1.00 Mbit/s"}, // 1_000_000 bit/s
|
||||
{50, time.Second, "400 bit/s"},
|
||||
{1_000_000, 5 * time.Second, "1.60 Mbit/s"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got := FormatBitsPerSecond(c.bytes, c.interval)
|
||||
if got != c.want {
|
||||
t.Errorf("FormatBitsPerSecond(%d, %s) = %q, want %q", c.bytes, c.interval, got, c.want)
|
||||
}
|
||||
}
|
||||
|
||||
// interval <= 0 should not panic and should default to 1s.
|
||||
if got := FormatBitsPerSecond(125, 0); !strings.Contains(got, "kbit/s") {
|
||||
t.Errorf("zero interval fallback: got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatByteCount(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cases := []struct {
|
||||
bytes uint64
|
||||
want string
|
||||
}{
|
||||
{0, "0 B"},
|
||||
{1023, "1023 B"},
|
||||
{1024, "1.0 KiB"},
|
||||
{1024 * 1024, "1.00 MiB"},
|
||||
{2 * 1024 * 1024, "2.00 MiB"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got := FormatByteCount(c.bytes)
|
||||
if got != c.want {
|
||||
t.Errorf("FormatByteCount(%d) = %q, want %q", c.bytes, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsDisabledNoOp(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := New(false)
|
||||
s.AddTx(1234)
|
||||
s.AddRx(5678)
|
||||
if got := s.tx.Load(); got != 0 {
|
||||
t.Errorf("disabled AddTx leaked: tx=%d", got)
|
||||
}
|
||||
if got := s.rx.Load(); got != 0 {
|
||||
t.Errorf("disabled AddRx leaked: rx=%d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsEnabledAccumulates(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := New(true)
|
||||
s.AddTx(100)
|
||||
s.AddTx(50)
|
||||
s.AddRx(7)
|
||||
s.AddTx(-5) // negative: ignored
|
||||
s.AddRx(0) // zero: ignored
|
||||
if got := s.tx.Load(); got != 150 {
|
||||
t.Errorf("tx=%d, want 150", got)
|
||||
}
|
||||
if got := s.rx.Load(); got != 7 {
|
||||
t.Errorf("rx=%d, want 7", got)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user