chore: configure undici dispatcher allowing HTTP2, caching DNS and retrying connection errors

This commit is contained in:
WebStreamr 2025-08-21 08:42:37 +00:00
parent 795c033a82
commit 05d11e366b
No known key found for this signature in database
2 changed files with 23 additions and 6 deletions

View file

@ -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);

View file

@ -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);