Skip to content

Commit

Permalink
grpc-js-xds: Use simpler search algorithm in weighted target picker
Browse files Browse the repository at this point in the history
  • Loading branch information
murgatroid99 committed Feb 24, 2023
1 parent cac499f commit 865731b
Showing 1 changed file with 7 additions and 22 deletions.
29 changes: 7 additions & 22 deletions packages/grpc-js-xds/src/load-balancer-weighted-target.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,31 +119,16 @@ class WeightedTargetPicker implements Picker {
pick(pickArgs: PickArgs): PickResult {
// num | 0 is equivalent to floor(num)
const selection = (Math.random() * this.rangeTotal) | 0;

/* Binary search for the element of the list such that
* pickerList[index - 1].rangeEnd <= selection < pickerList[index].rangeEnd
*/
let mid = 0;
let startIndex = 0;
let endIndex = this.pickerList.length - 1;
let index = 0;
while (endIndex > startIndex) {
mid = ((startIndex + endIndex) / 2) | 0;
if (this.pickerList[mid].rangeEnd > selection) {
endIndex = mid;
} else if (this.pickerList[mid].rangeEnd < selection) {
startIndex = mid + 1;
} else {
// + 1 here because the range is exclusive at the top end
index = mid + 1;
break;

for (const entry of this.pickerList) {
if (selection < entry.rangeEnd) {
return entry.picker.pick(pickArgs);
}
}
if (index === 0) {
index = startIndex;
}

return this.pickerList[index].picker.pick(pickArgs);
/* Default to first element if the iteration doesn't find anything for some
* reason. */
return this.pickerList[0].picker.pick(pickArgs);
}
}

Expand Down

0 comments on commit 865731b

Please sign in to comment.