Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodePath from "node:path";
4import * as NodeChildProcess from "node:child_process";
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import { assert, it } from "@effect/vitest";
7import * as FileSystem from "effect/FileSystem";
8import * as Schema from "effect/Schema";
9import * as Duration from "effect/Duration";
10import * as Effect from "effect/Effect";
11import * as Fiber from "effect/Fiber";
12import * as TestClock from "effect/testing/TestClock";
13import { vi } from "vite-plus/test";
14import { HostProcessPlatform } from "@v12/shared/hostProcess";
15
16import {
17 BootstrapEnvelopeDecodeError,
18 BootstrapFdStatError,
19 BootstrapInputStreamOpenError,
20 readBootstrapEnvelope,
21} from "./bootstrap.ts";
22import { assertNone, assertSome } from "@effect/vitest/utils";
23
24const openSyncInterceptor = vi.hoisted(() => ({
25 failPath: null as string | null,
26 errorCode: "ENXIO",
27}));
28const fstatSyncInterceptor = vi.hoisted(() => ({ failFd: null as number | null }));
29
30vi.mock("node:fs", async (importOriginal) => {
31 const actual = await importOriginal<typeof import("node:fs")>();
32 return {
33 ...actual,
34 openSync: (...args: Parameters<typeof actual.openSync>) => {
35 const [filePath, flags] = args;
36 if (
37 typeof filePath === "string" &&
38 filePath === openSyncInterceptor.failPath &&
39 flags === "r"
40 ) {
41 const error = new Error(`open failed with ${openSyncInterceptor.errorCode}`);
42 Object.assign(error, { code: openSyncInterceptor.errorCode });
43 throw error;
44 }
45 return (actual.openSync as (...a: typeof args) => number)(...args);
46 },
47 fstatSync: (...args: Parameters<typeof actual.fstatSync>) => {
48 if (args[0] === fstatSyncInterceptor.failFd) {
49 const error = new Error("permission denied");
50 Object.assign(error, { code: "EACCES" });
51 throw error;
52 }
53 return (actual.fstatSync as (...a: typeof args) => NodeFS.Stats)(...args);
54 },
55 };
56});
57
58const TestEnvelopeSchema = Schema.Struct({ mode: Schema.String });
59const encodeTestEnvelopeSchema = Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema));
60
61it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
62 it.effect("reads a bootstrap envelope from a provided fd", () =>
63 Effect.gen(function* () {
64 const fs = yield* FileSystem.FileSystem;
65 const filePath = yield* fs.makeTempFileScoped({
66 prefix: "v12-bootstrap-",
67 suffix: ".ndjson",
68 });
69
70 yield* fs.writeFileString(
71 filePath,
72 `${yield* encodeTestEnvelopeSchema({ mode: "desktop" })}\n`,
73 );
74
75 const fd = yield* Effect.acquireRelease(
76 Effect.sync(() => NodeFS.openSync(filePath, "r")),
77 (fd) => Effect.sync(() => NodeFS.closeSync(fd)),
78 );
79
80 const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
81 assertSome(payload, {
82 mode: "desktop",
83 });
84 }),
85 );
86
87 it.effect("falls back to reading the inherited fd when path duplication fails", () =>
88 Effect.gen(function* () {
89 const fs = yield* FileSystem.FileSystem;
90 const filePath = yield* fs.makeTempFileScoped({
91 prefix: "v12-bootstrap-",
92 suffix: ".ndjson",
93 });
94
95 yield* fs.writeFileString(
96 filePath,
97 `${yield* encodeTestEnvelopeSchema({ mode: "desktop" })}\n`,
98 );
99
100 // Open without acquireRelease: the direct-stream fallback uses autoClose: true,
101 // so the stream owns the fd lifecycle and closes it asynchronously on end.
102 // Attempting to also close it synchronously in a finalizer races with the
103 // stream's async close and produces an uncaught EBADF.
104 const fd = NodeFS.openSync(filePath, "r");
105
106 openSyncInterceptor.failPath = `/proc/self/fd/${fd}`;
107 try {
108 const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
109 timeoutMs: 100,
110 }).pipe(Effect.provideService(HostProcessPlatform, "linux"));
111 assertSome(payload, {
112 mode: "desktop",
113 });
114 } finally {
115 openSyncInterceptor.failPath = null;
116 }
117 }),
118 );
119
120 it.effect("preserves fd path, platform, and cause when opening the input stream fails", () =>
121 Effect.gen(function* () {
122 const fs = yield* FileSystem.FileSystem;
123 const filePath = yield* fs.makeTempFileScoped({
124 prefix: "v12-bootstrap-",
125 suffix: ".ndjson",
126 });
127 const fd = yield* Effect.acquireRelease(
128 Effect.sync(() => NodeFS.openSync(filePath, "r")),
129 (fd) => Effect.sync(() => NodeFS.closeSync(fd)),
130 );
131 const fdPath = `/proc/self/fd/${fd}`;
132
133 openSyncInterceptor.failPath = fdPath;
134 openSyncInterceptor.errorCode = "EIO";
135 try {
136 const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
137 timeoutMs: 100,
138 }).pipe(Effect.provideService(HostProcessPlatform, "linux"), Effect.flip);
139
140 assert.instanceOf(error, BootstrapInputStreamOpenError);
141 assert.equal(error.fd, fd);
142 assert.equal(error.platform, "linux");
143 assert.equal(error.fdPath, fdPath);
144 assert.equal((error.cause as NodeJS.ErrnoException).code, "EIO");
145 assert.equal(
146 error.message,
147 `Failed to open bootstrap input stream for file descriptor ${fd} via '${fdPath}' on 'linux'.`,
148 );
149 } finally {
150 openSyncInterceptor.failPath = null;
151 openSyncInterceptor.errorCode = "ENXIO";
152 }
153 }),
154 );
155
156 it.effect("returns none when the fd is unavailable", () =>
157 Effect.gen(function* () {
158 const fd = NodeFS.openSync("/dev/null", "r");
159 NodeFS.closeSync(fd);
160
161 const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
162 assertNone(payload);
163 }),
164 );
165
166 it.effect("preserves fd and cause when stat fails for a non-availability reason", () =>
167 Effect.gen(function* () {
168 const fd = yield* Effect.acquireRelease(
169 Effect.sync(() => NodeFS.openSync("/dev/null", "r")),
170 (fd) => Effect.sync(() => NodeFS.closeSync(fd)),
171 );
172
173 fstatSyncInterceptor.failFd = fd;
174 try {
175 const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
176 timeoutMs: 100,
177 }).pipe(Effect.flip);
178
179 assert.instanceOf(error, BootstrapFdStatError);
180 assert.equal(error.fd, fd);
181 assert.equal((error.cause as NodeJS.ErrnoException).code, "EACCES");
182 assert.equal(error.message, `Failed to stat bootstrap file descriptor ${fd}.`);
183 } finally {
184 fstatSyncInterceptor.failFd = null;
185 }
186 }),
187 );
188
189 it.effect("preserves fd and schema cause when decoding the envelope fails", () =>
190 Effect.gen(function* () {
191 const fs = yield* FileSystem.FileSystem;
192 const filePath = yield* fs.makeTempFileScoped({
193 prefix: "v12-bootstrap-",
194 suffix: ".ndjson",
195 });
196 yield* fs.writeFileString(filePath, '{"mode":42}\n');
197
198 const fd = yield* Effect.acquireRelease(
199 Effect.sync(() => NodeFS.openSync(filePath, "r")),
200 (fd) => Effect.sync(() => NodeFS.closeSync(fd)),
201 );
202 const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
203 timeoutMs: 100,
204 }).pipe(Effect.flip);
205
206 assert.instanceOf(error, BootstrapEnvelopeDecodeError);
207 assert.equal(error.fd, fd);
208 assert.isDefined(error.cause);
209 assert.equal(
210 error.message,
211 `Failed to decode bootstrap envelope from file descriptor ${fd}.`,
212 );
213 }),
214 );
215
216 it.effect("returns none when the bootstrap read times out before any value arrives", () =>
217 Effect.gen(function* () {
218 const fs = yield* FileSystem.FileSystem;
219 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "v12-bootstrap-" });
220 const fifoPath = NodePath.join(tempDir, "bootstrap.pipe");
221
222 yield* Effect.sync(() => NodeChildProcess.execFileSync("mkfifo", [fifoPath]));
223
224 const _writer = yield* Effect.acquireRelease(
225 Effect.sync(() =>
226 NodeChildProcess.spawn("sh", ["-c", 'exec 3>"$1"; sleep 60', "sh", fifoPath], {
227 stdio: ["ignore", "ignore", "ignore"],
228 }),
229 ),
230 (writer) =>
231 Effect.sync(() => {
232 writer.kill("SIGKILL");
233 }),
234 );
235
236 const fd = yield* Effect.acquireRelease(
237 Effect.sync(() => NodeFS.openSync(fifoPath, "r")),
238 (fd) => Effect.sync(() => NodeFS.closeSync(fd)),
239 );
240
241 const fiber = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
242 timeoutMs: 100,
243 }).pipe(Effect.forkScoped);
244
245 yield* Effect.yieldNow;
246 yield* TestClock.adjust(Duration.millis(100));
247
248 const payload = yield* Fiber.join(fiber);
249 assertNone(payload);
250 }).pipe(Effect.provide(TestClock.layer())),
251 );
252});