Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NFS from "node:fs";
3import * as Net from "node:net";
4import * as readline from "node:readline";
5import type { Readable } from "node:stream";
6
7import * as Data from "effect/Data";
8import * as Effect from "effect/Effect";
9import * as Option from "effect/Option";
10import * as Predicate from "effect/Predicate";
11import * as Result from "effect/Result";
12import * as Schema from "effect/Schema";
13import { decodeJsonResult } from "@t3tools/shared/schemaJson";
14
15class BootstrapError extends Data.TaggedError("BootstrapError")<{
16 readonly message: string;
17 readonly cause?: unknown;
18}> {}
19
20export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function* <A, I>(
21 schema: Schema.Codec<A, I>,
22 fd: number,
23 options?: {
24 timeoutMs?: number;
25 },
26): Effect.fn.Return<Option.Option<A>, BootstrapError> {
27 const fdReady = yield* isFdReady(fd);
28 if (!fdReady) return Option.none();
29
30 const stream = yield* makeBootstrapInputStream(fd);
31
32 const timeoutMs = options?.timeoutMs ?? 1000;
33
34 return yield* Effect.callback<Option.Option<A>, BootstrapError>((resume) => {
35 const input = readline.createInterface({
36 input: stream,
37 crlfDelay: Infinity,
38 });
39
40 const cleanup = () => {
41 stream.removeListener("error", handleError);
42 input.removeListener("line", handleLine);
43 input.removeListener("close", handleClose);
44 input.close();
45 stream.destroy();
46 };
47
48 const handleError = (error: Error) => {
49 if (isUnavailableBootstrapFdError(error)) {
50 resume(Effect.succeedNone);
51 return;
52 }
53 resume(
54 Effect.fail(
55 new BootstrapError({
56 message: "Failed to read bootstrap envelope.",
57 cause: error,
58 }),
59 ),
60 );
61 };
62
63 const handleLine = (line: string) => {
64 const parsed = decodeJsonResult(schema)(line);
65 if (Result.isSuccess(parsed)) {
66 resume(Effect.succeedSome(parsed.success));
67 } else {
68 resume(
69 Effect.fail(
70 new BootstrapError({
71 message: "Failed to decode bootstrap envelope.",
72 cause: parsed.failure,
73 }),
74 ),
75 );
76 }
77 };
78
79 const handleClose = () => {
80 resume(Effect.succeedNone);
81 };
82
83 stream.once("error", handleError);
84 input.once("line", handleLine);
85 input.once("close", handleClose);
86
87 return Effect.sync(cleanup);
88 }).pipe(Effect.timeoutOption(timeoutMs), Effect.map(Option.flatten));
89});
90
91const isUnavailableBootstrapFdError = Predicate.compose(
92 Predicate.hasProperty("code"),
93 (_) => _.code === "EBADF" || _.code === "ENOENT",
94);
95
96const isFdReady = (fd: number) =>
97 Effect.try({
98 try: () => NFS.fstatSync(fd),
99 catch: (error) =>
100 new BootstrapError({
101 message: "Failed to stat bootstrap fd.",
102 cause: error,
103 }),
104 }).pipe(
105 Effect.as(true),
106 Effect.catchIf(
107 (error) => isUnavailableBootstrapFdError(error.cause),
108 () => Effect.succeed(false),
109 ),
110 );
111
112const makeBootstrapInputStream = (fd: number) =>
113 Effect.try<Readable, BootstrapError>({
114 try: () => {
115 const fdPath = resolveFdPath(fd);
116 if (fdPath === undefined) {
117 return makeDirectBootstrapStream(fd);
118 }
119
120 let streamFd: number | undefined;
121 try {
122 streamFd = NFS.openSync(fdPath, "r");
123 return NFS.createReadStream("", {
124 fd: streamFd,
125 encoding: "utf8",
126 autoClose: true,
127 });
128 } catch (error) {
129 if (isBootstrapFdPathDuplicationError(error)) {
130 if (streamFd !== undefined) {
131 NFS.closeSync(streamFd);
132 }
133 return makeDirectBootstrapStream(fd);
134 }
135 throw error;
136 }
137 },
138 catch: (error) =>
139 new BootstrapError({
140 message: "Failed to duplicate bootstrap fd.",
141 cause: error,
142 }),
143 });
144
145const makeDirectBootstrapStream = (fd: number): Readable => {
146 try {
147 return NFS.createReadStream("", {
148 fd,
149 encoding: "utf8",
150 autoClose: true,
151 });
152 } catch {
153 const stream = new Net.Socket({
154 fd,
155 readable: true,
156 writable: false,
157 });
158 stream.setEncoding("utf8");
159 return stream;
160 }
161};
162
163const isBootstrapFdPathDuplicationError = Predicate.compose(
164 Predicate.hasProperty("code"),
165 (_) => _.code === "ENXIO" || _.code === "EINVAL" || _.code === "EPERM",
166);
167
168export function resolveFdPath(
169 fd: number,
170 platform: NodeJS.Platform = process.platform,
171): string | undefined {
172 if (platform === "linux") {
173 return `/proc/self/fd/${fd}`;
174 }
175 if (platform === "win32") {
176 return undefined;
177 }
178 return `/dev/fd/${fd}`;
179}