Skip to content

Commit

Permalink
policies: check available streams on conn
Browse files Browse the repository at this point in the history
RoundRobbin conn pool should check the available streams on a
connection before returning it.
  • Loading branch information
Zariel committed Nov 21, 2015
1 parent 7e6c797 commit f602774
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
20 changes: 14 additions & 6 deletions policies.go
Original file line number Diff line number Diff line change
Expand Up @@ -354,12 +354,20 @@ func (r *roundRobinConnPolicy) SetConns(conns []*Conn) {
}

func (r *roundRobinConnPolicy) Pick(qry *Query) *Conn {
pos := atomic.AddUint32(&r.pos, 1)
var conn *Conn
pos := int(atomic.AddUint32(&r.pos, 1) - 1)
r.mu.RLock()
if len(r.conns) > 0 {
conn = r.conns[pos%uint32(len(r.conns))]
defer r.mu.RUnlock()

if len(r.conns) == 0 {
return nil
}
r.mu.RUnlock()
return conn

for i := 0; i < len(r.conns); i++ {
conn := r.conns[(pos+i)%len(r.conns)]
if conn.AvailableStreams() > 0 {
return conn
}
}

return nil
}
12 changes: 6 additions & 6 deletions policies_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package gocql

import (
"fmt"
"github.com/gocql/gocql/internal/streams"
"testing"

"github.com/hailocab/go-hostpool"
Expand Down Expand Up @@ -147,23 +148,22 @@ func TestHostPoolHostPolicy(t *testing.T) {
func TestRoundRobinConnPolicy(t *testing.T) {
policy := RoundRobinConnPolicy()()

conn0 := &Conn{}
conn1 := &Conn{}
conn0 := &Conn{streams: streams.New(1)}
conn1 := &Conn{streams: streams.New(1)}
conn := []*Conn{
conn0,
conn1,
}

policy.SetConns(conn)

// the first conn selected is actually at [1], but this is ok for RR
if actual := policy.Pick(nil); actual != conn1 {
if actual := policy.Pick(nil); actual != conn0 {
t.Error("Expected conn1")
}
if actual := policy.Pick(nil); actual != conn0 {
if actual := policy.Pick(nil); actual != conn1 {
t.Error("Expected conn0")
}
if actual := policy.Pick(nil); actual != conn1 {
if actual := policy.Pick(nil); actual != conn0 {
t.Error("Expected conn1")
}
}
Expand Down

0 comments on commit f602774

Please sign in to comment.