Skip to content

Commit d7f6da6

Browse files
committed
fix(server): a dropped HTTP/2 connection no longer crashes the server
Node 26 bundles undici 8, whose fetch negotiates HTTP/2 with every h2-capable origin. When such a session hits its idle timeout, undici can emit 'error' on a ClientHttp2Stream with no listener, which exits the process and cancels every running turn. On runtimes whose built-in fetch defaults to HTTP/2, the CLI entry now installs an HTTP/1.1-only undici agent as the global dispatcher, which Node's built-in fetch (and Effect's FetchHttpClient on top of it) reads. An EnvHttpProxyAgent from --use-env-proxy is kept. Node 22/24 and Electron already stay on HTTP/1.1 and are left untouched. Fixes pingdotgg#18141
1 parent 3f70c83 commit d7f6da6

6 files changed

Lines changed: 166 additions & 1 deletion

File tree

‎apps/server/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
"proper-lockfile": "4.1.2",
6060
"stream-chain": "^4.2.5",
6161
"stream-json": "3.6.0",
62+
"undici": "catalog:",
6263
"yaml": "catalog:",
6364
"yauzl": "^3.4.0"
6465
},

‎apps/server/src/binCli.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { browserCommand } from "./cli/browser.ts";
1414
import { connectCommand } from "./cli/connect.ts";
1515
import { pairCommand } from "./cli/pair.ts";
1616
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
17+
import { keepOutboundFetchOnHttp1 } from "./outboundHttp.ts";
1718
import { sharedServerCommandFlags } from "./cli/config.ts";
1819
import { projectCommand } from "./cli/project.ts";
1920
import { runDefaultServerCommand, serveCommand, startCommand } from "./cli/server.ts";
@@ -92,6 +93,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
9293
export const cli = makeCli();
9394

