import type { CommandDescriptor } from "@core/command"; import type { CommandIO } from "@core/command_io"; import { createErrorResult, createSuccessResult, type ResultError, type ResultSuccess } from "@core/result"; import type { ShellState } from "@core/shell_state"; import { SIGNAL_MAP, type Signal } from "@core/signal"; import type { ShellError, SignalTerminationError } from "@core/util/errors"; import { createImmutableBuffer } from "@core/util/immutable_buffer"; import { concatUint8Arrays, splitUint8Array } from "@termos/util/concat"; import { EventEmitter } from "./event_emitter"; import type { ShellEventMap } from "./shell"; export class Process { private _SignalQueue: Signal[] = []; private _SignalHandler: ((signal: Signal) => void) | null = null; private _StdoutChunks: Uint8Array[] = []; private _StderrChunks: Uint8Array[] = []; private _Settled: boolean = false; private _EventEmitter: EventEmitter; private readonly _MaxChunkByteSize: number; readonly PID: number; readonly Name: string; readonly CommandDescriptor: CommandDescriptor; readonly State: ShellState; readonly Args: string[]; constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, args: string[]) { this.PID = pid; this.State = state; this.Name = descriptor.name; this.CommandDescriptor = descriptor; this.Args = args; // Check if positive later and throw an error if so this._MaxChunkByteSize = 1024; this._EventEmitter = new EventEmitter(); } // WARNING, CHUNKING OUTPUT BREAKS FORMATING private writeToOutput(chunks: Uint8Array[], eventType: "stdout" | "stderr", data: Uint8Array): void { if (this._Settled) return; if (data.length <= this._MaxChunkByteSize) { chunks.push(data); this._EventEmitter.emit(eventType, { pid: this.PID, data }); return; } else { const arr = splitUint8Array(data, this._MaxChunkByteSize); for (const ent of arr) { chunks.push(ent); this._EventEmitter.emit(eventType, { pid: this.PID, data: ent }); } } } public execute(): void { const io: CommandIO = { writeStdout: (data: Uint8Array) => this.writeToOutput(this._StdoutChunks, "stdout", data), writeStderr: (data: Uint8Array) => this.writeToOutput(this._StderrChunks, "stderr", data), getSignal: () => { const signal: Signal | undefined = this._SignalQueue.shift(); if (signal !== undefined) return Promise.resolve(signal); const promise = new Promise(resolve => { this._SignalHandler = resolve; }); return promise; }, }; const promise = this.CommandDescriptor.fn(io, this.State, this.Args); promise .then(output => { if (this._Settled) return; let result: ResultSuccess | ResultError; const stdout: Uint8Array = concatUint8Arrays(this._StdoutChunks); const stderr: Uint8Array = concatUint8Arrays(this._StderrChunks); if (output.result.type === "success") { result = createSuccessResult( this.CommandDescriptor.name, 0, createImmutableBuffer(stdout), createImmutableBuffer(stderr), ); } else { result = { ...output.result, stdout: createImmutableBuffer(stdout), stderr: createImmutableBuffer(stderr), }; } this._EventEmitter.emit("result", { pid: this.PID, result, state: output.state }); this._Settled = true; }) .catch(error => { if (this._Settled) return; const result: ResultError = createErrorResult( "GenericError", "Promised output from command function rejected", {}, this.CommandDescriptor.name, undefined, undefined, { name: "Caught error", message: String(error), }, ); this._EventEmitter.emit("result", { pid: this.PID, result, state: this.State }); }); } public sendSignal(signal: Signal): void { if (this._Settled) return; const result: ResultError = createErrorResult( "SignalTermination", `Process ${this.Name}(${this.PID}) killed by a ${SIGNAL_MAP[signal.type]}(${signal.type})`, { signalNumber: signal.type, signalName: SIGNAL_MAP[signal.type] }, this.CommandDescriptor.name, ); switch (signal.type) { case SIGNAL_MAP.SIGKILL: this._SignalHandler = null; this._Settled = true; this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State }); return; case SIGNAL_MAP.SIGTERM: if (this._SignalHandler !== null) { this._SignalHandler(signal); this._SignalHandler = null; } this._Settled = true; this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State }); return; case SIGNAL_MAP.SIGINT: if (this._SignalHandler !== null) { this._SignalHandler(signal); this._SignalHandler = null; } this._Settled = true; this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State }); return; default: if (this._SignalHandler !== null) { this._SignalHandler(signal); this._SignalHandler = null; } else { this._SignalQueue.push(signal); } } } public on(type: K, handler: (payload: ShellEventMap[K]) => void): () => void { return this._EventEmitter.on(type, handler); } public once(type: K, handler: (payload: ShellEventMap[K]) => void): () => void { return this._EventEmitter.once(type, handler); } public off(type: K, handler: (payload: ShellEventMap[K]) => void): void { this._EventEmitter.off(type, handler); } }