Virtual FileSystem fixed - (Needs unit testing)!

This commit is contained in:
2026-11-09 05:10:44 +01:00
parent 832fc6c759
commit dd804f6f14
6 changed files with 307 additions and 346 deletions
+19 -3
View File
@@ -1,4 +1,4 @@
import type { TreeNodeType } from "./node";
import type { NodePointer, NodeType } from "./node";
export type FileSystemError =
NotADirectoryError | AlreadyExistsError | NodeNotFoundError | IllegalMutationError | FileSystemInitializationError;
@@ -14,7 +14,15 @@ export interface NotADirectoryError {
message: string;
timestamp: number;
type: "NotADirectory";
nodeType: TreeNodeType;
nodeType: NodeType;
}
export interface NotAFileError {
inode: number;
message: string;
timestamp: number;
type: "NotAFile";
nodeType: NodeType;
}
export interface AlreadyExistsError {
@@ -28,7 +36,7 @@ export interface AlreadyExistsError {
export interface NodeNotFoundError {
type: "NodeNotFound";
message: string;
inode: number;
pointer: NodePointer;
timestamp: number;
}
@@ -52,3 +60,11 @@ export interface DirectoryLoopError {
descendantInode: number;
ancestorInode: number;
}
export interface InvalidNodeNameError {
type: "InvalidNodeName";
message: string;
timestamp: number;
pointer: NodePointer;
attemptedName: string;
}
+195 -199
View File
@@ -1,15 +1,18 @@
import type { UserInfo } from "@core/session_manager";
import { createImmutableBuffer, type ImmutableBuffer } from "@core/util/immutable_buffer";
import { dnTraverseTree, upTraverseTree } from "@core/util/tree_traversal";
import { upTraverseTree } from "@core/util/tree_traversal";
import { VDiskManager } from "@core/util/vdisk_manager";
import type { Blob } from "node:buffer";
import type { Readable } from "node:stream";
import type {
AlreadyExistsError,
DeviceNotFoundError,
DirectoryLoopError,
FileSystemInitializationError,
IllegalMutationError,
InvalidNodeNameError,
NodeNotFoundError,
NotADirectoryError,
NotAFileError,
} from "./errors";
import {
fromPtr,
@@ -91,7 +94,7 @@ export class FileSystem {
public getRoot(): DirectoryNode {
const dev = this._VDiskManager.getDisk(0);
if (!dev) throw new Error("Kernel Panic - Filesystem corrupted, system device not found!");
if (!dev) throw new Error("Filesystem corrupted, system device not found!");
return dev.getNode(0) as DirectoryNode;
}
@@ -120,7 +123,7 @@ export class FileSystem {
type: "NodeNotFound",
message: `Node under inode ${fptr.inode} not found under device ${fptr.device_id}`,
timestamp: Date.now(),
inode: fptr.inode,
pointer: ptr,
} satisfies NodeNotFoundError;
}
@@ -136,7 +139,7 @@ export class FileSystem {
type: "NodeNotFound",
message: `Node under inode ${fptr.inode} not found under device ${fptr.device_id}`,
timestamp: Date.now(),
inode: fptr.inode,
pointer: ptr,
} satisfies NodeNotFoundError;
}
@@ -152,7 +155,7 @@ export class FileSystem {
type: "NodeNotFound",
message: `Node under inode ${fptr.inode} not found under device ${fptr.device_id}`,
timestamp: Date.now(),
inode: fptr.inode,
pointer: ptr,
} satisfies NodeNotFoundError;
}
@@ -188,9 +191,9 @@ export class FileSystem {
if (sourceNode === undefined) {
throw {
type: "NodeNotFound",
message: `Source node under inode ${sptr.inode} not found`,
message: `Source node under ${source} not found`,
timestamp: Date.now(),
inode: sptr.inode,
pointer: source,
} satisfies NodeNotFoundError;
}
@@ -205,9 +208,9 @@ export class FileSystem {
if (destinationNode === undefined) {
throw {
type: "NodeNotFound",
message: `Destination node under inode ${dptr.inode} not found`,
message: `Destination node under ${destination} not found`,
timestamp: Date.now(),
inode: dptr.inode,
pointer: destination,
} satisfies NodeNotFoundError;
}
@@ -229,7 +232,7 @@ export class FileSystem {
const nodeName = name ?? s_entry[0].name;
if (destinationNode.children.get(nodeName) !== undefined) {
if (destinationNode.children.has(nodeName)) {
throw {
type: "AlreadyExists",
message: `A node inside the destination inode ${destinationNode.inode} under the name ${nodeName} already exists`,
@@ -239,6 +242,16 @@ export class FileSystem {
} satisfies AlreadyExistsError;
}
if (nodeName.length > this._maxNameLength) {
throw {
type: "InvalidNodeName",
message: `Invalid name for the ${source} source node`,
timestamp: Date.now(),
pointer: source,
attemptedName: nodeName,
} satisfies InvalidNodeNameError;
}
if (upTraverseTree(this, destination).includes(source)) {
throw {
type: "DirectoryLoop",
@@ -256,165 +269,81 @@ export class FileSystem {
}
}
public modifyNode(target: NodePointer, changes: Partial<Node>) {
const node = this.resolveNode(target);
if (node === undefined) {
throw {
type: "NodeNotFound",
message: `Node under inode ${inode} not found`,
timestamp: Date.now(),
inode: inode,
} satisfies NodeNotFoundError;
}
const tptr = fromPtr(target);
let newNode: TreeNode;
if (node.type === TreeNodeType.File) {
const fileNode: FileNode = {
type: node.type,
inode: node.inode,
name: node.name,
parent: node.parent,
mode: changes.mode ?? node.mode,
owner: changes.owner ?? node.owner,
group: changes.group ?? node.group,
mtime: changes.content ? Date.now() : node.mtime,
atime: node.atime,
ctime: Date.now(),
content: changes.content ?? node.content,
};
newNode = fileNode;
} else {
const directoryNode: DirectoryNode = {
type: node.type,
inode: node.inode,
name: node.name,
parent: node.parent,
mode: changes.mode ?? node.mode,
owner: changes.owner ?? node.owner,
group: changes.group ?? node.group,
mtime: changes.content ? Date.now() : node.mtime,
atime: node.atime,
ctime: Date.now(),
children: node.children,
};
newNode = directoryNode;
}
const map = new Map(this.Overlay);
map.set(node.inode, Object.freeze(newNode));
const newOverlay: ReadonlyMap<number, TreeNode | null> = map;
return FileSystem.init(this._BaseFS, newOverlay, this._INodeIndex);
}
public createNode(
parent: number,
parent: NodePointer,
name: string,
type: TreeNodeType,
mode: number,
owner: number,
group: number,
content?: ImmutableBuffer,
): FileSystem {
let node: TreeNode;
data:
| {
type: NodeType.File;
mode: number;
owner: number;
group: number;
content: Blob | Readable;
size: number;
}
| { type: NodeType.Directory; mode: number; owner: number; group: number }
| { type: NodeType.Symlink; mode: number; owner: number; group: number; target: string },
) {
const pptr = fromPtr(parent);
const pdev = this._VDiskManager.getDisk(pptr.device_id);
const parentNode = this.resolveNode(parent);
const time: number = Date.now();
const newInode: number = this._INodeIndex + 1;
if (parentNode === undefined) {
if (!pdev) {
throw {
type: "DeviceNotFound",
message: `Device under id ${pptr.device_id} not found`,
timestamp: Date.now(),
device_id: pptr.device_id,
} satisfies DeviceNotFoundError;
}
if (!parentNode) {
throw {
type: "NodeNotFound",
message: `Parent inode ${parent} not found`,
message: `Destination node under ${parent} not found`,
timestamp: Date.now(),
inode: parent,
pointer: parent,
} satisfies NodeNotFoundError;
}
if (parentNode.type === TreeNodeType.File) {
if (parentNode.type !== NodeType.Directory) {
throw {
type: "NotADirectory",
message: `Parent inode ${parent} is not a directory`,
message: `Destination node under inode ${pptr.inode} is not a directory`,
inode: pptr.inode,
timestamp: Date.now(),
inode: parent,
nodeType: parentNode.type,
} satisfies NotADirectoryError;
}
if (parentNode.type === TreeNodeType.Directory && parentNode.children[name] !== undefined) {
if (parentNode.children.has(name)) {
throw {
type: "AlreadyExists",
message: `Child under the name of ${name} inside the parent inode ${parent} already exists`,
message: `A node inside the destination inode ${parentNode.inode} under the name ${name} already exists`,
timestamp: Date.now(),
parentInode: parent,
name,
parentInode: parentNode.inode,
name: name,
} satisfies AlreadyExistsError;
}
if (type === TreeNodeType.File) {
const fileNode: FileNode = {
type,
inode: newInode,
name,
parent,
mode,
owner,
group,
mtime: time,
atime: time,
ctime: time,
content: content ?? createImmutableBuffer(new Uint8Array()),
};
node = fileNode;
} else {
const directoryNode: DirectoryNode = {
type,
inode: newInode,
name,
parent,
mode,
owner,
group,
mtime: time,
atime: time,
ctime: time,
children: {},
};
node = directoryNode;
if (name.length > this._maxNameLength) {
throw {
type: "InvalidNodeName",
message: `Invalid name for the new node`,
timestamp: Date.now(),
pointer: parent,
attemptedName: name,
} satisfies InvalidNodeNameError;
}
const newParentNode: DirectoryNode = {
type: parentNode.type,
inode: parent,
name: parentNode.name,
parent: parentNode.parent,
mode: parentNode.mode,
owner: parentNode.owner,
group: parentNode.group,
mtime: time,
atime: parentNode.atime,
ctime: time,
children: { ...parentNode.children, [name]: newInode },
};
const map = new Map(this.Overlay);
map.set(newInode, Object.freeze(node));
map.set(parent, Object.freeze(newParentNode));
const newOverlay: ReadonlyMap<number, TreeNode | null> = map;
return FileSystem.init(this._BaseFS, newOverlay, newInode);
pdev.createNodeEntry(pptr.inode, name, data);
}
public deleteNode(inode: number): FileSystem {
if (inode === 0) {
public deleteNode(target: NodePointer) {
const tptr = fromPtr(target);
const tdev = this._VDiskManager.getDisk(tptr.device_id);
if (tptr.device_id === 0 && tptr.inode === 0) {
throw {
type: "IllegalMutation",
message: `Attempt at illegal mutation of node under inode 0 (root)`,
@@ -422,64 +351,138 @@ export class FileSystem {
} satisfies IllegalMutationError;
}
const node = this.resolveNode(inode);
if (node === undefined) {
if (!tdev) {
throw {
type: "DeviceNotFound",
message: `Device under id ${tptr.device_id} not found`,
timestamp: Date.now(),
device_id: tptr.device_id,
} satisfies DeviceNotFoundError;
}
const tdevIndex = tdev.getIndex();
const t_entry = tdevIndex.get(target);
if (!t_entry || !t_entry[0]) throw new Error("File System corruption, reverse index is missing a field");
tdev.unlinkNodeEntry(tptr.inode, t_entry[0].name);
}
public writeContent(target: NodePointer, content: Blob) {
const ptr = fromPtr(target);
const dev = this._VDiskManager.getDisk(ptr.device_id);
const node = this.resolveNode(target);
if (!dev) {
throw {
type: "DeviceNotFound",
message: `Device under id ${ptr.device_id} not found`,
timestamp: Date.now(),
device_id: ptr.device_id,
} satisfies DeviceNotFoundError;
}
if (!node) {
throw {
type: "NodeNotFound",
message: `Node under inode ${inode} not found`,
message: `Destination node under ${target} not found`,
timestamp: Date.now(),
inode: inode,
pointer: target,
} satisfies NodeNotFoundError;
}
const time: number = Date.now();
const descendants: number[] = dnTraverseTree(this, inode);
const map: Map<number, TreeNode | null> = new Map(this._OverlayFS);
for (const entry of descendants) {
map.set(entry, null);
if (node.type === NodeType.Directory) {
throw {
type: "NotAFile",
message: `Node is not a file`,
inode: ptr.inode,
timestamp: Date.now(),
nodeType: node.type,
} satisfies NotAFileError;
}
const parentNode = this.resolveNode(node.parent) as DirectoryNode;
if (parentNode === undefined) {
dev.writeContent((node as FileNode).content, content);
}
public streamContent(target: NodePointer): Readable {
const ptr = fromPtr(target);
const dev = this._VDiskManager.getDisk(ptr.device_id);
const node = this.resolveNode(target);
if (!dev) {
throw {
type: "DeviceNotFound",
message: `Device under id ${ptr.device_id} not found`,
timestamp: Date.now(),
device_id: ptr.device_id,
} satisfies DeviceNotFoundError;
}
if (!node) {
throw {
type: "NodeNotFound",
message: `Parent inode ${node.parent} not found (should be impossible unless the filesystem corrupted!)`,
message: `Destination node under ${target} not found`,
timestamp: Date.now(),
inode: node.parent,
pointer: target,
} satisfies NodeNotFoundError;
}
const { [node.name]: __, ...newChildren } = parentNode.children;
const newParentNode: DirectoryNode = {
type: parentNode.type,
inode: parentNode.inode,
name: parentNode.name,
parent: parentNode.parent,
mode: parentNode.mode,
owner: parentNode.owner,
group: parentNode.group,
mtime: time,
atime: parentNode.atime,
ctime: time,
children: newChildren,
};
map.set(node.parent, Object.freeze(newParentNode));
const newOverlay: ReadonlyMap<number, TreeNode | null> = map;
return FileSystem.init(this._BaseFS, newOverlay, this._INodeIndex);
if (node.type === NodeType.Directory) {
throw {
type: "NotAFile",
message: `Node is not a file`,
inode: ptr.inode,
timestamp: Date.now(),
nodeType: node.type,
} satisfies NotAFileError;
}
public canRead(inode: number, user: UserInfo): boolean {
const node = this.resolveNode(inode);
if (node === undefined) {
return dev.streamContent((node as FileNode).content);
}
public modifyNode(target: NodePointer, data: { mode?: number; owner?: number; group?: number }) {
const ptr = fromPtr(target);
const dev = this._VDiskManager.getDisk(ptr.device_id);
const node = this.resolveNode(target);
if (!dev) {
throw {
type: "DeviceNotFound",
message: `Device under id ${ptr.device_id} not found`,
timestamp: Date.now(),
device_id: ptr.device_id,
} satisfies DeviceNotFoundError;
}
if (!node) {
throw {
type: "NodeNotFound",
message: `Node under inode ${inode} not found`,
message: `Destination node under ${target} not found`,
timestamp: Date.now(),
inode: inode,
pointer: target,
} satisfies NodeNotFoundError;
}
if (node.type === NodeType.Directory) {
throw {
type: "NotAFile",
message: `Node is not a file`,
inode: ptr.inode,
timestamp: Date.now(),
nodeType: node.type,
} satisfies NotAFileError;
}
dev.writeNodeEntry(node.inode, data);
}
public canRead(nodep: NodePointer, user: UserInfo): boolean {
const node = this.resolveNode(nodep);
if (!node) {
throw {
type: "NodeNotFound",
message: `Node under ${nodep} not found`,
timestamp: Date.now(),
pointer: nodep,
} satisfies NodeNotFoundError;
}
@@ -494,14 +497,14 @@ export class FileSystem {
}
}
public canWrite(inode: number, user: UserInfo): boolean {
const node = this.resolveNode(inode);
if (node === undefined) {
public canWrite(nodep: NodePointer, user: UserInfo): boolean {
const node = this.resolveNode(nodep);
if (!node) {
throw {
type: "NodeNotFound",
message: `Node under inode ${inode} not found`,
message: `Node under ${nodep} not found`,
timestamp: Date.now(),
inode: inode,
pointer: nodep,
} satisfies NodeNotFoundError;
}
@@ -516,14 +519,14 @@ export class FileSystem {
}
}
public canExecute(inode: number, user: UserInfo): boolean {
const node = this.resolveNode(inode);
if (node === undefined) {
public canExecute(nodep: NodePointer, user: UserInfo): boolean {
const node = this.resolveNode(nodep);
if (!node) {
throw {
type: "NodeNotFound",
message: `Node under inode ${inode} not found`,
message: `Node under ${nodep} not found`,
timestamp: Date.now(),
inode: inode,
pointer: nodep,
} satisfies NodeNotFoundError;
}
@@ -537,11 +540,4 @@ export class FileSystem {
return (node.mode & 0o001) !== 0;
}
}
/* public get Overlay(): ReadonlyMap<number, TreeNode | null> {
return this._OverlayFS;
}
public get INodeIndex(): number {
return this._INodeIndex;
} */
}
+18 -6
View File
@@ -1,3 +1,6 @@
import type { Blob } from "node:buffer";
import { Readable } from "node:stream";
import { blob } from "node:stream/consumers";
import {
NodeType,
toPtr,
@@ -58,7 +61,7 @@ export interface DataConfig {
export interface IDataStore {
read(uuid: string): Promise<Uint8Array>;
stream(uuid: string): ReadableStream;
stream(uuid: string): Readable;
put(uuid: string, blob: Blob): Promise<void>;
delete(uuid: string): Promise<void>;
has(uuid: string): Promise<boolean>;
@@ -204,15 +207,22 @@ export class VDisk {
return this._base.get(inode);
}
public createNodeEntry(
public async createNodeEntry(
pinode: number,
name: string,
data:
| { type: NodeType.File; mode: number; owner: number; group: number; content: string; size: number }
| {
type: NodeType.File;
mode: number;
owner: number;
group: number;
content: Blob | Readable;
size: number;
}
| { type: NodeType.Directory; mode: number; owner: number; group: number }
| { type: NodeType.Symlink; mode: number; owner: number; group: number; target: string },
): Promise<number> {
return this._batch(() => {
return this._batch(async () => {
this._isWritable();
const index = ++this._iIndex;
const time = Date.now();
@@ -231,11 +241,13 @@ export class VDisk {
};
const pnode = this.getNode(pinode) as DirectoryNode;
const uuid = crypto.randomUUID();
let node: Node;
switch (data.type) {
case NodeType.File:
node = { ...base, type: NodeType.File, content: data.content, size: data.size };
node = { ...base, type: NodeType.File, content: uuid, size: data.size };
this.writeContent(uuid, data.content instanceof Readable ? await blob(data.content) : data.content);
break;
case NodeType.Directory:
node = { ...base, type: NodeType.Directory, children: new Map() };
@@ -385,7 +397,7 @@ export class VDisk {
return this._dataStore.read(uuid);
}
public streamContent(uuid: string): ReadableStream {
public streamContent(uuid: string): Readable {
return this._dataStore.stream(uuid);
}
+4 -2
View File
@@ -1,5 +1,7 @@
import type { Node } from "@core/filesystem/node";
import type { IDataStore, IMetaStore } from "@core/filesystem/vdisk";
import type { Blob } from "node:buffer";
import { Readable } from "node:stream";
export class MemMetaStore implements IMetaStore {
private _data: Map<number, Node | null> = new Map();
@@ -33,11 +35,11 @@ export class MemDataStore implements IDataStore {
return new Uint8Array(buff);
}
public stream(uuid: string): ReadableStream {
public stream(uuid: string): Readable {
const blob = this._data.get(uuid);
if (!blob) throw new Error("Content missing - " + uuid);
return blob.stream();
return Readable.from(blob.stream());
}
public put(uuid: string, blob: Blob): Promise<void> {
+37 -62
View File
@@ -1,7 +1,10 @@
import { FileSystem } from "@core/filesystem/filesystem";
import { TreeNodeType, type DirectoryNode, type FileNode, type TreeNode } from "@core/filesystem/node";
import { NodeType, type FileNode } from "@core/filesystem/node";
import type { IDataStore, IMetaStore, VDiskConfig } from "@core/filesystem/vdisk";
import type { UserInfo } from "@core/session_manager";
import { createImmutableBuffer } from "@core/util/immutable_buffer";
import { MemDataStore, MemMetaStore } from "@core/util/temp_mem_stores";
import { deserializeFileSystem } from "@shell/serializer";
import {
expectAlreadyExistsError,
expectDirectoryLoopError,
@@ -9,83 +12,55 @@ import {
expectNodeNotFoundError,
expectNotADirectoryError,
} from "@tests/helpers/error_matchers";
import { buildTestFS, type FixtureNode } from "@tests/helpers/filesystems_fixture";
import { buildTestFS } from "@tests/helpers/filesystems_fixture";
import { Blob } from "node:buffer";
import { describe, expect, it } from "vitest";
const testTree: FixtureNode = {
inode: 0,
name: "root",
type: "Dir",
children: [
{
inode: 1,
name: "hello.txt",
type: "File",
content: "Goodbye World!",
children: [],
},
{
inode: 2,
name: "sub",
type: "Dir",
children: [
{
inode: 3,
name: "world.txt",
type: "File",
content: "Goodbye!",
children: [],
},
{
inode: 4,
name: "bye",
type: "Dir",
children: [],
},
],
},
],
};
const fs = buildTestFS(testTree);
const fs = buildTestFS();
describe("FileSystem.init", () => {
const map: Map<number, TreeNode> = new Map();
const time = Date.now();
const rawJson = `{"dev": [{"id": 0, "tree": {"type": "directory", "inode": 0, "mode": 443, "owner": 0, "group": 0, "parent": 0, "atime": 0, "mtime": 0, "ctime": 0, "children": []}}]}`;
const arr = deserializeFileSystem(rawJson);
const devices: { dstore: IDataStore; mstore: IMetaStore; config: VDiskConfig }[] = [];
const root: DirectoryNode = {
type: TreeNodeType.Directory,
inode: 0,
name: "root",
parent: 0,
mode: 0o555,
owner: 0,
group: 0,
mtime: time,
atime: time,
ctime: time,
children: {},
const data = new MemDataStore();
const meta = new MemMetaStore();
const config: VDiskConfig = {
id: 0,
label: `disk-0`,
index: 0,
readonly: false,
size: 1024 * 1024 * 1024 * 8, //8 GiB
base: arr[0]!.map,
dataC: {
chunkSize: 1024 * 8, //8 KiB
cacheSize: 1024 * 1024 * 64, //64 MiB
cacheTTL: 1000 * 60, // 1 min
},
};
map.set(0, root);
const base: ReadonlyMap<number, TreeNode> = map;
const overlay: ReadonlyMap<number, TreeNode | null> = new Map();
devices.push({ dstore: data, mstore: meta, config });
it("initializes correctly", () => {
const fs = FileSystem.init(base, overlay, 0);
const fs = FileSystem.init(devices);
expect(fs).toBeInstanceOf(FileSystem);
expect(fs.INodeIndex).toBe(0);
});
});
describe("createNode", () => {
const content = createImmutableBuffer(new TextEncoder().encode("Lorem ipsum"));
const content = new Blob([new TextEncoder().encode("Lorem ipsum")]);
it("creates a file and updates parent", () => {
const newFS = fs.createNode(0, "readme", TreeNodeType.File, 0o644, 0, 0, content);
fs.createNode("0:0", "readme", {
type: NodeType.File,
mode: 0o644,
owner: 0,
group: 0,
content: content,
size: content.size,
});
expect(newFS).toBeInstanceOf(FileSystem);
const newNode = newFS.getNode(5) as FileNode;
expect(fs).toBeInstanceOf(FileSystem);
const newNode = fs.getNode("0") as FileNode;
expect(newNode.type).toBe(TreeNodeType.File);
expect(newNode.name).toBe("readme");
File diff suppressed because one or more lines are too long