fix: periodicProxyStats.connectionCount race

And `failedConnectionCount`.
Convert the `int` / `uint` to `atomic.Int32` / `atomic.Uint32`.
The race was discovered by running a proxy with the `-race` flag.
This commit is contained in:
WofWca 2025-03-03 00:20:13 +04:00
parent 4205121689
commit 730e400123

View file

@ -3,6 +3,7 @@ package snowflake_proxy
import (
"io"
"log"
"sync/atomic"
"time"
"gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/event"
@ -44,9 +45,9 @@ func (p *proxyEventLogger) OnNewSnowflakeEvent(e event.SnowflakeEvent) {
type periodicProxyStats struct {
bytesLogger bytesLogger
// Completed successful connections.
connectionCount int
connectionCount atomic.Int32
// Connections that failed to establish.
failedConnectionCount uint
failedConnectionCount atomic.Uint32
logPeriod time.Duration
task *task.Periodic
dispatcher event.SnowflakeEventDispatcher
@ -62,9 +63,9 @@ func newPeriodicProxyStats(logPeriod time.Duration, dispatcher event.SnowflakeEv
func (p *periodicProxyStats) OnNewSnowflakeEvent(e event.SnowflakeEvent) {
switch e.(type) {
case event.EventOnProxyConnectionOver:
p.connectionCount += 1
p.connectionCount.Add(1)
case event.EventOnProxyConnectionFailed:
p.failedConnectionCount += 1
p.failedConnectionCount.Add(1)
}
}
@ -72,14 +73,12 @@ func (p *periodicProxyStats) logTick() error {
inboundSum, outboundSum := p.bytesLogger.GetStat()
e := event.EventOnProxyStats{
SummaryInterval: p.logPeriod,
ConnectionCount: p.connectionCount,
FailedConnectionCount: p.failedConnectionCount,
ConnectionCount: int(p.connectionCount.Swap(0)),
FailedConnectionCount: uint(p.failedConnectionCount.Swap(0)),
}
e.InboundBytes, e.InboundUnit = formatTraffic(inboundSum)
e.OutboundBytes, e.OutboundUnit = formatTraffic(outboundSum)
p.dispatcher.OnNewSnowflakeEvent(e)
p.connectionCount = 0
p.failedConnectionCount = 0
return nil
}