From 02c696fa28ac687e979a4c11f9bf630746ef3098 Mon Sep 17 00:00:00 2001 From: samosvalishe Date: Mon, 7 Sep 2026 02:45:48 +0300 Subject: [PATCH] fix(tunnel): race --- mobile/tunnel.go | 10 +++++++--- mobile/tunnel_test.go | 5 +++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/mobile/tunnel.go b/mobile/tunnel.go index 40cfd78..aaefc25 100644 --- a/mobile/tunnel.go +++ b/mobile/tunnel.go @@ -3,6 +3,7 @@ package mobile import ( "errors" "fmt" + "math" "net" "net/netip" "strings" @@ -256,13 +257,16 @@ func directSnapshot(l *live) *Snapshot { } func (l *live) fillRates(s *Snapshot) { + l.fillRatesAt(s, time.Now()) +} + +func (l *live) fillRatesAt(s *Snapshot, now time.Time) { l.rateMu.Lock() defer l.rateMu.Unlock() - now := time.Now() if dt := now.Sub(l.prevAt).Seconds(); !l.prevAt.IsZero() && dt > 0 { - s.TxRate = int64(float64(s.TxTotal-l.prevTx) / dt) - s.RxRate = int64(float64(s.RxTotal-l.prevRx) / dt) + s.TxRate = int64(math.Round(float64(s.TxTotal-l.prevTx) / dt)) + s.RxRate = int64(math.Round(float64(s.RxTotal-l.prevRx) / dt)) } l.prevTx, l.prevRx, l.prevAt = s.TxTotal, s.RxTotal, now } diff --git a/mobile/tunnel_test.go b/mobile/tunnel_test.go index eb29b6b..0abaccf 100644 --- a/mobile/tunnel_test.go +++ b/mobile/tunnel_test.go @@ -310,10 +310,11 @@ func TestDirectSnapshotErrorKeepsStreams(t *testing.T) { // Скорость берётся из дельты между опросами хоста. func TestFillRatesUsesDelta(t *testing.T) { - l := &live{prevTx: 1000, prevRx: 500, prevAt: time.Now().Add(-2 * time.Second)} + now := time.Now() + l := &live{prevTx: 1000, prevRx: 500, prevAt: now.Add(-2 * time.Second)} s := &Snapshot{TxTotal: 3000, RxTotal: 1500} - l.fillRates(s) + l.fillRatesAt(s, now) if s.TxRate != 1000 || s.RxRate != 500 { t.Errorf("rates = %d/%d, want 1000/500", s.TxRate, s.RxRate)