Skip to content

Commit

Permalink
scylla: conn picker int32 overflow fix
Browse files Browse the repository at this point in the history
Fixes #29
  • Loading branch information
Sebastian Restrepo authored and Henrik Johansson committed Feb 6, 2020
1 parent 3306947 commit e635f92
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
4 changes: 2 additions & 2 deletions scylla.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ type scyllaConnPicker struct {
nrConns int
nrShards int
msbIgnore uint64
pos int32
pos uint64
}

func newScyllaConnPicker(conn *Conn) *scyllaConnPicker {
Expand Down Expand Up @@ -231,7 +231,7 @@ func (p *scyllaConnPicker) closeExcessConns() {
}

func (p *scyllaConnPicker) randomConn() *Conn {
idx := int(atomic.AddInt32(&p.pos, 1))
idx := int(atomic.AddUint64(&p.pos, 1))
for i := 0; i < len(p.conns); i++ {
if conn := p.conns[(idx+i)%len(p.conns)]; conn != nil {
return conn
Expand Down
48 changes: 48 additions & 0 deletions scylla_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package gocql

import (
"math"
"runtime"
"sync"
"testing"
Expand Down Expand Up @@ -136,3 +137,50 @@ func TestScyllaConnPickerShardOf(t *testing.T) {
}
}
}

func TestScyllaRandomConnPIcker(t *testing.T) {
t.Parallel()

t.Run("max iterations", func(t *testing.T) {
s := &scyllaConnPicker{
nrShards: 4,
msbIgnore: 12,
pos: math.MaxUint64,
conns: []*Conn{nil, mockConn("1")},
}

if s.Pick(token(nil)) == nil {
t.Fatal("expected connection")
}
})

t.Run("async access of max iterations", func(t *testing.T) {
s := &scyllaConnPicker{
nrShards: 4,
msbIgnore: 12,
pos: math.MaxUint64,
conns: []*Conn{nil, mockConn("1")},
}

var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1)
go pickLoop(t, s, 3, &wg)
}
wg.Wait()

if s.pos != 8 {
t.Fatalf("expected position to be 8 | actual %d", s.pos)
}
})
}

func pickLoop(t *testing.T, s *scyllaConnPicker, c int, wg *sync.WaitGroup) {
t.Helper()
for i := 0; i < c; i++ {
if s.Pick(token(nil)) == nil {
t.Fatal("expected connection")
}
}
wg.Done()
}

0 comments on commit e635f92

Please sign in to comment.