diff --git a/backend/package.json b/backend/package.json index 6e505048..ac046bf6 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.23.31", + "version": "2.23.33", "description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.", "main": "src/main.js", "packageManager": "pnpm@11.0.9", diff --git a/backend/src/restful/settings.js b/backend/src/restful/settings.js index 52e0469d..fc55aad1 100644 --- a/backend/src/restful/settings.js +++ b/backend/src/restful/settings.js @@ -4,6 +4,10 @@ import { InternalServerError } from '@/restful/errors'; import $ from '@/core/app'; import Gist, { getGithubGistBaseURL } from '@/utils/gist'; import { clearLogSettingsCache } from '@/utils/debug-logs'; +import { + BACKEND_REQUEST_CONCURRENCY_SETTING, + BACKEND_REQUEST_CONCURRENCY_WAIT_TIME_SETTING, +} from '@/utils/request-concurrency'; const ARTIFACT_STORE_SETTING_KEYS = [ 'gistToken', @@ -92,6 +96,36 @@ async function updateSettings(req, res) { delete newSettings.logsMaxCount; } } + if (BACKEND_REQUEST_CONCURRENCY_SETTING in newSettings) { + const rawConcurrency = + newSettings[BACKEND_REQUEST_CONCURRENCY_SETTING]; + const value = Number(rawConcurrency); + if ( + rawConcurrency === null || + rawConcurrency === undefined || + rawConcurrency === '' || + !Number.isInteger(value) || + value < 1 + ) { + delete newSettings[BACKEND_REQUEST_CONCURRENCY_SETTING]; + } + } + if (BACKEND_REQUEST_CONCURRENCY_WAIT_TIME_SETTING in newSettings) { + const rawWaitTime = + newSettings[BACKEND_REQUEST_CONCURRENCY_WAIT_TIME_SETTING]; + const value = Number(rawWaitTime); + if ( + rawWaitTime === null || + rawWaitTime === undefined || + rawWaitTime === '' || + !Number.isInteger(value) || + value < 0 + ) { + delete newSettings[ + BACKEND_REQUEST_CONCURRENCY_WAIT_TIME_SETTING + ]; + } + } $.write(newSettings, SETTINGS_KEY); clearLogSettingsCache(); if (shouldRefreshArtifactStoreForSettingsPatch(req.body)) { diff --git a/backend/src/test/proxy-processors/resolve-domain.spec.js b/backend/src/test/proxy-processors/resolve-domain.spec.js index 3278a08c..bf572c99 100644 --- a/backend/src/test/proxy-processors/resolve-domain.spec.js +++ b/backend/src/test/proxy-processors/resolve-domain.spec.js @@ -3,6 +3,7 @@ import { describe, it, beforeEach, afterEach } from 'mocha'; import $ from '@/core/app'; import PROCESSORS, { ApplyProcessor } from '@/core/proxy-utils/processors'; +import { SETTINGS_KEY } from '@/constants'; import resourceCache from '@/utils/resource-cache'; import { hex_md5 } from '@/vendor/md5'; @@ -14,15 +15,18 @@ function sleep(ms) { describe('Resolve Domain Operator', function () { let originalGoogleResolver; + let originalRead; let cacheKeys; beforeEach(function () { originalGoogleResolver = ResolveDomainOperator.resolver.Google; + originalRead = $.read.bind($); cacheKeys = []; }); afterEach(function () { ResolveDomainOperator.resolver.Google = originalGoogleResolver; + $.read = originalRead; cacheKeys.forEach((key) => { delete resourceCache.resourceCache[key]; }); @@ -146,6 +150,67 @@ describe('Resolve Domain Operator', function () { expect(maxActiveRequests).to.equal(15); }); + it('does not use backend request concurrency as the default', async function () { + $.read = (key) => { + if (key === SETTINGS_KEY) return { backendRequestConcurrency: 1 }; + return originalRead(key); + }; + const domains = Array.from({ length: 20 }, (_, index) => ({ + name: `Node ${index}`, + server: `backend-setting-${index}.example.com`, + port: 443, + })); + let activeRequests = 0; + let maxActiveRequests = 0; + + ResolveDomainOperator.resolver.Google = async (domain) => { + activeRequests += 1; + maxActiveRequests = Math.max(maxActiveRequests, activeRequests); + await sleep(5); + activeRequests -= 1; + return `192.0.2.${Number(domain.match(/\d+/)[0]) + 1}`; + }; + + const processor = ResolveDomainOperator({ + provider: 'Google', + type: 'IPv4', + }); + await ApplyProcessor(processor, domains); + + expect(maxActiveRequests).to.equal(15); + }); + + it('prefers explicit domain resolver concurrency over backend request concurrency', async function () { + $.read = (key) => { + if (key === SETTINGS_KEY) return { backendRequestConcurrency: 1 }; + return originalRead(key); + }; + const domains = Array.from({ length: 5 }, (_, index) => ({ + name: `Node ${index}`, + server: `explicit-domain-${index}.example.com`, + port: 443, + })); + let activeRequests = 0; + let maxActiveRequests = 0; + + ResolveDomainOperator.resolver.Google = async (domain) => { + activeRequests += 1; + maxActiveRequests = Math.max(maxActiveRequests, activeRequests); + await sleep(5); + activeRequests -= 1; + return `192.0.2.${Number(domain.match(/\d+/)[0]) + 1}`; + }; + + const processor = ResolveDomainOperator({ + provider: 'Google', + type: 'IPv4', + concurrency: 2, + }); + await ApplyProcessor(processor, domains); + + expect(maxActiveRequests).to.equal(2); + }); + it('rejects invalid concurrency values', function () { expect(() => ResolveDomainOperator({ diff --git a/backend/src/test/restful/settings.spec.js b/backend/src/test/restful/settings.spec.js index d5900937..a241e973 100644 --- a/backend/src/test/restful/settings.spec.js +++ b/backend/src/test/restful/settings.spec.js @@ -1,11 +1,54 @@ import { expect } from 'chai'; -import { describe, it } from 'mocha'; +import { afterEach, describe, it } from 'mocha'; -import { +import $ from '@/core/app'; +import { SETTINGS_KEY } from '@/constants'; +import registerSettingsRoutes, { getGithubAvatarApiUrl, shouldRefreshArtifactStoreForSettingsPatch, } from '@/restful/settings'; +function createRouteApp() { + const handlers = new Map(); + const app = { + handlers, + route(pattern) { + const chain = {}; + chain.get = (handler) => { + handlers.set(`GET ${pattern}`, handler); + return chain; + }; + chain.patch = (handler) => { + handlers.set(`PATCH ${pattern}`, handler); + return chain; + }; + return chain; + }, + }; + + return app; +} + +function createResponse(routePath) { + return { + body: null, + req: { + route: { + path: routePath, + }, + }, + statusCode: 200, + status(code) { + this.statusCode = code; + return this; + }, + json(payload) { + this.body = payload; + return this; + }, + }; +} + describe('settings routes', function () { describe('artifact store refresh detection', function () { it('refreshes when GitHub API URL changes', function () { @@ -71,4 +114,105 @@ describe('settings routes', function () { ).to.equal('https://litegist.example.com/api/users/xream'); }); }); + + describe('backend request concurrency settings', function () { + const originalRead = $.read.bind($); + const originalWrite = $.write.bind($); + + afterEach(function () { + $.read = originalRead; + $.write = originalWrite; + }); + + async function patchSettings(initialSettings, body) { + const state = { + [SETTINGS_KEY]: initialSettings, + }; + $.read = (key) => state[key]; + $.write = (data, key) => { + state[key] = data; + return true; + }; + + const app = createRouteApp(); + registerSettingsRoutes(app); + const patchHandler = app.handlers.get('PATCH /api/settings'); + const res = createResponse('/api/settings'); + + await patchHandler({ body }, res); + + expect(res.body.status).to.equal('success'); + return state[SETTINGS_KEY]; + } + + it('persists positive integer backend request concurrency', async function () { + const settings = await patchSettings( + {}, + { backendRequestConcurrency: '15' }, + ); + + expect(settings).to.deep.include({ + backendRequestConcurrency: '15', + }); + }); + + it('allows backend request concurrency above proxy app guidance', async function () { + const settings = await patchSettings( + {}, + { backendRequestConcurrency: 21 }, + ); + + expect(settings).to.deep.include({ + backendRequestConcurrency: 21, + }); + }); + + it('clears invalid backend request concurrency values', async function () { + const invalidValues = ['', 'abc', '1.5', 0, -1, null]; + + for (const value of invalidValues) { + const settings = await patchSettings( + { backendRequestConcurrency: 8 }, + { backendRequestConcurrency: value }, + ); + + expect(settings).to.not.have.property( + 'backendRequestConcurrency', + ); + } + }); + + it('persists backend request concurrency wait time values', async function () { + const zeroWaitSettings = await patchSettings( + {}, + { backendRequestConcurrencyWaitTime: 0 }, + ); + const positiveWaitSettings = await patchSettings( + {}, + { backendRequestConcurrencyWaitTime: '50' }, + ); + + expect(zeroWaitSettings).to.deep.include({ + backendRequestConcurrencyWaitTime: 0, + }); + expect(positiveWaitSettings).to.deep.include({ + backendRequestConcurrencyWaitTime: '50', + }); + }); + + it('clears invalid backend request concurrency wait time values', async function () { + const invalidValues = ['', 'abc', '1.5', -1, null]; + + for (const value of invalidValues) { + const settings = await patchSettings( + { backendRequestConcurrencyWaitTime: 8 }, + { backendRequestConcurrencyWaitTime: value }, + ); + + expect(settings).to.not.have.property( + 'backendRequestConcurrencyWaitTime', + ); + } + }); + }); }); diff --git a/backend/src/test/utils/download.spec.js b/backend/src/test/utils/download.spec.js index b8d165fc..9f6da035 100644 --- a/backend/src/test/utils/download.spec.js +++ b/backend/src/test/utils/download.spec.js @@ -26,6 +26,13 @@ let tempDir; let previousDataBasePath; let capturedUrls; let errorLogs; +let activeRequests; +let maxActiveRequests; +let requestDelay; + +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} describe('download github proxy regex', function () { before(function () { @@ -76,6 +83,9 @@ describe('download github proxy regex', function () { beforeEach(function () { capturedUrls = []; errorLogs = []; + activeRequests = 0; + maxActiveRequests = 0; + requestDelay = 0; state = { [SETTINGS_KEY]: { githubProxy: 'https://ghproxy.test', @@ -109,6 +119,10 @@ describe('download github proxy regex', function () { openApi.HTTP = () => ({ get: async ({ url }) => { capturedUrls.push(url); + activeRequests += 1; + maxActiveRequests = Math.max(maxActiveRequests, activeRequests); + if (requestDelay > 0) await sleep(requestDelay); + activeRequests -= 1; return { body: 'test-body', headers: {}, @@ -164,4 +178,27 @@ describe('download github proxy regex', function () { expect(errorLogs).to.have.length(1); expect(errorLogs[0]).to.contain('GitHub 加速代理匹配正则无效'); }); + + it('limits concurrent outbound download requests by backend setting', async function () { + state[SETTINGS_KEY].backendRequestConcurrency = 2; + requestDelay = 5; + + await Promise.all( + Array.from({ length: 5 }, (_, index) => + download(`https://example.com/archive-${index}.txt`), + ), + ); + + expect(maxActiveRequests).to.equal(2); + }); + + it('uses cached download content without a new outbound request', async function () { + await download('https://example.com/cached.txt'); + await download('https://example.com/cached.txt'); + + expect(capturedUrls).to.deep.equal([ + 'https://example.com/cached.txt', + ]); + expect(maxActiveRequests).to.equal(1); + }); }); diff --git a/backend/src/test/utils/flow.spec.js b/backend/src/test/utils/flow.spec.js index ac9fe648..c371cffe 100644 --- a/backend/src/test/utils/flow.spec.js +++ b/backend/src/test/utils/flow.spec.js @@ -16,6 +16,13 @@ let originalENV; let state; let capturedRequests; let infoLogs; +let activeRequests; +let maxActiveRequests; +let requestDelay; + +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} describe('flow headers requests', function () { before(function () { @@ -51,6 +58,9 @@ describe('flow headers requests', function () { beforeEach(function () { capturedRequests = []; infoLogs = []; + activeRequests = 0; + maxActiveRequests = 0; + requestDelay = 0; state = { [SETTINGS_KEY]: { defaultFlowUserAgent: 'DefaultFlowUA', @@ -82,6 +92,10 @@ describe('flow headers requests', function () { openApi.HTTP = () => ({ head: async (options) => { capturedRequests.push({ method: 'HEAD', options }); + activeRequests += 1; + maxActiveRequests = Math.max(maxActiveRequests, activeRequests); + if (requestDelay > 0) await sleep(requestDelay); + activeRequests -= 1; return { headers: { 'subscription-userinfo': @@ -91,6 +105,10 @@ describe('flow headers requests', function () { }, get: async (options) => { capturedRequests.push({ method: 'GET', options }); + activeRequests += 1; + maxActiveRequests = Math.max(maxActiveRequests, activeRequests); + if (requestDelay > 0) await sleep(requestDelay); + activeRequests -= 1; return { body: 'upload=1; download=2; total=10', headers: {}, @@ -148,4 +166,27 @@ describe('flow headers requests', function () { '{"user-agent":"DefaultFlowUA","x-sub-token":"token-2"}', ); }); + + it('limits concurrent outbound flow requests by backend setting', async function () { + state[SETTINGS_KEY].backendRequestConcurrency = 2; + requestDelay = 5; + + await Promise.all( + Array.from({ length: 5 }, (_, index) => + getFlowHeaders(`https://example.com/sub-${index}`), + ), + ); + + expect(maxActiveRequests).to.equal(2); + }); + + it('uses cached flow headers without a new outbound request', async function () { + await getFlowHeaders('https://example.com/cached-flow'); + await getFlowHeaders('https://example.com/cached-flow'); + + expect(capturedRequests.map((request) => request.options.url)).to.deep.equal([ + 'https://example.com/cached-flow', + ]); + expect(maxActiveRequests).to.equal(1); + }); }); diff --git a/backend/src/test/utils/request-concurrency.spec.js b/backend/src/test/utils/request-concurrency.spec.js new file mode 100644 index 00000000..eb995a77 --- /dev/null +++ b/backend/src/test/utils/request-concurrency.spec.js @@ -0,0 +1,179 @@ +import { expect } from 'chai'; +import { afterEach, describe, it } from 'mocha'; + +import { SETTINGS_KEY } from '@/constants'; +import $ from '@/core/app'; +import { + getBackendRequestConcurrency, + getBackendRequestConcurrencyWaitTime, + normalizeBackendRequestConcurrency, + normalizeBackendRequestConcurrencyWaitTime, + runBackendRequestTask, + runBackendRequestTasks, +} from '@/utils/request-concurrency'; + +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +describe('backend request concurrency', function () { + const originalRead = $.read.bind($); + + afterEach(function () { + $.read = originalRead; + }); + + function setRequestConcurrencySettings(settings) { + $.read = (key) => { + if (key !== SETTINGS_KEY) return undefined; + return settings; + }; + } + + function setConcurrency(concurrency) { + setRequestConcurrencySettings({ + backendRequestConcurrency: concurrency, + }); + } + + it('normalizes missing and invalid values to the default', function () { + [undefined, null, '', 'abc', '1.5', 0, -1].forEach((value) => { + expect(normalizeBackendRequestConcurrency(value)).to.equal(15); + }); + }); + + it('normalizes missing and invalid wait time values to the default', function () { + [undefined, null, '', 'abc', '1.5', -1].forEach((value) => { + expect(normalizeBackendRequestConcurrencyWaitTime(value)).to.equal( + 0, + ); + }); + }); + + it('reads positive integer values from settings', function () { + setConcurrency('2'); + + expect(getBackendRequestConcurrency()).to.equal(2); + }); + + it('reads non-negative integer wait time values from settings', function () { + setRequestConcurrencySettings({ + backendRequestConcurrency: 2, + backendRequestConcurrencyWaitTime: '25', + }); + + expect(getBackendRequestConcurrencyWaitTime()).to.equal(25); + }); + + it('limits active backend request tasks to the configured concurrency', async function () { + setConcurrency(2); + let activeTasks = 0; + let maxActiveTasks = 0; + + await Promise.all( + Array.from({ length: 5 }, () => + runBackendRequestTask(async () => { + activeTasks += 1; + maxActiveTasks = Math.max(maxActiveTasks, activeTasks); + await sleep(5); + activeTasks -= 1; + }), + ), + ); + + expect(maxActiveTasks).to.equal(2); + }); + + it('releases request slots when a task rejects', async function () { + setConcurrency(1); + const completed = []; + + const results = await Promise.allSettled([ + runBackendRequestTask(async () => { + await sleep(5); + throw new Error('request failed'); + }), + runBackendRequestTask(async () => { + completed.push('second'); + return 'ok'; + }), + ]); + + expect(results[0].status).to.equal('rejected'); + expect(results[1]).to.deep.include({ + status: 'fulfilled', + value: 'ok', + }); + expect(completed).to.deep.equal(['second']); + }); + + it('waits after acquiring a request slot when configured', async function () { + setRequestConcurrencySettings({ + backendRequestConcurrency: 1, + backendRequestConcurrencyWaitTime: 15, + }); + const startedAt = Date.now(); + let taskStartedAfter = 0; + + await runBackendRequestTask(async () => { + taskStartedAfter = Date.now() - startedAt; + }); + + expect(taskStartedAfter).to.be.at.least(10); + }); + + it('starts queued tasks only after a request slot is released', async function () { + setConcurrency(1); + const events = []; + let releaseFirstTask; + let secondTaskStarted = false; + + const firstTask = runBackendRequestTask(async () => { + events.push('first:start'); + await new Promise((resolve) => { + releaseFirstTask = resolve; + }); + events.push('first:end'); + return 'first'; + }, 'first'); + + const secondTask = runBackendRequestTask(async () => { + secondTaskStarted = true; + events.push('second:start'); + return 'second'; + }, 'second'); + + await sleep(5); + + expect(secondTaskStarted).to.equal(false); + + releaseFirstTask(); + + const results = await Promise.all([firstTask, secondTask]); + + expect(results).to.deep.equal(['first', 'second']); + expect(events).to.deep.equal([ + 'first:start', + 'first:end', + 'second:start', + ]); + }); + + it('preserves result ordering for task lists', async function () { + setConcurrency(2); + + const results = await runBackendRequestTasks([ + async () => { + await sleep(10); + return 'first'; + }, + async () => { + await sleep(1); + return 'second'; + }, + async () => 'third', + ]); + + expect(results).to.deep.equal(['first', 'second', 'third']); + }); +}); diff --git a/backend/src/utils/download.js b/backend/src/utils/download.js index 75b9fdd5..21c6648e 100644 --- a/backend/src/utils/download.js +++ b/backend/src/utils/download.js @@ -15,6 +15,7 @@ import { findByName } from '@/utils/database'; import { produceArtifact } from '@/restful/sync'; import PROXY_PREPROCESSORS from '@/core/proxy-utils/preprocessors'; import { ProxyUtils } from '@/core/proxy-utils'; +import { runBackendRequestTask } from '@/utils/request-concurrency'; const clashPreprocessor = PROXY_PREPROCESSORS.find( (processor) => processor.name === 'Clash Pre-processor', @@ -288,14 +289,18 @@ export default async function download( }\nTimeout: ${requestTimeout}\nProxy: ${proxy}\nInsecure: ${!!insecure}\nPreprocess: ${preprocess}\nURL: ${url}`, ); try { - let { body, headers, statusCode } = await http.get({ - url, - ...(proxy ? { proxy } : {}), - ...(isLoon && proxy ? { node: proxy } : {}), - ...(isQX && proxy ? { opts: { policy: proxy } } : {}), - ...(proxy ? getPolicyDescriptor(proxy) : {}), - ...(insecure ? insecure : {}), - }); + let { body, headers, statusCode } = await runBackendRequestTask( + () => + http.get({ + url, + ...(proxy ? { proxy } : {}), + ...(isLoon && proxy ? { node: proxy } : {}), + ...(isQX && proxy ? { opts: { policy: proxy } } : {}), + ...(proxy ? getPolicyDescriptor(proxy) : {}), + ...(insecure ? insecure : {}), + }), + 'download', + ); $.info(`statusCode: ${statusCode}`); if (statusCode < 200 || statusCode >= 400) { throw new Error(`statusCode: ${statusCode}`); diff --git a/backend/src/utils/flow.js b/backend/src/utils/flow.js index 2e3e36e0..9590e40b 100644 --- a/backend/src/utils/flow.js +++ b/backend/src/utils/flow.js @@ -4,6 +4,7 @@ import { hex_md5 } from '@/vendor/md5'; import { getPolicyDescriptor } from '@/utils'; import $ from '@/core/app'; import headersResourceCache from '@/utils/headers-resource-cache'; +import { runBackendRequestTask } from '@/utils/request-concurrency'; export function getFlowField(headers) { const keys = Object.keys(headers); @@ -125,18 +126,22 @@ export async function getFlowHeaders( : `User-Agent: ${userAgent || ''}` }, Insecure: ${!!insecure}, Proxy: ${proxy}`, ); - const { headers, body, statusCode } = await http.get({ - url, - headers: customHeaders || { - 'User-Agent': userAgent, - }, - timeout: requestTimeout, - ...(proxy ? { proxy } : {}), - ...(isLoon && proxy ? { node: proxy } : {}), - ...(isQX && proxy ? { opts: { policy: proxy } } : {}), - ...(proxy ? getPolicyDescriptor(proxy) : {}), - ...(insecure ? insecure : {}), - }); + const { headers, body, statusCode } = + await runBackendRequestTask(() => + http.get({ + url, + headers: customHeaders || { + 'User-Agent': userAgent, + }, + timeout: requestTimeout, + ...(proxy ? { proxy } : {}), + ...(isLoon && proxy ? { node: proxy } : {}), + ...(isQX && proxy ? { opts: { policy: proxy } } : {}), + ...(proxy ? getPolicyDescriptor(proxy) : {}), + ...(insecure ? insecure : {}), + }), + 'flow body GET', + ); if (statusCode < 200 || statusCode >= 400) { throw new Error(`statusCode: ${statusCode}`); } @@ -203,30 +208,33 @@ export async function getFlowHeaders( : `User-Agent: ${userAgent || ''}` }, Insecure: ${!!insecure}, Proxy: ${proxy}`, ); - const { headers } = await http.head({ - url: url - .split(/[\r\n]+/) - .map((i) => i.trim()) - .filter((i) => i.length)[0], - headers: { - ...(customHeaders || { 'User-Agent': userAgent }), - ...(isStash && proxy - ? { - 'X-Stash-Selected-Proxy': - encodeURIComponent(proxy), - } - : {}), - ...(isShadowRocket && proxy - ? { 'X-Surge-Policy': proxy } - : {}), - }, - timeout: requestTimeout, - ...(proxy ? { proxy } : {}), - ...(isLoon && proxy ? { node: proxy } : {}), - ...(isQX && proxy ? { opts: { policy: proxy } } : {}), - ...(proxy ? getPolicyDescriptor(proxy) : {}), - ...(insecure ? insecure : {}), - }); + const { headers } = await runBackendRequestTask(() => + http.head({ + url: url + .split(/[\r\n]+/) + .map((i) => i.trim()) + .filter((i) => i.length)[0], + headers: { + ...(customHeaders || { 'User-Agent': userAgent }), + ...(isStash && proxy + ? { + 'X-Stash-Selected-Proxy': + encodeURIComponent(proxy), + } + : {}), + ...(isShadowRocket && proxy + ? { 'X-Surge-Policy': proxy } + : {}), + }, + timeout: requestTimeout, + ...(proxy ? { proxy } : {}), + ...(isLoon && proxy ? { node: proxy } : {}), + ...(isQX && proxy ? { opts: { policy: proxy } } : {}), + ...(proxy ? getPolicyDescriptor(proxy) : {}), + ...(insecure ? insecure : {}), + }), + 'flow headers HEAD', + ); flowInfo = getFlowField(headers); } catch (e) { $.error( @@ -247,30 +255,33 @@ export async function getFlowHeaders( : `User-Agent: ${userAgent || ''}` }, Insecure: ${!!insecure}, Proxy: ${proxy}`, ); - const { headers } = await http.get({ - url: url - .split(/[\r\n]+/) - .map((i) => i.trim()) - .filter((i) => i.length)[0], - headers: { - ...(customHeaders || { 'User-Agent': userAgent }), - ...(isStash && proxy - ? { - 'X-Stash-Selected-Proxy': - encodeURIComponent(proxy), - } - : {}), - ...(isShadowRocket && proxy - ? { 'X-Surge-Policy': proxy } - : {}), - }, - timeout: requestTimeout, - ...(proxy ? { proxy } : {}), - ...(isLoon && proxy ? { node: proxy } : {}), - ...(isQX && proxy ? { opts: { policy: proxy } } : {}), - ...(proxy ? getPolicyDescriptor(proxy) : {}), - ...(insecure ? insecure : {}), - }); + const { headers } = await runBackendRequestTask(() => + http.get({ + url: url + .split(/[\r\n]+/) + .map((i) => i.trim()) + .filter((i) => i.length)[0], + headers: { + ...(customHeaders || { 'User-Agent': userAgent }), + ...(isStash && proxy + ? { + 'X-Stash-Selected-Proxy': + encodeURIComponent(proxy), + } + : {}), + ...(isShadowRocket && proxy + ? { 'X-Surge-Policy': proxy } + : {}), + }, + timeout: requestTimeout, + ...(proxy ? { proxy } : {}), + ...(isLoon && proxy ? { node: proxy } : {}), + ...(isQX && proxy ? { opts: { policy: proxy } } : {}), + ...(proxy ? getPolicyDescriptor(proxy) : {}), + ...(insecure ? insecure : {}), + }), + 'flow headers GET', + ); flowInfo = getFlowField(headers); } } diff --git a/backend/src/utils/request-concurrency.js b/backend/src/utils/request-concurrency.js new file mode 100644 index 00000000..c3afde77 --- /dev/null +++ b/backend/src/utils/request-concurrency.js @@ -0,0 +1,129 @@ +import { SETTINGS_KEY } from '@/constants'; +import $ from '@/core/app'; + +export const DEFAULT_BACKEND_REQUEST_CONCURRENCY = 15; +export const BACKEND_REQUEST_CONCURRENCY_SETTING = 'backendRequestConcurrency'; +export const DEFAULT_BACKEND_REQUEST_CONCURRENCY_WAIT_TIME = 0; +export const BACKEND_REQUEST_CONCURRENCY_WAIT_TIME_SETTING = + 'backendRequestConcurrencyWaitTime'; + +let activeRequestCount = 0; + +const pendingRequestResolvers = []; + +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +export function normalizeBackendRequestConcurrency(concurrency) { + if ( + typeof concurrency === 'undefined' || + concurrency === null || + (typeof concurrency === 'string' && concurrency.trim() === '') + ) { + return DEFAULT_BACKEND_REQUEST_CONCURRENCY; + } + + const parsed = Number(concurrency); + if (!Number.isInteger(parsed) || parsed < 1) { + return DEFAULT_BACKEND_REQUEST_CONCURRENCY; + } + + return parsed; +} + +export function normalizeBackendRequestConcurrencyWaitTime(waitTime) { + if ( + typeof waitTime === 'undefined' || + waitTime === null || + (typeof waitTime === 'string' && waitTime.trim() === '') + ) { + return DEFAULT_BACKEND_REQUEST_CONCURRENCY_WAIT_TIME; + } + + const parsed = Number(waitTime); + if (!Number.isInteger(parsed) || parsed < 0) { + return DEFAULT_BACKEND_REQUEST_CONCURRENCY_WAIT_TIME; + } + + return parsed; +} + +export function getBackendRequestConcurrency() { + const settings = $.read(SETTINGS_KEY) || {}; + return normalizeBackendRequestConcurrency( + settings[BACKEND_REQUEST_CONCURRENCY_SETTING], + ); +} + +export function getBackendRequestConcurrencyWaitTime() { + const settings = $.read(SETTINGS_KEY) || {}; + return normalizeBackendRequestConcurrencyWaitTime( + settings[BACKEND_REQUEST_CONCURRENCY_WAIT_TIME_SETTING], + ); +} + +function formatRequestConcurrencyState(limit, waitTime) { + return `active=${activeRequestCount}, pending=${pendingRequestResolvers.length}, limit=${limit}, waitTime=${waitTime}ms`; +} + +function logRequestConcurrency(message, label, limit, waitTime) { + $.log( + `[Backend Request Concurrency] ${message}: ${label} (${formatRequestConcurrencyState( + limit, + waitTime, + )})`, + ); +} + +function resolveNextPendingRequest() { + const nextResolver = pendingRequestResolvers.shift(); + if (nextResolver) nextResolver(); +} + +async function waitForRequestSlot(label) { + let limit = getBackendRequestConcurrency(); + let waitTime = getBackendRequestConcurrencyWaitTime(); + + while (activeRequestCount >= limit) { + logRequestConcurrency('queued', label, limit, waitTime); + await new Promise((resolve) => { + pendingRequestResolvers.push(resolve); + }); + limit = getBackendRequestConcurrency(); + waitTime = getBackendRequestConcurrencyWaitTime(); + } + + activeRequestCount += 1; + logRequestConcurrency('acquired', label, limit, waitTime); + + if (waitTime > 0) { + logRequestConcurrency('waiting before request', label, limit, waitTime); + await sleep(waitTime); + } +} + +function releaseRequestSlot(label) { + activeRequestCount = Math.max(0, activeRequestCount - 1); + logRequestConcurrency( + 'released', + label, + getBackendRequestConcurrency(), + getBackendRequestConcurrencyWaitTime(), + ); + resolveNextPendingRequest(); +} + +export async function runBackendRequestTask(task, label = 'request') { + await waitForRequestSlot(label); + + try { + return await task(); + } finally { + releaseRequestSlot(label); + } +} + +export function runBackendRequestTasks(tasks, label = 'request') { + return Promise.all(tasks.map((task) => runBackendRequestTask(task, label))); +}