Skip to content

Commit

Permalink
feat(policy): Added StrictRoundRobinPolicy to solve the data race (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
flc1125 authored Apr 22, 2024
1 parent db961ff commit e56c9c9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
8 changes: 8 additions & 0 deletions ent/driver/multi/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package multi

import (
"math/rand"
"sync/atomic"

"entgo.io/ent/dialect"
)
Expand All @@ -24,6 +25,13 @@ func RoundRobinPolicy() Policy {
})
}

func StrictRoundRobinPolicy() Policy {
var i int64
return PolicyFunc(func(drivers []dialect.Driver) dialect.Driver {
return drivers[int(atomic.LoadInt64(&i))%len(drivers)]
})
}

func RandomPolicy() Policy {
return PolicyFunc(func(drivers []dialect.Driver) dialect.Driver {
return drivers[rand.Intn(len(drivers))]
Expand Down
19 changes: 17 additions & 2 deletions ent/driver/multi/policy_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package multi

import (
"sync/atomic"
"testing"

"entgo.io/ent/dialect"
Expand All @@ -10,11 +11,13 @@ import (
var driver1, driver2, driver3 dialect.Driver

func TestPolicy_RoundRobinPolicy(t *testing.T) {
p := RoundRobinPolicy()
p1 := RoundRobinPolicy()
p2 := StrictRoundRobinPolicy()
drivers := []dialect.Driver{driver1, driver2, driver3}

for i := 0; i < 10; i++ {
assert.Equal(t, drivers[i%3], p.Resolve(drivers))
assert.Equal(t, drivers[i%3], p1.Resolve(drivers))
assert.Equal(t, drivers[i%3], p2.Resolve(drivers))
}
}

Expand All @@ -26,3 +29,15 @@ func TestPolicy_RandomPolicy(t *testing.T) {
assert.Contains(t, drivers, p.Resolve(drivers))
}
}

func BenchmarkPolicy_StrictRoundRobinPolicy(b *testing.B) {
p := StrictRoundRobinPolicy()
drivers := []dialect.Driver{driver1, driver2, driver3}

var i int64
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
assert.Equal(b, drivers[int(atomic.AddInt64(&i, 1))%3], p.Resolve(drivers))
}
})
}

0 comments on commit e56c9c9

Please sign in to comment.