a lot of mess, keep working on VDisk for now.

This commit is contained in:
2026-09-17 10:32:31 +02:00
parent 9c5bd71a5c
commit 849e0e61f5
20 changed files with 839 additions and 259 deletions
+38 -20
View File
@@ -1,7 +1,7 @@
import { getCurrentSession } from "@core/session_manager";
import type { ShellState } from "@core/shell_state";
import type { NodeNotFoundError, NotADirectoryError } from "../filesystem/errors";
import { TreeNodeType, type DirectoryNode, type TreeNode } from "../filesystem/treenode";
import { TreeNodeType, type DirectoryNode, type NodeEntry, type NodePointer, type TreeNode } from "../filesystem/node";
/*
/home/grzegorz/Documents/homework
@@ -9,29 +9,55 @@ import { TreeNodeType, type DirectoryNode, type TreeNode } from "../filesystem/t
""
*/
export function resolvePath(state: ShellState, path: string): string {
export function resolvePath(state: ShellState, path: string): NodeEntry {
const session = getCurrentSession(state);
const isAbsolute = path.startsWith("/"); // true
const normalizedPath: string = path.replace(/^\/+|\/+$/g, ""); // home/grzegorz/Documents/homework
const pathComponents: string[] = normalizedPath.split("/").filter(name => name.length > 0); // ["home", "grzegorz", "Documents", "homework"]
let currentVD: number = state.filesystem.getSysPartitionID();
// Fix to dynamically get the root inode VV
if (pathComponents.length === 0 && isAbsolute) return 0;
if (pathComponents.length === 0 && isAbsolute) return [0, currentVD];
// Move behaviour into cd built-in
if (pathComponents.length === 0) return session.cwd;
if (pathComponents.length === 0) return [session.cwd, currentVD];
let currentNode =
isAbsolute === true ? state.filesystem.getRoot() : (state.filesystem.getNode(session.cwd) as DirectoryNode);
let currentNode = isAbsolute === true ? state.filesystem.getRoot() : state.filesystem.getNode(session.cwd)!;
if (!currentNode) return -1;
if (!currentNode) {
throw Error("Current working directory does not exist in the filesystem! Is the userdata corrupted?");
}
for (let i = 0; i < pathComponents.length; i++) {
// Null assertion because by this point the array cannot be empty
const name: string = pathComponents[i]!;
if (name === ".") continue;
if (name === "..") {
currentNode = state.filesystem.getNode(currentNode.parent) as DirectoryNode;
if (state.filesystem.isFile(currentNode.inode) && !(i === pathComponents.length - 1))
throw {
type: "NotADirectory",
message: `${name} is not a directory`,
timestamp: Date.now(),
inode: currentNode.inode,
nodeType: TreeNodeType.File,
} satisfies NotADirectoryError;
if (currentNode.type === TreeNodeType.Device) {
currentVD = currentNode.target_id;
continue;
}
if (currentNode.type === TreeNodeType.Symlink) {
const ptr: NodePointer = resolvePath(state, currentNode.target);
currentNode = state.filesystem.getNode(ptr)!;
if (!currentNode) {
throw {
type: "NodeNotFound",
message: `${name} not found`,
timestamp: Date.now(),
inode: ptr[0],
} satisfies NodeNotFoundError;
}
continue;
}
@@ -45,23 +71,15 @@ export function resolvePath(state: ShellState, path: string): string {
if (!inode)
throw {
type: "NodeNotFound",
message: `Child node in ${currentNode.name} under name ${name} not found`,
message: `${name} not found`,
timestamp: Date.now(),
inode: currentNode.inode,
} satisfies NodeNotFoundError;
if (state.filesystem.isFile(inode) && !(i === pathComponents.length - 1))
throw {
type: "NotADirectory",
message: `Child node ${name} is not a directory`,
timestamp: Date.now(),
inode: inode,
nodeType: TreeNodeType.File,
} satisfies NotADirectoryError;
currentNode = state.filesystem.getNode(inode) as DirectoryNode;
}
return currentNode.inode;
return [currentNode.inode, currentVD];
}
export function resolveInode(state: ShellState, inode: number): string {
+1 -1
View File
@@ -1,4 +1,4 @@
import type { FileNode, TreeNode } from "@core/filesystem/treenode";
import type { FileNode, TreeNode } from "@core/filesystem/node";
import type { ShellState } from "@core/shell_state";
import { Posix } from "@termos/util/posix";
+375 -102
View File
@@ -1,131 +1,404 @@
export class ReadableStream {
private _threshold: number;
private _buffer: Uint8Array[] = [];
private _state: "idle" | "open" | "waiting" | "closed" | "errored" = "idle";
private _pending: ((value: Uint8Array | null) => void) | null = null;
private _byteLength: number = 0;
private _error: Error | null = null;
export type StreamItem =
{ ok: true; done: false; value: Uint8Array } | { ok: true; done: true } | { ok: false; done: true; error: unknown };
// Default - 32 chunks of 64KB -> Buffer of 2MB
constructor(threshold: number = 1024 * 64 * 32) {
this._threshold = threshold;
export type StreamState = "open" | "closed" | "failed" | "cancelled";
export class StreamCancelled extends Error {
constructor(cause?: unknown) {
super("stream cancelled", { cause });
this.name = "StreamCancelled";
}
}
export interface StreamOptions {
/** Maximum bytes buffered before producers block. Default: 2 MiB. */
byteThreshold?: number;
}
export interface Writable {
push(chunk: Uint8Array): Promise<void>;
close(): void;
fail(error: unknown): void;
cancel(cause?: unknown): void;
}
export interface Readable extends AsyncIterable<StreamItem> {
read(): Promise<StreamItem>;
drain(): Promise<Uint8Array[]>;
pipeTo(sink: Writable): Promise<void>;
cancel(cause?: unknown): void;
readonly state: StreamState;
readonly error: unknown;
readonly bufferedBytes: number;
}
// === Internal core (shared by every class) ===
const DEFAULT_BYTE_THRESHOLD = 2 * 1024 * 1024;
type Waiter = (item: StreamItem) => void;
type ParkedPush = {
chunk: Uint8Array;
resolve: () => void;
reject: (error: unknown) => void;
};
class StreamCore {
readonly byteThreshold: number;
#buffer: Uint8Array[] = [];
#bufferedBytes = 0;
#waiters: Waiter[] = [];
#pendingPushes: ParkedPush[] = [];
#state: StreamState = "open";
#error: unknown = null;
constructor(options: StreamOptions = {}) {
this.byteThreshold = options.byteThreshold ?? DEFAULT_BYTE_THRESHOLD;
}
public push(chunk: Uint8Array): boolean {
if (this._state === "closed" || this._state === "errored") {
return false;
}
if (this._pending) {
const pending = this._pending;
this._pending = null;
pending(chunk);
this._state = this._buffer.length > 0 ? "open" : "idle";
return true;
}
this._buffer.push(chunk);
this._byteLength += chunk.byteLength;
this._state = "open";
return this._byteLength < this._threshold;
get state(): StreamState {
return this.#state;
}
get error(): unknown {
return this.#error;
}
get bufferedBytes(): number {
return this.#bufferedBytes;
}
public close(): void {
if (this._state === "errored") return;
this._state = "closed";
// --- Write side ---
if (this._pending) {
this._pending(null);
this._pending = null;
}
}
async push(chunk: Uint8Array): Promise<void> {
if (this.#state !== "open") throw new Error(`cannot push: stream is ${this.#state}`);
public error(err: Error): void {
this._error = err;
this._state = "errored";
if (this._pending) {
this._pending(null);
this._pending = null;
}
this._buffer = [];
this._byteLength = 0;
}
public read(): Promise<Uint8Array | null> {
if ((this._state = "errored")) {
return Promise.reject(this._error || new Error("Stream encountered an error"));
const waiter = this.#waiters.shift();
if (waiter) {
waiter({ ok: true, done: false, value: chunk });
return;
}
if (this._buffer.length > 0) {
const chunk: Uint8Array = this._buffer.shift()!;
this._byteLength -= chunk.byteLength;
if (this._buffer.length === 0) {
this._state = "idle";
}
return Promise.resolve(chunk);
if (this.#bufferedBytes + chunk.byteLength <= this.byteThreshold) {
this.#buffer.push(chunk);
this.#bufferedBytes += chunk.byteLength;
return;
}
if ((this._state = "closed")) {
return Promise.resolve(null);
}
this._state = "waiting";
return new Promise((resolve, reject) => {
this._pending = resolve;
if (this._error) {
reject(this._error);
this._pending = null;
}
await new Promise<void>((resolve, reject) => {
this.#pendingPushes.push({ chunk, resolve, reject });
});
}
public pipe(writable: WritableStream): Promise<void> {
return new Promise(async (resolve, reject) => {
close(): void {
this.#terminate("closed");
}
fail(error: unknown): void {
this.#terminate("failed", error);
}
cancel(cause?: unknown): void {
this.#terminate("cancelled", new StreamCancelled(cause));
}
#terminate(state: Exclude<StreamState, "open">, error: unknown = null): void {
if (this.#state !== "open") return;
this.#state = state;
this.#error = error;
const terminal: StreamItem = state === "closed" ? { ok: true, done: true } : { ok: false, done: true, error };
for (const waiter of this.#waiters.splice(0)) waiter(terminal);
for (const pending of this.#pendingPushes.splice(0)) pending.reject(error ?? new Error(`stream ${state}`));
}
// --- Read side ---
pull(): Promise<StreamItem> {
if (this.#buffer.length) {
const chunk = this.#buffer.shift()!;
this.#bufferedBytes -= chunk.byteLength;
this.#promoteParkedPushes();
return Promise.resolve({ ok: true, done: false, value: chunk });
}
if (this.#pendingPushes.length) {
const pending = this.#pendingPushes.shift()!;
pending.resolve();
return Promise.resolve({ ok: true, done: false, value: pending.chunk });
}
if (this.#state === "open") return new Promise(resolve => this.#waiters.push(resolve));
return Promise.resolve(
this.#state === "closed" ? { ok: true, done: true } : { ok: false, done: true, error: this.#error },
);
}
#promoteParkedPushes(): void {
while (this.#pendingPushes.length > 0) {
const next = this.#pendingPushes[0];
if (this.#bufferedBytes + next.chunk.byteLength > this.byteThreshold) break;
this.#pendingPushes.shift();
this.#buffer.push(next.chunk);
this.#bufferedBytes += next.chunk.byteLength;
next.resolve();
}
}
}
// === ReadableStream ===
export class ReadableStream implements Readable {
#core: StreamCore;
#writableView: WritableStream | null = null;
constructor(options: StreamOptions | StreamCore = {}) {
this.#core = options instanceof StreamCore ? options : new StreamCore(options);
}
read(): Promise<StreamItem> {
return this.#core.pull();
}
async drain(): Promise<Uint8Array[]> {
const chunks: Uint8Array[] = [];
for (;;) {
const item = await this.#core.pull();
if (item.done) {
if (!item.ok) throw item.error;
return chunks;
}
chunks.push(item.value);
}
}
async pipeTo(sink: Writable): Promise<void> {
for await (const item of this) {
if (item.done) {
item.ok ? sink.close() : sink.fail(item.error);
return;
}
await sink.push(item.value);
}
}
cancel(cause?: unknown): void {
this.#core.cancel(cause);
}
[Symbol.asyncIterator](): AsyncIterator<StreamItem> {
let terminalYielded = false;
return {
next: async () => {
const item = await this.#core.pull();
if (!item.done) return { done: false, value: item };
if (terminalYielded) return { done: true, value: undefined };
terminalYielded = true;
return { done: false, value: item };
},
return: async () => {
this.#core.cancel("consumer stopped iterating");
return { done: true, value: undefined };
},
};
}
get state(): StreamState {
return this.#core.state;
}
get error(): unknown {
return this.#core.error;
}
get bufferedBytes(): number {
return this.#core.bufferedBytes;
}
get writable(): WritableStream {
return (this.#writableView ??= new WritableStream(this.#core));
}
static fromAsyncIterable(source: AsyncIterable<Uint8Array>, options: StreamOptions = {}): ReadableStream {
const stream = new ReadableStream(options);
const sink = stream.writable;
(async () => {
try {
for await (const chunk of this) {
await writable.write(chunk);
}
await writable.close();
resolve();
} catch (err) {
reject(err);
for await (const chunk of source) await sink.push(chunk);
sink.close();
} catch (error) {
sink.fail(error);
}
});
})();
return stream;
}
async *[Symbol.asyncIterator](): AsyncIterator<Uint8Array> {
while (true) {
const chunk = await this.read();
if (chunk === null) break;
yield chunk;
}
static fromBlob(blob: Blob, options: StreamOptions & { chunkSize?: number } = {}): ReadableStream {
const { chunkSize = 1 << 16, ...streamOptions } = options;
const stream = new ReadableStream(streamOptions);
const sink = stream.writable;
(async () => {
try {
for (let offset = 0; offset < blob.size; offset += chunkSize) {
const slice = blob.slice(offset, offset + chunkSize);
await sink.push(new Uint8Array(await slice.arrayBuffer()));
}
sink.close();
} catch (error) {
sink.fail(error);
}
})();
return stream;
}
public get byteLength(): number {
return this._byteLength;
async toBlob(type?: string): Promise<Blob> {
return new Blob(await this.drain(), type ? { type } : undefined);
}
public get isFull(): boolean {
return this._byteLength >= this._threshold;
}
public get state(): string {
return this._state;
[Symbol.asyncDispose](): Promise<void> {
if (this.#core.state === "open") this.#core.cancel("disposed");
return Promise.resolve();
}
}
export class WritableStream {
write(chunk: Uint8Array): void {}
// === WritableStream ===
close(): void {}
export class WritableStream implements Writable {
#core: StreamCore;
#readableView: ReadableStream | null = null;
constructor(options: StreamOptions | StreamCore = {}) {
this.#core = options instanceof StreamCore ? options : new StreamCore(options);
}
push(chunk: Uint8Array): Promise<void> {
return this.#core.push(chunk);
}
close(): void {
this.#core.close();
}
fail(error: unknown): void {
this.#core.fail(error);
}
cancel(cause?: unknown): void {
this.#core.cancel(cause);
}
get state(): StreamState {
return this.#core.state;
}
get error(): unknown {
return this.#core.error;
}
get bufferedBytes(): number {
return this.#core.bufferedBytes;
}
get readable(): ReadableStream {
return (this.#readableView ??= new ReadableStream(this.#core));
}
[Symbol.asyncDispose](): Promise<void> {
if (this.#core.state === "open") this.#core.cancel("disposed");
return Promise.resolve();
}
}
export class DuplexStream {}
// === DuplexStream ===
export class TransformStream {}
export class DuplexStream implements Readable, Writable {
readonly readable: ReadableStream;
readonly writable: WritableStream;
constructor(options: StreamOptions = {}) {
const core = new StreamCore(options);
this.readable = new ReadableStream(core);
this.writable = new WritableStream(core);
}
push(chunk: Uint8Array): Promise<void> {
return this.writable.push(chunk);
}
close(): void {
this.writable.close();
}
fail(error: unknown): void {
this.writable.fail(error);
}
cancel(cause?: unknown): void {
this.writable.cancel(cause);
}
read(): Promise<StreamItem> {
return this.readable.read();
}
drain(): Promise<Uint8Array[]> {
return this.readable.drain();
}
pipeTo(sink: Writable): Promise<void> {
return this.readable.pipeTo(sink);
}
[Symbol.asyncIterator](): AsyncIterator<StreamItem> {
return this.readable[Symbol.asyncIterator]();
}
get state(): StreamState {
return this.writable.state;
}
get error(): unknown {
return this.writable.error;
}
get bufferedBytes(): number {
return this.writable.bufferedBytes;
}
[Symbol.asyncDispose](): Promise<void> {
if (this.state === "open") this.cancel("disposed");
return Promise.resolve();
}
}
// === TransformStream ===
export type TransformFn = (
chunk: Uint8Array,
) => Uint8Array | Uint8Array[] | void | Promise<Uint8Array | Uint8Array[] | void>;
export class TransformStream {
readonly readable: ReadableStream;
readonly writable: Writable;
#sink: WritableStream;
constructor(transform: TransformFn, options: StreamOptions = {}) {
this.readable = new ReadableStream(options);
this.#sink = this.readable.writable;
const sink = this.#sink;
this.writable = {
async push(chunk: Uint8Array): Promise<void> {
try {
const result = await transform(chunk);
if (result == null) return;
for (const output of Array.isArray(result) ? result : [result]) {
await sink.push(output);
}
} catch (error) {
sink.fail(error);
throw error;
}
},
close(): void {
sink.close();
},
fail(error: unknown): void {
sink.fail(error);
},
cancel(cause?: unknown): void {
sink.cancel(cause);
},
};
}
[Symbol.asyncDispose](): Promise<void> {
if (this.readable.state === "open") this.#sink.cancel("disposed");
return Promise.resolve();
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
import type { FileSystem } from "@core/filesystem/filesystem";
import { TreeNodeType, type TreeNode } from "@core/filesystem/treenode";
import { TreeNodeType, type TreeNode } from "@core/filesystem/node";
export function dnTraverseTree(fs: FileSystem, root: number): number[] {
if (fs.getNode(root) === undefined) return [];
+2
View File
@@ -1,5 +1,7 @@
import type { IDataStore, NodeHash, ShadowHash, VDisk } from "@core/filesystem/vdisk";
//export interface VDiskManagerConfig {}
export class VDiskManager {
private _VDiskHash: Map<number, VDisk> = new Map();