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

bootstrap.ts

180 lines4.8 KB

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