File size: 1,420 Bytes
c7052c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { ProxyAgent, Agent as UndiciAgent } from 'undici';

export interface AgentConfig {
  tls?: {
    key?: string;
    cert?: string;
    ca?: string[];
  };
}

let httpsAgent: UndiciAgent | undefined;
let requestTimeout: number | undefined;

const proxyAgentCache = new Map<string, ProxyAgent>();

export function getProxyAgent(proxyUrl: string): ProxyAgent {
  let agent = proxyAgentCache.get(proxyUrl);
  if (!agent) {
    agent = new ProxyAgent({
      allowH2: false,
      uri: proxyUrl,
      ...(requestTimeout ? { headersTimeout: requestTimeout, bodyTimeout: requestTimeout } : {}),
    });
    proxyAgentCache.set(proxyUrl, agent);
  }
  return agent;
}

export function getHttpsAgent(): UndiciAgent | undefined {
  return httpsAgent;
}

export function buildAgents(agentConfig: AgentConfig) {
  const { Environment } = require('./utils/env');
  const env = Environment({});

  requestTimeout =
    env?.REQUEST_TIMEOUT && parseInt(env.REQUEST_TIMEOUT)
      ? parseInt(env.REQUEST_TIMEOUT)
      : undefined;

  if (agentConfig.tls) {
    httpsAgent = new UndiciAgent({
      allowH2: false,
      ...(requestTimeout ? { headersTimeout: requestTimeout, bodyTimeout: requestTimeout } : {}),
      connect: agentConfig.tls,
    });
  } else if (requestTimeout) {
    httpsAgent = new UndiciAgent({
      allowH2: false,
      headersTimeout: requestTimeout,
      bodyTimeout: requestTimeout,
    });
  }
}