| 64 | }) |
| 65 | }) |
| 66 | const spawn = async (socketPath: string, token: string, { args, command, id, options }: Request) => { |
| 67 | const stdio = await Promise.allSettled( |
| 68 | options.stdio.map((mode, fd) => mode === "pipe" ? connect(socketPath, token, id, fd) : mode) |
| 69 | ) |
| 70 | const values = stdio.map((result) => result.status === "fulfilled" ? result.value : undefined) |
| 71 | const sockets = values.filter((value) => value instanceof Net.Socket) |
| 72 | try { |
| 73 | const failure = stdio.find((result) => result.status === "rejected") |
| 74 | if (failure) throw failure.reason |
| 75 | // The command shares the file status flags of each socket, and libuv only |
| 76 | // makes fds 0 to 2 blocking |
| 77 | for (const socket of sockets) { |
| 78 | // A socket that has lost its handle is rejected by `spawn` |
| 79 | const errno = (socket as SocketWithHandle)._handle?.setBlocking(true) |
| 80 | if (errno) throw new Error(`setBlocking failed: ${Util.getSystemErrorName(errno)}`) |
| 81 | } |
| 82 | const child = ChildProcess.spawn(command, args, { ...options, stdio: values as Array<Net.Socket | "inherit"> }) |
| 83 | child.on("error", (error) => send({ _tag: "Error", id, error: serializeError(error) })) |
| 84 | child.on("spawn", () => send({ _tag: "Spawned", id, pid: child.pid })) |
| 85 | child.on("exit", (code, signal) => send({ _tag: "Exit", id, code, signal })) |
| 86 | } catch (error) { |
| 87 | send({ _tag: "Error", id, error: serializeError(error as NodeJS.ErrnoException) }) |
| 88 | } finally { |
| 89 | // The command holds its own copies of the sockets |
| 90 | for (const socket of sockets) socket.destroy() |
| 91 | } |
| 92 | } |
| 93 | // The application decides how to handle these. Once it has disconnected, |
| 94 | // the proxy process exits when its commands have exited. |
| 95 | process.on("SIGINT", () => {}) |