diff --git a/package-lock.json b/package-lock.json index bdef4db..0cef11b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1567,10 +1567,20 @@ "license": "MIT" }, "node_modules/deepmerge-ts": { - "version": "7.1.5", - "resolved": "https://registry.npmjs.org/deepmerge-ts/-/deepmerge-ts-7.1.5.tgz", - "integrity": "sha512-HOJkrhaYsweh+W+e74Yn7YStZOilkoPb6fycpwNLKzSPtruFs48nYis0zy5yJz1+ktUhHxoRDJ27RQAWLIJVJw==", + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/deepmerge-ts/-/deepmerge-ts-7.1.6.tgz", + "integrity": "sha512-gQhL1ksGBLQbHeAo47YU6cs2ahd3Pv+8PFYoWogNZbQnNwQyOh9Ad5kbeHFiWwbKdeWQJ5Z7Y7mwb9ew2hXBLw==", "dev": true, + "funding": [ + { + "type": "ko-fi", + "url": "https://ko-fi.com/rebeccastevens" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/deepmerge-ts" + } + ], "license": "BSD-3-Clause", "engines": { "node": ">=16.0.0" diff --git a/src/core/command.ts b/src/core/command.ts index 644d318..da9d6b7 100644 --- a/src/core/command.ts +++ b/src/core/command.ts @@ -8,7 +8,7 @@ export type CommandFn = ( state: ShellState, flags: string[], args: string[], -) => CommandOutput; +) => Promise>; export interface CommandDescriptor { fn: CommandFn; diff --git a/src/core/util/errors.ts b/src/core/util/errors.ts index f42370e..4a77954 100644 --- a/src/core/util/errors.ts +++ b/src/core/util/errors.ts @@ -18,7 +18,7 @@ export function createShellError( let exitCode = EXIT_CODE_MAP[errorType] ?? 1; // Special handling for signal termination - if (errorType === "SIGNAL_TERMINATION") { + if (errorType === "SignalTermination") { const signalError = extraProps as unknown as { signalNumber: number }; exitCode = 128 + signalError.signalNumber; } diff --git a/src/shell/process.ts b/src/shell/process.ts index f2c0be5..8be6c0b 100644 --- a/src/shell/process.ts +++ b/src/shell/process.ts @@ -1,47 +1,174 @@ -import type { CommandFn } from "@core/command"; -import type { ProcessContext } from "@core/command_io"; +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 type { Signal } from "@core/signal"; -import type { EventEmitter } from "./event_emitter"; +import type { ShellError, SignalTerminationError } from "@core/util/errors"; +import { createImmutableBuffer } from "@core/util/immutable_buffer"; +import { EventEmitter } from "./event_emitter"; import type { ShellEventMap } from "./shell"; export class Process { - private signalQueue: Signal[]; - private signalHandler: ((signal: Signal) => void) | null; - private stdoutChunks: Uint8Array[]; - private stderrChunks: Uint8Array[]; - private settled: boolean; + private signalQueue: Signal[] = []; + private signalHandler: ((signal: Signal) => void) | null = null; + private stdoutChunks: Uint8Array[] = []; + private stderrChunks: Uint8Array[] = []; + private settled: boolean = false; private readonly maxChunkByteSize: number; - pid: number; - name: string; - commandFn: CommandFn; - state: ShellState; - args: string[]; - flags: string[]; + readonly pid: number; + readonly commandDescriptor: CommandDescriptor; + readonly state: ShellState; + readonly args: string[]; + readonly flags: string[]; events: EventEmitter; - constructor() { + constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]) { + this.pid = pid; + this.state = state; + this.commandDescriptor = descriptor; + this.flags = flags; + this.args = args; + // Check if positive later and throw an error if so this.maxChunkByteSize = 1024; + this.events = new EventEmitter(); } - private divideToChunks(data: Uint8Array): Uint8Array[] {} + private concatUint8Arrays(arrays: Uint8Array[]): Uint8Array { + const size = arrays.reduce((sum, arr) => sum + arr.length, 0); + const result = new Uint8Array(size); + + let offset = 0; + for (const arr of arrays) { + result.set(arr, offset); + offset += arr.length; + } + + return result; + } + + // Tested + private divideToChunks(data: Uint8Array): Uint8Array[] { + const nChunks: number = Math.ceil(data.length / this.maxChunkByteSize); + const chunks: Uint8Array[] = []; + + for (let i = 0; i < nChunks; i++) { + const start = this.maxChunkByteSize * i; + const end = this.maxChunkByteSize * (i + 1); + + chunks.push(data.subarray(start, end)); + } + + return chunks; + } private writeToOutput(chunks: Uint8Array[], eventType: "stdout" | "stderr", data: Uint8Array): void { - chunks.push(data); + if (this.settled) return; if (data.length <= this.maxChunkByteSize) { + chunks.push(data); this.events.emit(eventType, { pid: this.pid, data }); return; } else { - const chunk = data.slice(this.maxChunkByteSize); + const arr = this.divideToChunks(data); + for (const ent of arr) { + chunks.push(ent); + this.events.emit(eventType, { pid: this.pid, data: ent }); + } } } - private chunkData(data: Uint8Array): Uint8Array[] {} - start(): void { - const context: ProcessContext = { - writeStdout: data => this.writeOutput(data), + 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.flags, this.args); + + promise + .then(output => { + if (this.settled) return; + + let result: ResultSuccess | ResultError; + const stdout: Uint8Array = this.concatUint8Arrays(this.stdoutChunks); + const stderr: Uint8Array = this.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.events.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", + {}, + createImmutableBuffer(new Uint8Array()), + createImmutableBuffer(new Uint8Array()), + this.commandDescriptor.name, + { + name: "Caught error", + message: String(error), + }, + ); + + this.events.emit("result", { pid: this.pid, result, state: this.state }); + }); + } + + sendSignal(signal: Signal): void { + if (this.settled) return; + + if (signal.type === "SIGKILL") { + if (this.signalHandler !== null) { + this.signalHandler(signal); + this.signalHandler = null; + } + + this.settled = true; + const result: ResultError = createErrorResult( + "SignalTermination", + `Process ${this.pid} killed by signal sigkill`, + { signalNumber: 9, signalName: signal.type }, + createImmutableBuffer(new Uint8Array()), + createImmutableBuffer(new Uint8Array()), + this.commandDescriptor.name, + ); + + this.events.emit("result", { pid: this.pid, result, state: this.state }); + return; + } else { + if (this.signalHandler !== null) { + this.signalHandler(signal); + this.signalHandler = null; + } else { + this.signalQueue.push(signal); + } + } } } diff --git a/test/shell/process.test.ts b/test/shell/process.test.ts new file mode 100644 index 0000000..b51cadb --- /dev/null +++ b/test/shell/process.test.ts @@ -0,0 +1,29 @@ +import { expect, test } from "vitest"; + +function divideToChunks(data: Uint8Array): Uint8Array[] { + const nChunks: number = Math.ceil(data.length / 1024); + + const chunks: Uint8Array[] = []; + for (let i = 0; i < nChunks; i++) { + const start = 1024 * i; + const end = 1024 * (i + 1); + + chunks.push(data.slice(start, end)); + } + + console.log(chunks.length); + + return chunks; +} + +test("divide to chunks", () => { + const data: Uint8Array = new Uint8Array(2048); + const result: Uint8Array[] = divideToChunks(data); + expect(result.length).toEqual(2); +}); + +test("divide to chunks", () => { + const data: Uint8Array = new Uint8Array(2049); + const result = divideToChunks(data); + expect(result.length).toEqual(3); +});