-
Notifications
You must be signed in to change notification settings - Fork 29.9k
/
sharedProcess.ts
429 lines (346 loc) · 15.8 KB
/
sharedProcess.ts
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
419
420
421
422
423
424
425
426
427
428
429
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { BrowserWindow, Event as ElectronEvent, IpcMainEvent, MessagePortMain } from 'electron';
import { validatedIpcMain } from 'vs/base/parts/ipc/electron-main/ipcMain';
import { Barrier, DeferredPromise } from 'vs/base/common/async';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { FileAccess } from 'vs/base/common/network';
import { IProcessEnvironment } from 'vs/base/common/platform';
import { assertIsDefined } from 'vs/base/common/types';
import { connect as connectMessagePort } from 'vs/base/parts/ipc/electron-main/ipc.mp';
import { IEnvironmentMainService } from 'vs/platform/environment/electron-main/environmentMainService';
import { ILifecycleMainService } from 'vs/platform/lifecycle/electron-main/lifecycleMainService';
import { ILogService } from 'vs/platform/log/common/log';
import product from 'vs/platform/product/common/product';
import { IProtocolMainService } from 'vs/platform/protocol/electron-main/protocol';
import { ISharedProcess, ISharedProcessConfiguration } from 'vs/platform/sharedProcess/node/sharedProcess';
import { IUtilityProcessWorkerConfiguration } from 'vs/platform/utilityProcess/common/utilityProcessWorkerService';
import { IThemeMainService } from 'vs/platform/theme/electron-main/themeMainService';
import { WindowError } from 'vs/platform/window/electron-main/window';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { IUserDataProfilesService } from 'vs/platform/userDataProfile/common/userDataProfile';
import { IPolicyService } from 'vs/platform/policy/common/policy';
import { ILoggerMainService } from 'vs/platform/log/electron-main/loggerService';
import { UtilityProcess } from 'vs/platform/utilityProcess/electron-main/utilityProcess';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils';
import { canUseUtilityProcess } from 'vs/base/parts/sandbox/electron-main/electronTypes';
import { parseSharedProcessDebugPort } from 'vs/platform/environment/node/environmentService';
export class SharedProcess extends Disposable implements ISharedProcess {
private readonly _onDidError = this._register(new Emitter<{ type: WindowError; details?: { reason: string; exitCode: number } }>());
readonly onDidError = Event.buffer(this._onDidError.event); // buffer until we have a listener!
private readonly firstWindowConnectionBarrier = new Barrier();
private window: BrowserWindow | undefined = undefined;
private windowCloseListener: ((event: ElectronEvent) => void) | undefined = undefined;
private utilityProcess: UtilityProcess | undefined = undefined;
private readonly useUtilityProcess = (() => {
let useUtilityProcess = false;
if (canUseUtilityProcess) {
const sharedProcessUseUtilityProcess = this.configurationService.getValue<boolean>('window.experimental.sharedProcessUseUtilityProcess');
if (typeof sharedProcessUseUtilityProcess === 'boolean') {
useUtilityProcess = sharedProcessUseUtilityProcess;
} else {
useUtilityProcess = typeof product.quality === 'string' && product.quality !== 'stable';
}
}
return useUtilityProcess;
})();
constructor(
private readonly machineId: string,
private userEnv: IProcessEnvironment,
@IEnvironmentMainService private readonly environmentMainService: IEnvironmentMainService,
@IUserDataProfilesService private readonly userDataProfilesService: IUserDataProfilesService,
@ILifecycleMainService private readonly lifecycleMainService: ILifecycleMainService,
@ILogService private readonly logService: ILogService,
@ILoggerMainService private readonly loggerMainService: ILoggerMainService,
@IPolicyService private readonly policyService: IPolicyService,
@IThemeMainService private readonly themeMainService: IThemeMainService,
@IProtocolMainService private readonly protocolMainService: IProtocolMainService,
@IConfigurationService private readonly configurationService: IConfigurationService
) {
super();
this.registerListeners();
if (this.useUtilityProcess) {
this.logService.info('[SharedProcess] using utility process');
}
}
private registerListeners(): void {
// Shared process connections from workbench windows
validatedIpcMain.on('vscode:createSharedProcessMessageChannel', (e, nonce: string) => this.onWindowConnection(e, nonce));
// Shared process worker relay
validatedIpcMain.on('vscode:relaySharedProcessWorkerMessageChannel', (e, configuration: IUtilityProcessWorkerConfiguration) => this.onWorkerConnection(e, configuration));
// Lifecycle
this._register(this.lifecycleMainService.onWillShutdown(() => this.onWillShutdown()));
}
private async onWindowConnection(e: IpcMainEvent, nonce: string): Promise<void> {
this.logService.trace('[SharedProcess] on vscode:createSharedProcessMessageChannel');
// release barrier if this is the first window connection
if (!this.firstWindowConnectionBarrier.isOpen()) {
this.firstWindowConnectionBarrier.open();
}
// await the shared process to be overall ready
// we do not just wait for IPC ready because the
// workbench window will communicate directly
await this.whenReady();
// connect to the shared process
const port = await this.connect();
// Check back if the requesting window meanwhile closed
// Since shared process is delayed on startup there is
// a chance that the window close before the shared process
// was ready for a connection.
if (e.sender.isDestroyed()) {
return port.close();
}
// send the port back to the requesting window
e.sender.postMessage('vscode:createSharedProcessMessageChannelResult', nonce, [port]);
}
private onWorkerConnection(e: IpcMainEvent, configuration: IUtilityProcessWorkerConfiguration): void {
this.logService.trace('[SharedProcess] onWorkerConnection', configuration);
const disposables = new DisposableStore();
const disposeWorker = (reason: string) => {
if (!this.isWindowAlive()) {
return; // the shared process is already gone, no need to dispose anything
}
this.logService.trace(`[SharedProcess] disposing worker (reason: '${reason}')`, configuration);
// Only once!
disposables.dispose();
// Send this into the shared process who owns workers
this.sendToWindow('vscode:electron-main->shared-process=disposeWorker', configuration);
};
// Ensure the sender is a valid target to send to
const receiverWindow = BrowserWindow.fromId(configuration.reply.windowId);
if (!receiverWindow || receiverWindow.isDestroyed() || receiverWindow.webContents.isDestroyed() || !configuration.reply.channel) {
disposeWorker('unavailable');
return;
}
// Attach to lifecycle of receiver to manage worker lifecycle
disposables.add(Event.filter(this.lifecycleMainService.onWillLoadWindow, e => e.window.win === receiverWindow)(() => disposeWorker('load')));
disposables.add(Event.fromNodeEventEmitter(receiverWindow, 'closed')(() => disposeWorker('closed')));
// The shared process window asks us to relay a `MessagePort`
// from a shared process worker to the target window. It needs
// to be send via `postMessage` to transfer the port.
receiverWindow.webContents.postMessage(configuration.reply.channel, configuration.reply.nonce, e.ports);
}
private onWillShutdown(): void {
this.logService.trace('[SharedProcess] onWillShutdown');
if (this.utilityProcess) {
this.utilityProcess.postMessage('vscode:electron-main->shared-process=exit');
this.utilityProcess = undefined;
} else {
const window = this.window;
if (!window) {
return; // possibly too early before created
}
// Signal exit to shared process when shutting down
this.sendToWindow('vscode:electron-main->shared-process=exit');
// Shut the shared process down when we are quitting
//
// Note: because we veto the window close, we must first remove our veto.
// Otherwise the application would never quit because the shared process
// window is refusing to close!
//
if (this.windowCloseListener) {
window.removeListener('close', this.windowCloseListener);
this.windowCloseListener = undefined;
}
// Electron seems to crash on Windows without this setTimeout :|
setTimeout(() => {
try {
this.logService.trace('[SharedProcess] onWillShutdown window.close()');
window.close();
} catch (error) {
this.logService.trace(`[SharedProcess] onWillShutdown window.close() error: ${error}`); // ignore, as electron is already shutting down
}
this.window = undefined;
}, 0);
}
}
private sendToWindow(channel: string, ...args: any[]): void {
if (!this.isWindowAlive()) {
this.logService.warn(`Sending IPC message to channel '${channel}' for shared process that is destroyed`);
return;
}
try {
this.window?.webContents.send(channel, ...args);
} catch (error) {
this.logService.warn(`Error sending IPC message to channel '${channel}' of shared process: ${toErrorMessage(error)}`);
}
}
private _whenReady: Promise<void> | undefined = undefined;
whenReady(): Promise<void> {
if (!this._whenReady) {
this._whenReady = (async () => {
// Wait for shared process being ready to accept connection
await this.whenIpcReady;
// Overall signal that the shared process was loaded and
// all services within have been created.
const whenReady = new DeferredPromise<void>();
if (this.utilityProcess) {
this.utilityProcess.once('vscode:shared-process->electron-main=init-done', () => whenReady.complete());
} else {
validatedIpcMain.once('vscode:shared-process->electron-main=init-done', () => whenReady.complete());
}
await whenReady.p;
this.logService.trace('[SharedProcess] Overall ready');
})();
}
return this._whenReady;
}
private _whenIpcReady: Promise<void> | undefined = undefined;
private get whenIpcReady() {
if (!this._whenIpcReady) {
this._whenIpcReady = (async () => {
// Always wait for first window asking for connection
await this.firstWindowConnectionBarrier.wait();
// Spawn shared process
this.spawn();
// Wait for shared process indicating that IPC connections are accepted
const sharedProcessIpcReady = new DeferredPromise<void>();
if (this.utilityProcess) {
this.utilityProcess.once('vscode:shared-process->electron-main=ipc-ready', () => sharedProcessIpcReady.complete());
} else {
validatedIpcMain.once('vscode:shared-process->electron-main=ipc-ready', () => sharedProcessIpcReady.complete());
}
await sharedProcessIpcReady.p;
this.logService.trace('[SharedProcess] IPC ready');
})();
}
return this._whenIpcReady;
}
private spawn(): void {
// Spawn shared process
if (this.useUtilityProcess) {
this.createUtilityProcess();
} else {
this.createWindow();
}
// Listeners
this.registerSharedProcessListeners();
}
private createUtilityProcess(): void {
this.utilityProcess = this._register(new UtilityProcess(this.logService, NullTelemetryService, this.lifecycleMainService));
const inspectParams = parseSharedProcessDebugPort(this.environmentMainService.args, this.environmentMainService.isBuilt);
let execArgv: string[] | undefined = undefined;
if (inspectParams.port) {
execArgv = ['--nolazy'];
if (inspectParams.break) {
execArgv.push(`--inspect-brk=${inspectParams.port}`);
} else {
execArgv.push(`--inspect=${inspectParams.port}`);
}
}
this.utilityProcess.start({
type: 'shared-process',
entryPoint: 'vs/code/node/sharedProcess/sharedProcessMain',
payload: this.createSharedProcessConfiguration(),
execArgv
});
}
private createWindow(): void {
const configObjectUrl = this._register(this.protocolMainService.createIPCObjectUrl<ISharedProcessConfiguration>());
// shared process is a hidden window by default
this.window = new BrowserWindow({
show: false,
backgroundColor: this.themeMainService.getBackgroundColor(),
title: 'shared-process',
webPreferences: {
preload: FileAccess.asFileUri('vs/base/parts/sandbox/electron-browser/preload.js').fsPath,
additionalArguments: [`--vscode-window-config=${configObjectUrl.resource.toString()}`],
v8CacheOptions: this.environmentMainService.useCodeCache ? 'bypassHeatCheck' : 'none',
nodeIntegration: true,
nodeIntegrationInWorker: true,
contextIsolation: false,
enableWebSQL: false,
spellcheck: false,
images: false,
webgl: false
}
});
// Store into config object URL
configObjectUrl.update(this.createSharedProcessConfiguration());
// Load with config
this.window.loadURL(FileAccess.asBrowserUri(`vs/code/node/sharedProcess/sharedProcess${this.environmentMainService.isBuilt ? '' : '-dev'}.html`).toString(true));
}
private createSharedProcessConfiguration(): ISharedProcessConfiguration {
return {
machineId: this.machineId,
windowId: this.window?.id ?? -1, // TODO@bpasero what window id should this be in utility process?
appRoot: this.environmentMainService.appRoot,
codeCachePath: this.environmentMainService.codeCachePath,
profiles: {
home: this.userDataProfilesService.profilesHome,
all: this.userDataProfilesService.profiles,
},
userEnv: this.userEnv,
args: this.environmentMainService.args,
logLevel: this.loggerMainService.getLogLevel(),
loggers: this.loggerMainService.getRegisteredLoggers(),
product,
policiesData: this.policyService.serialize()
};
}
private registerSharedProcessListeners(): void {
// Hidden window
if (this.window) {
// Prevent the window from closing
this.windowCloseListener = (e: ElectronEvent) => {
this.logService.trace('SharedProcess#close prevented');
// We never allow to close the shared process unless we get explicitly disposed()
e.preventDefault();
// Still hide the window though if visible
if (this.window?.isVisible()) {
this.window.hide();
}
};
this.window.on('close', this.windowCloseListener);
// Crashes & Unresponsive & Failed to load
this.window.webContents.on('render-process-gone', (event, details) => this._onDidError.fire({ type: WindowError.PROCESS_GONE, details }));
this.window.on('unresponsive', () => this._onDidError.fire({ type: WindowError.UNRESPONSIVE }));
this.window.webContents.on('did-fail-load', (event, exitCode, reason) => this._onDidError.fire({ type: WindowError.LOAD, details: { reason, exitCode } }));
}
// Utility process
else if (this.utilityProcess) {
this._register(this.utilityProcess.onCrash(event => this._onDidError.fire({ type: WindowError.PROCESS_GONE, details: { reason: event.reason, exitCode: event.code } })));
}
}
async connect(): Promise<MessagePortMain> {
// Wait for shared process being ready to accept connection
await this.whenIpcReady;
// Connect and return message port
if (this.utilityProcess) {
return this.utilityProcess.connect();
} else {
return connectMessagePort(assertIsDefined(this.window));
}
}
async toggle(): Promise<void> {
// wait for window to be created
await this.whenIpcReady;
if (!this.window) {
return; // possibly disposed already
}
if (this.window.isVisible()) {
this.window.webContents.closeDevTools();
this.window.hide();
} else {
this.window.show();
this.window.webContents.openDevTools();
}
}
isVisible(): boolean {
return this.window?.isVisible() ?? false;
}
usingUtilityProcess(): boolean {
return !!this.utilityProcess;
}
private isWindowAlive(): boolean {
const window = this.window;
if (!window) {
return false;
}
return !window.isDestroyed() && !window.webContents.isDestroyed();
}
}