Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { it } from "@effect/vitest";
5import * as FileSystem from "effect/FileSystem";
6import * as Schema from "effect/Schema";
7import * as Effect from "effect/Effect";
8import { vi } from "vite-plus/test";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10
11import { readBootstrapEnvelope } from "./bootstrap.ts";
12import { assertNone, assertSome } from "@effect/vitest/utils";
13
14const openSyncInterceptor = vi.hoisted(() => ({
15 failPath: null as string | null,
16 errorCode: "ENXIO",
17}));
18const fstatSyncInterceptor = vi.hoisted(() => ({ failFd: null as number | null }));
19
20vi.mock("node:fs", async (importOriginal) => {
21 const actual = await importOriginal<typeof import("node:fs")>();
22 return {
23 ...actual,
24 openSync: (...args: Parameters<typeof actual.openSync>) => {
25 const [filePath, flags] = args;
26 if (
27 typeof filePath === "string" &&
28 filePath === openSyncInterceptor.failPath &&
29 flags === "r"
30 ) {
31 const error = new Error(`open failed with ${openSyncInterceptor.errorCode}`);
32 Object.assign(error, { code: openSyncInterceptor.errorCode });
33 throw error;
34 }
35 return (actual.openSync as (...a: typeof args) => number)(...args);
36 },
37 fstatSync: (...args: Parameters<typeof actual.fstatSync>) => {
38 if (args[0] === fstatSyncInterceptor.failFd) {
39 const error = new Error("permission denied");
40 Object.assign(error, { code: "EACCES" });
41 throw error;
42 }
43 return (actual.fstatSync as (...a: typeof args) => NodeFS.Stats)(...args);
44 },
45 };
46});
47
48const windowsHost = HostProcess.Platform.defaultValue() === "win32";
49const nullDevice = windowsHost ? "\\\\.\\NUL" : "/dev/null";
50const closeIfOpen = (fd: number) => {
51 try {
52 NodeFS.closeSync(fd);
53 } catch (error) {
54 if ((error as NodeJS.ErrnoException).code !== "EBADF") throw error;
55 }
56};
57
58// A successful Windows read streams the inherited fd with autoClose. POSIX
59// reopens the fd through /proc or /dev, so the test still owns the original.
60const openBootstrapInputFd = (filePath: string) =>
61 Effect.acquireRelease(
62 Effect.sync(() => NodeFS.openSync(filePath, "r")),
63 (fd) => (windowsHost ? Effect.void : Effect.sync(() => closeIfOpen(fd))),
64 );
65
66const TestEnvelopeSchema = Schema.Struct({ mode: Schema.String });
67const encodeTestEnvelopeSchema = Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema));
68
69it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
70 it.effect("reads a bootstrap envelope from a provided fd", () =>
71 Effect.gen(function* () {
72 const fs = yield* FileSystem.FileSystem;
73 const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
74
75 yield* fs.writeFileString(
76 filePath,
77 `${yield* encodeTestEnvelopeSchema({ mode: "desktop" })}\n`,
78 );
79
80 const fd = yield* openBootstrapInputFd(filePath);
81
82 const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
83 assertSome(payload, {
84 mode: "desktop",
85 });
86 }),
87 );
88
89 it.effect("falls back to reading the inherited fd when path duplication fails", () =>
90 Effect.gen(function* () {
91 const fs = yield* FileSystem.FileSystem;
92 const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
93
94 yield* fs.writeFileString(
95 filePath,
96 `${yield* encodeTestEnvelopeSchema({ mode: "desktop" })}\n`,
97 );
98
99 // Open without acquireRelease: the direct-stream fallback uses autoClose: true,
100 // so the stream owns the fd lifecycle and closes it asynchronously on end.
101 // Attempting to also close it synchronously in a finalizer races with the
102 // stream's async close and produces an uncaught EBADF.
103 const fd = NodeFS.openSync(filePath, "r");
104
105 openSyncInterceptor.failPath = `/proc/self/fd/${fd}`;
106 try {
107 const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
108 timeoutMs: 100,
109 }).pipe(Effect.provideService(HostProcess.Platform, "linux"));
110 assertSome(payload, {
111 mode: "desktop",
112 });
113 } finally {
114 openSyncInterceptor.failPath = null;
115 }
116 }),
117 );
118
119 it.effect("returns none when the fd is unavailable", () =>
120 Effect.gen(function* () {
121 const fd = NodeFS.openSync(nullDevice, "r");
122 NodeFS.closeSync(fd);
123
124 const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
125 assertNone(payload);
126 }),
127 );
128});