From f2b5f86a6c6a384d06b799bd16a30d2fe8d7b9d1 Mon Sep 17 00:00:00 2001 From: hyperion Date: Sun, 20 Sep 2026 12:40:38 +0200 Subject: [PATCH] Try initializing FileSystem now - vdisk finished - vdiskmanager finished - devices can properly initialize and hold aswell as retireve data - added mock synchronous store classes for testing --- src/core/filesystem/filesystem.ts | 55 ++-- src/core/filesystem/node.ts | 21 +- src/core/filesystem/vdisk.ts | 86 ++++++- src/core/util/stream.ts | 404 ------------------------------ src/core/util/temp_mem_stores.ts | 60 +++++ src/core/util/tree_traversal.ts | 6 +- src/core/util/vdisk_manager.ts | 9 +- src/dev.ts | 17 +- src/shell/serializer.ts | 152 ++++++----- src/util/cache_manager.ts | 74 ------ 10 files changed, 282 insertions(+), 602 deletions(-) delete mode 100644 src/core/util/stream.ts create mode 100644 src/core/util/temp_mem_stores.ts delete mode 100644 src/util/cache_manager.ts diff --git a/src/core/filesystem/filesystem.ts b/src/core/filesystem/filesystem.ts index 737d440..f3d1850 100644 --- a/src/core/filesystem/filesystem.ts +++ b/src/core/filesystem/filesystem.ts @@ -10,15 +10,8 @@ import type { NodeNotFoundError, NotADirectoryError, } from "./errors"; -import { - type DirectoryNode, - type FileNode, - type NodeEntry, - type NodeHash, - type NodePointer, - type ShadowHash, -} from "./node"; -import type { IDataStore } from "./vdisk"; +import { NodeType, type DirectoryNode, type FileNode, type Node, type NodePointer } from "./node"; +import type { IDataStore, IMetaStore, VDiskConfig } from "./vdisk"; export interface FileSystemConfig { maxPathLength: number; @@ -33,24 +26,23 @@ export class FileSystem { private _SysPartitionID: number = 0; private _Mounts: Map = new Map(); - private _VDiskManager: VDiskManager = new VDiskManager(); - private _EntryCache: Map; + private _VDiskManager: VDiskManager; - private constructor(store: IDataStore[], base: NodeHash[], overlay: ShadowHash[], id: number[]) { - for (let i = 0; i < id.length; i++) { - if (i === 0) { - this._VDiskManager.registerVDisk(store[0]!, base[0], overlay[0], id[0]); - this._Mounts.set(0, 0); - } - this._VDiskManager.registerVDisk(store[i]!, base[i], overlay[i], id[i]); + private constructor( + config: FileSystemConfig, + devices: Array<{ dstore: IDataStore; mstore: IMetaStore; config: VDiskConfig }>, + ) { + this._maxNameLength = config.maxNameLength; + this._maxPathLength = config.maxPathLength; + this._maxSymlinkDepth = config.maxSymlinkDepth; + + this._VDiskManager = new VDiskManager(); + for (const dev of devices) { + this._VDiskManager.registerDisk(dev.config, dev.dstore, dev.mstore); } - - this._EntryCache = this.buildNodeEntryCache(); } - private updateDentryCache(key: NodePointer, entry: NodeEntry): void {} - - private resolveNode(ptr: NodePointer): TreeNode | undefined { + private resolveNode(ptr: NodePointer): Node | undefined { const dev = this._VDiskManager.getVDisk(ptr[1]); if (!dev) return undefined; @@ -61,24 +53,27 @@ export class FileSystem { return dev.base.get(ptr[0]); } - public static init(store: IDataStore[], base: NodeHash[], overlay: ShadowHash[], index: number[]): FileSystem { - if (store.length === 0 || base.length === 0 || index.length === 0) { + public static init( + config: FileSystemConfig, + devices: Array<{ dstore: IDataStore; mstore: IMetaStore; config: VDiskConfig }>, + ): FileSystem { + if (devices.length === 0) { throw { type: "FileSystemInitializationError", - message: "File System tried to initialized without a base hashmap and store", + message: "File System tried to initialized without any devices", timestamp: Date.now(), } satisfies FileSystemInitializationError; } - if (base[0]!.get(0) === undefined) { + if (!devices.find(d => d.config.id === 0)) { throw { type: "FileSystemInitializationError", - message: "File System failed to initialize because root node is undefined or not assigned to inode 0", + message: "File System failed to initialize because no device with id 0 was present", timestamp: Date.now(), } satisfies FileSystemInitializationError; } - if (base[0]!.get(0)?.type !== TreeNodeType.Directory) { + if (devices[0]!.config.base.get(0)?.type !== NodeType.Directory) { throw { type: "FileSystemInitializationError", message: "File System failed to initialize because root node is not a directory", @@ -86,7 +81,7 @@ export class FileSystem { } satisfies FileSystemInitializationError; } - return new FileSystem(store, base, overlay, index); + return new FileSystem(config, devices); } public getRoot(): DirectoryNode { diff --git a/src/core/filesystem/node.ts b/src/core/filesystem/node.ts index eb5bf33..259946d 100644 --- a/src/core/filesystem/node.ts +++ b/src/core/filesystem/node.ts @@ -6,9 +6,9 @@ export type ShadowHash = ReadonlyMap; export type NodePointer = string; export interface NodeEntry { - pinode: number; - pdevice_id: number; - name: string; + readonly pinode: number; + readonly pdevice_id: number; + readonly name: string; } export interface FileNode { @@ -56,3 +56,18 @@ export enum NodeType { Directory = 1, Symlink = 2, } + +export function toPtr(deviceId: number, inode: number): NodePointer { + return `${deviceId}:${inode}`; +} + +export function fromPtr(ptr: NodePointer): { device_id: number; inode: number } { + if (!ptr.match(/\d+[:]\d+$/g)) { + throw new Error("Invalid node pointer format"); + } + const arr = ptr.split(":"); + return { + device_id: Number(arr[0]), + inode: Number(arr[1]), + }; +} diff --git a/src/core/filesystem/vdisk.ts b/src/core/filesystem/vdisk.ts index a26f5c1..bdb01ac 100644 --- a/src/core/filesystem/vdisk.ts +++ b/src/core/filesystem/vdisk.ts @@ -1,5 +1,44 @@ -import type { ReadableStream } from "@core/util/stream"; -import { NodeType, type DirectoryNode, type Node, type NodeEntry, type NodeHash, type NodePointer } from "./node"; +import { + NodeType, + toPtr, + type DirectoryNode, + type Node, + type NodeEntry, + type NodeHash, + type NodePointer, +} from "./node"; + +export function DefaultVDiskConfig(id: number): VDiskConfig { + const base = new Map(); + const root = { + type: NodeType.Directory, + inode: 0, + link_count: 2, + mode: 0o0555, + owner: 0, + group: 0, + mtime: 0, + ctime: 0, + atime: 0, + children: new Map(), + } satisfies DirectoryNode; + + base.set(0, root); + + return { + id, + label: `disk-${id}`, + readonly: false, + size: Infinity, + base, + index: 0, + dataC: { + chunkSize: 8096, + cacheSize: 64 * 1024 * 1024, + cacheTTL: 60_000, + }, + }; +} export interface VDiskConfig { id: number; @@ -62,7 +101,7 @@ export class VDisk { this._overlay = new Map(); this._rIndex = new Map(); - this._rIndexInvalid = true; + this._rIndexInvalid = false; this._pending = null; this._flush = Promise.resolve(); } @@ -101,6 +140,41 @@ export class VDisk { if (this._readonly) throw Error(`The ${this._label} device under id - ${this._id} is marked readonly`); } + private _buildReverseIndex(): Map { + const index: Map = new Map(); + const stack: [number, number, number, string][] = []; + + const root = this.getNode(0) as DirectoryNode; + for (const [name, inode] of root.children) { + stack.push([inode, 0, this._id, name]); + } + + while (stack.length > 0) { + const [inode, pinode, pdevice_id, name] = stack.pop()!; + const node = this.getNode(inode); + if (node === undefined) continue; + + const key = toPtr(this._id, inode); + const entry = { + pinode, + pdevice_id, + name, + }; + + const arr = index.get(key); + if (arr) arr.push(entry); + else index.set(key, [entry]); + + if (node.type === NodeType.Directory) { + for (const [name, cinode] of node.children) { + stack.push([cinode, inode, pdevice_id, name]); + } + } + } + + return index; + } + private _putNode(inode: number, node: Node | null): void { if (!this._pending) throw new Error( @@ -113,6 +187,8 @@ export class VDisk { public static async open(config: VDiskConfig, data: IDataStore, meta: IMetaStore): Promise { const vdisk = new VDisk(config, data, meta); await vdisk.loadOverlay(); + vdisk._rIndex = vdisk._buildReverseIndex(); + return vdisk; } @@ -138,7 +214,7 @@ export class VDisk { ): Promise { return this._batch(() => { this._isWritable(); - const index = this._iIndex++; + const index = ++this._iIndex; const time = Date.now(); const link_count = data.type === NodeType.Directory ? 2 : 1; @@ -341,7 +417,7 @@ export class VDisk { public getIndex(): ReadonlyMap> { if (this._rIndexInvalid) { - this._rIndex = this._buildRIndex(); + this._rIndex = this._buildReverseIndex(); this._rIndexInvalid = false; } return this._rIndex; diff --git a/src/core/util/stream.ts b/src/core/util/stream.ts deleted file mode 100644 index 45a2dbf..0000000 --- a/src/core/util/stream.ts +++ /dev/null @@ -1,404 +0,0 @@ -export type StreamItem = - { ok: true; done: false; value: Uint8Array } | { ok: true; done: true } | { ok: false; done: true; error: unknown }; - -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; - close(): void; - fail(error: unknown): void; - cancel(cause?: unknown): void; -} - -export interface Readable extends AsyncIterable { - read(): Promise; - drain(): Promise; - pipeTo(sink: Writable): Promise; - 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; - } - - get state(): StreamState { - return this.#state; - } - get error(): unknown { - return this.#error; - } - get bufferedBytes(): number { - return this.#bufferedBytes; - } - - // --- Write side --- - - async push(chunk: Uint8Array): Promise { - if (this.#state !== "open") throw new Error(`cannot push: stream is ${this.#state}`); - - const waiter = this.#waiters.shift(); - if (waiter) { - waiter({ ok: true, done: false, value: chunk }); - return; - } - - if (this.#bufferedBytes + chunk.byteLength <= this.byteThreshold) { - this.#buffer.push(chunk); - this.#bufferedBytes += chunk.byteLength; - return; - } - - await new Promise((resolve, reject) => { - this.#pendingPushes.push({ chunk, 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, 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 { - 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 { - return this.#core.pull(); - } - - async drain(): Promise { - 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 { - 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 { - 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, options: StreamOptions = {}): ReadableStream { - const stream = new ReadableStream(options); - const sink = stream.writable; - (async () => { - try { - for await (const chunk of source) await sink.push(chunk); - sink.close(); - } catch (error) { - sink.fail(error); - } - })(); - return stream; - } - - 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; - } - - async toBlob(type?: string): Promise { - return new Blob(await this.drain(), type ? { type } : undefined); - } - - [Symbol.asyncDispose](): Promise { - if (this.#core.state === "open") this.#core.cancel("disposed"); - return Promise.resolve(); - } -} - -// === WritableStream === - -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 { - 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 { - if (this.#core.state === "open") this.#core.cancel("disposed"); - return Promise.resolve(); - } -} - -// === DuplexStream === - -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 { - 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 { - return this.readable.read(); - } - drain(): Promise { - return this.readable.drain(); - } - pipeTo(sink: Writable): Promise { - return this.readable.pipeTo(sink); - } - - [Symbol.asyncIterator](): AsyncIterator { - 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 { - if (this.state === "open") this.cancel("disposed"); - return Promise.resolve(); - } -} - -// === TransformStream === - -export type TransformFn = ( - chunk: Uint8Array, -) => Uint8Array | Uint8Array[] | void | Promise; - -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 { - 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 { - if (this.readable.state === "open") this.#sink.cancel("disposed"); - return Promise.resolve(); - } -} diff --git a/src/core/util/temp_mem_stores.ts b/src/core/util/temp_mem_stores.ts new file mode 100644 index 0000000..0a78510 --- /dev/null +++ b/src/core/util/temp_mem_stores.ts @@ -0,0 +1,60 @@ +import type { Node } from "@core/filesystem/node"; +import type { IDataStore, IMetaStore } from "@core/filesystem/vdisk"; + +export class MemMetaStore implements IMetaStore { + private _data: Map = new Map(); + + public loadAll(): Promise> { + return Promise.resolve(this._data); + } + + public write(entries: Array<[number, Node | null]>): Promise { + for (const [inode, node] of entries) { + this._data.set(inode, node); + } + return Promise.resolve(); + } + + public delete(entries: number[]): Promise { + for (const inode of entries) { + this._data.delete(inode); + } + return Promise.resolve(); + } +} + +export class MemDataStore implements IDataStore { + private _data: Map = new Map(); + + public async read(uuid: string): Promise { + const blob = this._data.get(uuid); + if (!blob) throw new Error("Content missing - " + uuid); + const buff = await blob.arrayBuffer(); + return new Uint8Array(buff); + } + + public stream(uuid: string): ReadableStream { + const blob = this._data.get(uuid); + if (!blob) throw new Error("Content missing - " + uuid); + + return blob.stream(); + } + + public put(uuid: string, blob: Blob): Promise { + this._data.set(uuid, blob); + return Promise.resolve(); + } + + public delete(uuid: string): Promise { + this._data.delete(uuid); + return Promise.resolve(); + } + + public has(uuid: string): Promise { + return Promise.resolve(this._data.has(uuid)); + } + + public list(): Promise { + return Promise.resolve(Array.from(this._data.keys())); + } +} diff --git a/src/core/util/tree_traversal.ts b/src/core/util/tree_traversal.ts index ad25096..7bbf113 100644 --- a/src/core/util/tree_traversal.ts +++ b/src/core/util/tree_traversal.ts @@ -1,5 +1,5 @@ import type { FileSystem } from "@core/filesystem/filesystem"; -import { TreeNodeType, type TreeNode } from "@core/filesystem/node"; +import { NodeType, type Node } from "@core/filesystem/node"; export function dnTraverseTree(fs: FileSystem, root: number): number[] { if (fs.getNode(root) === undefined) return []; @@ -13,7 +13,7 @@ export function dnTraverseTree(fs: FileSystem, root: number): number[] { result.push(node.inode); - if (node.type === TreeNodeType.Directory) { + if (node.type === NodeType.Directory) { const children = Object.values(node.children); for (let i = children.length - 1; i >= 0; i--) { stack.push(children[i] as number); @@ -32,7 +32,7 @@ export function upTraverseTree(fs: FileSystem, inode: number): number[] { let currentInode = inode; while (currentInode !== 0) { - const node = fs.getNode(currentInode) as TreeNode; + const node = fs.getNode(currentInode) as Node; if (!node) break; result.push(node.parent); diff --git a/src/core/util/vdisk_manager.ts b/src/core/util/vdisk_manager.ts index 3b583ac..5b248b1 100644 --- a/src/core/util/vdisk_manager.ts +++ b/src/core/util/vdisk_manager.ts @@ -2,11 +2,9 @@ import { IDataStore, IMetaStore, VDisk, VDiskConfig } from "@core/filesystem/vdi export class VDiskManager { private _disks: Map; - private _isMounted: (id: number) => boolean; - constructor(isMounted: (id: number) => boolean) { + constructor() { this._disks = new Map(); - this._isMounted = isMounted; } public async registerDisk(config: VDiskConfig, data: IDataStore, meta: IMetaStore): Promise { @@ -26,7 +24,7 @@ export class VDiskManager { } public hasDisk(id: number): boolean { - return this._disks.get(id) ? true : false; + return this._disks.has(id); } public listDisk(): VDisk[] { @@ -41,9 +39,6 @@ export class VDiskManager { if (!this._disks.has(id)) { throw new Error("Disk of this id doesnt exist"); } - if (this._isMounted(id)) { - throw new Error("Could not unregister disk. Is mounted."); - } this._disks.delete(id); } diff --git a/src/dev.ts b/src/dev.ts index aead219..32670ad 100644 --- a/src/dev.ts +++ b/src/dev.ts @@ -10,18 +10,21 @@ namespace Termos { } */ -import { FileSystem } from "@core/filesystem/filesystem"; -import type { TreeNode } from "@core/filesystem/node"; -import { getCurrentSession, type GroupInfo, type UserInfo } from "@core/session_manager"; -import { createInitialShellState, type ShellState } from "@core/shell_state"; -import { resolveInodeToHome } from "@core/util/path_resolver"; +//import { FileSystem } from "@core/filesystem/filesystem"; +import type { FileSystemConfig } from "@core/filesystem/filesystem"; +import type { IDataStore, IMetaStore, VDiskConfig } from "@core/filesystem/vdisk"; +//import { getCurrentSession, type GroupInfo, type UserInfo } from "@core/session_manager"; +//import { createInitialShellState, type ShellState } from "@core/shell_state"; +//import { resolveInodeToHome } from "@core/util/path_resolver"; import { deserializeFileSystem } from "@shell/serializer"; -import { Shell } from "@shell/shell"; +//import { deserializeFileSystem } from "@shell/serializer"; +//import { Shell } from "@shell/shell"; const rawJson = `{"dev":[{"id":0,"tree":{"atime":1773013637,"children":[{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":1,"mode":493,"mtime":1757686809,"name":"run","owner":1000,"parent":0,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":2,"mode":493,"mtime":1757686772,"name":"dev","owner":1000,"parent":0,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":3,"mode":493,"mtime":1757686804,"name":"proc","owner":1000,"parent":0,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":4,"mode":493,"mtime":1757686785,"name":"lost+found","owner":1000,"parent":0,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":5,"mode":493,"mtime":1757686768,"name":"boot","owner":1000,"parent":0,"type":"directory"},{"atime":1773013637,"children":[{"atime":1788458583,"children":[{"atime":1788459229,"children":[],"content":"","ctime":1788459246,"group":1000,"inode":8,"mode":493,"mtime":1788459147,"name":"cat","owner":1000,"parent":7,"type":"regular"}],"content":null,"ctime":1788459229,"group":1000,"inode":7,"mode":493,"mtime":1788459229,"name":"bin","owner":1000,"parent":6,"type":"directory"}],"content":null,"ctime":1788458583,"group":1000,"inode":6,"mode":493,"mtime":1788458583,"name":"usr","owner":1000,"parent":0,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":9,"mode":493,"mtime":1757686775,"name":"etc","owner":1000,"parent":0,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":10,"mode":493,"mtime":1757686830,"name":"srv","owner":1000,"parent":0,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":11,"mode":493,"mtime":1757686781,"name":"lib64","owner":1000,"parent":0,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":12,"mode":493,"mtime":1757686689,"name":"root","owner":1000,"parent":0,"type":"directory"},{"atime":1773013637,"children":[{"atime":1773013637,"children":[{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":15,"mode":493,"mtime":1757766627,"name":".config","owner":1000,"parent":14,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":16,"mode":493,"mtime":1757766646,"name":".npm","owner":1000,"parent":14,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":17,"mode":493,"mtime":1757766597,"name":"Videos","owner":1000,"parent":14,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":18,"mode":493,"mtime":1757766631,"name":".java","owner":1000,"parent":14,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":19,"mode":493,"mtime":1757766614,"name":".cache","owner":1000,"parent":14,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":20,"mode":493,"mtime":1757766580,"name":"Downloads","owner":1000,"parent":14,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":21,"mode":493,"mtime":1757766577,"name":"Desktop","owner":1000,"parent":14,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":22,"mode":493,"mtime":1757766652,"name":".ssh","owner":1000,"parent":14,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":23,"mode":493,"mtime":1757766551,"name":"Documents","owner":1000,"parent":14,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":24,"mode":493,"mtime":1757766620,"name":".cargo","owner":1000,"parent":14,"type":"directory"},{"atime":1773013637,"children":[{"atime":1773013637,"children":[{"atime":1773013637,"children":[{"atime":1773013637,"children":[],"content":"","ctime":1773013637,"group":1000,"inode":28,"mode":493,"mtime":1759940170,"name":"about.md","owner":1000,"parent":27,"type":"regular"}],"content":null,"ctime":1773013637,"group":1000,"inode":27,"mode":493,"mtime":1759940182,"name":"This Website","owner":1000,"parent":26,"type":"directory"},{"atime":1773013637,"children":[{"atime":1773013637,"children":[],"content":"","ctime":1773013637,"group":1000,"inode":30,"mode":493,"mtime":1759940170,"name":"about.md","owner":1000,"parent":29,"type":"regular"}],"content":null,"ctime":1773013637,"group":1000,"inode":29,"mode":493,"mtime":1759942574,"name":"Sheepo","owner":1000,"parent":26,"type":"directory"},{"atime":1773013637,"children":[{"atime":1773013637,"children":[],"content":"","ctime":1773013637,"group":1000,"inode":32,"mode":493,"mtime":1759940170,"name":"about.md","owner":1000,"parent":31,"type":"regular"}],"content":null,"ctime":1773013637,"group":1000,"inode":31,"mode":493,"mtime":1759942576,"name":"SchoolProjectManager","owner":1000,"parent":26,"type":"directory"}],"content":null,"ctime":1773013637,"group":1000,"inode":26,"mode":493,"mtime":1759940133,"name":"Websites","owner":1000,"parent":25,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":33,"mode":493,"mtime":1759939881,"name":"C#","owner":1000,"parent":25,"type":"directory"}],"content":null,"ctime":1773013637,"group":1000,"inode":25,"mode":493,"mtime":1759939982,"name":"Projects","owner":1000,"parent":14,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":34,"mode":493,"mtime":1757766640,"name":".local","owner":1000,"parent":14,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":35,"mode":493,"mtime":1757766591,"name":"Pictures","owner":1000,"parent":14,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":36,"mode":493,"mtime":1757766660,"name":".var","owner":1000,"parent":14,"type":"directory"},{"atime":1773013637,"children":[{"atime":1773013637,"children":[],"content":"","ctime":1773013637,"group":1000,"inode":38,"mode":493,"mtime":1757812927,"name":"nggyu.lrc","owner":1000,"parent":37,"type":"regular"}],"content":null,"ctime":1773013637,"group":1000,"inode":37,"mode":493,"mtime":1759939803,"name":"Music","owner":1000,"parent":14,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":39,"mode":493,"mtime":1757766636,"name":".dotnet","owner":1000,"parent":14,"type":"directory"},{"atime":1773013637,"children":[],"content":"","ctime":1773013637,"group":1000,"inode":40,"mode":493,"mtime":1757780849,"name":".bash_logout","owner":1000,"parent":14,"type":"regular"},{"atime":1773013637,"children":[],"content":"","ctime":1773013637,"group":1000,"inode":41,"mode":493,"mtime":1757780715,"name":".bashrc","owner":1000,"parent":14,"type":"regular"},{"atime":1773013637,"children":[],"content":"","ctime":1773013637,"group":1000,"inode":42,"mode":493,"mtime":1757780715,"name":".bash_profile","owner":1000,"parent":14,"type":"regular"},{"atime":1773013637,"children":[],"content":"","ctime":1773013637,"group":1000,"inode":43,"mode":493,"mtime":1757780889,"name":".xinitrc","owner":1000,"parent":14,"type":"regular"},{"atime":1773013637,"children":[],"content":"","ctime":1773013637,"group":1000,"inode":44,"mode":493,"mtime":1757780811,"name":".bash_history","owner":1000,"parent":14,"type":"regular"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":45,"mode":493,"mtime":1771137563,"name":"Test test","owner":1000,"parent":14,"type":"directory"}],"content":null,"ctime":1773013637,"group":1000,"inode":14,"mode":493,"mtime":1771137563,"name":"kamil","owner":1000,"parent":13,"type":"directory"}],"content":null,"ctime":1773013637,"group":1000,"inode":13,"mode":493,"mtime":1757766534,"name":"home","owner":1000,"parent":0,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":46,"mode":493,"mtime":1757686867,"name":"tmp","owner":1000,"parent":0,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":47,"mode":493,"mtime":1757686765,"name":"bin","owner":1000,"parent":0,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":48,"mode":493,"mtime":1757686874,"name":"var","owner":1000,"parent":0,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":49,"mode":493,"mtime":1757686823,"name":"sbin","owner":1000,"parent":0,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":50,"mode":493,"mtime":1757686863,"name":"sys","owner":1000,"parent":0,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":51,"mode":493,"mtime":1757686777,"name":"lib","owner":1000,"parent":0,"type":"directory"},{"atime":1773013637,"children":[],"content":null,"ctime":1773013637,"group":1000,"inode":52,"mode":493,"mtime":1757686791,"name":"opt","owner":1000,"parent":0,"type":"directory"}],"content":null,"ctime":1773013637,"group":1000,"inode":0,"mode":493,"mtime":1757686876,"name":"root_fs","owner":1000,"parent":0,"type":"directory"}},{"id":1,"tree":{}}]}`; const base = deserializeFileSystem(rawJson); -const overlay: ReadonlyMap = new Map(); +const fsConf: FileSystemConfig = {}; +const devices: { dstore: IDataStore; mstore: IMetaStore; config: VDiskConfig }[]; const fs = FileSystem.init(base, overlay, base.size - 1); diff --git a/src/shell/serializer.ts b/src/shell/serializer.ts index cc1dd1f..bee6786 100644 --- a/src/shell/serializer.ts +++ b/src/shell/serializer.ts @@ -1,87 +1,101 @@ -import { - TreeNodeType, - type DirectoryNode, - type FileNode, - type NodeEntry, - type NodePointer, - type TreeNode, -} from "../core/filesystem/node"; +import { NodeType, type DirectoryNode, type FileNode, type Node, type SymlinkNode } from "../core/filesystem/node"; /* export function serializeFileSystem(map: ReadonlyMap): string { } */ -export function deserializeFileSystem(json: string): { - dev_list: number[]; - map: ReadonlyMap; - cache: Map; -} { +export function deserializeFileSystem(json: string): { id: number; map: Map }[] { const raw = JSON.parse(json); - //const validated = TreeNodeSchema.parse(raw); - const map = new Map(); - const cache = new Map(); // prettier-ignore - function parseObj(obj: any): number[] { // eslint-disable-line @typescript-eslint/no-explicit-any - const result: number[] = []; - for (const dev of obj.dev) { - const id = dev.id; - result.push(id); - - const tree = dev.tree; - - parseNode(tree, tree.inode, id); + function parseNode(tree: any, map: Map): void { // eslint-disable-line @typescript-eslint/no-explicit-any + if(tree === null || tree.type === undefined) { + const time = Date.now(); + const defaultNode: DirectoryNode = { + type: NodeType.Directory, + inode: 0, + link_count: 2, + mode: 0o0555, + owner: 0, + group: 0, + mtime: time, + ctime: time, + atime: time, + children: new Map(), + }; + map.set(0, Object.freeze(defaultNode)); + return; } - return result; - } + switch(tree.type) { + case "directory": { + const children: Map = new Map(); - const deviceList: number[] = parseObj(raw); + for (const child of tree.children) { + parseNode(child, map); + children.set(child.name, child.inode); + } - // prettier-ignore - function parseNode(tree: any, parent: number, dev_id: number): void { // eslint-disable-line @typescript-eslint/no-explicit-any - if (tree.type === "directory") { - const prt = [tree.inode, dev_id]; - const children: Map = new Map(); - - for (const child of tree.children) { - parseNode(child, tree.inode, dev_id); - children.set(child.name, child.inode); + const directoryNode: DirectoryNode = { + type: NodeType.Directory, + inode: tree.inode, + link_count: tree.link_count, + mode: tree.mode, + owner: tree.owner, + group: tree.group, + mtime: tree.mtime, + ctime: tree.ctime, + atime: tree.atime, + children, + }; + map.set(tree.inode, Object.freeze(directoryNode)); + break; } - - const directoryNode: DirectoryNode = { - type: TreeNodeType.Directory, - inode: tree.inode, - link_count: tree.link_count, - mode: tree.mode, - owner: tree.owner, - group: tree.group, - mtime: tree.mtime, - ctime: tree.ctime, - atime: tree.atime, - content: children, - device_id: dev_id, - }; - map.set(tree.inode, Object.freeze(directoryNode)); - } else { - const fileNode: FileNode = { - type: TreeNodeType.File, - inode: tree.inode, - mode: tree.mode, - link_count: tree.link_count, - owner: tree.owner, - group: tree.group, - mtime: tree.mtime, - ctime: tree.ctime, - atime: tree.atime, - content: tree.content, - device_id: dev_id, - }; - map.set(tree.inode, Object.freeze(fileNode)); + case "regular": { + const fileNode: FileNode = { + type: NodeType.File, + inode: tree.inode, + mode: tree.mode, + link_count: tree.link_count, + owner: tree.owner, + group: tree.group, + mtime: tree.mtime, + ctime: tree.ctime, + atime: tree.atime, + content: tree.content, + size: tree.size, + }; + map.set(tree.inode, Object.freeze(fileNode)); + break; + } + case "symlink": { + const symlinkNode: SymlinkNode = { + type: NodeType.Symlink, + inode: tree.inode, + mode: tree.mode, + link_count: tree.link_count, + owner: tree.owner, + group: tree.group, + mtime: tree.mtime, + ctime: tree.ctime, + atime: tree.atime, + target: tree.target, + }; + map.set(tree.inode, Object.freeze(symlinkNode)); + break; + } + default: + throw new Error(`Unknown node type in JSON ${tree.type}`); } } - const base: ReadonlyMap = map; + const result: { id: number; map: Map }[] = []; + for (const dev of raw.dev) { + const map = new Map(); + parseNode(dev.tree, map); - return { map: base, cache: new Map() }; + result.push({ id: dev.id, map }); + } + + return result; } diff --git a/src/util/cache_manager.ts b/src/util/cache_manager.ts deleted file mode 100644 index d882219..0000000 --- a/src/util/cache_manager.ts +++ /dev/null @@ -1,74 +0,0 @@ -/* import { MD5 } from "./hash"; - -//INDEXED DB IS SO FUCKING DOGSHIT ITS INSANE - -//TODO: load IDB db name from config; - -export async function initializeIDB() { - const request = indexedDB.open("cache"); - request.onerror = e => { - throw new Error(`Failed to open the IDB during the init - ${request.error}`); - }; - - request.onsuccess = e => { - const DB = request.result; - const STORE = DB.createObjectStore("fs", { autoIncrement: true }); - - STORE.createIndex("json", "json"); - STORE.createIndex("checksum", "checksum"); - }; -} - -export async function writeFileSystemCache(cache: string, checksum: string) { - if (cache.length === 0 || checksum.length === 0) { - throw new Error(`Cache value or the checksum value cannot be empty!`); - } - - if (!isChecksumMatching(cache, checksum)) - throw new Error("The cache value checksum does not match the provided checksum"); - - const request = indexedDB.open("cache"); - request.onerror = e => { - throw new Error(`Failed to open the IDB during the init - ${request.error}`); - }; - - request.onsuccess = e => { - const DB = request.result; - const T = DB.transaction(["cache"], "readwrite"); - const STOREFS = T.objectStore("fs"); - const STORECK = T.objectStore("fs"); - - const RFS = STOREFS.add(cache); - //const CFS = - }; -} - -export async function fetchFileSystemCache(): Promise<{ cache: string; checksum: string }> { - const request = indexedDB.open("cache"); - - request.onerror = e => { - throw new Error(`Failed to open the IDB - ${request.error}`); - }; - - request.onsuccess = e => { - const DB = request.result; - const T = DB.transaction(["cache"], "readonly"); - const STORE = T.objectStore("fs"); - - const R = STORE.get("1"); - - R.onerror = e => { - throw new Error(`Some IDB error - ${R.error}`); - }; - - R.onsuccess = e => { - console.log(R.result.json, R.result.checksum); - }; - }; -} - -function isChecksumMatching(json: string, checksum: string): boolean { - const resourceChksm = MD5.hash(json); - return resourceChksm === checksum; -} - */