Refactor server picker and limit ping requests
This commit is contained in:
+7
-6
@@ -16,6 +16,7 @@ import {
|
||||
} from './gatewayPresence.js';
|
||||
import { createSingboxRuntime } from './singboxRuntime.js';
|
||||
import { tcpPing } from './ping.js';
|
||||
import { checkServerHealth } from './serverHealth.js';
|
||||
import { buildSharedProxyInfo } from './sharedProxy.js';
|
||||
import {
|
||||
buildGatewayConfig,
|
||||
@@ -577,12 +578,12 @@ async function handleApi(req, res) {
|
||||
|
||||
if (req.method === 'POST' && req.url === '/api/servers/ping-all') {
|
||||
const state = stateStore.read();
|
||||
const results = await Promise.all((state.servers || []).map(async (server) => ({
|
||||
id: server.id,
|
||||
tag: server.label,
|
||||
...await tcpPing(server.host, server.port),
|
||||
checkedAt: new Date().toISOString(),
|
||||
})));
|
||||
const { serverIds = [] } = await readBody(req);
|
||||
const requestedIds = new Set(Array.isArray(serverIds) ? serverIds.map(String) : []);
|
||||
const servers = requestedIds.size
|
||||
? (state.servers || []).filter((server) => requestedIds.has(server.id))
|
||||
: state.servers || [];
|
||||
const results = await checkServerHealth(servers, tcpPing);
|
||||
return sendState(res, { results });
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
export const SERVER_HEALTH_MAX_COUNT = 30;
|
||||
export const SERVER_HEALTH_CONCURRENCY = 4;
|
||||
|
||||
export async function checkServerHealth(servers, ping, {
|
||||
maxCount = SERVER_HEALTH_MAX_COUNT,
|
||||
concurrency = SERVER_HEALTH_CONCURRENCY,
|
||||
} = {}) {
|
||||
const queue = servers.slice(0, maxCount);
|
||||
const results = new Array(queue.length);
|
||||
let nextIndex = 0;
|
||||
|
||||
async function worker() {
|
||||
while (nextIndex < queue.length) {
|
||||
const index = nextIndex++;
|
||||
const server = queue[index];
|
||||
results[index] = {
|
||||
id: server.id,
|
||||
tag: server.label,
|
||||
...await ping(server.host, server.port),
|
||||
checkedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(Array.from({ length: Math.min(concurrency, queue.length) }, worker));
|
||||
return results;
|
||||
}
|
||||
Reference in New Issue
Block a user