9495
export function runCli() {
96+
keepOutboundFetchOnHttp1();
9597
Command.run(cli, { version: packageJson.version }).pipe(
9698
Effect.scoped,
9799
Effect.provide(layerCliRuntime),
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
// @effect-diagnostics nodeBuiltinImport:off
2+
import * as NodeHttp2 from "node:http2";
3+
import * as NodeNet from "node:net";
4+
import * as NodeTls from "node:tls";
5+
6+
import { it } from "@effect/vitest";
7+
import * as Effect from "effect/Effect";
8+
import { FetchHttpClient, HttpClient } from "effect/http";
9+
import * as Undici from "undici";
10+
import { afterAll, afterEach, beforeAll, describe, expect } from "vite-plus/test";
11+
12+
import { builtinFetchUsesHttp2, installHttp1FetchDispatcher } from "./outboundHttp.ts";
13+
14+
// Self-signed P-256 certificate for 127.0.0.1, valid until 2126. Test-only:
15+
// it lets a local server offer h2 over ALPN, which only happens over TLS.
16+
const TEST_KEY = `-----BEGIN PRIVATE KEY-----
17+
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg3EwCztQysKTvzdcR
18+
g0LWq+axzUd4tHi9PyMdqh7PlGShRANCAARfQpoLgv/tOsHWCLriDza7Ruaey2b7
19+
mR/nS6mLu6W7+agkEqDm0mE3F/ngpPjL4Jj0IGadeMcKNKFRSBgiLdfn
20+
-----END PRIVATE KEY-----
21+
`;
22+
const TEST_CERT = `-----BEGIN CERTIFICATE-----
23+
MIIBsDCCAVagAwIBAgIUWbn2Wt5kTxii1UU57NJMt/wTaUgwCgYIKoZIzj0EAwIw
24+
JDEiMCAGA1UEAwwZdDNjb2RlIG91dGJvdW5kIGh0dHAgdGVzdDAgFw0yNjEwMTEy
25+
MjQyMzZaGA8yMTI2MDkxNzIyNDIzNlowJDEiMCAGA1UEAwwZdDNjb2RlIG91dGJv
26+
dW5kIGh0dHAgdGVzdDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABF9CmguC/+06
27+
wdYIuuIPNrtG5p7LZvuZH+dLqYu7pbv5qCQSoObSYTcX+eCk+MvgmPQgZp14xwo0
28+
oVFIGCIt1+ejZDBiMB0GA1UdDgQWBBSsekAc30Q/zdIE/tvVDQKJL5oiCDAfBgNV
29+
HSMEGDAWgBSsekAc30Q/zdIE/tvVDQKJL5oiCDAPBgNVHRMBAf8EBTADAQH/MA8G
30+
A1UdEQQIMAaHBH8AAAEwCgYIKoZIzj0EAwIDSAAwRQIgebUrkyP56242EJB7nCV7
31+
A+Ke/q0rNPya3fjQa9O5B+kCIQC1SfmdNaFcNJ4JINlus4FfrRnfKiADS2MIJR9f
32+
99BN0A==
33+
-----END CERTIFICATE-----
34+
`;
35+
36+
// An h2-capable origin, like api.github.com, that answers with the HTTP
37+
// version the client negotiated.
38+
const server = NodeHttp2.createSecureServer(
39+
{ allowHTTP1: true, key: TEST_KEY, cert: TEST_CERT },
40+
(request, response) => response.end(request.httpVersion),
41+
);
42+
let origin = "";
43+
const defaultCaCertificates = NodeTls.getCACertificates("default");
44+
const defaultDispatcher = Undici.getGlobalDispatcher();
45+
46+
beforeAll(async () => {
47+
NodeTls.setDefaultCACertificates([...defaultCaCertificates, TEST_CERT]);
48+
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
49+
origin = `https://127.0.0.1:${(server.address() as NodeNet.AddressInfo).port}/`;
50+
});
51+
52+
afterEach(() => {
53+
Undici.setGlobalDispatcher(defaultDispatcher);
54+
});
55+
56+
afterAll(async () => {
57+
NodeTls.setDefaultCACertificates(defaultCaCertificates);
58+
await new Promise<void>((resolve) => server.close(() => resolve()));
59+
});
60+
61+
const versionViaGlobalDispatcher = async () => (await Undici.request(origin)).body.text();
62+
63+
const versionViaEffectFetch = () =>
64+
HttpClient.get(origin).pipe(
65+
Effect.flatMap((response) => response.text),
66+
Effect.provide(FetchHttpClient.layer),
67+
);
68+
69+
describe("installHttp1FetchDispatcher", () => {
70+
it("makes the global dispatcher negotiate HTTP/1.1 with an h2-capable origin", async () => {
71+
// undici 8's default agent, the one Node 26's fetch uses.
72+
Undici.setGlobalDispatcher(new Undici.Agent());
73+
expect(await versionViaGlobalDispatcher()).toBe("2.0");
74+
75+
installHttp1FetchDispatcher();
76+
77+
expect(await versionViaGlobalDispatcher()).toBe("1.1");
78+
});
79+
80+
it("keeps the environment proxy agent Node installs for --use-env-proxy", async () => {
81+
Undici.setGlobalDispatcher(new Undici.EnvHttpProxyAgent());
82+
83+
installHttp1FetchDispatcher();
84+
85+
expect(Undici.getGlobalDispatcher()).toBeInstanceOf(Undici.EnvHttpProxyAgent);
86+
expect(await versionViaGlobalDispatcher()).toBe("1.1");
87+
});
88+
89+
// Only a runtime that bundles undici 8 (Node 26+) offers h2 through the
90+
// built-in fetch, so only there can the server's own request path show it.
91+
it.effect.runIf(builtinFetchUsesHttp2(process.versions.undici))(
92+
"moves the built-in fetch behind Effect's FetchHttpClient off HTTP/2",
93+
() =>
94+
Effect.gen(function* () {
95+
expect(yield* versionViaEffectFetch()).toBe("2.0");
96+
97+
installHttp1FetchDispatcher();
98+
99+
expect(yield* versionViaEffectFetch()).toBe("1.1");
100+
}),
101+
);
102+
});

‎apps/server/src/outboundHttp.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import * as NodeModule from "node:module";
2+
3+
import type * as Undici from "undici";
4+
5+
// undici stays external to the CLI bundle (scripts/lib/cli-external-packages.ts).
6+
// Inside a Node single-executable only `require` can load it from disk.
7+
const requireUndici = NodeModule.createRequire(import.meta.url);
8+
9+
/**
10+
* True when the runtime's built-in `fetch` negotiates HTTP/2 by default.
11+
* Node 26 bundles undici 8, which offers h2 over ALPN to every HTTPS origin.
12+
* Node 22/24 (and Electron) bundle undici 6/7, whose fetch stays on HTTP/1.1.
13+
*/
14+
export const builtinFetchUsesHttp2 = (bundledUndiciVersion: string | undefined) =>
15+
Number.parseInt(bundledUndiciVersion ?? "", 10) >= 8;
16+
17+
/**
18+
* Replaces the process-wide fetch dispatcher with one that only speaks HTTP/1.1.
19+
*
20+
* Node's built-in fetch reads its dispatcher from the
21+
* `Symbol.for("undici.globalDispatcher.1"/".2")` globals, and the npm package's
22+
* `setGlobalDispatcher` writes both. This covers requests using the default
23+
* fetch dispatcher, including Effect's `FetchHttpClient`; `node:http` callers
24+
* (e.g. `cli/sshHelper.ts`) are unaffected and already speak HTTP/1.1.
25+
*
26+
* Node's `--use-env-proxy` / `NODE_USE_ENV_PROXY` installs an
27+
* `EnvHttpProxyAgent` at startup; that choice is kept so proxies still apply.
28+
*/
29+
export function installHttp1FetchDispatcher(): void {
30+
const undici = requireUndici("undici") as typeof Undici;
31+
const options = { allowH2: false };
32+
const usesEnvProxy = undici.getGlobalDispatcher().constructor.name === "EnvHttpProxyAgent";
33+
undici.setGlobalDispatcher(
34+
usesEnvProxy ? new undici.EnvHttpProxyAgent(options) : new undici.Agent(options),
35+
);
36+
}
37+
38+
/**
39+
* Keeps outbound fetch on HTTP/1.1. An undici HTTP/2 session that hits its
40+
* idle timeout can emit `'error'` on a stream with no listener, which Node
41+
* turns into an uncaught exception that exits the server
42+
* (https://github.com/nodejs/undici/issues/5936). Runtimes whose fetch never
43+
* negotiates h2 are left untouched.
44+
*/
45+
export function keepOutboundFetchOnHttp1(): void {
46+
if (builtinFetchUsesHttp2(process.versions.undici)) installHttp1FetchDispatcher();
47+
}

‎pnpm-lock.yaml‎

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎scripts/lib/cli-external-packages.test.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,14 @@ describe("selectCliRuntimeExternalDependencies", () => {
8383
it("selects every external root declared by the server", () => {
8484
assert.deepStrictEqual(
8585
Object.keys(selectCliRuntimeExternalDependencies(serverPackageJson.dependencies)).sort(),
86-
["@cursor/sdk", "@ff-labs/fff-node", "@napi-rs/keyring", "node-pty", "playwright-core"],
86+
[
87+
"@cursor/sdk",
88+
"@ff-labs/fff-node",
89+
"@napi-rs/keyring",
90+
"node-pty",
91+
"playwright-core",
92+
"undici",
93+
],
8794
);
8895
});
8996
});

0 commit comments

Comments
 (0)