Fix bridge SIGTERM handling

This commit is contained in:
hensm
2022-09-20 15:48:37 +01:00
parent cc7641da03
commit 72d82987f3
2 changed files with 29 additions and 12 deletions

View File

@@ -179,7 +179,11 @@ export async function startMediaServer(filePath: string, port: number) {
export function stopMediaServer() {
return new Promise<void>((resolve, reject) => {
if (mediaServer?.listening) {
if (!mediaServer?.listening) {
resolve();
return;
}
mediaServer.close(err => {
if (err) {
reject();
@@ -189,6 +193,5 @@ export function stopMediaServer() {
});
mediaServer = undefined;
}
});
}

View File

@@ -1,12 +1,22 @@
import http from "http";
import https from "https";
import { spawn } from "child_process";
import { ChildProcess, spawn } from "child_process";
import { Readable } from "stream";
import WebSocket from "ws";
import { DecodeTransform, EncodeTransform } from "./transforms.js";
const bridgeInstances = new Set<ChildProcess>();
// Ensure child processes are killed on exit
process.on("SIGTERM", async () => {
for (const bridge of bridgeInstances) {
bridge.kill();
}
process.exit(1);
});
export interface DaemonOpts {
host: string;
port: number;
@@ -46,6 +56,7 @@ export function init(opts: DaemonOpts) {
* version of self in bridge mode.
*/
const bridge = spawn(process.execPath, [process.argv[1]]);
bridgeInstances.add(bridge);
// socket -> bridge.stdin
messageStream.pipe(new EncodeTransform()).pipe(bridge.stdin);
@@ -61,7 +72,10 @@ export function init(opts: DaemonOpts) {
// Handle termination
socket.on("close", () => bridge.kill());
bridge.on("exit", () => socket.close());
bridge.on("exit", () => {
socket.close();
bridgeInstances.delete(bridge);
});
});
/**