Skip to content

Commit

Permalink
redo the shuffle to be a single pass
Browse files Browse the repository at this point in the history
  • Loading branch information
demmer committed Apr 12, 2024
1 parent 2622872 commit ff32f97
Showing 1 changed file with 17 additions and 13 deletions.
30 changes: 17 additions & 13 deletions go/vt/vtgateproxy/discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -267,19 +267,23 @@ func (b *JSONGateResolverBuilder) update(r *JSONGateResolver) {
}
}

// Shuffle to ensure every host has a different order to iterate through
b.rand.Shuffle(len(targets), func(i, j int) {
targets[i], targets[j] = targets[j], targets[i]
})

// If affinity is specified, then shuffle those hosts to the front
if r.affinity != "" {
i := 0
for j := 0; j < len(targets); j++ {
if r.affinity == targets[j].affinity {
targets[i], targets[j] = targets[j], targets[i]
i++
}
// Shuffle to ensure every host has a different order to iterate through, putting
// the affinity matching (e.g. same az) hosts at the front and the non-matching ones
// at the end.
//
// Only need to do n-1 swaps since the last host is always in the right place.
n := len(targets)
head := 0
tail := n - 1
for i := 0; i < n-1; i++ {
j := head + rand.Intn(tail-head+1)

if r.affinity == "" || r.affinity == targets[j].affinity {
targets[head], targets[j] = targets[j], targets[head]
head++
} else {
targets[tail], targets[j] = targets[j], targets[tail]
tail--
}
}

Expand Down

0 comments on commit ff32f97

Please sign in to comment.