Skip to content
Merged
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
7 changes: 6 additions & 1 deletion src/utils/http-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,12 @@ export const testUrls = async (urls?: string[]) => {
if (!urls?.length) {
return null;
}
const ret = await promiseAny(urls.map(ping));
let ret: string | null = null;
try {
ret = await promiseAny(urls.map(ping));
} catch (_e) {
// fallback to urls[0]
}
if (ret) {
return ret;
}
Expand Down
57 changes: 56 additions & 1 deletion tests/http-helper.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { describe, expect, test } from 'bun:test';
import { afterEach, describe, expect, mock, test } from 'bun:test';

const runtimeFetchMock = mock(() => Promise.resolve({ status: 200 }));
mock.module('../src/utils/runtime', () => ({
runtimeFetch: runtimeFetchMock,
}));

import { promiseAny, testUrls } from '../src/utils/http-helper';

describe('promiseAny', () => {
Expand Down Expand Up @@ -41,3 +47,52 @@ describe('testUrls', () => {
expect(result).toBeNull();
});
});

describe('testUrls edge cases', () => {
afterEach(() => {
runtimeFetchMock.mockReset();
});

test('Happy Path: returns successful URL', async () => {
runtimeFetchMock.mockImplementation((url: string) => {
if (url === 'http://success.local') {
return Promise.resolve({ status: 200 });
}
return Promise.reject(new Error('fail'));
});

const result = await testUrls([
'http://fail.local',
'http://success.local',
]);
expect(result).toBe('http://success.local');
});

test('Fastest Response: returns the URL that resolves first', async () => {
runtimeFetchMock.mockImplementation((url: string) => {
if (url === 'http://fast.local') {
return new Promise((resolve) =>
setTimeout(() => resolve({ status: 200 }), 10),
);
}
if (url === 'http://slow.local') {
return new Promise((resolve) =>
setTimeout(() => resolve({ status: 200 }), 50),
);
}
return Promise.reject(new Error('fail'));
});

const result = await testUrls(['http://slow.local', 'http://fast.local']);
expect(result).toBe('http://fast.local');
});

test('All Failures (Fallback): returns urls[0] without throwing', async () => {
runtimeFetchMock.mockImplementation(() => {
return Promise.resolve({ status: 500 });
});

const result = await testUrls(['http://fail1.local', 'http://fail2.local']);
expect(result).toBe('http://fail1.local');
});
});