Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion src/__tests__/endpoint.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, mock, test } from 'bun:test';
import { executeEndpointFallback } from '../endpoint';
import { executeEndpointFallback, pickRandomEndpoint } from '../endpoint';

const delay = (ms: number) =>
new Promise<void>(resolve => {
Expand Down Expand Up @@ -90,3 +90,34 @@ describe('executeEndpointFallback', () => {
expect(tryEndpoint.mock.calls.map(call => call[0])).toEqual(['a', 'b', 'c']);
});
});

describe('pickRandomEndpoint', () => {
test('returns undefined for empty arrays', () => {
expect(pickRandomEndpoint([])).toBeUndefined();
});

test('deterministically selects an endpoint using a custom random parameter', () => {
const endpoints = ['a', 'b', 'c'];

// Test random = 0 (picks first)
const endpoints1 = [...endpoints];
expect(pickRandomEndpoint(endpoints1, () => 0)).toBe('a');

// Test random = 0.5 (picks middle)
const endpoints2 = [...endpoints];
expect(pickRandomEndpoint(endpoints2, () => 0.5)).toBe('b');

// Test random = 0.99 (picks last)
const endpoints3 = [...endpoints];
expect(pickRandomEndpoint(endpoints3, () => 0.99)).toBe('c');
});

test('mutates the original array by removing the selected endpoint', () => {
const endpoints = ['a', 'b', 'c'];
const result = pickRandomEndpoint(endpoints, () => 0.5);

expect(result).toBe('b');
expect(endpoints).toEqual(['a', 'c']);
expect(endpoints.length).toBe(2);
});
});
14 changes: 8 additions & 6 deletions src/endpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,11 @@ export const dedupeEndpoints = (

export const pickRandomEndpoint = (
endpoints: string[],
random: () => number = Math.random,
) => {
if (!endpoints.length) {
throw new Error('No endpoints configured');
}
return endpoints[Math.floor(random() * endpoints.length)];
random = Math.random,
): string | undefined => {
if (endpoints.length === 0) return undefined;
const index = Math.floor(random() * endpoints.length);
return endpoints.splice(index, 1)[0];
Comment on lines 45 to +51
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟑 Minor

Validate the injected RNG output before using it as an index.

random is part of the API here. Values like 1, negatives, or NaN can make splice(index, 1)[0] return the wrong element or undefined, which also makes the non-null assertion at Line 125 unsafe.

Proposed fix
 export const pickRandomEndpoint = (
   endpoints: string[],
   random = Math.random,
 ): string | undefined => {
   if (endpoints.length === 0) return undefined;
-  const index = Math.floor(random() * endpoints.length);
+  const value = random();
+  if (!Number.isFinite(value) || value < 0 || value >= 1) {
+    throw new RangeError('random() must return a number in [0, 1)');
+  }
+  const index = Math.floor(value * endpoints.length);
   return endpoints.splice(index, 1)[0];
 };
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const pickRandomEndpoint = (
endpoints: string[],
random: () => number = Math.random,
) => {
if (!endpoints.length) {
throw new Error('No endpoints configured');
}
return endpoints[Math.floor(random() * endpoints.length)];
random = Math.random,
): string | undefined => {
if (endpoints.length === 0) return undefined;
const index = Math.floor(random() * endpoints.length);
return endpoints.splice(index, 1)[0];
export const pickRandomEndpoint = (
endpoints: string[],
random = Math.random,
): string | undefined => {
if (endpoints.length === 0) return undefined;
const value = random();
if (!Number.isFinite(value) || value < 0 || value >= 1) {
throw new RangeError('random() must return a number in [0, 1)');
}
const index = Math.floor(value * endpoints.length);
return endpoints.splice(index, 1)[0];
};
πŸ€– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/endpoint.ts` around lines 45 - 51, The RNG output used in
pickRandomEndpoint (params: endpoints, random) must be validated before
computing the splice index: read random() into a value, coerce to Number, verify
it's finite and within [0,1), then compute index = Math.floor(value *
endpoints.length) and clamp to the valid index range (0 .. endpoints.length-1)
to avoid NaN, negatives or >=1 producing out-of-range indices; if validation
fails, fall back to a safe default index (e.g., 0) and then call
endpoints.splice(index, 1)[0] so the returned element is always defined and safe
for downstream non-null usage.

};

export async function selectFastestSuccessfulEndpoint<T>(
Expand Down Expand Up @@ -124,6 +123,9 @@ export async function executeEndpointFallback<T>({
}

const firstEndpoint = pickRandomEndpoint(candidates, random);
if (!firstEndpoint) {
throw new Error('No endpoints configured');
}

try {
return {
Expand Down