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 { namespace Termos {
export function init(config: Partial<TermosConfig>) { export function init(config: Partial<TermosConfig>) {
config = { ...defaultConfig, ...config}; config = { ...defaultConfig, ...config };
console.log("termos initialized"); console.log("termos initialized");
} }
} }
@@ -13,3 +13,6 @@ const message: string = "Hello, World!";
console.log(message); console.log(message);
export { Termos }; export { Termos };
const value = () => {};
value();
+7 -7
View File
@@ -1,26 +1,26 @@
export class EventEmitter<TEvents> { 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 { 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) { if (listeners) {
listeners.add(handler); listeners.add(handler);
} else { } else {
const set: Set<Function> = new Set(); const set: Set<Function> = new Set();
set.add(handler); set.add(handler);
this.handlers.set(type, set); this.Handlers.set(type, set);
} }
return (): void => this.off(type, handler); return (): void => this.off(type, handler);
} }
public off<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): void { 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 { 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]) => { const wrapper = (payload: TEvents[K]) => {
handler(payload); handler(payload);
@@ -32,14 +32,14 @@ export class EventEmitter<TEvents> {
} else { } else {
const set: Set<Function> = new Set(); const set: Set<Function> = new Set();
set.add(wrapper); set.add(wrapper);
this.handlers.set(type, set); this.Handlers.set(type, set);
} }
return (): void => this.off(type, wrapper); return (): void => this.off(type, wrapper);
} }
public emit<K extends keyof TEvents>(type: K, payload: TEvents[K]): void { 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) { if (listeners) {
for (const listener of [...listeners]) { for (const listener of [...listeners]) {
+55 -54
View File
@@ -9,29 +9,29 @@ import { EventEmitter } from "./event_emitter";
import type { ShellEventMap } from "./shell"; import type { ShellEventMap } from "./shell";
export class Process { export class Process {
private signalQueue: Signal[] = []; private _SignalQueue: Signal[] = [];
private signalHandler: ((signal: Signal) => void) | null = null; private _SignalHandler: ((signal: Signal) => void) | null = null;
private stdoutChunks: Uint8Array[] = []; private _StdoutChunks: Uint8Array[] = [];
private stderrChunks: Uint8Array[] = []; private _StderrChunks: Uint8Array[] = [];
private settled: boolean = false; private _Settled: boolean = false;
private readonly maxChunkByteSize: number; private readonly _MaxChunkByteSize: number;
readonly pid: number; readonly PID: number;
readonly commandDescriptor: CommandDescriptor; readonly CommandDescriptor: CommandDescriptor;
readonly state: ShellState; readonly State: ShellState;
readonly args: string[]; readonly Args: string[];
readonly flags: string[]; readonly Flags: string[];
events: EventEmitter<ShellEventMap>; EventEmitter: EventEmitter<ShellEventMap>;
constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]) { constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]) {
this.pid = pid; this.PID = pid;
this.state = state; this.State = state;
this.commandDescriptor = descriptor; this.CommandDescriptor = descriptor;
this.flags = flags; this.Flags = flags;
this.args = args; this.Args = args;
// Check if positive later and throw an error if so // Check if positive later and throw an error if so
this.maxChunkByteSize = 1024; this._MaxChunkByteSize = 1024;
this.events = new EventEmitter<ShellEventMap>(); this.EventEmitter = new EventEmitter<ShellEventMap>();
} }
private concatUint8Arrays(arrays: Uint8Array[]): Uint8Array { private concatUint8Arrays(arrays: Uint8Array[]): Uint8Array {
@@ -49,12 +49,12 @@ export class Process {
// Tested // Tested
private divideToChunks(data: Uint8Array): Uint8Array[] { 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[] = []; const chunks: Uint8Array[] = [];
for (let i = 0; i < nChunks; i++) { for (let i = 0; i < nChunks; i++) {
const start = this.maxChunkByteSize * i; const start = this._MaxChunkByteSize * i;
const end = this.maxChunkByteSize * (i + 1); const end = this._MaxChunkByteSize * (i + 1);
chunks.push(data.subarray(start, end)); chunks.push(data.subarray(start, end));
} }
@@ -63,49 +63,49 @@ export class Process {
} }
private writeToOutput(chunks: Uint8Array[], eventType: "stdout" | "stderr", data: Uint8Array): void { 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); chunks.push(data);
this.events.emit(eventType, { pid: this.pid, data }); this.EventEmitter.emit(eventType, { pid: this.PID, data });
return; return;
} else { } else {
const arr = this.divideToChunks(data); const arr = this.divideToChunks(data);
for (const ent of arr) { for (const ent of arr) {
chunks.push(ent); 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 = { const io: CommandIO = {
writeStdout: (data: Uint8Array) => this.writeToOutput(this.stdoutChunks, "stdout", data), writeStdout: (data: Uint8Array) => this.writeToOutput(this._StdoutChunks, "stdout", data),
writeStderr: (data: Uint8Array) => this.writeToOutput(this.stderrChunks, "stderr", data), writeStderr: (data: Uint8Array) => this.writeToOutput(this._StderrChunks, "stderr", data),
getSignal: () => { getSignal: () => {
const signal: Signal | undefined = this.signalQueue.shift(); const signal: Signal | undefined = this._SignalQueue.shift();
if (signal !== undefined) return Promise.resolve(signal); if (signal !== undefined) return Promise.resolve(signal);
const promise = new Promise<Signal>(resolve => { const promise = new Promise<Signal>(resolve => {
this.signalHandler = resolve; this._SignalHandler = resolve;
}); });
return promise; 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 promise
.then(output => { .then(output => {
if (this.settled) return; if (this._Settled) return;
let result: ResultSuccess | ResultError<ShellError>; let result: ResultSuccess | ResultError<ShellError>;
const stdout: Uint8Array = this.concatUint8Arrays(this.stdoutChunks); const stdout: Uint8Array = this.concatUint8Arrays(this._StdoutChunks);
const stderr: Uint8Array = this.concatUint8Arrays(this.stderrChunks); const stderr: Uint8Array = this.concatUint8Arrays(this._StderrChunks);
if (output.result.type === "success") { if (output.result.type === "success") {
result = createSuccessResult( result = createSuccessResult(
this.commandDescriptor.name, this.CommandDescriptor.name,
0, 0,
createImmutableBuffer(stdout), createImmutableBuffer(stdout),
createImmutableBuffer(stderr), createImmutableBuffer(stderr),
@@ -118,11 +118,11 @@ export class Process {
}; };
} }
this.events.emit("result", { pid: this.pid, result, state: output.state }); this.EventEmitter.emit("result", { pid: this.PID, result, state: output.state });
this.settled = true; this._Settled = true;
}) })
.catch(error => { .catch(error => {
if (this.settled) return; if (this._Settled) return;
const result: ResultError<ShellError> = createErrorResult( const result: ResultError<ShellError> = createErrorResult(
"GenericError", "GenericError",
@@ -130,44 +130,45 @@ export class Process {
{}, {},
createImmutableBuffer(new Uint8Array()), createImmutableBuffer(new Uint8Array()),
createImmutableBuffer(new Uint8Array()), createImmutableBuffer(new Uint8Array()),
this.commandDescriptor.name, this.CommandDescriptor.name,
{ {
name: "Caught error", name: "Caught error",
message: String(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 { public sendSignal(signal: Signal): void {
if (this.settled) return; if (this._Settled) return;
//Make global signals an enum later on
if (signal.type === "SIGKILL") { if (signal.type === "SIGKILL") {
if (this.signalHandler !== null) { if (this._SignalHandler !== null) {
this.signalHandler(signal); this._SignalHandler(signal);
this.signalHandler = null; this._SignalHandler = null;
} }
this.settled = true; this._Settled = true;
const result: ResultError<SignalTerminationError> = createErrorResult( const result: ResultError<SignalTerminationError> = createErrorResult(
"SignalTermination", "SignalTermination",
`Process ${this.pid} killed by signal sigkill`, `Process ${this.PID} killed by signal sigkill`,
{ signalNumber: 9, signalName: signal.type }, { signalNumber: 9, signalName: signal.type },
createImmutableBuffer(new Uint8Array()), createImmutableBuffer(new Uint8Array()),
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; return;
} else { } else {
if (this.signalHandler !== null) { if (this._SignalHandler !== null) {
this.signalHandler(signal); this._SignalHandler(signal);
this.signalHandler = null; this._SignalHandler = null;
} else { } 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"; import { parseCommand } from "@core/util/parser";
export class Shell { export class Shell {
static #instance: Shell; static #Instance: Shell;
static #promise: Promise<Shell> | null = null; static #Promise: Promise<Shell> | null = null;
private _state: Readonly<ShellState>; private _State: Readonly<ShellState>;
private constructor(state: ShellState) { private constructor(state: ShellState) {
this._state = Object.freeze(state); this._State = Object.freeze(state);
} }
static async init(initialState: ShellState): Promise<Shell> { static async init(initialState: ShellState): Promise<Shell> {
if (Shell.#instance) { if (Shell.#Instance) {
console.warn("Shell already initialized"); 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 { try {
Shell.#instance = new Shell(initialState); Shell.#Instance = new Shell(initialState);
return Shell.#instance; return Shell.#Instance;
} finally { } finally {
Shell.#promise = null; Shell.#Promise = null;
} }
})(); })();
return Shell.#promise; return Shell.#Promise;
} }
public async Execute(input: string): Promise<Result<ShellError>> { 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); const command = COMMAND_REGISTRY.get(parsed.command);
if (!command) if (!command)
@@ -72,7 +72,7 @@ export class Shell {
parsed.command, parsed.command,
) satisfies ResultError<CommandNotFoundError>; ) satisfies ResultError<CommandNotFoundError>;
if (command.requiresRoot && getCurrentSession(this._state).user.uid != 0) { if (command.requiresRoot && getCurrentSession(this._State).user.uid != 0) {
return createErrorResult( return createErrorResult(
"PermissionDenied", "PermissionDenied",
`Permission Denied`, `Permission Denied`,
@@ -83,28 +83,28 @@ export class Shell {
) satisfies ResultError<PermissionDeniedError>; ) satisfies ResultError<PermissionDeniedError>;
} }
const out = command.fn(this._state, parsed.flags, parsed.args); const out = command.fn(this._State, parsed.flags, parsed.args);
this._state = out.state; this._State = out.state;
if (out.result.type === "error") { if (out.result.type === "error") {
this._state = withExitCode(this._state, out.result.error.exitCode); this._State = withExitCode(this._State, out.result.error.exitCode);
} else { } else {
this._state = withExitCode(this._state, out.result.exitCode); this._State = withExitCode(this._State, out.result.exitCode);
} }
return out.result; return out.result;
} }
public get State(): Readonly<ShellState> { public get State(): Readonly<ShellState> {
return this._state; return this._State;
} }
public static get Instance(): Shell | undefined { 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."); console.error("Shell has not been initialised yet. Call `await Shell.init()` first.");
return; return;
} }
return Shell.#instance; return Shell.#Instance;
} }
} }