Repository navigation
Expand file tree
/
Copy pathbootstrap.ts
More file actions
241 lines (218 loc) · 6.48 KB
/
Copy pathbootstrap.ts
File metadata and controls
241 lines (218 loc) · 6.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodeNet from "node:net";
import * as NodeReadline from "node:readline";
import type * as NodeStream from "node:stream";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Predicate from "effect/Predicate";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import * as HostProcess from "@t3tools/shared/HostProcess";
export class BootstrapFdStatError extends Schema.TaggedError<BootstrapFdStatError>()(
"BootstrapFdStatError",
{
fd: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to stat bootstrap file descriptor ${this.fd}.`;
}
}
export class BootstrapInputStreamOpenError extends Schema.TaggedError<BootstrapInputStreamOpenError>()(
"BootstrapInputStreamOpenError",
{
fd: Schema.Number,
platform: Schema.String,
fdPath: Schema.optional(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
const path = this.fdPath === undefined ? "" : ` via '${this.fdPath}'`;
return `Failed to open bootstrap input stream for file descriptor ${this.fd}${path} on '${this.platform}'.`;
}
}
export class BootstrapEnvelopeReadError extends Schema.TaggedError<BootstrapEnvelopeReadError>()(
"BootstrapEnvelopeReadError",
{
fd: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read bootstrap envelope from file descriptor ${this.fd}.`;
}
}
export class BootstrapEnvelopeDecodeError extends Schema.TaggedError<BootstrapEnvelopeDecodeError>()(
"BootstrapEnvelopeDecodeError",
{
fd: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to decode bootstrap envelope from file descriptor ${this.fd}.`;
}
}
export const BootstrapError = Schema.Union([
BootstrapFdStatError,
BootstrapInputStreamOpenError,
BootstrapEnvelopeReadError,
BootstrapEnvelopeDecodeError,
]);
export type BootstrapError = typeof BootstrapError.Type;
export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function* <A, I>(
schema: Schema.Codec<A, I>,
fd: number,
options?: {
timeoutMs?: number;
},
): Effect.fn.Return<Option.Option<A>, BootstrapError> {
const fdReady = yield* isFdReady(fd);
if (!fdReady) return Option.none();
const stream = yield* makeBootstrapInputStream(fd);
const timeoutMs = options?.timeoutMs ?? 1000;
return yield* Effect.callback<
Option.Option<A>,
BootstrapEnvelopeReadError | BootstrapEnvelopeDecodeError
>((resume) => {
const input = NodeReadline.createInterface({
input: stream,
crlfDelay: Infinity,
});
const cleanup = () => {
stream.removeListener("error", handleError);
input.removeListener("line", handleLine);
input.removeListener("close", handleClose);
input.close();
stream.destroy();
};
const handleError = (error: Error) => {
if (isUnavailableBootstrapFdError(error)) {
resume(Effect.succeedNone);
return;
}
resume(
Effect.fail(
new BootstrapEnvelopeReadError({
fd,
cause: error,
}),
),
);
};
const handleLine = (line: string) => {
const parsed = decodeJsonResult(schema)(line);
if (Result.isSuccess(parsed)) {
resume(Effect.succeedSome(parsed.success));
} else {
resume(
Effect.fail(
new BootstrapEnvelopeDecodeError({
fd,
cause: parsed.failure,
}),
),
);
}
};
const handleClose = () => {
resume(Effect.succeedNone);
};
stream.once("error", handleError);
input.once("line", handleLine);
input.once("close", handleClose);
return Effect.sync(cleanup);
}).pipe(Effect.timeoutOption(timeoutMs), Effect.map(Option.flatten));
});
const isUnavailableBootstrapFdError = Predicate.compose(
Predicate.hasProperty("code"),
(_) => _.code === "EBADF" || _.code === "ENOENT",
);
const isFdReady = (fd: number) =>
Effect.try({
try: () => NodeFS.fstatSync(fd),
catch: (error) =>
new BootstrapFdStatError({
fd,
cause: error,
}),
}).pipe(
Effect.as(true),
Effect.catchTags({
BootstrapFdStatError: (error) =>
isUnavailableBootstrapFdError(error.cause) ? Effect.succeed(false) : Effect.fail(error),
}),
);
const makeBootstrapInputStream = Effect.fn("bootstrap.makeBootstrapInputStream")(function* (
fd: number,
) {
const platform = yield* HostProcess.Platform;
const fdPath = resolveFdPath(fd, platform);
return yield* Effect.try<NodeStream.Readable, BootstrapInputStreamOpenError>({
try: () => {
if (fdPath === undefined) {
return makeDirectBootstrapStream(fd);
}
let streamFd: number | undefined;
try {
streamFd = NodeFS.openSync(fdPath, "r");
return NodeFS.createReadStream("", {
fd: streamFd,
encoding: "utf8",
autoClose: true,
});
} catch (error) {
if (isBootstrapFdPathDuplicationError(error)) {
if (streamFd !== undefined) {
NodeFS.closeSync(streamFd);
}
return makeDirectBootstrapStream(fd);
}
throw error;
}
},
catch: (error) =>
new BootstrapInputStreamOpenError({
fd,
platform,
...(fdPath === undefined ? {} : { fdPath }),
cause: error,
}),
});
});
const makeDirectBootstrapStream = (fd: number): NodeStream.Readable => {
try {
return NodeFS.createReadStream("", {
fd,
encoding: "utf8",
autoClose: true,
});
} catch {
const stream = new NodeNet.Socket({
fd,
readable: true,
writable: false,
});
stream.setEncoding("utf8");
return stream;
}
};
// WSL-inherited stdin pipes cannot be reopened via /proc/self/fd/0 (EACCES),
// so they must be read directly.
const isBootstrapFdPathDuplicationError = Predicate.compose(
Predicate.hasProperty("code"),
(_) => _.code === "ENXIO" || _.code === "EINVAL" || _.code === "EPERM" || _.code === "EACCES",
);
function resolveFdPath(fd: number, platform: NodeJS.Platform): string | undefined {
if (platform === "linux") {
return `/proc/self/fd/${fd}`;
}
if (platform === "win32") {
return undefined;
}
return `/dev/fd/${fd}`;
}