forked from coder/code-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.ts
More file actions
418 lines (360 loc) · 14.7 KB
/
helpers.ts
File metadata and controls
418 lines (360 loc) · 14.7 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/// <reference path="../../../../lib/vscode/src/typings/spdlog.d.ts" />
import { ChildProcess, SpawnOptions, ForkOptions } from "child_process";
import { EventEmitter } from "events";
import { Socket } from "net";
import { Duplex, Readable, Writable } from "stream";
import { IDisposable } from "@coder/disposable";
import { logger } from "@coder/logger";
// tslint:disable no-any
export type ForkProvider = (modulePath: string, args: string[], options: ForkOptions) => ChildProcess;
export interface Disposer extends IDisposable {
onDidDispose: (cb: () => void) => void;
}
interface ActiveEvalEmitter {
removeAllListeners(event?: string): void;
emit(event: string, ...args: any[]): void;
on(event: string, cb: (...args: any[]) => void): void;
}
/**
* Helper class for server-side evaluations.
*/
export class EvalHelper {
// For any non-external modules that are not built in, we need to require and
// access them here. A require on the client-side won't work since that code
// won't exist on the server (and bloat the client with an unused import), and
// we can't manually import on the server-side and then call
// `__webpack_require__` on the client-side because Webpack stores modules by
// their paths which would require us to hard-code the path. These aren't
// required immediately so we have a chance to unpack the .node files and set
// their locations.
public modules = {
spdlog: require("spdlog") as typeof import("spdlog"),
pty: require("node-pty-prebuilt") as typeof import("node-pty"),
};
/**
* Some spawn code tries to preserve the env (the debug adapter for instance)
* but the env is mostly blank (since we're in the browser), so we'll just
* always preserve the main process.env here, otherwise it won't have access
* to PATH, etc.
* TODO: An alternative solution would be to send the env to the browser?
*/
public preserveEnv(options: SpawnOptions | ForkOptions): void {
if (options && options.env) {
options.env = { ...process.env, ...options.env };
}
}
}
/**
* Helper class for client-side active evaluations.
*/
export class ActiveEvalHelper implements ActiveEvalEmitter {
public constructor(private readonly emitter: ActiveEvalEmitter) {}
public removeAllListeners(event?: string): void {
this.emitter.removeAllListeners(event);
}
public emit(event: string, ...args: any[]): void {
this.emitter.emit(event, ...args);
}
public on(event: string, cb: (...args: any[]) => void): void {
this.emitter.on(event, cb);
}
/**
* Create a new helper to make unique events for an item.
*/
public createUnique(id: number | "stdout" | "stderr" | "stdin"): ActiveEvalHelper {
return new ActiveEvalHelper(this.createUniqueEmitter(id));
}
/**
* Wrap the evaluation emitter to make unique events for an item to prevent
* conflicts when it shares that emitter with other items.
*/
protected createUniqueEmitter(id: number | "stdout" | "stderr" | "stdin"): ActiveEvalEmitter {
let events = <string[]>[];
return {
removeAllListeners: (event?: string): void => {
if (!event) {
events.forEach((e) => this.removeAllListeners(e));
events = [];
} else {
const index = events.indexOf(event);
if (index !== -1) {
events.splice(index, 1);
this.removeAllListeners(`${event}:${id}`);
}
}
},
emit: (event: string, ...args: any[]): void => {
this.emit(`${event}:${id}`, ...args);
},
on: (event: string, cb: (...args: any[]) => void): void => {
if (!events.includes(event)) {
events.push(event);
}
this.on(`${event}:${id}`, cb);
},
};
}
}
/**
* Helper class for server-side active evaluations.
*/
export class ServerActiveEvalHelper extends ActiveEvalHelper implements EvalHelper {
private readonly evalHelper = new EvalHelper();
public modules = this.evalHelper.modules;
public constructor(emitter: ActiveEvalEmitter, public readonly fork: ForkProvider) {
super(emitter);
}
public preserveEnv(options: SpawnOptions | ForkOptions): void {
this.evalHelper.preserveEnv(options);
}
/**
* If there is a callback ID, return a function that emits the callback event
* on the active evaluation with that ID and all arguments passed to it.
* Otherwise, return undefined.
*/
public maybeCallback(callbackId?: number): ((...args: any[]) => void) | undefined {
return typeof callbackId !== "undefined" ? (...args: any[]): void => {
this.emit("callback", callbackId, ...args);
} : undefined;
}
/**
* Bind a socket to an active evaluation and returns a disposer.
*/
public bindSocket(socket: Socket): Disposer {
socket.on("connect", () => this.emit("connect"));
socket.on("lookup", (error, address, family, host) => this.emit("lookup", error, address, family, host));
socket.on("timeout", () => this.emit("timeout"));
this.on("connect", (options, callbackId) => socket.connect(options, this.maybeCallback(callbackId)));
this.on("ref", () => socket.ref());
this.on("setKeepAlive", (enable, initialDelay) => socket.setKeepAlive(enable, initialDelay));
this.on("setNoDelay", (noDelay) => socket.setNoDelay(noDelay));
this.on("setTimeout", (timeout, callbackId) => socket.setTimeout(timeout, this.maybeCallback(callbackId)));
this.on("unref", () => socket.unref());
this.bindReadable(socket);
this.bindWritable(socket);
return {
onDidDispose: (cb): Socket => socket.on("close", cb),
dispose: (): void => {
socket.removeAllListeners();
socket.end();
socket.destroy();
socket.unref();
},
};
}
/**
* Bind a writable stream to the active evaluation.
*/
public bindWritable(writable: Writable | Duplex): void {
if (!((writable as Readable).read)) { // To avoid binding twice.
writable.on("close", () => this.emit("close"));
writable.on("error", (error) => this.emit("error", error));
this.on("destroy", () => writable.destroy());
}
writable.on("drain", () => this.emit("drain"));
writable.on("finish", () => this.emit("finish"));
writable.on("pipe", () => this.emit("pipe"));
writable.on("unpipe", () => this.emit("unpipe"));
this.on("cork", () => writable.cork());
this.on("end", (chunk, encoding, callbackId) => writable.end(chunk, encoding, this.maybeCallback(callbackId)));
this.on("setDefaultEncoding", (encoding) => writable.setDefaultEncoding(encoding));
this.on("uncork", () => writable.uncork());
// Sockets can pass an fd instead of a callback but streams cannot.
this.on("write", (chunk, encoding, fd, callbackId) => writable.write(chunk, encoding, this.maybeCallback(callbackId) || fd));
}
/**
* Bind a readable stream to the active evaluation.
*/
public bindReadable(readable: Readable): void {
// Streams don't have an argument on close but sockets do.
readable.on("close", (...args: any[]) => this.emit("close", ...args));
readable.on("data", (data) => this.emit("data", data));
readable.on("end", () => this.emit("end"));
readable.on("error", (error) => this.emit("error", error));
readable.on("readable", () => this.emit("readable"));
this.on("destroy", () => readable.destroy());
this.on("pause", () => readable.pause());
this.on("push", (chunk, encoding) => readable.push(chunk, encoding));
this.on("resume", () => readable.resume());
this.on("setEncoding", (encoding) => readable.setEncoding(encoding));
this.on("unshift", (chunk) => readable.unshift(chunk));
}
public createUnique(id: number | "stdout" | "stderr" | "stdin"): ServerActiveEvalHelper {
return new ServerActiveEvalHelper(this.createUniqueEmitter(id), this.fork);
}
}
/**
* An event emitter that can store callbacks with IDs in a map so we can pass
* them back and forth through an active evaluation using those IDs.
*/
export class CallbackEmitter extends EventEmitter {
private _ae: ActiveEvalHelper | undefined;
private callbackId = 0;
private readonly callbacks = new Map<number, Function>();
public constructor(ae?: ActiveEvalHelper) {
super();
if (ae) {
this.ae = ae;
}
}
protected get ae(): ActiveEvalHelper {
if (!this._ae) {
throw new Error("trying to access active evaluation before it has been set");
}
return this._ae;
}
protected set ae(ae: ActiveEvalHelper) {
if (this._ae) {
throw new Error("cannot override active evaluation");
}
this._ae = ae;
this.ae.on("callback", (callbackId, ...args: any[]) => this.runCallback(callbackId, ...args));
}
/**
* Store the callback and return and ID referencing its location in the map.
*/
protected storeCallback(callback?: Function): number | undefined {
if (!callback) {
return undefined;
}
const callbackId = this.callbackId++;
this.callbacks.set(callbackId, callback);
return callbackId;
}
/**
* Call the function with the specified ID and delete it from the map.
* If the ID is undefined or doesn't exist, nothing happens.
*/
private runCallback(callbackId?: number, ...args: any[]): void {
const callback = typeof callbackId !== "undefined" && this.callbacks.get(callbackId);
if (callback && typeof callbackId !== "undefined") {
this.callbacks.delete(callbackId);
callback(...args);
}
}
}
/**
* A writable stream over an active evaluation.
*/
export class ActiveEvalWritable extends CallbackEmitter implements Writable {
public constructor(ae: ActiveEvalHelper) {
super(ae);
// Streams don't have an argument on close but sockets do.
this.ae.on("close", (...args: any[]) => this.emit("close", ...args));
this.ae.on("drain", () => this.emit("drain"));
this.ae.on("error", (error) => this.emit("error", error));
this.ae.on("finish", () => this.emit("finish"));
this.ae.on("pipe", () => logger.warn("pipe is not supported"));
this.ae.on("unpipe", () => logger.warn("unpipe is not supported"));
}
public get writable(): boolean { throw new Error("not implemented"); }
public get writableHighWaterMark(): number { throw new Error("not implemented"); }
public get writableLength(): number { throw new Error("not implemented"); }
public _write(): void { throw new Error("not implemented"); }
public _destroy(): void { throw new Error("not implemented"); }
public _final(): void { throw new Error("not implemented"); }
public pipe<T>(): T { throw new Error("not implemented"); }
public cork(): void { this.ae.emit("cork"); }
public destroy(): void { this.ae.emit("destroy"); }
public setDefaultEncoding(encoding: string): this {
this.ae.emit("setDefaultEncoding", encoding);
return this;
}
public uncork(): void { this.ae.emit("uncork"); }
public write(chunk: any, encoding?: string | ((error?: Error | null) => void), callback?: (error?: Error | null) => void): boolean {
if (typeof encoding === "function") {
callback = encoding;
encoding = undefined;
}
// Sockets can pass an fd instead of a callback but streams cannot..
this.ae.emit("write", chunk, encoding, undefined, this.storeCallback(callback));
// Always true since we can't get this synchronously.
return true;
}
public end(data?: any, encoding?: string | Function, callback?: Function): void {
if (typeof encoding === "function") {
callback = encoding;
encoding = undefined;
}
this.ae.emit("end", data, encoding, this.storeCallback(callback));
}
}
/**
* A readable stream over an active evaluation.
*/
export class ActiveEvalReadable extends CallbackEmitter implements Readable {
public constructor(ae: ActiveEvalHelper) {
super(ae);
this.ae.on("close", () => this.emit("close"));
this.ae.on("data", (data) => this.emit("data", data));
this.ae.on("end", () => this.emit("end"));
this.ae.on("error", (error) => this.emit("error", error));
this.ae.on("readable", () => this.emit("readable"));
}
public get readable(): boolean { throw new Error("not implemented"); }
public get readableHighWaterMark(): number { throw new Error("not implemented"); }
public get readableLength(): number { throw new Error("not implemented"); }
public _read(): void { throw new Error("not implemented"); }
public read(): any { throw new Error("not implemented"); }
public isPaused(): boolean { throw new Error("not implemented"); }
public pipe<T>(): T { throw new Error("not implemented"); }
public unpipe(): this { throw new Error("not implemented"); }
public unshift(): this { throw new Error("not implemented"); }
public wrap(): this { throw new Error("not implemented"); }
public push(): boolean { throw new Error("not implemented"); }
public _destroy(): void { throw new Error("not implemented"); }
public [Symbol.asyncIterator](): AsyncIterableIterator<any> { throw new Error("not implemented"); }
public destroy(): void { this.ae.emit("destroy"); }
public pause(): this { return this.emitReturnThis("pause"); }
public resume(): this { return this.emitReturnThis("resume"); }
public setEncoding(encoding?: string): this { return this.emitReturnThis("setEncoding", encoding); }
// tslint:disable-next-line no-any
protected emitReturnThis(event: string, ...args: any[]): this {
this.ae.emit(event, ...args);
return this;
}
}
/**
* An duplex stream over an active evaluation.
*/
export class ActiveEvalDuplex extends ActiveEvalReadable implements Duplex {
// Some unfortunate duplication here since we can't have multiple extends.
public constructor(ae: ActiveEvalHelper) {
super(ae);
this.ae.on("drain", () => this.emit("drain"));
this.ae.on("finish", () => this.emit("finish"));
this.ae.on("pipe", () => logger.warn("pipe is not supported"));
this.ae.on("unpipe", () => logger.warn("unpipe is not supported"));
}
public get writable(): boolean { throw new Error("not implemented"); }
public get writableHighWaterMark(): number { throw new Error("not implemented"); }
public get writableLength(): number { throw new Error("not implemented"); }
public _write(): void { throw new Error("not implemented"); }
public _destroy(): void { throw new Error("not implemented"); }
public _final(): void { throw new Error("not implemented"); }
public pipe<T>(): T { throw new Error("not implemented"); }
public cork(): void { this.ae.emit("cork"); }
public destroy(): void { this.ae.emit("destroy"); }
public setDefaultEncoding(encoding: string): this {
this.ae.emit("setDefaultEncoding", encoding);
return this;
}
public uncork(): void { this.ae.emit("uncork"); }
public write(chunk: any, encoding?: string | ((error?: Error | null) => void), callback?: (error?: Error | null) => void): boolean {
if (typeof encoding === "function") {
callback = encoding;
encoding = undefined;
}
// Sockets can pass an fd instead of a callback but streams cannot..
this.ae.emit("write", chunk, encoding, undefined, this.storeCallback(callback));
// Always true since we can't get this synchronously.
return true;
}
public end(data?: any, encoding?: string | Function, callback?: Function): void {
if (typeof encoding === "function") {
callback = encoding;
encoding = undefined;
}
this.ae.emit("end", data, encoding, this.storeCallback(callback));
}
}