diff --git a/utils/network.js b/utils/network.js index b4eb275..a45c778 100644 --- a/utils/network.js +++ b/utils/network.js @@ -1,29 +1,27 @@ -import http from 'http'; -import https from 'https'; -export async function checkLatency(url) { - let request = http; - if (url.startsWith('https')) { - request = https; +import fetch from 'node-fetch'; + +export async function checkLatency(url, timeout = 5000) { + const controller = new AbortController() + const { signal } = controller + const timeoutId = setTimeout(() => controller.abort(), timeout) + + const start = Date.now() + + try { + await fetch(url, { signal }) + const latency = Date.now() - start + return { url, latency } + } catch (err) { + logger.debug(`下载节点 ${url} 连接失败:`, err.message) + return { url, latency: Infinity } + } finally { + clearTimeout(timeoutId) } - return new Promise(resolve => { - const start = Date.now(); - request - .get(url, res => { - res.on('data', () => {}); - res.on('end', () => { - const latency = Date.now() - start; - resolve({ url, latency }); - }); - }) - .on('error', err => { - logger.debug(`下载节点 ${url} 连接失败:`, err.message); - resolve({ url, latency: Infinity }); - }); - }); } + export async function findLowestLatencyUrl(urls) { - const results = await Promise.all(urls.map(checkLatency)); + const results = await Promise.allSettled(urls.map(checkLatency)); const lowestLatencyResult = results.reduce((prev, curr) => prev.latency < curr.latency ? prev : curr ); diff --git a/utils/request.js b/utils/request.js index e728ab8..4e99a5f 100644 --- a/utils/request.js +++ b/utils/request.js @@ -23,18 +23,24 @@ const _request = async (url, options) => { * @param {number} retry 重试次数 * @returns {Promise} */ -const request = (url, options, retry = 0) => { +const request = (url, options, retry = 0, timeout = 5000) => { let err; + const controller = new AbortController() + const { signal } = controller + const timeoutId = setTimeout(() => controller.abort(), timeout) + const _fetch = async (url, options, retryCount = 0) => { if (retryCount > retry) { throw new Error('Retry limit reached', err); } try { - return await _request(url, options); + return await _request(url, { signal, ...options }); } catch (error) { - logger.debug(`Fetch error: ${error.message}`); + logger.debug(error.name === 'AbortError' ? 'Request timed out' : `Fetch error: ${error.message}`); err = error; return await _fetch(url, options, retryCount + 1); + } finally { + clearTimeout(timeoutId) } }; return _fetch(url, options); @@ -49,8 +55,8 @@ const request = (url, options, retry = 0) => { */ request.get = async (url, data, options) => { const params = new URLSearchParams(data); - const { retry, ...restOptions } = options; - return request(`${url}?${params}`, restOptions, retry); + const { retry, timeout, ...restOptions } = options; + return request(`${url}?${params}`, restOptions, retry, timeout); }; /** @@ -62,8 +68,8 @@ request.get = async (url, data, options) => { */ request.post = async (url, data, options) => { const body = JSON.stringify(data); - const { retry, ...restOptions } = options; - return request(url, { ...restOptions, method: 'POST', body }, retry); + const { retry, timeout, ...restOptions } = options; + return request(url, { ...restOptions, method: 'POST', body }, retry, timeout); }; export default request;