Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(cdp): route third-party requests through the egress proxy per team (#101497)

Meikel Ratzae9b8647d24c
diff --git a/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.ts b/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.ts
index 01f1e85625e7..8e5df3474885 100644
--- a/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.ts
+++ b/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.ts
@@ -73,6 +73,7 @@ export class LegacyWebhookService {
headers: { 'Content-Type': 'application/json' },
},
templateId: 'legacy-zapier-webhook',
+ teamId: team.id,
})
if (response.fetchError) {
diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts b/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
index 1e797e47be81..6d142129ea7e 100644
--- a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
@@ -143,6 +143,7 @@ describe('PushNotificationService', () => {
url: 'https://fcm.googleapis.com/v1/projects/test-project/messages:send',
fetchParams: expect.objectContaining({ method: 'POST' }),
templateId: 'unknown',
+ teamId: invocation.teamId,
})
})
@@ -629,6 +630,7 @@ describe('PushNotificationService', () => {
}),
}),
templateId: 'unknown',
+ teamId: invocation.teamId,
})
})
diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.ts b/nodejs/src/cdp/services/messaging/push-notification.service.ts
index 8ba2a84090ba..214bce2afd68 100644
--- a/nodejs/src/cdp/services/messaging/push-notification.service.ts
+++ b/nodejs/src/cdp/services/messaging/push-notification.service.ts
@@ -151,7 +151,7 @@ function pushSendError(platform: PushPlatform, err: NormalizedPushError, retryAf
}
export type PushNotificationFetchUtils = {
- trackedFetch: (args: { url: string; fetchParams: FetchOptions; templateId: string }) => Promise<{
+ trackedFetch: (args: { url: string; fetchParams: FetchOptions; templateId: string; teamId?: number }) => Promise<{
fetchError: Error | null
fetchResponse: FetchResponse | null
fetchDuration: number
@@ -415,6 +415,7 @@ export class PushNotificationService {
url,
fetchParams,
templateId,
+ teamId: result.invocation.teamId,
})
result.invocation.state.timings.push({
@@ -525,6 +526,7 @@ export class PushNotificationService {
url,
fetchParams,
templateId,
+ teamId: result.invocation.teamId,
})
result.invocation.state.timings.push({
diff --git a/nodejs/src/cdp/utils/cdp-fetch.ts b/nodejs/src/cdp/utils/cdp-fetch.ts
index 4c833af9b20f..591af1a5386f 100644
--- a/nodejs/src/cdp/utils/cdp-fetch.ts
+++ b/nodejs/src/cdp/utils/cdp-fetch.ts
@@ -120,8 +120,8 @@ export async function cdpTrackedFetch({
}> {
const start = performance.now()
- // Attribution read by the URL-validation check logs in common/utils/request.ts, which
- // run inside undici's connect flow where no caller context is otherwise available.
+ // Attribution read by the URL-validation check logs and the egress proxy rollout in common/utils/request.ts,
+ // which run inside undici's connect flow where no caller context is otherwise available.
const doFetch = () =>
fetchAttribution.run({ teamId, hogFunctionId, templateId }, () =>
tryCatch(async () => await fetch(url, fetchParams))
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.ts
index 2cc459944ed5..456bf4151754 100644
--- a/nodejs/src/common/config.ts
+++ b/nodejs/src/common/config.ts
@@ -222,6 +222,11 @@ export type CommonConfig = BaseServerConfig & {
// an HTTP/2 origin's stream limit. Keep it above the largest per-origin concurrency a caller runs. The image fetch
// lane allows 6 per registrable domain.
EXTERNAL_REQUEST_H2_CONNECTIONS: number
+ // Which teams send their third-party requests through the egress proxy. Only a deployment in the rollout sets
+ // this. Left unset, a configured proxy carries every request, which is the behavior from before the rollout.
+ // Takes the buildIntegerMatcherWithPercentage syntax: '2' for team 2 only, '2,*:0.1' for team 2 plus a tenth of
+ // everyone else's requests, '*' for all.
+ EXTERNAL_REQUEST_PROXY_TEAMS: string
// PostHog analytics
POSTHOG_API_KEY: string
@@ -261,6 +266,7 @@ export type ExternalRequestConfig = Pick<
| 'EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS'
| 'EXTERNAL_REQUEST_CONNECTIONS'
| 'EXTERNAL_REQUEST_H2_CONNECTIONS'
+ | 'EXTERNAL_REQUEST_PROXY_TEAMS'
>
export function getExternalRequestConfig(): ExternalRequestConfig {
@@ -273,6 +279,7 @@ export function getExternalRequestConfig(): ExternalRequestConfig {
EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS: Number(process.env.EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS ?? 10000),
EXTERNAL_REQUEST_CONNECTIONS: Number(process.env.EXTERNAL_REQUEST_CONNECTIONS ?? 500),
EXTERNAL_REQUEST_H2_CONNECTIONS: Number(process.env.EXTERNAL_REQUEST_H2_CONNECTIONS ?? 8),
+ EXTERNAL_REQUEST_PROXY_TEAMS: process.env.EXTERNAL_REQUEST_PROXY_TEAMS ?? '',
}
}
@@ -428,6 +435,7 @@ export function getDefaultCommonConfig(): CommonConfig {
EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS: 10000,
EXTERNAL_REQUEST_CONNECTIONS: 500,
EXTERNAL_REQUEST_H2_CONNECTIONS: 8,
+ EXTERNAL_REQUEST_PROXY_TEAMS: '',
// PostHog analytics
POSTHOG_API_KEY: '',
diff --git a/nodejs/src/common/config/config.ts b/nodejs/src/common/config/config.ts
index 1f357d26c373..bc895f2ba550 100644
--- a/nodejs/src/common/config/config.ts
+++ b/nodejs/src/common/config/config.ts
@@ -109,69 +109,8 @@ export function overrideConfigWithEnv<T extends Record<string, unknown>>(
return result
}
-export function buildIntegerMatcher(config: string | undefined, allowStar: boolean): ValueMatcher<number> {
- // Builds a ValueMatcher on a comma-separated list of values.
- // Optionally, supports a '*' value to match everything
- if (!config || config.trim().length == 0) {
- return () => false
- } else if (allowStar && config === '*') {
- return () => true
- } else {
- const values = new Set(
- config
- .split(',')
- .map((n) => parseInt(n))
- .filter((num) => !isNaN(num))
- )
- return (v: number) => {
- return values.has(v)
- }
- }
-}
-
-/**
- * Builds a matcher that supports team IDs and/or percentage-based rollout.
- *
- * Formats:
- * '' → no match
- * '*' → match all
- * '123,456' → only teams 123 and 456
- * '*:0.1' → 10% of all traffic (random per call)
- * '123,*:0.05' → team 123 always + 5% of all other teams
- */
-export function buildIntegerMatcherWithPercentage(config: string | undefined): ValueMatcher<number> {
- if (!config || config.trim().length === 0) {
- return () => false
- }
- if (config.trim() === '*') {
- return () => true
- }
-
- const parts = config.split(',').map((s) => s.trim())
- const teamIds = new Set<number>()
- let percentage = 0
-
- for (const part of parts) {
- if (part.startsWith('*:')) {
- percentage = parseFloat(part.slice(2))
- } else {
- const num = parseInt(part)
- if (!isNaN(num)) {
- teamIds.add(num)
- }
- }
- }
-
- return (teamId: number) => {
- if (teamIds.has(teamId)) {
- return true
- }
- if (percentage > 0) {
- return Math.random() < percentage
- }
- return false
- }
-}
+// These live in ./matchers because importing this module builds defaultConfig, which throws without database env.
+export { buildIntegerMatcher, buildIntegerMatcherWithPercentage } from './matchers'
export function buildStringMatcher(config: string | undefined, allowStar: boolean): ValueMatcher<string> {
// Builds a ValueMatcher on a comma-separated list of values.
diff --git a/nodejs/src/common/config/config.test.ts b/nodejs/src/common/config/matchers.test.ts
similarity index 90%
rename from nodejs/src/common/config/config.test.ts
rename to nodejs/src/common/config/matchers.test.ts
index b3a1d15a4346..435c8fddc7dd 100644
--- a/nodejs/src/common/config/config.test.ts
+++ b/nodejs/src/common/config/matchers.test.ts
@@ -1,4 +1,4 @@
-import { buildIntegerMatcherWithPercentage } from './config'
+import { buildIntegerMatcherWithPercentage } from './matchers'
describe('buildIntegerMatcherWithPercentage', () => {
it.each([
diff --git a/nodejs/src/common/config/matchers.ts b/nodejs/src/common/config/matchers.ts
new file mode 100644
index 000000000000..2c043d2a042b
--- /dev/null
+++ b/nodejs/src/common/config/matchers.ts
@@ -0,0 +1,68 @@
+import type { ValueMatcher } from '~/types'
+
+// These live apart from config.ts because that module builds `defaultConfig` at import time and throws without
+// database env. The session replay rasterizer reaches this code through its otel chain and has no such env.
+
+export function buildIntegerMatcher(config: string | undefined, allowStar: boolean): ValueMatcher<number> {
+ // Builds a ValueMatcher on a comma-separated list of values.
+ // Optionally, supports a '*' value to match everything
+ if (!config || config.trim().length == 0) {
+ return () => false
+ } else if (allowStar && config === '*') {
+ return () => true
+ } else {
+ const values = new Set(
+ config
+ .split(',')
+ .map((n) => parseInt(n))
+ .filter((num) => !isNaN(num))
+ )
+ return (v: number) => {
+ return values.has(v)
+ }
+ }
+}
+
+/**
+ * Builds a matcher that supports team IDs and/or percentage-based rollout.
+ *
+ * Formats:
+ * '' → no match
+ * '*' → match all
+ * '123,456' → only teams 123 and 456
+ * '*:0.1' → 10% of all traffic (random per call)
+ * '123,*:0.05' → team 123 always + 5% of all other teams
+ */
+export function buildIntegerMatcherWithPercentage(config: string | undefined): ValueMatcher<number> {
+ if (!config || config.trim().length === 0) {
+ return () => false
+ }
+ if (config.trim() === '*') {
+ return () => true
+ }
+
+ const parts = config.split(',').map((s) => s.trim())
+ const teamIds = new Set<number>()
+ let percentage = 0
+
+ for (const part of parts) {
+ if (part.startsWith('*:')) {
+ percentage = parseFloat(part.slice(2))
+ } else {
+ const num = parseInt(part)
+ if (!isNaN(num)) {
+ teamIds.add(num)
+ }
+ }
+ }
+
+ return (teamId: number) => {
+ if (teamIds.has(teamId)) {
+ return true
+ }
+ if (percentage > 0) {
+ return Math.random() < percentage
+ }
+ return false
+ }
+}
diff --git a/nodejs/src/common/utils/request-http2.test.ts b/nodejs/src/common/utils/request-http2.test.ts
index 920066389282..9bdf3097be97 100644
--- a/nodejs/src/common/utils/request-http2.test.ts
+++ b/nodejs/src/common/utils/request-http2.test.ts
@@ -1,3 +1,4 @@
+import { AsyncLocalStorage } from 'node:async_hooks'
import http from 'node:http'
import http2 from 'node:http2'
import https from 'node:https'
@@ -10,6 +11,8 @@ import { TestTlsIdentity, createTestTlsIdentity } from '~/tests/helpers/tls'
type RequestModule = typeof import('./request')
type Client = import('undici').Client
+type FetchResponseLike = Awaited<ReturnType<RequestModule['fetch']>>
+type LegacyResponseLike = Awaited<ReturnType<RequestModule['legacyFetch']>>
const proxyEnvironmentNames = ['HTTPS_PROXY', 'HTTP_PROXY', 'https_proxy', 'http_proxy'] as const
@@ -265,6 +268,104 @@ describe('secure HTTP/2 requests', () => {
expect(proxyAuthorities).toEqual([plainAuthority])
}, 10000)
+ describe('egress proxy rollout', () => {
+ // resetModules gives `request` a fresh copy of the attribution store, so the test has to reach the caller
+ // side through that same copy rather than through a top-level import.
+ let attribution: AsyncLocalStorage<Record<string, unknown>>
+
+ // The plain origin is reached by IP so the direct route needs no DNS.
+ const loadWithProxyTeams = (proxyTeams: string): void => {
+ process.env.EXTERNAL_REQUEST_PROXY_TEAMS = proxyTeams
+ jest.resetModules()
+ requestModule = require('./request') as RequestModule
+ attribution = (require('./fetch-attribution') as typeof import('./fetch-attribution')).fetchAttribution
+ }
+
+ // A caller that sets no attribution at all, such as the session replay image lane. A team of undefined is a
+ // caller that has attribution but no invocation. Both reach the matcher as team 0 once a rollout is set.
+ const NO_ATTRIBUTION = 'no-attribution'
+ type Caller = number | undefined | typeof NO_ATTRIBUTION
+
+ const fetchAs = (caller: Caller, url: string, options = {}): Promise<FetchResponseLike> => {
+ const run = (): Promise<FetchResponseLike> => requestModule.fetch(url, { timeoutMs: 2000, ...options })
+ return caller === NO_ATTRIBUTION ? run() : attribution.run({ teamId: caller }, run)
+ }
+
+ afterEach(() => {
+ delete process.env.EXTERNAL_REQUEST_PROXY_TEAMS
+ })
+
+ it.each<[string, Caller, boolean]>([
+ // An unset value means the deployment is not in the rollout, so every caller keeps the proxy.
+ ['', 2, true],
+ ['', NO_ATTRIBUTION, true],
+ ['2', 2, true],
+ ['2', 3, false],
+ ['2', undefined, false],
+ ['2', NO_ATTRIBUTION, false],
+ ['2,*:1', 3, true],
+ ['*', 3, true],
+ ['*:1', undefined, true],
+ ])(
+ 'with EXTERNAL_REQUEST_PROXY_TEAMS=%j and caller %s, proxied: %s',
+ async (proxyTeams, caller, expectProxied) => {
+ loadWithProxyTeams(proxyTeams)
+ const authority = `127.0.0.1:${serverPort(plainOrigin)}`
+
+ const response = await fetchAs(caller, `http://${authority}/routing`)
+
+ expect(await response.text()).toBe('/routing')
+ expect(proxyAuthorities).toEqual(expectProxied ? [authority] : [])
+ },
+ 10000
+ )
+
+ it.each([['*:10'], ['*:bad'], ['2,*:'], ['*:0.1,*:10']])(
+ 'refuses to start with EXTERNAL_REQUEST_PROXY_TEAMS=%j',
+ (proxyTeams) => {
+ // A fraction read as a percentage would proxy every team at once, which is what the staged rollout exists
+ // to prevent.
+ expect(() => loadWithProxyTeams(proxyTeams)).toThrow(/takes a fraction between 0 and 1/)
+ }
+ )
+
+ // legacyFetch picks its own dispatcher instead of taking one from `fetch`, so it needs its own coverage.
+ // A shared agent assigned there directly would pin the helper to one route whatever the rollout says.
+ it.each<[Caller, boolean]>([
+ [2, true],
+ [3, false],
+ [NO_ATTRIBUTION, false],
+ ])(
+ 'routes legacyFetch for caller %s through the proxy: %s',
+ async (caller, expectProxied) => {
+ loadWithProxyTeams('2')
+ const authority = `127.0.0.1:${serverPort(plainOrigin)}`
+ const run = (): Promise<LegacyResponseLike> => requestModule.legacyFetch(`http://${authority}/legacy`)
+
+ const response = await (caller === NO_ATTRIBUTION ? run() : attribution.run({ teamId: caller }, run))
+
+ expect(await response.text()).toBe('/legacy')
+ expect(proxyAuthorities).toEqual(expectProxied ? [authority] : [])
+ },
+ 10000
+ )
+
+ it('keeps the two routes on separate HTTP/2 dispatchers for one idle timeout', async () => {
+ loadWithProxyTeams('2')
+ const authority = `127.0.0.1:${serverPort(plainOrigin)}`
+ const options = { allowH2: true, http2IdleTimeoutMs: 42_000 }
+
+ const proxied = await fetchAs(2, `http://${authority}/proxied`, options)
+ const direct = await fetchAs(3, `http://${authority}/direct`, options)
+
+ expect(await proxied.text()).toBe('/proxied')
+ expect(await direct.text()).toBe('/direct')
+ // A single dispatcher map keyed only by the idle timeout would hand the direct request the proxied
+ // dispatcher, and the second authority would show up here.
+ expect(proxyAuthorities).toEqual([authority])
+ }, 10000)
+ })
+
it('carries a burst to a cold origin on one session', async () => {
const http2Url = `https://origin.test:${serverPort(http2Origin)}`
const paths = Array.from({ length: 6 }, (_, index) => `/burst-${index}`)
diff --git a/nodejs/src/common/utils/request.ts b/nodejs/src/common/utils/request.ts
index 39eff21f001e..062eb2c78614 100644
--- a/nodejs/src/common/utils/request.ts
+++ b/nodejs/src/common/utils/request.ts
@@ -19,6 +19,7 @@ import {
import { URL } from 'url'
import { getExternalRequestConfig } from '~/common/config'
+import { buildIntegerMatcherWithPercentage } from '~/common/config/matchers'
import { ColdStartGate } from './cold-start-gate'
import { isProdEnv } from './env-utils'
@@ -37,6 +38,14 @@ const unsafeRequestCounter = new Counter({
labelNames: ['reason'],
})
+// The only signal on this side that says which way a request left the pod. Smokescreen records the destination of a
+// tunnel it carries, but nothing here otherwise separates a proxied request from a direct one.
+const externalRequestRouteCounter = new Counter({
+ name: 'node_external_request_route_total',
+ help: 'Third-party requests by egress route, proxy or direct',
+ labelNames: ['route'],
+})
+
// Gauge tracking the number of external HTTP requests currently in flight.
// This is the primary scaling signal for the cdp-cyclotron-worker: it directly
// measures I/O saturation rather than CPU (which stays low while waiting on responses)
@@ -277,23 +286,69 @@ class InsecureAgent extends Agent {
}
}
-// When a proxy URL is available, external requests go through a CONNECT tunnel.
-// The proxy handles SSRF blocking (private IP rejection) at the network level,
-// so we skip the DNS lookup (httpStaticLookup) which would be redundant.
+const proxyUrl =
+ process.env.HTTPS_PROXY || process.env.HTTP_PROXY || process.env.https_proxy || process.env.http_proxy || ''
+
+// The percentage form rolls per call rather than per team, so a destination that fails through the proxy gets a fresh
+// draw on its next retry.
+const proxyTeamMatcher = buildIntegerMatcherWithPercentage(requestConfig.EXTERNAL_REQUEST_PROXY_TEAMS)
+
+// The parser takes a fraction, so '*:10' reads as "always" rather than the ten percent an operator means by it, and
+// '*:bad' reads as "never" while the rollout looks live. Both defeat the staged rollout silently, so fail at startup
+// the way EXTERNAL_REQUEST_H2_CONNECTIONS does below. The parser keeps the last '*:' token it reads, so every one of
+// them has to hold rather than only the first.
+const proxyRolloutPercentages = requestConfig.EXTERNAL_REQUEST_PROXY_TEAMS.split(',')
+ .map((part) => part.trim())
+ .filter((part) => part.startsWith('*:'))
+ .map((part) => part.slice(2))
+for (const rolloutPercentage of proxyRolloutPercentages) {
+ const percentage = Number(rolloutPercentage)
+ if (rolloutPercentage === '' || !Number.isFinite(percentage) || percentage < 0 || percentage > 1) {
+ throw new Error(
+ `EXTERNAL_REQUEST_PROXY_TEAMS takes a fraction between 0 and 1 after '*:', got '${rolloutPercentage}'`
+ )
+ }
+}
+
+const proxyRolloutConfigured = requestConfig.EXTERNAL_REQUEST_PROXY_TEAMS.trim().length > 0
+
+// Only a deployment in the rollout sets EXTERNAL_REQUEST_PROXY_TEAMS. Everywhere else keeps the behavior from before
+// the rollout existed, which the session replay image lane depends on to send customer URLs through the proxy.
+// A deployment in the rollout takes the team from the attribution context the URL-validation logs already use, rather
+// than from FetchOptions, so that routing stays out of the request shape every caller and its tests assert on.
+function useProxyForTeam(): boolean {
+ if (!proxyUrl) {
+ return false
+ }
+ if (!proxyRolloutConfigured) {
+ return true
+ }
+ const teamId = fetchAttribution.getStore()?.teamId
+ // A caller with no team never matches a team in the list, but a percentage rollout still covers it.
+ return proxyTeamMatcher(typeof teamId === 'number' ? teamId : 0)
+}
+
+type SecureRoute = 'proxy' | 'direct'
+
+const routeOf = (useProxy: boolean): SecureRoute => (useProxy ? 'proxy' : 'direct')
+
+// A proxied request goes through a CONNECT tunnel. The proxy handles SSRF blocking (private IP rejection) at the
+// network level, so we skip the DNS lookup (httpStaticLookup) which would be redundant. NOTE: undici's ProxyAgent
+// does not read NO_PROXY, so a carve-out set in the environment does not apply here.
function makeSecureDispatcher({
+ useProxy,
allowH2,
keepAliveTimeoutMs = requestConfig.EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS,
}: {
+ useProxy: boolean
allowH2: boolean
keepAliveTimeoutMs?: number
}): Dispatcher {
- const proxyUrl =
- process.env.HTTPS_PROXY || process.env.HTTP_PROXY || process.env.https_proxy || process.env.http_proxy
const connections = allowH2
? requestConfig.EXTERNAL_REQUEST_H2_CONNECTIONS
: requestConfig.EXTERNAL_REQUEST_CONNECTIONS
- if (proxyUrl) {
+ if (useProxy) {
return new ProxyAgent({
uri: proxyUrl,
keepAliveTimeout: keepAliveTimeoutMs,
@@ -316,7 +371,8 @@ function makeSecureDispatcher({
})
}
-const sharedSecureAgent = makeSecureDispatcher({ allowH2: false })
+const sharedSecureAgent = makeSecureDispatcher({ useProxy: false, allowH2: false })
+const sharedSecureProxyAgent = proxyUrl ? makeSecureDispatcher({ useProxy: true, allowH2: false }) : null
const sharedInsecureAgent = new InsecureAgent()
// undici only reads the value when the first HTTP/2 request builds its pool, and treats 0 as unbounded, so a bad
@@ -332,39 +388,56 @@ if (
type SecureDispatcher = { dispatcher: Dispatcher; gate: ColdStartGate | null }
-// undici sets the idle timeout per dispatcher, so each distinct idle timeout gets its own HTTP/2 dispatcher.
-const sharedSecureH2Agents = new Map<number, SecureDispatcher>()
+// undici sets the idle timeout per dispatcher, so each distinct idle timeout gets its own HTTP/2 dispatcher. The two
+// routes keep separate maps so a caller cannot exhaust one route's budget with timeouts it only ever uses on the other.
+const sharedSecureH2Agents: Record<SecureRoute, Map<number, SecureDispatcher>> = {
+ direct: new Map(),
+ proxy: new Map(),
+}
const MAX_SECURE_H2_AGENTS = 8
// Node clamps a setTimeout delay above this value to 1 ms. A session would then close as soon as it goes idle.
const MAX_H2_IDLE_TIMEOUT_MS = 2_147_483_647
let sharedAgentsClosed = false
-function getSecureH2Agent(idleTimeoutMs = requestConfig.EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS): SecureDispatcher {
+function getSecureH2Agent(
+ useProxy: boolean,
+ idleTimeoutMs = requestConfig.EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS
+): SecureDispatcher {
// InvalidRequestError is not retriable in cdp-fetch, so a value that can never work fails once.
if (!Number.isFinite(idleTimeoutMs) || idleTimeoutMs <= 0 || idleTimeoutMs > MAX_H2_IDLE_TIMEOUT_MS) {
throw new InvalidRequestError(`http2IdleTimeoutMs must be a number between 1 and ${MAX_H2_IDLE_TIMEOUT_MS}`)
}
- let agent = sharedSecureH2Agents.get(idleTimeoutMs)
+ const agents = sharedSecureH2Agents[routeOf(useProxy)]
+ let agent = agents.get(idleTimeoutMs)
if (!agent) {
if (sharedAgentsClosed) {
throw new undiciErrors.ClientDestroyedError()
}
- if (sharedSecureH2Agents.size >= MAX_SECURE_H2_AGENTS) {
+ if (agents.size >= MAX_SECURE_H2_AGENTS) {
throw new InvalidRequestError(`http2IdleTimeoutMs takes at most ${MAX_SECURE_H2_AGENTS} distinct values`)
}
agent = {
- dispatcher: makeSecureDispatcher({ allowH2: true, keepAliveTimeoutMs: idleTimeoutMs }),
+ dispatcher: makeSecureDispatcher({ useProxy, allowH2: true, keepAliveTimeoutMs: idleTimeoutMs }),
gate: new ColdStartGate(idleTimeoutMs),
}
- sharedSecureH2Agents.set(idleTimeoutMs, agent)
+ agents.set(idleTimeoutMs, agent)
}
return agent
}
function getSecureDispatcher(options: { allowH2?: boolean; http2IdleTimeoutMs?: number }): SecureDispatcher {
- return options.allowH2
- ? getSecureH2Agent(options.http2IdleTimeoutMs)
- : { dispatcher: sharedSecureAgent, gate: null }
+ const useProxy = useProxyForTeam()
+ // useProxyForTeam only returns true when a proxy URL was configured, so the agent exists whenever it is needed.
+ const secure = options.allowH2
+ ? getSecureH2Agent(useProxy, options.http2IdleTimeoutMs)
+ : {
+ dispatcher: useProxy && sharedSecureProxyAgent ? sharedSecureProxyAgent : sharedSecureAgent,
+ gate: null,
+ }
+ // Counted here because every route decision passes through this function. A throw from getSecureH2Agent leaves
+ // the request uncounted, which is right: it never picked a route.
+ externalRequestRouteCounter.inc({ route: routeOf(useProxy) })
+ return secure
}
// The timer only bounds the wait in closeSharedAgents. When close finishes first, an unref'd timer does not keep the
@@ -383,8 +456,9 @@ export async function closeSharedAgents(gracePeriodMs = 5000): Promise<void> {
sharedAgentsClosed = true
const agents = [
sharedSecureAgent,
+ ...(sharedSecureProxyAgent ? [sharedSecureProxyAgent] : []),
sharedInsecureAgent,
- ...[...sharedSecureH2Agents.values()].map((h2) => h2.dispatcher),
+ ...Object.values(sharedSecureH2Agents).flatMap((route) => [...route.values()].map((h2) => h2.dispatcher)),
]
const stillOpen = new Set(agents)
const closed = Promise.allSettled(agents.map((agent) => agent.close().finally(() => stillOpen.delete(agent)))).then(
@@ -753,7 +827,7 @@ export function legacyFetch(input: RequestInfo, options?: RequestInit): Promise<
validateHostnameIPLiteral(parsed.hostname, !isProdEnv())
const requestOptions = options ?? {}
- requestOptions.dispatcher = sharedSecureAgent
+ requestOptions.dispatcher = getSecureDispatcher({}).dispatcher
requestOptions.signal = AbortSignal.timeout(requestConfig.EXTERNAL_REQUEST_THIRD_PARTY_TIMEOUT_MS)
return undiciFetch(parsed.toString(), requestOptions)