Skip to content

Commit 601a693

Browse files
author
Leonid Skorobogatyy
committed
fix: cache undici dispatcher promise to avoid orphaned Agent
Concurrent first calls to nodeFetchWithDispatcher could each create an Agent before either cached the result. Cache the import promise itself so all callers share one resolution.
1 parent caa91bc commit 601a693

1 file changed

Lines changed: 9 additions & 13 deletions

File tree

packages/sdk/js/src/node-fetch.ts

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,19 @@
66
// undici is a hard dependency, but we still import it lazily inside the guard
77
// so browser bundlers don't pull undici (and its node:* deps) into the bundle
88
// when the SDK is loaded in a non-Node environment.
9+
//
10+
// The promise is cached so concurrent first calls share a single Agent —
11+
// without this, two parallel calls could each create and race to assign an
12+
// Agent, leaving the loser orphaned (never closed).
913
type UndiciAgent = InstanceType<typeof import("undici").Agent>
1014

11-
let nodeDispatcher: UndiciAgent | undefined | null
12-
13-
async function ensureDispatcher() {
14-
if (nodeDispatcher !== undefined) return nodeDispatcher
15-
if (typeof process === "undefined" || !process.versions || process.versions.bun) {
16-
nodeDispatcher = null
17-
return null
18-
}
19-
const { Agent } = await import("undici")
20-
nodeDispatcher = new Agent({ headersTimeout: 0, bodyTimeout: 0 })
21-
return nodeDispatcher
22-
}
15+
const nodeDispatcher: Promise<UndiciAgent | null> =
16+
typeof process === "undefined" || !process.versions || process.versions.bun
17+
? Promise.resolve(null)
18+
: import("undici").then(({ Agent }) => new Agent({ headersTimeout: 0, bodyTimeout: 0 }))
2319

2420
export async function nodeFetchWithDispatcher(req: Request) {
25-
const dispatcher = await ensureDispatcher()
21+
const dispatcher = await nodeDispatcher
2622
if (!dispatcher) return fetch(req)
2723
return fetch(req, { dispatcher } as RequestInit)
2824
}

0 commit comments

Comments
 (0)