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