Repository navigation
Expand file tree
/
Copy pathNodeServicePlugin.ts
More file actions
417 lines (356 loc) · 14.5 KB
/
Copy pathNodeServicePlugin.ts
File metadata and controls
417 lines (356 loc) · 14.5 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
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import * as child_process from 'node:child_process';
import * as process from 'node:process';
import { InternalError, SubprocessTerminator } from '@rushstack/node-core-library';
import type { IHeftTaskPlugin } from '../pluginFramework/IHeftPlugin';
import type { HeftConfiguration } from '../configuration/HeftConfiguration';
import type {
IHeftTaskSession,
IHeftTaskRunIncrementalHookOptions
} from '../pluginFramework/HeftTaskSession';
import type { IScopedLogger } from '../pluginFramework/logging/ScopedLogger';
import { CoreConfigFiles } from '../utilities/CoreConfigFiles';
const PLUGIN_NAME: 'node-service-plugin' = 'node-service-plugin';
const SERVE_PARAMETER_LONG_NAME: '--serve' = '--serve';
const _isWindows: boolean = process.platform === 'win32';
export interface INodeServicePluginCompleteConfiguration {
commandName: string;
ignoreMissingScript: boolean;
waitForTerminateMs: number;
waitForKillMs: number;
}
export interface INodeServicePluginConfiguration extends Partial<INodeServicePluginCompleteConfiguration> {}
enum State {
/**
* The service process is not running, and _activeChildProcess is undefined.
*
* In this state, there may or may not be a timeout scheduled that will later restart the service.
*/
Stopped,
/**
* The service process is running normally.
*/
Running,
/**
* The SIGTERM signal has been sent to the service process, and we are waiting for it
* to shut down gracefully.
*
* NOTE: On Windows OS, SIGTERM is skipped and we proceed directly to SIGKILL.
*/
Stopping,
/**
* The SIGKILL signal has been sent to forcibly terminate the service process, and we are waiting
* to confirm that the operation has completed.
*/
Killing
}
export default class NodeServicePlugin implements IHeftTaskPlugin {
#activeChildProcess: child_process.ChildProcess | undefined;
#childProcessExitPromise: Promise<void> | undefined;
#childProcessExitPromiseResolveFn: (() => void) | undefined;
#childProcessExitPromiseRejectFn: ((e: unknown) => void) | undefined;
#state: State = State.Stopped;
#logger!: IScopedLogger;
/**
* The state machine schedules at most one setInterval() timeout at any given time. It is for:
*
* - waitForTerminateMs in State.Stopping
* - waitForKillMs in State.Killing
*/
#timeout: NodeJS.Timeout | undefined = undefined;
/**
* The data read from the node-service.json config file, or "undefined" if the file is missing.
*/
#rawConfiguration: INodeServicePluginConfiguration | undefined = undefined;
/**
* The effective configuration, with defaults applied.
*/
#configuration!: INodeServicePluginCompleteConfiguration;
/**
* The script body obtained from the "scripts" section in the project's package.json.
*/
#shellCommand: string | undefined;
#pluginEnabled: boolean = false;
public apply(taskSession: IHeftTaskSession, heftConfiguration: HeftConfiguration): void {
// Set this immediately to make it available to the internal methods that use it
this.#logger = taskSession.logger;
const isServeMode: boolean = taskSession.parameters.getFlagParameter(SERVE_PARAMETER_LONG_NAME).value;
if (isServeMode && !taskSession.parameters.watch) {
throw new Error(
`The ${JSON.stringify(
SERVE_PARAMETER_LONG_NAME
)} parameter is only available when running in watch mode.` +
` Try replacing "${taskSession.parsedCommandLine?.unaliasedCommandName}" with` +
` "${taskSession.parsedCommandLine?.unaliasedCommandName}-watch" in your Heft command line.`
);
}
if (!isServeMode) {
taskSession.logger.terminal.writeVerboseLine(
`Not launching the service because the "${SERVE_PARAMETER_LONG_NAME}" parameter was not specified`
);
return;
}
taskSession.hooks.runIncremental.tapPromise(
PLUGIN_NAME,
async (runIncrementalOptions: IHeftTaskRunIncrementalHookOptions) => {
await this.#runCommandAsync(taskSession, heftConfiguration);
}
);
}
async #loadStageConfigurationAsync(
taskSession: IHeftTaskSession,
heftConfiguration: HeftConfiguration
): Promise<void> {
if (!this.#rawConfiguration) {
this.#rawConfiguration = await CoreConfigFiles.tryLoadNodeServiceConfigurationFileAsync(
taskSession.logger.terminal,
heftConfiguration.buildFolderPath,
heftConfiguration.rigConfig
);
// defaults
this.#configuration = {
commandName: 'serve',
ignoreMissingScript: false,
waitForTerminateMs: 2000,
waitForKillMs: 2000
};
// TODO: @rushstack/heft-config-file should be able to read a *.defaults.json file
if (this.#rawConfiguration) {
this.#pluginEnabled = true;
if (this.#rawConfiguration.commandName !== undefined) {
this.#configuration.commandName = this.#rawConfiguration.commandName;
}
if (this.#rawConfiguration.ignoreMissingScript !== undefined) {
this.#configuration.ignoreMissingScript = this.#rawConfiguration.ignoreMissingScript;
}
if (this.#rawConfiguration.waitForTerminateMs !== undefined) {
this.#configuration.waitForTerminateMs = this.#rawConfiguration.waitForTerminateMs;
}
if (this.#rawConfiguration.waitForKillMs !== undefined) {
this.#configuration.waitForKillMs = this.#rawConfiguration.waitForKillMs;
}
this.#shellCommand = (heftConfiguration.projectPackageJson.scripts || {})[
this.#configuration.commandName
];
if (this.#shellCommand === undefined) {
if (this.#configuration.ignoreMissingScript) {
taskSession.logger.terminal.writeLine(
`The node service cannot be started because the project's package.json` +
` does not have a "${this.#configuration.commandName}" script`
);
} else {
throw new Error(
`The node service cannot be started because the project's package.json ` +
`does not have a "${this.#configuration.commandName}" script`
);
}
this.#pluginEnabled = false;
}
} else {
throw new Error(
'The node service cannot be started because the task config file was not found: ' +
CoreConfigFiles.nodeServiceConfigurationProjectRelativeFilePath
);
}
}
}
async #runCommandAsync(
taskSession: IHeftTaskSession,
heftConfiguration: HeftConfiguration
): Promise<void> {
await this.#loadStageConfigurationAsync(taskSession, heftConfiguration);
if (!this.#pluginEnabled) {
return;
}
this.#logger.terminal.writeLine(`Starting Node service...`);
await this.#stopChildAsync();
this.#startChild();
}
async #stopChildAsync(): Promise<void> {
if (this.#state !== State.Running) {
if (this.#childProcessExitPromise) {
// If we have an active process but are not in the running state, we must be in the process of
// terminating or the process is already stopped.
await this.#childProcessExitPromise;
}
return;
}
if (_isWindows) {
// On Windows, SIGTERM can kill Cmd.exe and leave its children running in the background
this.#transitionToKilling();
} else {
if (!this.#activeChildProcess) {
// All the code paths that set _activeChildProcess=undefined should also leave the Running state
throw new InternalError('_activeChildProcess should not be undefined');
}
this.#state = State.Stopping;
this.#logger.terminal.writeVerboseLine('Sending SIGTERM to gracefully shut down the service process');
// Passing a negative PID terminates the entire group instead of just the one process.
// This works because we set detached=true for child_process.spawn()
const pid: number | undefined = this.#activeChildProcess.pid;
if (pid !== undefined) {
// If pid was undefined, the process failed to spawn
process.kill(-pid, 'SIGTERM');
}
this.#clearTimeout();
this.#timeout = setTimeout(() => {
try {
if (this.#state !== State.Stopped) {
this.#logger.terminal.writeWarningLine('The service process is taking too long to terminate');
this.#transitionToKilling();
}
} catch (e: unknown) {
this.#childProcessExitPromiseRejectFn!(e);
}
}, this.#configuration.waitForTerminateMs);
}
await this.#childProcessExitPromise;
}
#transitionToKilling(): void {
this.#state = State.Killing;
if (!this.#activeChildProcess) {
// All the code paths that set _activeChildProcess=undefined should also leave the Running state
throw new InternalError('_activeChildProcess should not be undefined');
}
this.#logger.terminal.writeVerboseLine('Attempting to killing the service process');
SubprocessTerminator.killProcessTree(this.#activeChildProcess, SubprocessTerminator.RECOMMENDED_OPTIONS);
this.#clearTimeout();
this.#timeout = setTimeout(() => {
try {
if (this.#state !== State.Stopped) {
this.#logger.terminal.writeErrorLine(
'Abandoning the service process because it could not be killed'
);
this.#transitionToStopped();
}
} catch (e: unknown) {
this.#childProcessExitPromiseRejectFn!(e);
}
}, this.#configuration.waitForKillMs);
}
#transitionToStopped(): void {
// Failed to start
this.#state = State.Stopped;
this.#clearTimeout();
this.#activeChildProcess = undefined;
this.#childProcessExitPromiseResolveFn!();
}
#startChild(): void {
if (this.#state !== State.Stopped) {
throw new InternalError('Invalid state');
}
this.#state = State.Running;
this.#clearTimeout();
this.#logger.terminal.writeLine(`Invoking command: "${this.#shellCommand!}"`);
const childProcess: child_process.ChildProcess = child_process.spawn(this.#shellCommand!, {
shell: true,
...SubprocessTerminator.RECOMMENDED_OPTIONS
});
SubprocessTerminator.killProcessTreeOnExit(childProcess, SubprocessTerminator.RECOMMENDED_OPTIONS);
const childPid: number | undefined = childProcess.pid;
if (childPid === undefined) {
throw new InternalError(`Failed to spawn child process`);
}
this.#logger.terminal.writeVerboseLine(`Started service process #${childPid}`);
// Create a promise that resolves when the child process exits
this.#childProcessExitPromise = new Promise<void>((resolve, reject) => {
this.#childProcessExitPromiseResolveFn = resolve;
this.#childProcessExitPromiseRejectFn = reject;
childProcess.stdout?.on('data', (data: Buffer) => {
this.#logger.terminal.write(data.toString());
});
childProcess.stderr?.on('data', (data: Buffer) => {
this.#logger.terminal.writeError(data.toString());
});
childProcess.on('close', (exitCode: number | null, signal: NodeJS.Signals | null): void => {
try {
// The 'close' event is emitted after a process has ended and the stdio streams of a child process
// have been closed. This is distinct from the 'exit' event, since multiple processes might share the
// same stdio streams. The 'close' event will always emit after 'exit' was already emitted,
// or 'error' if the child failed to spawn.
if (this.#state === State.Running) {
this.#logger.terminal.writeWarningLine(
`The service process #${childPid} terminated unexpectedly` +
this.#formatCodeOrSignal(exitCode, signal)
);
this.#transitionToStopped();
return;
}
if (this.#state === State.Stopping || this.#state === State.Killing) {
this.#logger.terminal.writeVerboseLine(
`The service process #${childPid} terminated successfully` +
this.#formatCodeOrSignal(exitCode, signal)
);
this.#transitionToStopped();
return;
}
} catch (e: unknown) {
reject(e);
}
});
childProcess.on('exit', (code: number | null, signal: string | null) => {
try {
// Under normal conditions we don't reject the promise here, because 'data' events can continue
// to fire as data is flushed, before finally concluding with the 'close' event.
this.#logger.terminal.writeVerboseLine(
`The service process fired its "exit" event` + this.#formatCodeOrSignal(code, signal)
);
} catch (e: unknown) {
reject(e);
}
});
childProcess.on('error', (err: Error) => {
try {
// "The 'error' event is emitted whenever:
// 1. The process could not be spawned, or
// 2. The process could not be killed, or
// 3. Sending a message to the child process failed.
//
// The 'exit' event may or may not fire after an error has occurred. When listening to both the 'exit'
// and 'error' events, guard against accidentally invoking handler functions multiple times."
if (this.#state === State.Running) {
this.#logger.terminal.writeErrorLine(`Failed to start: ` + err.toString());
this.#transitionToStopped();
return;
}
if (this.#state === State.Stopping) {
this.#logger.terminal.writeWarningLine(
`The service process #${childPid} rejected the shutdown signal: ` + err.toString()
);
this.#transitionToKilling();
return;
}
if (this.#state === State.Killing) {
this.#logger.terminal.writeErrorLine(
`The service process #${childPid} could not be killed: ` + err.toString()
);
this.#transitionToStopped();
return;
}
} catch (e: unknown) {
reject(e);
}
});
});
this.#activeChildProcess = childProcess;
}
#clearTimeout(): void {
if (this.#timeout) {
clearTimeout(this.#timeout);
this.#timeout = undefined;
}
}
#formatCodeOrSignal(
code: child_process.ChildProcess['exitCode'],
signal: string | child_process.ChildProcess['signalCode']
): string {
if (signal) {
return ` (signal=${code})`;
}
if (typeof code === 'number') {
return ` (exit code ${code})`;
}
return '';
}
}