"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ForkedProcessTaskRunner = void 0;
const fs_1 = require("fs");
const child_process_1 = require("child_process");
const output_1 = require("../utils/output");
const utils_1 = require("./utils");
const path_1 = require("path");
const batch_messages_1 = require("./batch/batch-messages");
const strip_indents_1 = require("../utils/strip-indents");
const pseudo_terminal_1 = require("./pseudo-terminal");
const exit_codes_1 = require("../utils/exit-codes");
const node_child_process_1 = require("./running-tasks/node-child-process");
const batch_process_1 = require("./running-tasks/batch-process");
const forkScript = (0, path_1.join)(__dirname, './fork.js');
const workerPath = (0, path_1.join)(__dirname, './batch/run-batch.js');
class ForkedProcessTaskRunner {
    constructor(options) {
        this.options = options;
        this.cliPath = (0, utils_1.getCliPath)();
        this.verbose = process.env.NX_VERBOSE_LOGGING === 'true';
        this.processes = new Set();
        this.pseudoTerminal = pseudo_terminal_1.PseudoTerminal.isSupported()
            ? (0, pseudo_terminal_1.getPseudoTerminal)()
            : null;
    }
    async init() {
        if (this.pseudoTerminal) {
            await this.pseudoTerminal.init();
        }
        this.setupProcessEventListeners();
    }
    // TODO: vsavkin delegate terminal output printing
    async forkProcessForBatch({ executorName, taskGraph: batchTaskGraph }, fullTaskGraph, env) {
        const count = Object.keys(batchTaskGraph.tasks).length;
        if (count > 1) {
            output_1.output.logSingleLine(`Running ${output_1.output.bold(count)} ${output_1.output.bold('tasks')} with ${output_1.output.bold(executorName)}`);
        }
        else {
            const args = (0, utils_1.getPrintableCommandArgsForTask)(Object.values(batchTaskGraph.tasks)[0]);
            output_1.output.logCommand(args.join(' '));
        }
        const p = (0, child_process_1.fork)(workerPath, {
            stdio: ['inherit', 'inherit', 'inherit', 'ipc'],
            env,
        });
        const cp = new batch_process_1.BatchProcess(p, executorName);
        this.processes.add(cp);
        cp.onExit(() => {
            this.processes.delete(cp);
        });
        // Start the tasks
        cp.send({
            type: batch_messages_1.BatchMessageType.RunTasks,
            executorName,
            batchTaskGraph,
            fullTaskGraph,
        });
        return cp;
    }
    async forkProcessLegacy(task, { temporaryOutputPath, streamOutput, pipeOutput, taskGraph, env, }) {
        return pipeOutput
            ? this.forkProcessWithPrefixAndNotTTY(task, {
                temporaryOutputPath,
                streamOutput,
                taskGraph,
                env,
            })
            : this.forkProcessDirectOutputCapture(task, {
                temporaryOutputPath,
                streamOutput,
                taskGraph,
                env,
            });
    }
    async forkProcess(task, { temporaryOutputPath, streamOutput, taskGraph, env, disablePseudoTerminal, }) {
        const shouldPrefix = streamOutput && process.env.NX_PREFIX_OUTPUT === 'true';
        // streamOutput would be false if we are running multiple targets
        // there's no point in running the commands in a pty if we are not streaming the output
        if (!this.pseudoTerminal ||
            disablePseudoTerminal ||
            !streamOutput ||
            shouldPrefix) {
            return this.forkProcessWithPrefixAndNotTTY(task, {
                temporaryOutputPath,
                streamOutput,
                taskGraph,
                env,
            });
        }
        else {
            return this.forkProcessWithPseudoTerminal(task, {
                temporaryOutputPath,
                streamOutput,
                taskGraph,
                env,
            });
        }
    }
    async forkProcessWithPseudoTerminal(task, { temporaryOutputPath, streamOutput, taskGraph, env, }) {
        const args = (0, utils_1.getPrintableCommandArgsForTask)(task);
        if (streamOutput) {
            output_1.output.logCommand(args.join(' '));
        }
        const childId = task.id;
        const p = await this.pseudoTerminal.fork(childId, forkScript, {
            cwd: process.cwd(),
            execArgv: process.execArgv,
            jsEnv: env,
            quiet: !streamOutput,
        });
        p.send({
            targetDescription: task.target,
            overrides: task.overrides,
            taskGraph,
            isVerbose: this.verbose,
        });
        this.processes.add(p);
        let terminalOutput = '';
        p.onOutput((msg) => {
            terminalOutput += msg;
        });
        p.onExit((code) => {
            if (code > 128) {
                process.exit(code);
            }
            this.processes.delete(p);
            this.writeTerminalOutput(temporaryOutputPath, terminalOutput);
        });
        return p;
    }
    forkProcessWithPrefixAndNotTTY(task, { streamOutput, temporaryOutputPath, taskGraph, env, }) {
        try {
            const args = (0, utils_1.getPrintableCommandArgsForTask)(task);
            if (streamOutput) {
                output_1.output.logCommand(args.join(' '));
            }
            const p = (0, child_process_1.fork)(this.cliPath, {
                stdio: ['inherit', 'pipe', 'pipe', 'ipc'],
                env,
            });
            // Send message to run the executor
            p.send({
                targetDescription: task.target,
                overrides: task.overrides,
                taskGraph,
                isVerbose: this.verbose,
            });
            const cp = new node_child_process_1.NodeChildProcessWithNonDirectOutput(p, {
                streamOutput,
                prefix: task.target.project,
            });
            this.processes.add(cp);
            cp.onExit((code, terminalOutput) => {
                this.processes.delete(cp);
                if (!streamOutput) {
                    this.options.lifeCycle.printTaskTerminalOutput(task, code === 0 ? 'success' : 'failure', terminalOutput);
                }
                this.writeTerminalOutput(temporaryOutputPath, terminalOutput);
            });
            return cp;
        }
        catch (e) {
            console.error(e);
            throw e;
        }
    }
    forkProcessDirectOutputCapture(task, { streamOutput, temporaryOutputPath, taskGraph, env, }) {
        try {
            const args = (0, utils_1.getPrintableCommandArgsForTask)(task);
            if (streamOutput) {
                output_1.output.logCommand(args.join(' '));
            }
            const p = (0, child_process_1.fork)(this.cliPath, {
                stdio: ['inherit', 'inherit', 'inherit', 'ipc'],
                env,
            });
            const cp = new node_child_process_1.NodeChildProcessWithDirectOutput(p, temporaryOutputPath);
            this.processes.add(cp);
            // Send message to run the executor
            p.send({
                targetDescription: task.target,
                overrides: task.overrides,
                taskGraph,
                isVerbose: this.verbose,
            });
            cp.onExit((code, signal) => {
                this.processes.delete(cp);
                // we didn't print any output as we were running the command
                // print all the collected output
                try {
                    const terminalOutput = cp.getTerminalOutput();
                    if (!streamOutput) {
                        this.options.lifeCycle.printTaskTerminalOutput(task, code === 0 ? 'success' : 'failure', terminalOutput);
                    }
                }
                catch (e) {
                    console.log((0, strip_indents_1.stripIndents) `
              Unable to print terminal output for Task "${task.id}".
              Task failed with Exit Code ${code} and Signal "${signal}".

              Received error message:
              ${e.message}
            `);
                }
            });
            return cp;
        }
        catch (e) {
            console.error(e);
            throw e;
        }
    }
    writeTerminalOutput(outputPath, content) {
        (0, fs_1.writeFileSync)(outputPath, content);
    }
    setupProcessEventListeners() {
        if (this.pseudoTerminal) {
            this.pseudoTerminal.onMessageFromChildren((message) => {
                process.send(message);
            });
        }
        // When the nx process gets a message, it will be sent into the task's process
        process.on('message', (message) => {
            if (this.pseudoTerminal) {
                this.pseudoTerminal.sendMessageToChildren(message);
            }
            this.processes.forEach((p) => {
                if ('send' in p) {
                    p.send(message);
                }
            });
        });
        // Terminate any task processes on exit
        process.on('exit', () => {
            this.processes.forEach((p) => {
                p.kill();
            });
        });
        process.on('SIGINT', () => {
            this.processes.forEach((p) => {
                p.kill('SIGTERM');
            });
            // we exit here because we don't need to write anything to cache.
            process.exit((0, exit_codes_1.signalToCode)('SIGINT'));
        });
        process.on('SIGTERM', () => {
            this.processes.forEach((p) => {
                p.kill('SIGTERM');
            });
            // no exit here because we expect child processes to terminate which
            // will store results to the cache and will terminate this process
        });
        process.on('SIGHUP', () => {
            this.processes.forEach((p) => {
                p.kill('SIGTERM');
            });
            // no exit here because we expect child processes to terminate which
            // will store results to the cache and will terminate this process
        });
    }
}
exports.ForkedProcessTaskRunner = ForkedProcessTaskRunner;
