Skip to content

Commit

Permalink
fix: use atomic in retrier to prevent race conditions (#518)
Browse files Browse the repository at this point in the history
  • Loading branch information
ignoramous authored Jun 25, 2024
1 parent ede31e6 commit 5c6d68d
Showing 1 changed file with 7 additions and 12 deletions.
19 changes: 7 additions & 12 deletions Android/app/src/go/intra/split/retrier.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"math/rand"
"net"
"sync"
"sync/atomic"
"time"

"github.com/Jigsaw-Code/getsni"
Expand Down Expand Up @@ -62,8 +63,8 @@ type retrier struct {
// Flag indicating when retry is finished or unnecessary.
retryCompleteFlag chan struct{}
// Flags indicating whether the caller has called CloseRead and CloseWrite.
readCloseFlag chan struct{}
writeCloseFlag chan struct{}
readCloseFlag atomic.Bool
writeCloseFlag atomic.Bool
stats *RetryStats
}

Expand All @@ -87,11 +88,11 @@ func closed(c chan struct{}) bool {
}

func (r *retrier) readClosed() bool {
return closed(r.readCloseFlag)
return r.readCloseFlag.Load()
}

func (r *retrier) writeClosed() bool {
return closed(r.writeCloseFlag)
return r.writeCloseFlag.Load()
}

func (r *retrier) retryCompleted() bool {
Expand Down Expand Up @@ -142,8 +143,6 @@ func DialWithSplitRetry(ctx context.Context, dialer *net.Dialer, addr *net.TCPAd
conn: conn.(*net.TCPConn),
timeout: timeout(before, after),
retryCompleteFlag: make(chan struct{}),
readCloseFlag: make(chan struct{}),
writeCloseFlag: make(chan struct{}),
stats: stats,
}

Expand Down Expand Up @@ -211,9 +210,7 @@ func (r *retrier) retry(buf []byte) (n int, err error) {
}

func (r *retrier) CloseRead() error {
if !r.readClosed() {
close(r.readCloseFlag)
}
r.readCloseFlag.Store(true)
r.mutex.Lock()
defer r.mutex.Unlock()
return r.conn.CloseRead()
Expand Down Expand Up @@ -363,9 +360,7 @@ func (r *retrier) ReadFrom(reader io.Reader) (bytes int64, err error) {
}

func (r *retrier) CloseWrite() error {
if !r.writeClosed() {
close(r.writeCloseFlag)
}
r.writeCloseFlag.Store(true)
r.mutex.Lock()
defer r.mutex.Unlock()
return r.conn.CloseWrite()
Expand Down

0 comments on commit 5c6d68d

Please sign in to comment.