Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

bootstrap.test.ts

240 lines8.6 KB

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 "@t3tools/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({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
66​
67 yield* fs.writeFileString(
68 filePath,
69 `${yield* encodeTestEnvelopeSchema({ mode: "desktop" })}\n`,
70 );
71​
72 const fd = yield* Effect.acquireRelease(
73 Effect.sync(() => NodeFS.openSync(filePath, "r")),
74 (fd) => Effect.sync(() => NodeFS.closeSync(fd)),
75 );
76​
77 const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
78 assertSome(payload, {
79 mode: "desktop",
80 });
81 }),
82 );
83​
84 it.effect("falls back to reading the inherited fd when path duplication fails", () =>
85 Effect.gen(function* () {
86 const fs = yield* FileSystem.FileSystem;
87 const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
88​
89 yield* fs.writeFileString(
90 filePath,
91 `${yield* encodeTestEnvelopeSchema({ mode: "desktop" })}\n`,
92 );
93​
94 // Open without acquireRelease: the direct-stream fallback uses autoClose: true,
95 // so the stream owns the fd lifecycle and closes it asynchronously on end.
96 // Attempting to also close it synchronously in a finalizer races with the
97 // stream's async close and produces an uncaught EBADF.
98 const fd = NodeFS.openSync(filePath, "r");
99​
100 openSyncInterceptor.failPath = `/proc/self/fd/${fd}`;
101 try {
102 const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
103 timeoutMs: 100,
104 }).pipe(Effect.provideService(HostProcessPlatform, "linux"));
105 assertSome(payload, {
106 mode: "desktop",
107 });
108 } finally {
109 openSyncInterceptor.failPath = null;
110 }
111 }),
112 );
113​
114 it.effect("preserves fd path, platform, and cause when opening the input stream fails", () =>
115 Effect.gen(function* () {
116 const fs = yield* FileSystem.FileSystem;
117 const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
118 const fd = yield* Effect.acquireRelease(
119 Effect.sync(() => NodeFS.openSync(filePath, "r")),
120 (fd) => Effect.sync(() => NodeFS.closeSync(fd)),
121 );
122 const fdPath = `/proc/self/fd/${fd}`;
123​
124 openSyncInterceptor.failPath = fdPath;
125 openSyncInterceptor.errorCode = "EIO";
126 try {
127 const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
128 timeoutMs: 100,
129 }).pipe(Effect.provideService(HostProcessPlatform, "linux"), Effect.flip);
130​
131 assert.instanceOf(error, BootstrapInputStreamOpenError);
132 assert.equal(error.fd, fd);
133 assert.equal(error.platform, "linux");
134 assert.equal(error.fdPath, fdPath);
135 assert.equal((error.cause as NodeJS.ErrnoException).code, "EIO");
136 assert.equal(
137 error.message,
138 `Failed to open bootstrap input stream for file descriptor ${fd} via '${fdPath}' on 'linux'.`,
139 );
140 } finally {
141 openSyncInterceptor.failPath = null;
142 openSyncInterceptor.errorCode = "ENXIO";
143 }
144 }),
145 );
146​
147 it.effect("returns none when the fd is unavailable", () =>
148 Effect.gen(function* () {
149 const fd = NodeFS.openSync("/dev/null", "r");
150 NodeFS.closeSync(fd);
151​
152 const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
153 assertNone(payload);
154 }),
155 );
156​
157 it.effect("preserves fd and cause when stat fails for a non-availability reason", () =>
158 Effect.gen(function* () {
159 const fd = yield* Effect.acquireRelease(
160 Effect.sync(() => NodeFS.openSync("/dev/null", "r")),
161 (fd) => Effect.sync(() => NodeFS.closeSync(fd)),
162 );
163​
164 fstatSyncInterceptor.failFd = fd;
165 try {
166 const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
167 timeoutMs: 100,
168 }).pipe(Effect.flip);
169​
170 assert.instanceOf(error, BootstrapFdStatError);
171 assert.equal(error.fd, fd);
172 assert.equal((error.cause as NodeJS.ErrnoException).code, "EACCES");
173 assert.equal(error.message, `Failed to stat bootstrap file descriptor ${fd}.`);
174 } finally {
175 fstatSyncInterceptor.failFd = null;
176 }
177 }),
178 );
179​
180 it.effect("preserves fd and schema cause when decoding the envelope fails", () =>
181 Effect.gen(function* () {
182 const fs = yield* FileSystem.FileSystem;
183 const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
184 yield* fs.writeFileString(filePath, '{"mode":42}\n');
185​
186 const fd = yield* Effect.acquireRelease(
187 Effect.sync(() => NodeFS.openSync(filePath, "r")),
188 (fd) => Effect.sync(() => NodeFS.closeSync(fd)),
189 );
190 const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
191 timeoutMs: 100,
192 }).pipe(Effect.flip);
193​
194 assert.instanceOf(error, BootstrapEnvelopeDecodeError);
195 assert.equal(error.fd, fd);
196 assert.isDefined(error.cause);
197 assert.equal(
198 error.message,
199 `Failed to decode bootstrap envelope from file descriptor ${fd}.`,
200 );
201 }),
202 );
203​
204 it.effect("returns none when the bootstrap read times out before any value arrives", () =>
205 Effect.gen(function* () {
206 const fs = yield* FileSystem.FileSystem;
207 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bootstrap-" });
208 const fifoPath = NodePath.join(tempDir, "bootstrap.pipe");
209​
210 yield* Effect.sync(() => NodeChildProcess.execFileSync("mkfifo", [fifoPath]));
211​
212 const _writer = yield* Effect.acquireRelease(
213 Effect.sync(() =>
214 NodeChildProcess.spawn("sh", ["-c", 'exec 3>"$1"; sleep 60', "sh", fifoPath], {
215 stdio: ["ignore", "ignore", "ignore"],
216 }),
217 ),
218 (writer) =>
219 Effect.sync(() => {
220 writer.kill("SIGKILL");
221 }),
222 );
223​
224 const fd = yield* Effect.acquireRelease(
225 Effect.sync(() => NodeFS.openSync(fifoPath, "r")),
226 (fd) => Effect.sync(() => NodeFS.closeSync(fd)),
227 );
228​
229 const fiber = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
230 timeoutMs: 100,
231 }).pipe(Effect.forkScoped);
232​
233 yield* Effect.yieldNow;
234 yield* TestClock.adjust(Duration.millis(100));
235​
236 const payload = yield* Fiber.join(fiber);
237 assertNone(payload);
238 }).pipe(Effect.provide(TestClock.layer())),
239 );
240});