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