|
| 1 | +/** |
| 2 | + * Copyright 2024 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +import { ChildProcess, spawn } from 'child_process'; |
| 18 | +import terminate from 'terminate'; |
| 19 | +import { logger } from '../utils'; |
| 20 | + |
| 21 | +export type ProcessStatus = 'running' | 'stopped' | 'unconfigured'; |
| 22 | + |
| 23 | +export interface AppProcessStatus { |
| 24 | + status: ProcessStatus; |
| 25 | +} |
| 26 | + |
| 27 | +export interface ProcessManagerStartOptions { |
| 28 | + nonInteractive?: boolean; |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * Manages a child process. |
| 33 | + */ |
| 34 | +export class ProcessManager { |
| 35 | + private appProcess?: ChildProcess; |
| 36 | + private originalStdIn?: NodeJS.ReadStream; |
| 37 | + private _status: ProcessStatus = 'stopped'; |
| 38 | + private manualRestart = false; |
| 39 | + |
| 40 | + constructor( |
| 41 | + private readonly command: string, |
| 42 | + private readonly args: string[], |
| 43 | + private readonly env: NodeJS.ProcessEnv = {} |
| 44 | + ) {} |
| 45 | + |
| 46 | + /** |
| 47 | + * Starts the process. |
| 48 | + */ |
| 49 | + start(options?: ProcessManagerStartOptions): Promise<void> { |
| 50 | + return new Promise((resolve, reject) => { |
| 51 | + this._status = 'running'; |
| 52 | + this.appProcess = spawn(this.command, this.args, { |
| 53 | + env: { |
| 54 | + ...process.env, |
| 55 | + ...this.env, |
| 56 | + }, |
| 57 | + shell: process.platform === 'win32', |
| 58 | + }); |
| 59 | + |
| 60 | + if (!options?.nonInteractive) { |
| 61 | + this.originalStdIn = process.stdin; |
| 62 | + this.appProcess.stderr?.pipe(process.stderr); |
| 63 | + this.appProcess.stdout?.pipe(process.stdout); |
| 64 | + process.stdin?.pipe(this.appProcess.stdin!); |
| 65 | + } |
| 66 | + |
| 67 | + this.appProcess.on('error', (error): void => { |
| 68 | + logger.error(`Error in app process: ${error}`); |
| 69 | + this.cleanup(); |
| 70 | + reject(error); |
| 71 | + }); |
| 72 | + |
| 73 | + this.appProcess.on('exit', (code, signal) => { |
| 74 | + this.cleanup(); |
| 75 | + if (this.manualRestart) { |
| 76 | + this.manualRestart = false; |
| 77 | + return; |
| 78 | + } |
| 79 | + // If the process was killed by a signal, it's not an error in this context. |
| 80 | + if (code === 0 || signal) { |
| 81 | + resolve(); |
| 82 | + } else { |
| 83 | + reject(new Error(`app process exited with code ${code}`)); |
| 84 | + } |
| 85 | + }); |
| 86 | + }); |
| 87 | + } |
| 88 | + |
| 89 | + /** |
| 90 | + * Kills the currently-running process and starts a new one. |
| 91 | + */ |
| 92 | + async restart(options?: ProcessManagerStartOptions): Promise<void> { |
| 93 | + this.manualRestart = true; |
| 94 | + await this.kill(); |
| 95 | + this.start(options).catch(() => {}); |
| 96 | + } |
| 97 | + |
| 98 | + /** |
| 99 | + * Kills the currently-running process. |
| 100 | + */ |
| 101 | + kill(): Promise<void> { |
| 102 | + return new Promise((resolve) => { |
| 103 | + if (!this.appProcess || !this.appProcess.pid || this.appProcess.killed) { |
| 104 | + this._status = 'stopped'; |
| 105 | + resolve(); |
| 106 | + return; |
| 107 | + } |
| 108 | + |
| 109 | + // The 'exit' listener is set up in start() and will handle cleanup. |
| 110 | + this.appProcess.on('exit', () => { |
| 111 | + resolve(); |
| 112 | + }); |
| 113 | + |
| 114 | + terminate(this.appProcess.pid, 'SIGTERM', (err) => { |
| 115 | + if (err) { |
| 116 | + // This can happen if the process is already gone, which is fine. |
| 117 | + logger.debug(`Error during process termination: ${err.message}`); |
| 118 | + } |
| 119 | + resolve(); |
| 120 | + }); |
| 121 | + }); |
| 122 | + } |
| 123 | + |
| 124 | + status(): AppProcessStatus { |
| 125 | + return { |
| 126 | + status: this._status, |
| 127 | + }; |
| 128 | + } |
| 129 | + |
| 130 | + private cleanup() { |
| 131 | + if (this.originalStdIn) { |
| 132 | + process.stdin.unpipe(this.appProcess?.stdin!); |
| 133 | + this.originalStdIn = undefined; |
| 134 | + } |
| 135 | + if (this.appProcess) { |
| 136 | + this.appProcess.stdout?.unpipe(process.stdout); |
| 137 | + this.appProcess.stderr?.unpipe(process.stderr); |
| 138 | + } |
| 139 | + this.appProcess = undefined; |
| 140 | + this._status = 'stopped'; |
| 141 | + } |
| 142 | +} |
0 commit comments