fixed naming convention and text casing to use CamelCase on class fields. Process manager implemented, not tested, needs integration with current shell implementation

This commit is contained in:
2026-08-20 09:44:03 +02:00
parent 075c999435
commit 16a1805f25
5 changed files with 141 additions and 83 deletions
+4 -1
View File
@@ -4,7 +4,7 @@ let config: TermosConfig = { ...defaultConfig };
namespace Termos {
export function init(config: Partial<TermosConfig>) {
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();
+7 -7
View File
@@ -1,26 +1,26 @@
export class EventEmitter<TEvents> {
private handlers: Map<keyof TEvents, Set<Function>> = new Map();
private Handlers: Map<keyof TEvents, Set<Function>> = new Map();
public on<K extends keyof TEvents>(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<Function> = new Set();
set.add(handler);
this.handlers.set(type, set);
this.Handlers.set(type, set);
}
return (): void => this.off(type, handler);
}
public off<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): void {
this.handlers.get(type)?.delete(handler);
this.Handlers.get(type)?.delete(handler);
}
public once<K extends keyof TEvents>(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<TEvents> {
} else {
const set: Set<Function> = new Set();
set.add(wrapper);
this.handlers.set(type, set);
this.Handlers.set(type, set);
}
return (): void => this.off(type, wrapper);
}
public emit<K extends keyof TEvents>(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]) {
+55 -54
View File
@@ -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<ShellEventMap>;
readonly PID: number;
readonly CommandDescriptor: CommandDescriptor;
readonly State: ShellState;
readonly Args: string[];
readonly Flags: string[];
EventEmitter: EventEmitter<ShellEventMap>;
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<ShellEventMap>();
this._MaxChunkByteSize = 1024;
this.EventEmitter = new EventEmitter<ShellEventMap>();
}
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<Signal>(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<ShellError>;
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<ShellError> = 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<SignalTerminationError> = 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);
}
}
}
+54
View File
@@ -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<number, Process> = new Map();
private _PIDIndex: number = 0;
EventEmitter: EventEmitter<ShellEventMap> = 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);
}
}
+21 -21
View File
@@ -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<Shell> | null = null;
private _state: Readonly<ShellState>;
static #Instance: Shell;
static #Promise: Promise<Shell> | null = null;
private _State: Readonly<ShellState>;
private constructor(state: ShellState) {
this._state = Object.freeze(state);
this._State = Object.freeze(state);
}
static async init(initialState: ShellState): Promise<Shell> {
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<Result<ShellError>> {
@@ -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<CommandNotFoundError>;
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<PermissionDeniedError>;
}
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<ShellState> {
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;
}
}