From 16a1805f25cbfc97598f353fdcd2ac3ae77561e8 Mon Sep 17 00:00:00 2001 From: hyperion Date: Thu, 20 Aug 2026 09:44:03 +0200 Subject: [PATCH] fixed naming convention and text casing to use CamelCase on class fields. Process manager implemented, not tested, needs integration with current shell implementation --- src/index.ts | 5 +- src/shell/event_emitter.ts | 14 ++--- src/shell/process.ts | 109 ++++++++++++++++++----------------- src/shell/process_manager.ts | 54 +++++++++++++++++ src/shell/shell.ts | 42 +++++++------- 5 files changed, 141 insertions(+), 83 deletions(-) create mode 100644 src/shell/process_manager.ts diff --git a/src/index.ts b/src/index.ts index 9fc19e0..2364573 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,7 +4,7 @@ let config: TermosConfig = { ...defaultConfig }; namespace Termos { export function init(config: Partial) { - config = { ...defaultConfig, ...config}; + config = { ...defaultConfig, ...config }; console.log("termos initialized"); } } @@ -13,3 +13,6 @@ const message: string = "Hello, World!"; console.log(message); export { Termos }; + +const value = () => {}; +value(); diff --git a/src/shell/event_emitter.ts b/src/shell/event_emitter.ts index bdce7c1..0ee26fe 100644 --- a/src/shell/event_emitter.ts +++ b/src/shell/event_emitter.ts @@ -1,26 +1,26 @@ export class EventEmitter { - private handlers: Map> = new Map(); + private Handlers: Map> = new Map(); public on(type: K, handler: (payload: TEvents[K]) => void): () => void { - const listeners = this.handlers.get(type); + const listeners = this.Handlers.get(type); if (listeners) { listeners.add(handler); } else { const set: Set = new Set(); set.add(handler); - this.handlers.set(type, set); + this.Handlers.set(type, set); } return (): void => this.off(type, handler); } public off(type: K, handler: (payload: TEvents[K]) => void): void { - this.handlers.get(type)?.delete(handler); + this.Handlers.get(type)?.delete(handler); } public once(type: K, handler: (payload: TEvents[K]) => void): () => void { - const listeners = this.handlers.get(type); + const listeners = this.Handlers.get(type); const wrapper = (payload: TEvents[K]) => { handler(payload); @@ -32,14 +32,14 @@ export class EventEmitter { } else { const set: Set = new Set(); set.add(wrapper); - this.handlers.set(type, set); + this.Handlers.set(type, set); } return (): void => this.off(type, wrapper); } public emit(type: K, payload: TEvents[K]): void { - const listeners = this.handlers.get(type); + const listeners = this.Handlers.get(type); if (listeners) { for (const listener of [...listeners]) { diff --git a/src/shell/process.ts b/src/shell/process.ts index 8be6c0b..683145b 100644 --- a/src/shell/process.ts +++ b/src/shell/process.ts @@ -9,29 +9,29 @@ 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 readonly maxChunkByteSize: number; + private _SignalQueue: Signal[] = []; + private _SignalHandler: ((signal: Signal) => void) | null = null; + private _StdoutChunks: Uint8Array[] = []; + private _StderrChunks: Uint8Array[] = []; + private _Settled: boolean = false; + private readonly _MaxChunkByteSize: number; - readonly pid: number; - readonly commandDescriptor: CommandDescriptor; - readonly state: ShellState; - readonly args: string[]; - readonly flags: string[]; - events: EventEmitter; + readonly PID: number; + readonly CommandDescriptor: CommandDescriptor; + readonly State: ShellState; + readonly Args: string[]; + readonly Flags: string[]; + EventEmitter: EventEmitter; 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; + 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(); + this._MaxChunkByteSize = 1024; + this.EventEmitter = new EventEmitter(); } private concatUint8Arrays(arrays: Uint8Array[]): Uint8Array { @@ -49,12 +49,12 @@ export class Process { // Tested private divideToChunks(data: Uint8Array): Uint8Array[] { - const nChunks: number = Math.ceil(data.length / this.maxChunkByteSize); + 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); + const start = this._MaxChunkByteSize * i; + const end = this._MaxChunkByteSize * (i + 1); chunks.push(data.subarray(start, end)); } @@ -63,49 +63,49 @@ export class Process { } private writeToOutput(chunks: Uint8Array[], eventType: "stdout" | "stderr", data: Uint8Array): void { - if (this.settled) return; + if (this._Settled) return; - if (data.length <= this.maxChunkByteSize) { + if (data.length <= this._MaxChunkByteSize) { chunks.push(data); - this.events.emit(eventType, { pid: this.pid, data }); + this.EventEmitter.emit(eventType, { pid: this.PID, data }); return; } else { const arr = this.divideToChunks(data); for (const ent of arr) { chunks.push(ent); - this.events.emit(eventType, { pid: this.pid, data: ent }); + this.EventEmitter.emit(eventType, { pid: this.PID, data: ent }); } } } - start(): void { + public execute(): void { const io: CommandIO = { - writeStdout: (data: Uint8Array) => this.writeToOutput(this.stdoutChunks, "stdout", data), - writeStderr: (data: Uint8Array) => this.writeToOutput(this.stderrChunks, "stderr", data), + 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(); + const signal: Signal | undefined = this._SignalQueue.shift(); if (signal !== undefined) return Promise.resolve(signal); const promise = new Promise(resolve => { - this.signalHandler = resolve; + this._SignalHandler = resolve; }); return promise; }, }; - const promise = this.commandDescriptor.fn(io, this.state, this.flags, this.args); + const promise = this.CommandDescriptor.fn(io, this.State, this.Flags, this.Args); promise .then(output => { - if (this.settled) return; + if (this._Settled) return; let result: ResultSuccess | ResultError; - const stdout: Uint8Array = this.concatUint8Arrays(this.stdoutChunks); - const stderr: Uint8Array = this.concatUint8Arrays(this.stderrChunks); + const stdout: Uint8Array = this.concatUint8Arrays(this._StdoutChunks); + const stderr: Uint8Array = this.concatUint8Arrays(this._StderrChunks); if (output.result.type === "success") { result = createSuccessResult( - this.commandDescriptor.name, + this.CommandDescriptor.name, 0, createImmutableBuffer(stdout), createImmutableBuffer(stderr), @@ -118,11 +118,11 @@ export class Process { }; } - this.events.emit("result", { pid: this.pid, result, state: output.state }); - this.settled = true; + this.EventEmitter.emit("result", { pid: this.PID, result, state: output.state }); + this._Settled = true; }) .catch(error => { - if (this.settled) return; + if (this._Settled) return; const result: ResultError = createErrorResult( "GenericError", @@ -130,44 +130,45 @@ export class Process { {}, createImmutableBuffer(new Uint8Array()), createImmutableBuffer(new Uint8Array()), - this.commandDescriptor.name, + this.CommandDescriptor.name, { name: "Caught error", message: String(error), }, ); - this.events.emit("result", { pid: this.pid, result, state: this.state }); + this.EventEmitter.emit("result", { pid: this.PID, result, state: this.State }); }); } - sendSignal(signal: Signal): void { - if (this.settled) return; + public sendSignal(signal: Signal): void { + if (this._Settled) return; + //Make global signals an enum later on if (signal.type === "SIGKILL") { - if (this.signalHandler !== null) { - this.signalHandler(signal); - this.signalHandler = null; + if (this._SignalHandler !== null) { + this._SignalHandler(signal); + this._SignalHandler = null; } - this.settled = true; + this._Settled = true; const result: ResultError = createErrorResult( "SignalTermination", - `Process ${this.pid} killed by signal sigkill`, + `Process ${this.PID} killed by signal sigkill`, { signalNumber: 9, signalName: signal.type }, createImmutableBuffer(new Uint8Array()), createImmutableBuffer(new Uint8Array()), - this.commandDescriptor.name, + this.CommandDescriptor.name, ); - this.events.emit("result", { pid: this.pid, result, state: this.state }); + this.EventEmitter.emit("result", { pid: this.PID, result, state: this.State }); return; } else { - if (this.signalHandler !== null) { - this.signalHandler(signal); - this.signalHandler = null; + if (this._SignalHandler !== null) { + this._SignalHandler(signal); + this._SignalHandler = null; } else { - this.signalQueue.push(signal); + this._SignalQueue.push(signal); } } } diff --git a/src/shell/process_manager.ts b/src/shell/process_manager.ts new file mode 100644 index 0000000..4bcb65f --- /dev/null +++ b/src/shell/process_manager.ts @@ -0,0 +1,54 @@ +import type { CommandDescriptor } from "@core/command"; +import type { ShellState } from "@core/shell_state"; +import type { Signal } from "@core/signal"; +import { EventEmitter } from "./event_emitter"; +import { Process } from "./process"; +import type { ShellEventMap } from "./shell"; + +export class ProcessManager { + private _Processes: Map = new Map(); + private _PIDIndex: number = 0; + + EventEmitter: EventEmitter = new EventEmitter(); + + public createProcess(state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]): void { + const pid = ++this._PIDIndex; + const process = new Process(pid, state, descriptor, flags, args); + this._Processes.set(pid, process); + + process.EventEmitter.on("stdout", payload => this.EventEmitter.emit("stdout", payload)); + process.EventEmitter.on("stderr", payload => this.EventEmitter.emit("stderr", payload)); + process.EventEmitter.on("result", payload => { + this._Processes.delete(payload.pid); + this.EventEmitter.emit("result", payload); + }); + + this.EventEmitter.emit("process", { pid, name: descriptor.name }); + process.execute(); + } + + public sendSignal(pid: number, signal: Signal): void { + const process = this._Processes.get(pid); + + if (!process) { + //Implement a proper error object later to return to shell + console.error("PID not found"); + return; + } + + process.sendSignal(signal); + } + + public kill(pid: number): void { + const process = this._Processes.get(pid); + + if (!process) { + //Implement a proper error object later to return to shell + console.error("PID not found"); + return; + } + + //Make global signals an enum later + process.sendSignal({ type: "SIGKILL" } satisfies Signal); + } +} diff --git a/src/shell/shell.ts b/src/shell/shell.ts index f651790..818c826 100644 --- a/src/shell/shell.ts +++ b/src/shell/shell.ts @@ -7,32 +7,32 @@ import { createImmutableBuffer } from "@core/util/immutable_buffer"; import { parseCommand } from "@core/util/parser"; export class Shell { - static #instance: Shell; - static #promise: Promise | null = null; - private _state: Readonly; + static #Instance: Shell; + static #Promise: Promise | null = null; + private _State: Readonly; private constructor(state: ShellState) { - this._state = Object.freeze(state); + this._State = Object.freeze(state); } static async init(initialState: ShellState): Promise { - if (Shell.#instance) { + if (Shell.#Instance) { console.warn("Shell already initialized"); - return this.#instance; + return this.#Instance; } - if (Shell.#promise) return Shell.#promise; + if (Shell.#Promise) return Shell.#Promise; - Shell.#promise = (async () => { + Shell.#Promise = (async () => { try { - Shell.#instance = new Shell(initialState); - return Shell.#instance; + Shell.#Instance = new Shell(initialState); + return Shell.#Instance; } finally { - Shell.#promise = null; + Shell.#Promise = null; } })(); - return Shell.#promise; + return Shell.#Promise; } public async Execute(input: string): Promise> { @@ -59,7 +59,7 @@ export class Shell { ); } - this._state = withHistory(this._state, input); + this._State = withHistory(this._State, input); const command = COMMAND_REGISTRY.get(parsed.command); if (!command) @@ -72,7 +72,7 @@ export class Shell { parsed.command, ) satisfies ResultError; - if (command.requiresRoot && getCurrentSession(this._state).user.uid != 0) { + if (command.requiresRoot && getCurrentSession(this._State).user.uid != 0) { return createErrorResult( "PermissionDenied", `Permission Denied`, @@ -83,28 +83,28 @@ export class Shell { ) satisfies ResultError; } - const out = command.fn(this._state, parsed.flags, parsed.args); - this._state = out.state; + const out = command.fn(this._State, parsed.flags, parsed.args); + this._State = out.state; if (out.result.type === "error") { - this._state = withExitCode(this._state, out.result.error.exitCode); + this._State = withExitCode(this._State, out.result.error.exitCode); } else { - this._state = withExitCode(this._state, out.result.exitCode); + this._State = withExitCode(this._State, out.result.exitCode); } return out.result; } public get State(): Readonly { - return this._state; + return this._State; } public static get Instance(): Shell | undefined { - if (!Shell.#instance) { + if (!Shell.#Instance) { console.error("Shell has not been initialised yet. Call `await Shell.init()` first."); return; } - return Shell.#instance; + return Shell.#Instance; } }