Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

grpc-js-xds: Use simpler search algorithm in weighted target picker #2395

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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