Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - the test runs a real TLS h2 server to see which protocol fetch negotiates.
2import * as NodeHttp2 from "node:http2";
3import * as NodeNet from "node:net";
4import * as NodeTls from "node:tls";
5
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import { it } from "@effect/vitest";
8import * as Effect from "effect/Effect";
9import * as Stream from "effect/Stream";
10import { ChildProcess, ChildProcessSpawner } from "effect/process";
11import { FetchHttpClient, HttpClient } from "effect/http";
12import * as Undici from "undici";
13import { afterAll, afterEach, beforeAll, describe, expect } from "vite-plus/test";
14
15import {
16 builtinFetchUsesHttp2,
17 ignoreMacosTypeOfServiceEinval,
18 installHttp1FetchDispatcher,
19} from "./outboundHttp.ts";
20
21// Test-only self-signed P-256 certificate for 127.0.0.1, valid until 2126; not a
22// secret. Node cannot mint X.509 certificates without a library, and a local
23// server only offers h2 over ALPN, which needs TLS.
24const TEST_KEY = `-----BEGIN PRIVATE KEY-----
25MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg3EwCztQysKTvzdcR
26g0LWq+axzUd4tHi9PyMdqh7PlGShRANCAARfQpoLgv/tOsHWCLriDza7Ruaey2b7
27mR/nS6mLu6W7+agkEqDm0mE3F/ngpPjL4Jj0IGadeMcKNKFRSBgiLdfn
28-----END PRIVATE KEY-----
29`;
30const TEST_CERT = `-----BEGIN CERTIFICATE-----
31MIIBsDCCAVagAwIBAgIUWbn2Wt5kTxii1UU57NJMt/wTaUgwCgYIKoZIzj0EAwIw
32JDEiMCAGA1UEAwwZdDNjb2RlIG91dGJvdW5kIGh0dHAgdGVzdDAgFw0yNjEwMTEy
33MjQyMzZaGA8yMTI2MDkxNzIyNDIzNlowJDEiMCAGA1UEAwwZdDNjb2RlIG91dGJv
34dW5kIGh0dHAgdGVzdDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABF9CmguC/+06
35wdYIuuIPNrtG5p7LZvuZH+dLqYu7pbv5qCQSoObSYTcX+eCk+MvgmPQgZp14xwo0
36oVFIGCIt1+ejZDBiMB0GA1UdDgQWBBSsekAc30Q/zdIE/tvVDQKJL5oiCDAfBgNV
37HSMEGDAWgBSsekAc30Q/zdIE/tvVDQKJL5oiCDAPBgNVHRMBAf8EBTADAQH/MA8G
38A1UdEQQIMAaHBH8AAAEwCgYIKoZIzj0EAwIDSAAwRQIgebUrkyP56242EJB7nCV7
39A+Ke/q0rNPya3fjQa9O5B+kCIQC1SfmdNaFcNJ4JINlus4FfrRnfKiADS2MIJR9f
4099BN0A==
41-----END CERTIFICATE-----
42`;
43
44const server = NodeHttp2.createSecureServer(
45 { allowHTTP1: true, key: TEST_KEY, cert: TEST_CERT },
46 (request, response) => response.end(request.httpVersion),
47);
48let origin = "";
49const defaultCaCertificates = NodeTls.getCACertificates("default");
50const defaultDispatcher = Undici.getGlobalDispatcher();
51const defaultAttemptTimeout = NodeNet.getDefaultAutoSelectFamilyAttemptTimeout();
52
53beforeAll(async () => {
54 NodeTls.setDefaultCACertificates([...defaultCaCertificates, TEST_CERT]);
55 await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
56 origin = `https://127.0.0.1:${(server.address() as NodeNet.AddressInfo).port}/`;
57});
58
59afterEach(() => {
60 Undici.setGlobalDispatcher(defaultDispatcher);
61 NodeNet.setDefaultAutoSelectFamilyAttemptTimeout(defaultAttemptTimeout);
62});
63
64afterAll(async () => {
65 NodeTls.setDefaultCACertificates(defaultCaCertificates);
66 await new Promise<void>((resolve) => server.close(() => resolve()));
67});
68
69const versionViaGlobalDispatcher = async () => (await Undici.request(origin)).body.text();
70
71const versionViaBuiltinFetch = () =>
72 HttpClient.get(origin).pipe(
73 Effect.flatMap((response) => response.text),
74 Effect.provide(FetchHttpClient.layer),
75 );
76
77describe("installHttp1FetchDispatcher", () => {
78 it("makes the global dispatcher negotiate HTTP/1.1 and keeps the env proxy agent", async () => {
79 Undici.setGlobalDispatcher(new Undici.Agent());
80 expect(await versionViaGlobalDispatcher()).toBe("2.0");
81
82 installHttp1FetchDispatcher();
83 expect(await versionViaGlobalDispatcher()).toBe("1.1");
84
85 Undici.setGlobalDispatcher(new Undici.EnvHttpProxyAgent());
86 installHttp1FetchDispatcher();
87 expect(Undici.getGlobalDispatcher()).toBeInstanceOf(Undici.EnvHttpProxyAgent);
88 });
89
90 // Only a runtime that bundles undici 8 (Node 26+) offers h2 through the
91 // built-in fetch, so only there can this prove fetch reads the new dispatcher.
92 it.effect.runIf(builtinFetchUsesHttp2(process.versions.undici))(
93 "moves the built-in fetch off HTTP/2",
94 () =>
95 Effect.gen(function* () {
96 expect(yield* versionViaBuiltinFetch()).toBe("2.0");
97 installHttp1FetchDispatcher();
98 expect(yield* versionViaBuiltinFetch()).toBe("1.1");
99 }),
100 );
101});
102
103const runNode = Effect.fnUntraced(function* (args: Array<string>) {
104 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
105 const child = yield* spawner.spawn(ChildProcess.make(process.execPath, args));
106 return yield* Effect.all(
107 {
108 stdout: child.stdout.pipe(Stream.decodeText(), Stream.mkString),
109 stderr: child.stderr.pipe(Stream.decodeText(), Stream.mkString),
110 exitCode: child.exitCode.pipe(Effect.map(Number)),
111 },
112 { concurrency: "unbounded" },
113 );
114}, Effect.scoped);
115
116describe("ignoreMacosTypeOfServiceEinval", () => {
117 const errnoError = (code: string) =>
118 Object.assign(new Error(`setTypeOfService ${code}`), { code, syscall: "setTypeOfService" });
119
120 it("swallows only an Error with code EINVAL on macOS", () => {
121 let error: unknown = errnoError("EINVAL");
122 const prototype = {
123 setTypeOfService(this: NodeNet.Socket, _typeOfService: number): NodeNet.Socket {
124 throw error;
125 },
126 };
127 ignoreMacosTypeOfServiceEinval("darwin", prototype);
128
129 const socket = new NodeNet.Socket();
130 expect(prototype.setTypeOfService.call(socket, 0)).toBe(socket);
131
132 error = errnoError("EPERM");
133 expect(() => prototype.setTypeOfService.call(socket, 0)).toThrow(error);
134
135 error = { code: "EINVAL" };
136 expect(() => prototype.setTypeOfService.call(socket, 0)).toThrow();
137 });
138
139 // Bundled undici 7 calls this API from a socket callback. Keep the real fetch
140 // in a child so an escaped EINVAL exits that process instead of breaking Vitest.
141 it.effect.runIf(
142 typeof (NodeNet.Socket.prototype as { setTypeOfService?: unknown }).setTypeOfService ===
143 "function" && process.versions.undici?.startsWith("7.") === true,
144 )("keeps built-in fetch working when setTypeOfService throws EINVAL", () =>
145 Effect.gen(function* () {
146 const child = yield* runNode([
147 "--input-type=module",
148 "--eval",
149 `
150import * as NodeNet from "node:net";
151import * as NodeTls from "node:tls";
152import { ignoreMacosTypeOfServiceEinval } from ${JSON.stringify(new URL("./outboundHttp.ts", import.meta.url).href)};
153
154NodeTls.setDefaultCACertificates([${JSON.stringify(TEST_CERT)}]);
155let calls = 0;
156NodeNet.Socket.prototype.setTypeOfService = () => {
157 calls++;
158 throw Object.assign(new Error("setTypeOfService EINVAL"), { code: "EINVAL" });
159};
160ignoreMacosTypeOfServiceEinval("darwin");
161console.log(await (await fetch(${JSON.stringify(origin)})).text());
162if (calls === 0) throw new Error("fetch did not call setTypeOfService");
163`,
164 ]);
165 expect(child.exitCode, child.stderr).toBe(0);
166 expect(child.stdout.trim()).toBe("1.1");
167 }).pipe(Effect.provide(NodeServices.layer)),
168 );
169});