diff --git a/jest.setup.ts b/jest.setup.ts index d8d34fd..71d0ea0 100644 --- a/jest.setup.ts +++ b/jest.setup.ts @@ -1,5 +1,5 @@ import { socksDispatcher } from 'fetch-socks'; -import { ProxyAgent, setGlobalDispatcher } from 'undici'; +import { Agent, Dispatcher, interceptors, ProxyAgent, setGlobalDispatcher } from 'undici'; jest.mock('randomstring', () => ({ generate: jest.fn(() => 'mocked-random-string'), @@ -9,11 +9,19 @@ beforeEach(() => { jest.spyOn(Date, 'now').mockImplementation(() => 639837296000); }); +let dispatcher: Dispatcher; if (process.env['ALL_PROXY']) { const proxyUrl = new URL(process.env['ALL_PROXY']); if (proxyUrl.protocol === 'socks5:') { - setGlobalDispatcher(socksDispatcher({ type: 5, host: proxyUrl.hostname, port: parseInt(proxyUrl.port) })); + dispatcher = socksDispatcher({ type: 5, host: proxyUrl.hostname, port: parseInt(proxyUrl.port) }, { allowH2: true }); } else { - setGlobalDispatcher(new ProxyAgent({ uri: proxyUrl.href })); + dispatcher = new ProxyAgent({ uri: proxyUrl.href, allowH2: true }); } +} else { + dispatcher = new Agent({ allowH2: true }); } +dispatcher.compose( + interceptors.dns(), + interceptors.retry({ maxRetries: 3 }), +); +setGlobalDispatcher(dispatcher); diff --git a/src/index.ts b/src/index.ts index 00adb30..d6b106a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,6 @@ import express, { NextFunction, Request, Response } from 'express'; import { socksDispatcher } from 'fetch-socks'; -import { ProxyAgent, setGlobalDispatcher } from 'undici'; +import { Agent, Dispatcher, interceptors, ProxyAgent, setGlobalDispatcher } from 'undici'; import { v4 as uuidv4 } from 'uuid'; import winston from 'winston'; import { ConfigureController, ManifestController, StreamController } from './controller'; @@ -36,14 +36,23 @@ process.on('unhandledRejection', (reason) => { logger.error('Unhandled rejection: ', reason); }); +let dispatcher: Dispatcher; if (process.env['ALL_PROXY']) { const proxyUrl = new URL(process.env['ALL_PROXY']); if (proxyUrl.protocol === 'socks5:') { - setGlobalDispatcher(socksDispatcher({ type: 5, host: proxyUrl.hostname, port: parseInt(proxyUrl.port) })); + dispatcher = socksDispatcher({ type: 5, host: proxyUrl.hostname, port: parseInt(proxyUrl.port) }, { allowH2: true }); } else { - setGlobalDispatcher(new ProxyAgent({ uri: proxyUrl.href })); + dispatcher = new ProxyAgent({ uri: proxyUrl.href, allowH2: true }); } +} else { + dispatcher = new Agent({ allowH2: true }); } +dispatcher.compose( + interceptors.dns(), + interceptors.retry({ maxRetries: 3 }), +); +setGlobalDispatcher(dispatcher); + const fetcher = new Fetcher(logger); const sources = createSources(fetcher);