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(nodejs): upgrade undici to v8 (#96061)

Robbie84822aec4614
diff --git a/nodejs/package.json b/nodejs/package.json
index 494bc19ac6da..ad2f1474f84b 100644
--- a/nodejs/package.json
+++ b/nodejs/package.json
@@ -147,7 +147,7 @@
"typescript": "catalog:",
"uWebSockets.js": "https://codeload.github.com/uNetworking/uWebSockets.js/tar.gz/cfc9a40d8132a34881813cec3d5f8e3a185b3ce3",
"ultimate-express": "2.0.9",
- "undici": "^7.24.0",
+ "undici": "^8.10.1",
"undici-types": "7.3.0",
"uuid": "^11.1.1",
"xml-js": "^1.6.11",
diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.ts b/nodejs/src/cdp/services/messaging/push-notification.service.ts
index d45bfb41ff48..8ba2a84090ba 100644
--- a/nodejs/src/cdp/services/messaging/push-notification.service.ts
+++ b/nodejs/src/cdp/services/messaging/push-notification.service.ts
@@ -69,6 +69,9 @@ const pushNotificationRescheduledCounter = new Counter({
// keyed by the auth key id so the whole fleet reuses one token per key rather than minting one per send.
const APNS_JWT_CACHE_PREFIX = '@posthog/apns-provider-jwt/'
const APNS_JWT_TTL_SECONDS = 45 * 60
+// Apple asks providers to keep a connection open for hours to days, and treats rapid reconnects as abuse. undici
+// sends an HTTP/2 ping every 60 s by default, which keeps the egress proxy tunnel open across the idle window.
+const APNS_IDLE_TIMEOUT_MS = 60 * 60 * 1000
// One entry per signing key, so the ceiling is the number of APNs integrations routed through this pod.
// Pruned on write rather than on a timer.
@@ -509,6 +512,7 @@ export class PushNotificationService {
body: JSON.stringify(apnsPayload),
// APNs requires HTTP/2
allowH2: true,
+ http2IdleTimeoutMs: APNS_IDLE_TIMEOUT_MS,
}
if (params.timeoutMs !== undefined) {
diff --git a/nodejs/src/cdp/services/segment-destination-executor.service.ts b/nodejs/src/cdp/services/segment-destination-executor.service.ts
index b2afe18d1a52..b2ea437b063a 100644
--- a/nodejs/src/cdp/services/segment-destination-executor.service.ts
+++ b/nodejs/src/cdp/services/segment-destination-executor.service.ts
@@ -125,6 +125,9 @@ const convertFetchResponse = <Data = unknown>(response: FetchResponse, text: str
bytes: () => {
throw new Error('Not implemented')
},
+ textStream: () => {
+ throw new Error('Not implemented')
+ },
blob: () => {
throw new Error('Not implemented')
},
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.ts
index 63ac42d8e5a8..ff46924e133b 100644
--- a/nodejs/src/common/config.ts
+++ b/nodejs/src/common/config.ts
@@ -217,6 +217,11 @@ export type CommonConfig = BaseServerConfig & {
EXTERNAL_REQUEST_CONNECT_TIMEOUT_MS: number
EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS: number
EXTERNAL_REQUEST_CONNECTIONS: number
+ // The number of connections the HTTP/2 dispatchers open per origin. The request helper holds a burst to a cold
+ // origin behind one probe request, so this cap only bounds an origin that negotiates HTTP/1.1 and the spill past
+ // 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
// PostHog analytics
POSTHOG_API_KEY: string
@@ -249,6 +254,7 @@ export type ExternalRequestConfig = Pick<
| 'EXTERNAL_REQUEST_CONNECT_TIMEOUT_MS'
| 'EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS'
| 'EXTERNAL_REQUEST_CONNECTIONS'
+ | 'EXTERNAL_REQUEST_H2_CONNECTIONS'
>
export function getExternalRequestConfig(): ExternalRequestConfig {
@@ -260,6 +266,7 @@ export function getExternalRequestConfig(): ExternalRequestConfig {
EXTERNAL_REQUEST_CONNECT_TIMEOUT_MS: Number(process.env.EXTERNAL_REQUEST_CONNECT_TIMEOUT_MS ?? 3000),
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),
}
}
@@ -414,6 +421,7 @@ export function getDefaultCommonConfig(): CommonConfig {
EXTERNAL_REQUEST_CONNECT_TIMEOUT_MS: 3000,
EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS: 10000,
EXTERNAL_REQUEST_CONNECTIONS: 500,
+ EXTERNAL_REQUEST_H2_CONNECTIONS: 8,
// PostHog analytics
POSTHOG_API_KEY: '',
diff --git a/nodejs/src/common/utils/cold-start-gate.test.ts b/nodejs/src/common/utils/cold-start-gate.test.ts
new file mode 100644
index 000000000000..d468278ec76c
--- /dev/null
+++ b/nodejs/src/common/utils/cold-start-gate.test.ts
@@ -0,0 +1,81 @@
+import { ColdStartGate } from './cold-start-gate'
+
+const ORIGIN = 'https://origin.test'
+
+// Reports whether a promise has settled by the time one macrotask has run.
+async function settledWithinATick(promise: Promise<unknown>): Promise<boolean> {
+ const pending = Symbol('pending')
+ const tick = new Promise<typeof pending>((resolve) => setImmediate(() => resolve(pending)))
+ return (await Promise.race([promise.then(() => 'settled'), tick])) !== pending
+}
+
+describe('ColdStartGate', () => {
+ let now: number
+
+ beforeEach(() => {
+ now = 1_000_000
+ jest.spyOn(Date, 'now').mockImplementation(() => now)
+ })
+
+ it('holds later requests behind the probe and releases them together once it has headers', async () => {
+ const gate = new ColdStartGate(1000)
+
+ const admission = await gate.acquire(ORIGIN)
+ expect(admission.probe).toBe(true)
+ const held = [gate.acquire(ORIGIN), gate.acquire(ORIGIN)]
+ expect(await settledWithinATick(Promise.race(held))).toBe(false)
+
+ gate.touch(ORIGIN)
+ admission.release()
+ expect((await Promise.all(held)).map((entry) => entry.probe)).toEqual([false, false])
+
+ // The origin is warm now, so a new request starts at once and is not a probe.
+ expect((await gate.acquire(ORIGIN)).probe).toBe(false)
+ })
+
+ it('makes the next waiter the probe when the probe fails', async () => {
+ const gate = new ColdStartGate(1000)
+
+ const failedProbe = await gate.acquire(ORIGIN)
+ const waiter = gate.acquire(ORIGIN)
+ failedProbe.release()
+ const secondProbe = await waiter
+ expect(secondProbe.probe).toBe(true)
+
+ // The origin is still cold, so the second probe holds a new request until it releases.
+ const heldBehindSecondProbe = gate.acquire(ORIGIN)
+ expect(await settledWithinATick(heldBehindSecondProbe)).toBe(false)
+ gate.touch(ORIGIN)
+ secondProbe.release()
+ expect(await settledWithinATick(heldBehindSecondProbe)).toBe(true)
+ })
+
+ it('rejects a held request with its own reason when its signal aborts', async () => {
+ const gate = new ColdStartGate(1000)
+ const controller = new AbortController()
+ const reason = new Error('deadline')
+
+ const admission = await gate.acquire(ORIGIN)
+ const held = gate.acquire(ORIGIN, controller.signal)
+ controller.abort(reason)
+
+ await expect(held).rejects.toBe(reason)
+ // The probe is unaffected, and a later request still waits for it.
+ expect(await settledWithinATick(gate.acquire(ORIGIN))).toBe(false)
+ admission.release()
+ })
+
+ it('counts an origin as warm until the idle timeout has passed since its last activity', async () => {
+ const gate = new ColdStartGate(1000)
+ gate.touch(ORIGIN)
+
+ now += 999
+ expect(await settledWithinATick(gate.acquire(ORIGIN))).toBe(true)
+
+ now += 2
+ const probe = await gate.acquire(ORIGIN)
+ expect(probe.probe).toBe(true)
+ expect(await settledWithinATick(gate.acquire(ORIGIN))).toBe(false)
+ probe.release()
+ })
+})
diff --git a/nodejs/src/common/utils/cold-start-gate.ts b/nodejs/src/common/utils/cold-start-gate.ts
new file mode 100644
index 000000000000..d49574486ee5
--- /dev/null
+++ b/nodejs/src/common/utils/cold-start-gate.ts
@@ -0,0 +1,97 @@
+type OriginWarmth = { warmUntil: number; probe: Promise<void> | null }
+
+export type ColdStartAdmission = { probe: boolean; release: () => void }
+
+const MAX_TRACKED_ORIGINS = 10_000
+
+/**
+ * Holds a burst of requests to a cold origin behind one probe request. undici sizes its pool before ALPN tells it
+ * the protocol, so without the gate a burst to a cold HTTP/2 origin opens one session per request. The probe's
+ * response headers mean the origin's SETTINGS frame has arrived, so the released requests multiplex on that
+ * session. An origin that negotiates HTTP/1.1 still gets one connection per released request. An origin counts as
+ * warm until the dispatcher's idle timeout has passed since its last response activity, which is when undici closes
+ * the idle session. A session the origin closes earlier, with a GOAWAY, still counts as warm, so a burst inside that
+ * window fans out up to the pool cap.
+ */
+export class ColdStartGate {
+ private readonly origins = new Map<string, OriginWarmth>()
+ private nextSweepAt = 0
+
+ constructor(private readonly idleTimeoutMs: number) {}
+
+ /**
+ * Resolves once the request may start. `release` frees the held requests and must run when the probe has
+ * response headers or has failed; for a request that is not the probe it does nothing. A held request whose
+ * signal aborts rejects with the signal's reason, as undici does for a request it never sent. When a probe fails,
+ * the next waiter becomes the probe, so a burst does not fan out after one failed connection.
+ */
+ async acquire(origin: string, signal?: AbortSignal): Promise<ColdStartAdmission> {
+ for (;;) {
+ const now = Date.now()
+ const state = this.origins.get(origin)
+ if (state?.probe) {
+ await this.waitForProbe(state.probe, signal)
+ continue
+ }
+ if (state && state.warmUntil > now) {
+ return { probe: false, release: () => {} }
+ }
+ let releaseProbe!: () => void
+ const probe = new Promise<void>((resolve) => (releaseProbe = resolve))
+ const probing: OriginWarmth = { warmUntil: state?.warmUntil ?? 0, probe }
+ this.origins.set(origin, probing)
+ this.sweep(now)
+ return {
+ probe: true,
+ release: () => {
+ if (probing.probe === probe) {
+ probing.probe = null
+ }
+ releaseProbe()
+ },
+ }
+ }
+ }
+
+ touch(origin: string): void {
+ const warmUntil = Date.now() + this.idleTimeoutMs
+ const state = this.origins.get(origin)
+ if (state) {
+ state.warmUntil = warmUntil
+ } else {
+ this.origins.set(origin, { warmUntil, probe: null })
+ }
+ }
+
+ private async waitForProbe(probe: Promise<void>, signal?: AbortSignal): Promise<void> {
+ if (!signal) {
+ await probe
+ return
+ }
+ if (signal.aborted) {
+ throw signal.reason
+ }
+ let onAbort!: () => void
+ const aborted = new Promise<never>((_, reject) => {
+ onAbort = () => reject(signal.reason)
+ signal.addEventListener('abort', onAbort, { once: true })
+ })
+ try {
+ await Promise.race([probe, aborted])
+ } finally {
+ signal.removeEventListener('abort', onAbort)
+ }
+ }
+
+ private sweep(now: number): void {
+ if (this.origins.size < MAX_TRACKED_ORIGINS || now < this.nextSweepAt) {
+ return
+ }
+ this.nextSweepAt = now + 1000
+ for (const [origin, state] of this.origins) {
+ if (!state.probe && state.warmUntil <= now) {
+ this.origins.delete(origin)
+ }
+ }
+ }
+}
diff --git a/nodejs/src/common/utils/request-http2.test.ts b/nodejs/src/common/utils/request-http2.test.ts
index a701ed0e9b25..18f308791bad 100644
--- a/nodejs/src/common/utils/request-http2.test.ts
+++ b/nodejs/src/common/utils/request-http2.test.ts
@@ -4,6 +4,7 @@ import https from 'node:https'
import net, { AddressInfo } from 'node:net'
import tls from 'node:tls'
+import { waitForExpect } from '~/tests/helpers/expectations'
import { TestTlsIdentity, createTestTlsIdentity } from '~/tests/helpers/tls'
type RequestModule = typeof import('./request')
@@ -29,16 +30,21 @@ describe('secure HTTP/2 requests', () => {
let requestModule: RequestModule
let http2Origin: http2.Http2SecureServer
let http1Origin: https.Server
+ let plainOrigin: http.Server
let connectProxy: http.Server
let tlsConnectSpy: jest.SpyInstance
let tlsIdentity: TestTlsIdentity | undefined
const originalExternalRequestConnections = process.env.EXTERNAL_REQUEST_CONNECTIONS
+ const originalH2Connections = process.env.EXTERNAL_REQUEST_H2_CONNECTIONS
+ const originalKeepAliveTimeout = process.env.EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS
+ const keepAliveTimeoutMs = 3000
const originalProxyEnvironment = Object.fromEntries(
proxyEnvironmentNames.map((name) => [name, process.env[name]])
) as Record<(typeof proxyEnvironmentNames)[number], string | undefined>
let http2SessionCount = 0
const http2OriginProtocols: string[] = []
const http1OriginProtocols: string[] = []
+ let http1ConnectionCount = 0
const proxyAuthorities: string[] = []
const openSockets = new Set<net.Socket>()
const openHttp2Sessions = new Set<http2.ServerHttp2Session>()
@@ -67,6 +73,9 @@ describe('secure HTTP/2 requests', () => {
return
}
finishResponse()
+ if (request.url === '/goaway') {
+ request.stream.session?.close()
+ }
})
http2Origin.on('session', (session) => {
http2SessionCount += 1
@@ -83,8 +92,17 @@ describe('secure HTTP/2 requests', () => {
response.end(request.url)
}
)
+ http1Origin.on('connection', () => {
+ http1ConnectionCount += 1
+ })
await listen(http1Origin)
+ plainOrigin = http.createServer((request, response) => {
+ response.writeHead(200, { 'content-type': 'text/plain' })
+ response.end(request.url)
+ })
+ await listen(plainOrigin)
+
connectProxy = http.createServer()
connectProxy.on('connection', (socket) => {
openSockets.add(socket)
@@ -102,7 +120,11 @@ describe('secure HTTP/2 requests', () => {
originSocket.pipe(clientSocket)
})
openSockets.add(originSocket)
- originSocket.once('close', () => openSockets.delete(originSocket))
+ originSocket.once('close', () => {
+ openSockets.delete(originSocket)
+ clientSocket.destroy()
+ })
+ clientSocket.once('close', () => originSocket.destroy())
originSocket.once('error', () => clientSocket.destroy())
clientSocket.once('error', () => originSocket.destroy())
})
@@ -118,14 +140,28 @@ describe('secure HTTP/2 requests', () => {
)) as typeof tls.connect)
process.env.HTTPS_PROXY = `http://127.0.0.1:${serverPort(connectProxy)}`
process.env.EXTERNAL_REQUEST_CONNECTIONS = '2'
+ process.env.EXTERNAL_REQUEST_H2_CONNECTIONS = '4'
+ process.env.EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS = String(keepAliveTimeoutMs)
delete process.env.HTTP_PROXY
delete process.env.https_proxy
delete process.env.http_proxy
+ })
+ beforeEach(() => {
+ http2SessionCount = 0
+ http2OriginProtocols.length = 0
+ http1OriginProtocols.length = 0
+ http1ConnectionCount = 0
+ proxyAuthorities.length = 0
jest.resetModules()
requestModule = require('./request') as RequestModule
})
+ afterEach(async () => {
+ await requestModule.closeSharedAgents()
+ await waitForExpect(() => expect(openHttp2Sessions.size).toBe(0), 2000)
+ })
+
afterAll(async () => {
for (const name of proxyEnvironmentNames) {
const value = originalProxyEnvironment[name]
@@ -140,6 +176,16 @@ describe('secure HTTP/2 requests', () => {
} else {
process.env.EXTERNAL_REQUEST_CONNECTIONS = originalExternalRequestConnections
}
+ if (originalH2Connections === undefined) {
+ delete process.env.EXTERNAL_REQUEST_H2_CONNECTIONS
+ } else {
+ process.env.EXTERNAL_REQUEST_H2_CONNECTIONS = originalH2Connections
+ }
+ if (originalKeepAliveTimeout === undefined) {
+ delete process.env.EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS
+ } else {
+ process.env.EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS = originalKeepAliveTimeout
+ }
tlsConnectSpy.mockRestore()
for (const session of openHttp2Sessions) {
@@ -149,12 +195,13 @@ describe('secure HTTP/2 requests', () => {
socket.destroy()
}
http1Origin.closeAllConnections()
+ plainOrigin.closeAllConnections()
connectProxy.closeAllConnections()
- await Promise.all([close(http2Origin), close(http1Origin), close(connectProxy)])
+ await Promise.all([close(http2Origin), close(http1Origin), close(plainOrigin), close(connectProxy)])
await tlsIdentity?.cleanup()
})
- it('negotiates, reuses, runs concurrently, defaults, and falls back through a CONNECT proxy', async () => {
+ it('negotiates, multiplexes, defaults, and falls back through a CONNECT proxy', async () => {
const http2Authority = `origin.test:${serverPort(http2Origin)}`
const http2Url = `https://${http2Authority}`
const bufferedResponse = await requestModule.fetch(`${http2Url}/buffered`, { allowH2: true, timeoutMs: 2000 })
@@ -189,7 +236,160 @@ describe('secure HTTP/2 requests', () => {
expect(http2OriginProtocols).toEqual(['2.0', '2.0', '2.0', '2.0', '1.1'])
expect(http1OriginProtocols).toEqual(['1.1'])
+ // undici multiplexes the concurrent requests on one session, up to the server's max concurrent streams.
+ expect(http2SessionCount).toBe(1)
+ expect(proxyAuthorities).toEqual([http2Authority, http2Authority, http1Authority])
+ }, 10000)
+
+ it('sends a plain http target through the CONNECT tunnel', async () => {
+ // The proxy applies its checks to the tunnel. An absolute-form request forwarded to the proxy would take a
+ // different path there, so a target that undici would not tunnel by default must still show up as CONNECT.
+ const plainAuthority = `origin.test:${serverPort(plainOrigin)}`
+ const response = await requestModule.fetch(`http://${plainAuthority}/plain`, { timeoutMs: 2000 })
+
+ expect(await response.text()).toBe('/plain')
+ expect(proxyAuthorities).toEqual([plainAuthority])
+ }, 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}`)
+
+ const bodies = await Promise.all(
+ paths.map(async (path) => {
+ const response = await requestModule.fetchStreamed(`${http2Url}${path}`, {
+ allowH2: true,
+ timeoutMs: 2000,
+ })
+ return (await response.read(100)).bytes.toString()
+ })
+ )
+
+ expect(bodies).toEqual(paths)
+ // The pool cap is 4, so only the cold-start gate can hold six requests on one session.
+ expect(http2SessionCount).toBe(1)
+ }, 10000)
+
+ it('still fans a burst out to an origin that negotiates HTTP/1.1', async () => {
+ const http1Url = `https://origin.test:${serverPort(http1Origin)}`
+ const paths = ['/h1-burst-a', '/h1-burst-b', '/h1-burst-c']
+
+ const bodies = await Promise.all(
+ paths.map(async (path) => {
+ const response = await requestModule.fetchStreamed(`${http1Url}${path}`, {
+ allowH2: true,
+ timeoutMs: 2000,
+ })
+ return (await response.read(100)).bytes.toString()
+ })
+ )
+
+ expect(bodies).toEqual(paths)
+ expect(http1OriginProtocols).toEqual(['1.1', '1.1', '1.1'])
+ // The probe finds HTTP/1.1, so the released requests open their own connections instead of queueing.
+ expect(http1ConnectionCount).toBeGreaterThanOrEqual(2)
+ }, 10000)
+
+ it('releases a held burst when the probe request fails', async () => {
+ const closedPort = await new Promise<number>((resolve) => {
+ const probe = net.createServer()
+ probe.listen(0, '127.0.0.1', () => {
+ const port = (probe.address() as AddressInfo).port
+ probe.close(() => resolve(port))
+ })
+ })
+ const deadUrl = `https://origin.test:${closedPort}`
+
+ const results = await Promise.allSettled(
+ ['/a', '/b', '/c'].map((path) =>
+ requestModule.fetchStreamed(`${deadUrl}${path}`, { allowH2: true, timeoutMs: 2000 })
+ )
+ )
+
+ // Held requests must not wait for their own timeout, which only starts once they are released.
+ expect(results.map((result) => result.status)).toEqual(['rejected', 'rejected', 'rejected'])
+ }, 10000)
+
+ it('opens a new session after the origin sends GOAWAY', async () => {
+ const http2Url = `https://origin.test:${serverPort(http2Origin)}`
+ const goawayResponse = await requestModule.fetchStreamed(`${http2Url}/goaway`, {
+ allowH2: true,
+ timeoutMs: 2000,
+ })
+ expect((await goawayResponse.read(100)).bytes.toString()).toBe('/goaway')
+ const sessionsBeforeReconnect = http2SessionCount
+
+ const afterGoawayResponse = await requestModule.fetchStreamed(`${http2Url}/after-goaway`, {
+ allowH2: true,
+ timeoutMs: 2000,
+ })
+ expect((await afterGoawayResponse.read(100)).bytes.toString()).toBe('/after-goaway')
+
+ expect(http2SessionCount).toBe(sessionsBeforeReconnect + 1)
+ }, 10000)
+
+ it('closes an idle session after the keep-alive timeout', async () => {
+ const http2Url = `https://origin.test:${serverPort(http2Origin)}`
+ const response = await requestModule.fetchStreamed(`${http2Url}/idle`, { allowH2: true, timeoutMs: 2000 })
+ expect((await response.read(100)).bytes.toString()).toBe('/idle')
+ expect(openHttp2Sessions.size).toBeGreaterThan(0)
+
+ await waitForExpect(() => expect(openHttp2Sessions.size).toBe(0), keepAliveTimeoutMs * 3)
+ }, 15000)
+
+ it('keeps a session open for the idle timeout a caller asks for', async () => {
+ const http2Url = `https://origin.test:${serverPort(http2Origin)}`
+ const [defaultResponse, patientResponse] = await Promise.all([
+ requestModule.fetchStreamed(`${http2Url}/default-idle`, { allowH2: true, timeoutMs: 2000 }),
+ requestModule.fetchStreamed(`${http2Url}/patient-idle`, {
+ allowH2: true,
+ timeoutMs: 2000,
+ http2IdleTimeoutMs: 60_000,
+ }),
+ ])
+ expect((await defaultResponse.read(100)).bytes.toString()).toBe('/default-idle')
+ expect((await patientResponse.read(100)).bytes.toString()).toBe('/patient-idle')
+ expect(openHttp2Sessions.size).toBe(2)
+
+ // The default session closes first. The caller's session must outlive it.
+ await waitForExpect(() => expect(openHttp2Sessions.size).toBe(1), keepAliveTimeoutMs * 3)
expect(http2SessionCount).toBe(2)
- expect(proxyAuthorities).toEqual([http2Authority, http2Authority, http2Authority, http1Authority])
+ }, 15000)
+
+ it('closes open sessions and proxy tunnels when the shared agents shut down', async () => {
+ const http2Url = `https://origin.test:${serverPort(http2Origin)}`
+ const response = await requestModule.fetchStreamed(`${http2Url}/shutdown`, {
+ allowH2: true,
+ timeoutMs: 2000,
+ })
+ expect((await response.read(100)).bytes.toString()).toBe('/shutdown')
+ expect(openHttp2Sessions.size).toBeGreaterThan(0)
+ const requestedAt = Date.now()
+
+ await requestModule.closeSharedAgents()
+
+ await waitForExpect(() => {
+ expect(openHttp2Sessions.size).toBe(0)
+ expect(openSockets.size).toBe(0)
+ }, 2000)
+ // The wait ended well inside the keep-alive timeout, so the shutdown closed the session and not the idle timer.
+ expect(Date.now() - requestedAt).toBeLessThan(keepAliveTimeoutMs)
+
+ // Every path rejects the same way after the agents close. undici guards the destroyed HTTP/1.1 and HTTP/2
+ // dispatchers. The closed flag covers a timeout that has no dispatcher yet.
+ const destroyed = { name: 'ClientDestroyedError', code: 'UND_ERR_DESTROYED' }
+ await expect(requestModule.fetch(`${http2Url}/after-close`, { timeoutMs: 2000 })).rejects.toMatchObject(
+ destroyed
+ )
+ await expect(
+ requestModule.fetchStreamed(`${http2Url}/after-close`, { allowH2: true, timeoutMs: 2000 })
+ ).rejects.toMatchObject(destroyed)
+ await expect(
+ requestModule.fetchStreamed(`${http2Url}/after-close`, {
+ allowH2: true,
+ timeoutMs: 2000,
+ http2IdleTimeoutMs: 42_000,
+ })
+ ).rejects.toMatchObject(destroyed)
}, 10000)
})
diff --git a/nodejs/src/common/utils/request-streamed.test.ts b/nodejs/src/common/utils/request-streamed.test.ts
index ddd9a551c4db..d82ff2202a71 100644
--- a/nodejs/src/common/utils/request-streamed.test.ts
+++ b/nodejs/src/common/utils/request-streamed.test.ts
@@ -2,7 +2,7 @@ import { Readable } from 'node:stream'
// eslint-disable-next-line no-restricted-imports
import { request } from 'undici'
-import { InvalidRequestError, fetchStreamed } from './request'
+import { InvalidRequestError, fetch, fetchStreamed } from './request'
jest.mock('undici', () => ({
...jest.requireActual('undici'),
@@ -120,4 +120,24 @@ describe('fetchStreamed', () => {
expect(requestMock).not.toHaveBeenCalled()
})
+
+ it('releases the cold-start gate when a request throws before it is sent', async () => {
+ // A probe that never reaches undici must still release its origin, or every later request to it waits forever.
+ await expect(fetch('ftp://origin.test/a', { allowH2: true })).rejects.toThrow('URL must have HTTP or HTTPS')
+ await expect(fetch('ftp://origin.test/b', { allowH2: true })).rejects.toThrow('URL must have HTTP or HTTPS')
+
+ expect(requestMock).not.toHaveBeenCalled()
+ }, 5000)
+
+ it.each([[0], [-1], [NaN], [2 ** 31]])(
+ 'refuses an http2IdleTimeoutMs of %p before opening a socket',
+ async (ms) => {
+ // InvalidRequestError is not retriable, so a bad constant fails once instead of using its retries.
+ await expect(
+ fetchStreamed('https://example.com/a.png', { timeoutMs: 1000, allowH2: true, http2IdleTimeoutMs: ms })
+ ).rejects.toThrow(InvalidRequestError)
+
+ expect(requestMock).not.toHaveBeenCalled()
+ }
+ )
})
diff --git a/nodejs/src/common/utils/request.ts b/nodejs/src/common/utils/request.ts
index 58e592750e93..39eff21f001e 100644
--- a/nodejs/src/common/utils/request.ts
+++ b/nodejs/src/common/utils/request.ts
@@ -13,12 +13,14 @@ import {
RequestInit,
Response,
request,
+ errors as undiciErrors,
fetch as undiciFetch,
} from 'undici'
import { URL } from 'url'
import { getExternalRequestConfig } from '~/common/config'
+import { ColdStartGate } from './cold-start-gate'
import { isProdEnv } from './env-utils'
import { fetchAttribution } from './fetch-attribution'
import { parseJSON } from './json-parse'
@@ -50,7 +52,14 @@ export type FetchOptions = {
headers?: HeadersInit
body?: string | Buffer
timeoutMs?: number
+ // The TLS handshake offers HTTP/2 and HTTP/1.1. The origin selects the protocol. undici lists HTTP/1.1 first, so an
+ // origin that follows the client's order selects HTTP/1.1. APNs supports only HTTP/2, so it selects HTTP/2. The
+ // undici connect option `preferH2` lists HTTP/2 first.
allowH2?: boolean
+ // The time an idle HTTP/2 session to the origin stays open. The default is the keep-alive timeout. An origin that
+ // negotiates HTTP/1.1 uses the same dispatcher, so its idle sockets also close after this time. Pass a constant:
+ // each distinct value keeps a dispatcher for the life of the process, and at most 8 values are allowed.
+ http2IdleTimeoutMs?: number
}
export type FetchResponse = {
@@ -259,6 +268,8 @@ class InsecureAgent extends Agent {
super({
keepAliveTimeout: requestConfig.EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS,
connections: requestConfig.EXTERNAL_REQUEST_CONNECTIONS,
+ // undici enables HTTP/2 by default. Internal services stay on HTTP/1.1 because nothing here needs multiplexing. HTTP/2 sessions also fail in different ways, with GOAWAY replays and refused streams.
+ allowH2: false,
connect: {
timeout: requestConfig.EXTERNAL_REQUEST_CONNECT_TIMEOUT_MS,
},
@@ -269,22 +280,34 @@ 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.
-function makeSecureDispatcher({ allowH2 }: { allowH2: boolean }): Dispatcher {
+function makeSecureDispatcher({
+ allowH2,
+ keepAliveTimeoutMs = requestConfig.EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS,
+}: {
+ 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) {
return new ProxyAgent({
uri: proxyUrl,
- keepAliveTimeout: requestConfig.EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS,
- connections: requestConfig.EXTERNAL_REQUEST_CONNECTIONS,
+ keepAliveTimeout: keepAliveTimeoutMs,
+ connections,
+ // undici 8 tunnels only https targets by default. The proxy applies its checks to the tunnel, so a plain
+ // http target must not go to the proxy as an absolute-form request instead.
+ proxyTunnel: true,
allowH2,
requestTls: { allowH2 },
})
}
return new Agent({
- keepAliveTimeout: Number(requestConfig.EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS),
- connections: requestConfig.EXTERNAL_REQUEST_CONNECTIONS,
+ keepAliveTimeout: keepAliveTimeoutMs,
+ connections,
allowH2,
connect: {
lookup: httpStaticLookup,
@@ -294,9 +317,89 @@ function makeSecureDispatcher({ allowH2 }: { allowH2: boolean }): Dispatcher {
}
const sharedSecureAgent = makeSecureDispatcher({ allowH2: false })
-const sharedSecureH2Agent = makeSecureDispatcher({ allowH2: true })
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
+// value would surface late and as a retriable error. Failing here stops the process at startup instead.
+if (
+ !Number.isInteger(requestConfig.EXTERNAL_REQUEST_H2_CONNECTIONS) ||
+ requestConfig.EXTERNAL_REQUEST_H2_CONNECTIONS < 1
+) {
+ throw new Error(
+ `EXTERNAL_REQUEST_H2_CONNECTIONS must be a positive integer, got ${process.env.EXTERNAL_REQUEST_H2_CONNECTIONS}`
+ )
+}
+
+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>()
+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 {
+ // 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)
+ if (!agent) {
+ if (sharedAgentsClosed) {
+ throw new undiciErrors.ClientDestroyedError()
+ }
+ if (sharedSecureH2Agents.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 }),
+ gate: new ColdStartGate(idleTimeoutMs),
+ }
+ sharedSecureH2Agents.set(idleTimeoutMs, agent)
+ }
+ return agent
+}
+
+function getSecureDispatcher(options: { allowH2?: boolean; http2IdleTimeoutMs?: number }): SecureDispatcher {
+ return options.allowH2
+ ? getSecureH2Agent(options.http2IdleTimeoutMs)
+ : { dispatcher: sharedSecureAgent, gate: null }
+}
+
+// The timer only bounds the wait in closeSharedAgents. When close finishes first, an unref'd timer does not keep the
+// process alive for the rest of the grace period.
+function unrefDelay(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms).unref())
+}
+
+/**
+ * Closes the shared dispatchers at shutdown. Idle keep-alive sockets and HTTP/2 sessions close now
+ * instead of at their idle timeout. `close` waits for in-flight requests to settle. A streamed body
+ * that no caller reads or discards holds its socket forever, so the grace period bounds the wait and
+ * `destroy` ends whatever remains.
+ */
+export async function closeSharedAgents(gracePeriodMs = 5000): Promise<void> {
+ sharedAgentsClosed = true
+ const agents = [
+ sharedSecureAgent,
+ sharedInsecureAgent,
+ ...[...sharedSecureH2Agents.values()].map((h2) => h2.dispatcher),
+ ]
+ const stillOpen = new Set(agents)
+ const closed = Promise.allSettled(agents.map((agent) => agent.close().finally(() => stillOpen.delete(agent)))).then(
+ () => true
+ )
+ const closedInTime = await Promise.race([closed, unrefDelay(gracePeriodMs).then(() => false)])
+ if (!closedInTime) {
+ logger.warn('[request] Destroying shared agents with requests still in flight at shutdown', {
+ gracePeriodMs,
+ openAgents: stillOpen.size,
+ })
+ }
+ await Promise.allSettled(agents.map((agent) => agent.destroy()))
+}
+
function destroyBody(body: Dispatcher.ResponseData['body']): void {
try {
body.on('error', () => {})
@@ -336,11 +439,22 @@ async function readAndDestroyBody(body: Dispatcher.ResponseData['body']): Promis
return text
}
+// Hooks for the cold-start gate. The signal is created before the hold, so time spent held counts against the
+// caller's timeout. onHeaders or onError runs once the request settles; onBodyDone runs when the caller has read or
+// discarded the body.
+type RequestLifecycle = {
+ signal: AbortSignal | undefined
+ onHeaders: () => void
+ onError: () => void
+ onBodyDone: () => void
+}
+
export async function _fetch(
url: string,
options: FetchOptions = {},
dispatcher: Dispatcher,
- defaultTimeoutMs: number = requestConfig.EXTERNAL_REQUEST_TIMEOUT_MS
+ defaultTimeoutMs: number = requestConfig.EXTERNAL_REQUEST_TIMEOUT_MS,
+ lifecycle?: RequestLifecycle
): Promise<FetchResponse> {
let parsed: URL
try {
@@ -355,14 +469,21 @@ export async function _fetch(
options.timeoutMs = options.timeoutMs ?? defaultTimeoutMs
- const result = await request(parsed.toString(), {
- method: options.method ?? 'GET',
- headers: options.headers,
- body: options.body,
- dispatcher,
- // request() does not follow redirects, so a response can never bounce to an unvalidated host
- signal: options.timeoutMs ? AbortSignal.timeout(options.timeoutMs) : undefined,
- })
+ let result: Dispatcher.ResponseData
+ try {
+ result = await request(parsed.toString(), {
+ method: options.method ?? 'GET',
+ headers: options.headers,
+ body: options.body,
+ dispatcher,
+ // request() does not follow redirects, so a response can never bounce to an unvalidated host
+ signal: lifecycle?.signal ?? (options.timeoutMs ? AbortSignal.timeout(options.timeoutMs) : undefined),
+ })
+ } catch (error) {
+ lifecycle?.onError()
+ throw error
+ }
+ lifecycle?.onHeaders()
const headers = flattenHeaders(result.headers)
@@ -373,7 +494,7 @@ export async function _fetch(
const readBody = (): Promise<string> => {
if (!bodyPromise) {
- bodyPromise = readAndDestroyBody(result.body)
+ bodyPromise = readAndDestroyBody(result.body).finally(() => lifecycle?.onBodyDone())
}
return bodyPromise
}
@@ -387,12 +508,45 @@ export async function _fetch(
if (!bodyPromise) {
bodyPromise = Promise.resolve('')
destroyBody(result.body)
+ lifecycle?.onBodyDone()
}
return Promise.resolve()
},
}
}
+const coldStartGateCounter = new Counter({
+ name: 'node_request_cold_start_gate_total',
+ help: 'Requests the HTTP/2 cold-start gate saw: probes to a cold origin, requests held behind a probe, and probes that failed',
+ labelNames: ['event'],
+})
+
+async function gatedLifecycle(
+ gate: ColdStartGate | null,
+ origin: string,
+ signal: AbortSignal | undefined
+): Promise<RequestLifecycle | undefined> {
+ if (!gate) {
+ return undefined
+ }
+ const { probe, release } = await gate.acquire(origin, signal)
+ coldStartGateCounter.inc({ event: probe ? 'probe' : 'held' })
+ return {
+ signal,
+ onHeaders: () => {
+ gate.touch(origin)
+ release()
+ },
+ onError: () => {
+ if (probe) {
+ coldStartGateCounter.inc({ event: 'probe_failed' })
+ }
+ release()
+ },
+ onBodyDone: () => gate.touch(origin),
+ }
+}
+
export async function internalFetch(url: string, options: FetchOptions = {}): Promise<FetchResponse> {
return await _fetch(url, options, sharedInsecureAgent)
}
@@ -407,9 +561,17 @@ export async function fetch(url: string, options: FetchOptions = {}): Promise<Fe
const parsed = new URL(url)
validateHostnameIPLiteral(parsed.hostname, !isProdEnv())
inflightExternalRequests.inc()
+ let lifecycle: RequestLifecycle | undefined
try {
- const dispatcher = options.allowH2 ? sharedSecureH2Agent : sharedSecureAgent
- return await _fetch(url, options, dispatcher, requestConfig.EXTERNAL_REQUEST_THIRD_PARTY_TIMEOUT_MS)
+ const { dispatcher, gate } = getSecureDispatcher(options)
+ options.timeoutMs = options.timeoutMs ?? requestConfig.EXTERNAL_REQUEST_THIRD_PARTY_TIMEOUT_MS
+ const signal = options.timeoutMs ? AbortSignal.timeout(options.timeoutMs) : undefined
+ lifecycle = await gatedLifecycle(gate, parsed.origin, signal)
+ return await _fetch(url, options, dispatcher, requestConfig.EXTERNAL_REQUEST_THIRD_PARTY_TIMEOUT_MS, lifecycle)
+ } catch (error) {
+ // Releases the probe when a throw happens before request() runs. The release is idempotent.
+ lifecycle?.onError()
+ throw error
} finally {
inflightExternalRequests.dec()
}
@@ -419,6 +581,7 @@ export type StreamedFetchOptions = {
headers?: HeadersInit
timeoutMs: number
allowH2?: boolean
+ http2IdleTimeoutMs?: number
}
export type StreamedResponse = {
@@ -518,18 +681,24 @@ export async function fetchStreamed(url: string, options: StreamedFetchOptions):
inflightExternalRequests.inc()
let result: Dispatcher.ResponseData
+ let lifecycle: RequestLifecycle | undefined
try {
+ const { dispatcher, gate } = getSecureDispatcher(options)
+ const signal = AbortSignal.timeout(options.timeoutMs)
+ lifecycle = await gatedLifecycle(gate, parsed.origin, signal)
result = await request(parsed.toString(), {
method: 'GET',
headers: options.headers,
- dispatcher: options.allowH2 ? sharedSecureH2Agent : sharedSecureAgent,
- signal: AbortSignal.timeout(options.timeoutMs),
+ dispatcher,
+ signal,
responseHeaders: 'raw',
})
} catch (error) {
+ lifecycle?.onError()
inflightExternalRequests.dec()
throw error
}
+ lifecycle?.onHeaders()
// The gauge holds until the body is done, not until the headers arrive, because the body takes
// nearly all the time of an image request.
@@ -539,6 +708,7 @@ export async function fetchStreamed(url: string, options: StreamedFetchOptions):
return false
}
settled = true
+ lifecycle?.onBodyDone()
inflightExternalRequests.dec()
return true
}
diff --git a/nodejs/src/servers/base-server.ts b/nodejs/src/servers/base-server.ts
index 46d7b20b1756..9ca83ab943d0 100644
--- a/nodejs/src/servers/base-server.ts
+++ b/nodejs/src/servers/base-server.ts
@@ -13,6 +13,7 @@ import { logger } from '~/common/utils/logger'
import { NodeInstrumentation } from '~/common/utils/node-instrumentation'
import { captureException, shutdown as posthogShutdown } from '~/common/utils/posthog'
import { PubSub } from '~/common/utils/pubsub'
+import { closeSharedAgents } from '~/common/utils/request'
import { delay } from '~/common/utils/utils'
import { onShutdown } from '../lifecycle'
@@ -163,6 +164,7 @@ export class ServerLifecycle {
...resources.kafkaProducers.map((p) => p.disconnect()),
...resources.redisPools.map((p) => p.drain()),
resources.postgres?.end(),
+ closeSharedAgents(),
])
for (const pool of resources.redisPools) {
await pool.clear()
diff --git a/nodejs/tests/helpers/mocks/request.mock.ts b/nodejs/tests/helpers/mocks/request.mock.ts
index f8152bf09427..5b30f31ddb50 100644
--- a/nodejs/tests/helpers/mocks/request.mock.ts
+++ b/nodejs/tests/helpers/mocks/request.mock.ts
@@ -18,6 +18,7 @@ jest.mock('~/common/utils/request', () => {
text: () => Promise.resolve(''),
} as FetchResponse)
),
+ closeSharedAgents: jest.fn(() => Promise.resolve()),
}
})
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 34bd5ad2f044..e3fdf991a038 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1748,8 +1748,8 @@ importers:
specifier: 2.0.9
version: 2.0.9
undici:
- specifier: ^7.24.0
- version: 7.24.8
+ specifier: ^8.10.1
+ version: 8.10.1
undici-types:
specifier: 7.3.0
version: 7.3.0
@@ -22742,6 +22742,10 @@ packages:
resolution: {integrity: sha512-6KQ/+QxK49Z/p3HO6E5ZCZWNnCasyZLa5ExaVYyvPxUwKtbCPMKELJOqh7EqOle0t9cH/7d2TaaTRRa6Nhs4YQ==}
engines: {node: '>=20.18.1'}
+ resolution: {integrity: sha512-YQ3WlbqjYMmNpdvDH64jAgLjxuAR9+649calDWhbshYaeQGO2bR4nI94ORJmwI3J9YhoKQnpyGOK+0zlWS5N5Q==}
+ engines: {node: '>=22.19.0'}
+
resolution: {integrity: sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==}
@@ -45536,6 +45540,8 @@ snapshots:
+
dependencies:
pathe: 2.0.3