ipc.cp.ts 5.5 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

J
Joao Moreno 已提交
6
import { ChildProcess, fork } from 'child_process';
E
Erich Gamma 已提交
7 8 9 10
import { IDisposable } from 'vs/base/common/lifecycle';
import { Promise} from 'vs/base/common/winjs.base';
import { Delayer } from 'vs/base/common/async';
import { clone, assign } from 'vs/base/common/objects';
J
Joao Moreno 已提交
11
import { IServiceCtor, Server as IPCServer, Client as IPCClient, IServiceMap } from 'vs/base/parts/ipc/common/ipc';
E
Erich Gamma 已提交
12 13 14 15

export class Server extends IPCServer {
	constructor() {
		super({
J
Joao Moreno 已提交
16
			send: r => { try { process.send(r); } catch (e) { /* not much to do */ } },
E
Erich Gamma 已提交
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
			onMessage: cb => process.on('message', cb)
		});

		process.once('disconnect', () => this.dispose());
	}
}

export interface IServiceOptions {

	/**
	 * A descriptive name for the server this connection is to. Used in logging.
	 */
	serverName: string;

	/**
	 * Time in millies before killing the service process. The next request after killing will start it again.
	 */
	timeout?:number;

	/**
	 * Arguments to the module to execute.
	 */
	args?:string[];

	/**
	 * Environment key-value pairs to be passed to the process that gets spawned for the service.
	 */
	env?:any;

	/**
	 * Allows to assign a debug port for debugging the application executed.
	 */
	debug?:number;

	/**
	 * Allows to assign a debug port for debugging the application and breaking it on the first line.
	 */
	debugBrk?:number;
}

export class Client implements IDisposable {

	private disposeDelayer: Delayer<void>;
	private activeRequests: Promise[];
J
Joao Moreno 已提交
61
	private child: ChildProcess;
E
Erich Gamma 已提交
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
	private _client: IPCClient;
	private services: IServiceMap;

	constructor(private modulePath: string, private options: IServiceOptions) {
		const timeout = options && options.timeout ? options.timeout : Number.MAX_VALUE;
		this.disposeDelayer = new Delayer<void>(timeout);
		this.activeRequests = [];
		this.child = null;
		this._client = null;
		this.services = Object.create(null);
	}

	getService<TService>(serviceName: string, serviceCtor: IServiceCtor<TService>): TService {
		return <TService>Object.keys(serviceCtor.prototype)
			.filter(key => key !== 'constructor')
			.reduce((service, key) => assign(service, { [key]: (...args) => this.request(serviceName, serviceCtor, key, ...args) }), {});
	}

	protected request<TService>(serviceName: string, serviceCtor: IServiceCtor<TService>, name: string, ...args: any[]): Promise {
		this.disposeDelayer.cancel();

		let service = this.services[serviceName];

		if (!service) {
			service = this.services[serviceName] = this.client.getService(serviceName, serviceCtor);
		}

		const request: Promise = service[name].apply(service, args);

		// Progress doesn't propagate across 'then', we need to create a promise wrapper
		const result = new Promise((c, e, p) => {
			request.then(c, e, p).done(() => {
				this.activeRequests.splice(this.activeRequests.indexOf(result), 1);
				this.disposeDelayer.trigger(() => this.disposeClient());
			});
		}, () => request.cancel());

		this.activeRequests.push(result);
		return result;
	}

	private get client(): IPCClient {
		if (!this._client) {
			const args = this.options && this.options.args ? this.options.args : [];
			let forkOpts:any = undefined;

			if (this.options) {
				forkOpts = Object.create(null);

				if (this.options.env) {
					forkOpts.env = assign(clone(process.env), this.options.env);
				}

				if (typeof this.options.debug === 'number') {
					forkOpts.execArgv = ['--nolazy', '--debug=' + this.options.debug];
				}

				if (typeof this.options.debugBrk === 'number') {
					forkOpts.execArgv = ['--nolazy', '--debug-brk=' + this.options.debugBrk];
				}
			}

J
Joao Moreno 已提交
124
			this.child = fork(this.modulePath, args, forkOpts);
E
Erich Gamma 已提交
125
			this._client = new IPCClient({
J
npe  
Joao Moreno 已提交
126
				send: r => this.child && this.child.connected && this.child.send(r),
E
Erich Gamma 已提交
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
				onMessage: cb => {
					this.child.on('message', (msg) => {

						// Handle console logs specially
						if (msg && msg.type === '__$console') {
							let args = ['%c[Service Library: ' + this.options.serverName + ']', 'color: darkgreen'];
							try {
								const parsed = JSON.parse(msg.arguments);
								args = args.concat(Object.getOwnPropertyNames(parsed).map(o => parsed[o]));
							} catch (error) {
								args.push(msg.arguments);
							}

							console[msg.severity].apply(console, args);
						}

						// Anything else goes to the outside
						else {
							cb(msg);
						}
					});
				}
			});

			const onExit = () => this.disposeClient();
			process.once('exit', onExit);

			this.child.on('error', err => console.warn('Service "' + this.options.serverName + '" errored with ' + err));

			this.child.on('exit', (code: any, signal: any) => {
				process.removeListener('exit', onExit);

				if (this.activeRequests) {
					this.activeRequests.forEach(req => req.cancel());
					this.activeRequests = [];
				}

				if (code && signal !== 'SIGTERM') {
					console.warn('Service "' + this.options.serverName + '" crashed with exit code ' + code);
					this.disposeDelayer.cancel();
					this.disposeClient();
				}
			});
		}

		return this._client;
	}

	private disposeClient() {
		if (this._client) {
			this.child.kill();
			this.child = null;
			this._client = null;
			this.services = Object.create(null);
		}
	}

	dispose() {
		this.disposeDelayer.cancel();
		this.disposeDelayer = null;
		this.disposeClient();
		this.activeRequests = null;
	}
}