// @core/filesystem/filesystem.test.ts import { FileSystem, type FileSystemConfig } from "@core/filesystem/filesystem"; import { NodePointer, NodeType, type DirectoryNode, type FileNode, type Node, type NodeEntry, type SymlinkNode, } from "@core/filesystem/node"; import { DefaultVDiskConfig, VDisk, type IDataStore, type IMetaStore } from "@core/filesystem/vdisk"; import type { UserInfo } from "@core/session_manager"; import { VDiskManager } from "@core/util/vdisk_manager"; import { expectAlreadyExistsError, expectDeviceNotFoundError, expectDirectoryLoopError, expectFileSystemInitializationError, expectIllegalMutationError, expectInvalidNodeNameError, expectNodeNotFoundError, expectNotADirectoryError, expectNotAFileError, } from "@tests/helpers/error_matchers"; import { afterEach, describe, expect, it, vi } from "vitest"; (""); // ============================================================================ // Fixtures // ============================================================================ function makeDirectoryNode(overrides: Partial = {}): DirectoryNode { return { type: NodeType.Directory, inode: 0, link_count: 2, mode: 0o755, owner: 0, group: 0, mtime: 0, ctime: 0, atime: 0, children: new Map(), ...overrides, }; } function makeFileNode(overrides: Partial = {}): FileNode { return { type: NodeType.File, inode: 1, link_count: 1, mode: 0o644, owner: 0, group: 0, mtime: 0, ctime: 0, atime: 0, content: "some-uuid", size: 0, ...overrides, }; } function makeSymlinkNode(overrides: Partial = {}): SymlinkNode { return { type: NodeType.Symlink, inode: 2, link_count: 1, mode: 0o777, owner: 0, group: 0, mtime: 0, ctime: 0, atime: 0, target: "/nonexistent", ...overrides, }; } function makeUser(overrides: Partial = {}): UserInfo { return { username: "test", uid: 1000, gid: 1000, group: [], home: NodePointer.parse("0:0"), ...overrides, }; } interface FakeDisk { ID: number; Label: string; IsReadonly: boolean; ByteSize: number; getNode: ReturnType; getIndex: ReturnType; createNodeEntry: ReturnType; unlinkNodeEntry: ReturnType; moveNodeEntry: ReturnType; writeContent: ReturnType; streamContent: ReturnType; writeNodeEntry: ReturnType; _deviceId: number; _nodes: Map; _nextInode: number; } /** * Builds a reverse index by walking the tree rooted at inode 0. * Mirrors `VDisk._buildReverseIndex` so `upTraverseTree` works. */ function buildReverseIndex(nodes: Map, deviceId: number): Map { const index = new Map(); const root = nodes.get(0); if (!root || root.type !== NodeType.Directory) return index; const stack: [number, number, string][] = []; for (const [name, inode] of root.children) stack.push([inode, 0, name]); while (stack.length > 0) { const [inode, pinode, name] = stack.pop()!; const node = nodes.get(inode); if (!node) continue; const key = NodePointer.of(deviceId, inode); const entry: NodeEntry = { pinode, pdevice_id: deviceId, name }; const arr = index.get(key); if (arr) arr.push(entry); else index.set(key, [entry]); if (node.type === NodeType.Directory) { for (const [cname, cinode] of node.children) stack.push([cinode, inode, cname]); } } return index; } /** * A `VDisk`-shaped object. Only the surface `FileSystem` uses is provided. * Mutating methods are Vitest mocks; read methods operate over an in-memory map. */ function makeFakeDisk(id: number): FakeDisk { const nodes = new Map(); nodes.set(0, makeDirectoryNode({ inode: 0 })); const disk: FakeDisk = { ID: id, Label: `disk-${id}`, IsReadonly: false, ByteSize: Infinity, _deviceId: id, _nodes: nodes, _nextInode: 1, getNode: vi.fn((inode: number) => nodes.get(inode)), getIndex: vi.fn(() => buildReverseIndex(nodes, id)), createNodeEntry: vi.fn(async () => disk._nextInode++), unlinkNodeEntry: vi.fn(async () => undefined), moveNodeEntry: vi.fn(async () => undefined), writeContent: vi.fn(async () => undefined), streamContent: vi.fn(() => new Blob(["data"]).stream()), writeNodeEntry: vi.fn(async () => undefined), }; return disk; } /** * Attaches `node` under `parentInode` on `disk`, mutating the in-memory tree * so the derived reverse index stays consistent. */ function addChild(disk: FakeDisk, parentInode: number, name: string, node: Node): void { const parent = disk._nodes.get(parentInode); if (!parent || parent.type !== NodeType.Directory) { throw new Error(`Parent ${parentInode} is not a directory on disk ${disk.ID}`); } const newChildren = new Map(parent.children); newChildren.set(name, node.inode); disk._nodes.set(parentInode, { ...parent, children: newChildren }); disk._nodes.set(node.inode, node); } interface FSFixture { fs: FileSystem; disks: Map; } /** * Builds a `FileSystem` with mocked `VDisk.open`. Flushes pending microtasks * so the fire-and-forget `registerDisk` calls settle before returning. * (The flush is a workaround for the "init does not await" bug — see the BUG test.) */ async function makeFS( opts: { devices?: Array<{ id: number; setup?: (disk: FakeDisk) => void }>; config?: Partial; } = {}, ): Promise { const deviceDefs = opts.devices ?? [{ id: 0 }]; const disks = new Map(); const vdiskConfigs = deviceDefs.map(d => { const disk = makeFakeDisk(d.id); d.setup?.(disk); disks.set(d.id, disk); return { dstore: {} as IDataStore, mstore: {} as IMetaStore, config: DefaultVDiskConfig(d.id), }; }); vi.spyOn(VDisk, "open").mockImplementation(async config => disks.get(config.id) as unknown as VDisk); const fs = await FileSystem.init(vdiskConfigs, { maxNameLength: 255, maxPathLength: Infinity, maxSymlinkDepth: 40, ...opts.config, }); await new Promise(r => setImmediate(r)); return { fs, disks }; } afterEach(() => { vi.restoreAllMocks(); }); // ============================================================================ // FileSystem.init // ============================================================================ describe("FileSystem.init", () => { /** * `init` must reject empty device lists with the typed initialization error. */ it("throws FileSystemInitializationError when the device list is empty", () => { expectFileSystemInitializationError(() => FileSystem.init([]), { message: expect.stringMatching(/without any devices/), }); }); /** * Device id 0 is required by convention — the filesystem mounts it as root. */ it("throws FileSystemInitializationError when no device has id 0", () => { expectFileSystemInitializationError( () => FileSystem.init([ { dstore: {} as IDataStore, mstore: {} as IMetaStore, config: DefaultVDiskConfig(1) }, ]), { message: expect.stringMatching(/no device with id 0/) }, ); }); /** * The base root of device 0 must be a directory, not a file or symlink. */ it("throws FileSystemInitializationError when device 0 has no node at inode 0", () => { expectFileSystemInitializationError(() => FileSystem.init([ { dstore: {} as IDataStore, mstore: {} as IMetaStore, config: { ...DefaultVDiskConfig(0), base: new Map() }, }, ]), ); }); /** * The root at inode 0 must be a directory; anything else is a corrupt disk. */ it("throws FileSystemInitializationError when device 0's root is not a directory", () => { expectFileSystemInitializationError(() => FileSystem.init([ { dstore: {} as IDataStore, mstore: {} as IMetaStore, config: { ...DefaultVDiskConfig(0), base: new Map([[0, makeFileNode({ inode: 0 })]]), }, }, ]), ); }); /** * Happy path: `init` registers one disk per device via `VDiskManager`. */ it("registers every device with the VDiskManager", async () => { const spy = vi.spyOn(VDiskManager.prototype, "registerDisk"); await makeFS({ devices: [{ id: 0 }, { id: 1 }, { id: 2 }] }); expect(spy).toHaveBeenCalledTimes(3); expect(spy).toHaveBeenCalledWith(expect.objectContaining({ id: 0 }), expect.anything(), expect.anything()); expect(spy).toHaveBeenCalledWith(expect.objectContaining({ id: 2 }), expect.anything(), expect.anything()); }); /** * BUG: `init` returns synchronously without awaiting `registerDisk`. * Immediately after init, `getRoot()` fails because no disk is registered. * Fix is non-trivial (making `init` async changes the public API), so this * documents the current behavior. When patched, this test should be deleted. */ it("BUG: init returns before registerDisk resolves — no disk is available right after init", async () => { vi.spyOn(VDisk, "open").mockResolvedValue({} as VDisk); const fs = await FileSystem.init([ { dstore: {} as IDataStore, mstore: {} as IMetaStore, config: DefaultVDiskConfig(0) }, ]); expect(() => fs.getRoot()).toThrow(/system device not found/); }); /** * Defensive: the root-type validation reads `devices[0].config` positionally * instead of finding device id 0 by id. With device 0 placed at index 1 and * its root set to a file (invalid), the validation silently passes because it * checks device 1 (index 0) instead. Correct behavior would be to throw. */ it("BUG: validates devices[0] positionally instead of by config.id === 0", () => { vi.spyOn(VDisk, "open").mockResolvedValue({} as VDisk); const config0Bad = { ...DefaultVDiskConfig(0), base: new Map([[0, makeFileNode({ inode: 0 })]]) }; const config1Ok = DefaultVDiskConfig(1); expect(() => FileSystem.init([ { dstore: {} as IDataStore, mstore: {} as IMetaStore, config: config1Ok }, { dstore: {} as IDataStore, mstore: {} as IMetaStore, config: config0Bad }, ]), ).not.toThrow(); // ^ Correct behavior: throw, because device 0 (config0Bad) has a file root. }); /** * Sanity: default config is `{ maxNameLength: 255, maxPathLength: Infinity, maxSymlinkDepth: 40 }`. * Observable indirectly: `createNode` accepts names up to 255 chars. */ it("defaults maxNameLength to 255", async () => { const { fs } = await makeFS(); const longName = "a".repeat(256); expectInvalidNodeNameError(() => fs.createNode(NodePointer.of(0, 0), longName, { type: NodeType.Directory, mode: 0o755, owner: 0, group: 0, }), ); }); /** * Custom config overrides defaults — maxNameLength 5 rejects a 6-char name. */ it("respects a custom maxNameLength", async () => { const { fs } = await makeFS({ config: { maxNameLength: 5 } }); expectInvalidNodeNameError(() => fs.createNode(NodePointer.of(0, 0), "abcdef", { type: NodeType.Directory, mode: 0o755, owner: 0, group: 0, }), ); }); /** * BUG: `maxPathLength` and `maxSymlinkDepth` are stored but never enforced. * This documents that they are currently dead config — no observable behavior * changes with tiny values. */ it("BUG: maxPathLength and maxSymlinkDepth are accepted but never enforced", async () => { const { fs } = await makeFS({ config: { maxPathLength: 1, maxSymlinkDepth: 0 } }); // No API path exercises these limits today; the calls below succeed regardless. expect(() => fs.createNode(NodePointer.of(0, 0), "a-very-long-name", { type: NodeType.Directory, mode: 0o755, owner: 0, group: 0, }), ).not.toThrow(); }); /** * BUG: `_Mounts` is declared but unused. Documents that no mount API is wired up. * (Intentionally just a type-level note; runtime behavior is identical with or * without it, so we cannot distinguish via the public API today.) */ it("BUG: _Mounts field is never read or written", async () => { const { fs } = await makeFS(); // @ts-expect-error accessing private field intentionally to document non-use expect(fs._Mounts.size).toBe(0); }); }); // ============================================================================ // getRoot // ============================================================================ describe("FileSystem.getRoot", () => { /** * Happy path: returns the DirectoryNode at inode 0 on device 0. */ it("returns the directory node at inode 0 of device 0", async () => { const { fs } = await makeFS(); const root = fs.getRoot(); expect(root.type).toBe(NodeType.Directory); expect(root.inode).toBe(0); }); /** * BUG: when device 0 is missing (e.g., unregistered post-init), `getRoot` * throws a raw `Error` instead of a typed error such as `DeviceNotFound`. */ it("BUG: throws a raw Error (not typed) when device 0 is missing", async () => { const { fs } = await makeFS(); // @ts-expect-error private access to simulate a corrupted manager const mgr = fs._VDiskManager as VDiskManager; mgr.unregisterDisk(0); expect(() => fs.getRoot()).toThrow(/system device not found/); }); }); // ============================================================================ // getNode / exists // ============================================================================ describe("FileSystem.getNode", () => { /** * Happy path: resolves a pointer to its node. */ it("returns the node for a valid pointer", async () => { const { fs } = await makeFS({ devices: [{ id: 0, setup: d => addChild(d, 0, "f", makeFileNode({ inode: 1 })) }], }); expect(fs.getNode(NodePointer.of(0, 1))).toBeDefined(); }); /** * Missing inode on an existing device → undefined (not a throw). */ it("returns undefined when the inode is missing on an existing device", async () => { const { fs } = await makeFS(); expect(fs.getNode(NodePointer.of(0, 99))).toBeUndefined(); }); /** * Missing device → undefined (not a throw). */ it("returns undefined when the device does not exist", async () => { const { fs } = await makeFS(); expect(fs.getNode(NodePointer.of(99, 0))).toBeUndefined(); }); }); describe("FileSystem.exists", () => { /** * `exists` is exactly `getNode !== undefined`. */ it("returns true when the node resolves, false otherwise", async () => { const { fs } = await makeFS({ devices: [{ id: 0, setup: d => addChild(d, 0, "f", makeFileNode({ inode: 1 })) }], }); expect(fs.exists(NodePointer.of(0, 1))).toBe(true); expect(fs.exists(NodePointer.of(0, 42))).toBe(false); expect(fs.exists(NodePointer.of(99, 0))).toBe(false); }); }); // ============================================================================ // getNodeEntries // ============================================================================ describe("FileSystem.getNodeEntries", () => { /** * Happy path: returns the reverse-index entries for the pointer. */ it("returns the reverse-index entries for a child node", async () => { const { fs } = await makeFS({ devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeFileNode({ inode: 1 })) }], }); const entries = fs.getNodeEntries(NodePointer.of(0, 1)); expect(entries).toHaveLength(1); expect(entries![0]).toMatchObject({ pinode: 0, pdevice_id: 0, name: "a" }); }); /** * Missing pointer on an existing device → undefined. */ it("returns undefined when the pointer is not in the index", async () => { const { fs } = await makeFS(); expect(fs.getNodeEntries(NodePointer.of(0, 99))).toBeUndefined(); }); /** * EXPECTED-TO-FAIL: a missing device currently produces a raw TypeError * (`undefined.getIndex()`), not a typed DeviceNotFoundError. This is a hole * in `getNodeEntries` — the non-null assertion `getDisk(...)!` is unsafe. */ it("should throw DeviceNotFoundError when the device is missing", async () => { const { fs } = await makeFS(); await expectDeviceNotFoundError(() => fs.getNodeEntries(NodePointer.of(99, 0))); }); }); // ============================================================================ // isFile / isDirectory / isSymlink // ============================================================================ describe("FileSystem.isFile / isDirectory / isSymlink", () => { /** * Happy path for each discriminator. */ it("classifies file, directory, and symlink nodes correctly", async () => { const { fs } = await makeFS({ devices: [ { id: 0, setup: d => { addChild(d, 0, "f", makeFileNode({ inode: 1 })); addChild(d, 0, "d", makeDirectoryNode({ inode: 2 })); addChild(d, 0, "l", makeSymlinkNode({ inode: 3 })); }, }, ], }); const f = NodePointer.of(0, 1); const d = NodePointer.of(0, 2); const l = NodePointer.of(0, 3); expect(fs.isFile(f)).toBe(true); expect(fs.isDirectory(f)).toBe(false); expect(fs.isSymlink(f)).toBe(false); expect(fs.isFile(d)).toBe(false); expect(fs.isDirectory(d)).toBe(true); expect(fs.isSymlink(d)).toBe(false); expect(fs.isFile(l)).toBe(false); expect(fs.isDirectory(l)).toBe(false); expect(fs.isSymlink(l)).toBe(true); }); /** * Missing node → typed NodeNotFoundError. */ it("throws NodeNotFoundError when the node does not exist", async () => { const { fs } = await makeFS(); expectNodeNotFoundError(() => fs.isFile(NodePointer.of(0, 99))); expectNodeNotFoundError(() => fs.isDirectory(NodePointer.of(0, 99))); expectNodeNotFoundError(() => fs.isSymlink(NodePointer.of(0, 99))); }); /** * EXPECTED-TO-FAIL: missing *device* is conflated with missing node because * `resolveNode` returns undefined for both. Correct behavior: DeviceNotFound. */ it("should throw DeviceNotFoundError when the device is missing", async () => { const { fs } = await makeFS(); await expectDeviceNotFoundError(() => fs.isFile(NodePointer.of(99, 0))); await expectDeviceNotFoundError(() => fs.isDirectory(NodePointer.of(99, 0))); await expectDeviceNotFoundError(() => fs.isSymlink(NodePointer.of(99, 0))); }); }); // ============================================================================ // createNode // ============================================================================ describe("FileSystem.createNode", () => { /** * Happy path: creating a file forwards to the parent device. */ it("creates a file by delegating to the parent device", async () => { const { fs, disks } = await makeFS(); const data = { type: NodeType.File as const, mode: 0o644, owner: 1, group: 1, content: new Blob(), size: 0 }; fs.createNode(NodePointer.of(0, 0), "f", data); expect(disks.get(0)!.createNodeEntry).toHaveBeenCalledWith(0, "f", data); }); /** * Happy path: creating a directory. */ it("creates a directory", async () => { const { fs, disks } = await makeFS(); const data = { type: NodeType.Directory as const, mode: 0o755, owner: 1, group: 1 }; fs.createNode(NodePointer.of(0, 0), "d", data); expect(disks.get(0)!.createNodeEntry).toHaveBeenCalledWith(0, "d", data); }); /** * Happy path: creating a symlink. */ it("creates a symlink", async () => { const { fs, disks } = await makeFS(); const data = { type: NodeType.Symlink as const, mode: 0o777, owner: 1, group: 1, target: "/x" }; fs.createNode(NodePointer.of(0, 0), "l", data); expect(disks.get(0)!.createNodeEntry).toHaveBeenCalledWith(0, "l", data); }); /** * Missing device → typed DeviceNotFoundError. */ it("throws DeviceNotFoundError when the parent's device is missing", async () => { const { fs } = await makeFS(); await expectDeviceNotFoundError(() => fs.createNode(NodePointer.of(99, 0), "x", { type: NodeType.Directory, mode: 0o755, owner: 0, group: 0, }), ); }); /** * Missing parent inode → typed NodeNotFoundError. */ it("throws NodeNotFoundError when the parent inode does not exist", async () => { const { fs } = await makeFS(); expectNodeNotFoundError(() => fs.createNode(NodePointer.of(0, 99), "x", { type: NodeType.Directory, mode: 0o755, owner: 0, group: 0, }), ); }); /** * Parent is a file, not a directory → typed NotADirectoryError. */ it("throws NotADirectoryError when the parent is a file", async () => { const { fs } = await makeFS({ devices: [{ id: 0, setup: d => addChild(d, 0, "f", makeFileNode({ inode: 1 })) }], }); expectNotADirectoryError(() => fs.createNode(NodePointer.of(0, 1), "x", { type: NodeType.Directory, mode: 0o755, owner: 0, group: 0, }), ); }); /** * Name collision at the parent → typed AlreadyExistsError. */ it("throws AlreadyExistsError when a sibling of the same name exists", async () => { const { fs } = await makeFS({ devices: [{ id: 0, setup: d => addChild(d, 0, "f", makeFileNode({ inode: 1 })) }], }); expectAlreadyExistsError(() => fs.createNode(NodePointer.of(0, 0), "f", { type: NodeType.Directory, mode: 0o755, owner: 0, group: 0, }), ); }); /** * Name longer than maxNameLength → typed InvalidNodeNameError. */ it("throws InvalidNodeNameError when the name exceeds maxNameLength", async () => { const { fs } = await makeFS({ config: { maxNameLength: 3 } }); expectInvalidNodeNameError(() => fs.createNode(NodePointer.of(0, 0), "four", { type: NodeType.Directory, mode: 0o755, owner: 0, group: 0, }), ); }); /** * Boundary: name exactly `maxNameLength` characters must be accepted. */ it("accepts a name whose length equals maxNameLength exactly", async () => { const { fs, disks } = await makeFS({ config: { maxNameLength: 4 } }); fs.createNode(NodePointer.of(0, 0), "abcd", { type: NodeType.Directory, mode: 0o755, owner: 0, group: 0, }); expect(disks.get(0)!.createNodeEntry).toHaveBeenCalledWith(0, "abcd", expect.anything()); }); }); // ============================================================================ // deleteNode // ============================================================================ describe("FileSystem.deleteNode", () => { /** * Happy path: deletes a file via `unlinkNodeEntry(parentInode, name)`. */ it("deletes a file by unlinking it from its parent", async () => { const { fs, disks } = await makeFS({ devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeFileNode({ inode: 1 })) }], }); fs.deleteNode(NodePointer.of(0, 1)); expect(disks.get(0)!.unlinkNodeEntry).toHaveBeenCalledWith(0, "a"); }); /** * Root protection: inode 0 on device 0 is immortal. */ it("throws IllegalMutationError when deleting device 0's root", async () => { const { fs } = await makeFS(); expectIllegalMutationError(() => fs.deleteNode(NodePointer.of(0, 0))); }); /** * Missing device → typed DeviceNotFoundError. */ it("throws DeviceNotFoundError when the device does not exist", async () => { const { fs } = await makeFS(); await expectDeviceNotFoundError(() => fs.deleteNode(NodePointer.of(99, 1))); }); }); // ============================================================================ // moveNode // ============================================================================ describe("FileSystem.moveNode", () => { /** * Happy path: rename within the same directory. */ it("renames a node in place", async () => { const { fs, disks } = await makeFS({ devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeFileNode({ inode: 1 })) }], }); fs.moveNode(NodePointer.of(0, 1), NodePointer.of(0, 0), "b"); expect(disks.get(0)!.moveNodeEntry).toHaveBeenCalledWith(0, 0, "a", "b"); }); /** * Happy path: move to a different directory, preserving the name. * When `name` is omitted, `undefined` is forwarded to the device, which is * how `VDisk.moveNodeEntry` distinguishes "keep current name". */ it("moves a node to a different directory, keeping the source name", async () => { const { fs, disks } = await makeFS({ devices: [ { id: 0, setup: d => { addChild(d, 0, "src", makeDirectoryNode({ inode: 1 })); addChild(d, 0, "dst", makeDirectoryNode({ inode: 2 })); addChild(d, 1, "f", makeFileNode({ inode: 3 })); }, }, ], }); fs.moveNode(NodePointer.of(0, 3), NodePointer.of(0, 2)); expect(disks.get(0)!.moveNodeEntry).toHaveBeenCalledWith(1, 2, "f", undefined); }); /** * Happy path: move to a different directory with a new name. */ it("moves a node to a different directory with a new name", async () => { const { fs, disks } = await makeFS({ devices: [ { id: 0, setup: d => { addChild(d, 0, "src", makeDirectoryNode({ inode: 1 })); addChild(d, 0, "dst", makeDirectoryNode({ inode: 2 })); addChild(d, 1, "f", makeFileNode({ inode: 3 })); }, }, ], }); fs.moveNode(NodePointer.of(0, 3), NodePointer.of(0, 2), "g"); expect(disks.get(0)!.moveNodeEntry).toHaveBeenCalledWith(1, 2, "f", "g"); }); /** * Missing source device → typed DeviceNotFoundError. */ it("throws DeviceNotFoundError when the source device is missing", async () => { const { fs } = await makeFS(); await expectDeviceNotFoundError(() => fs.moveNode(NodePointer.of(99, 1), NodePointer.of(0, 0))); }); /** * Missing destination device → typed DeviceNotFoundError. */ it("throws DeviceNotFoundError when the destination device is missing", async () => { const { fs } = await makeFS({ devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeFileNode({ inode: 1 })) }], }); await expectDeviceNotFoundError(() => fs.moveNode(NodePointer.of(0, 1), NodePointer.of(99, 0))); }); /** * Missing source node → typed NodeNotFoundError. */ it("throws NodeNotFoundError when the source node is missing", async () => { const { fs } = await makeFS(); expectNodeNotFoundError(() => fs.moveNode(NodePointer.of(0, 99), NodePointer.of(0, 0))); }); /** * Root of device 0 is protected. */ it("throws IllegalMutationError when the source is device 0's root", async () => { const { fs } = await makeFS({ devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeDirectoryNode({ inode: 1 })) }], }); expectIllegalMutationError(() => fs.moveNode(NodePointer.of(0, 0), NodePointer.of(0, 1))); }); /** * Missing destination node → typed NodeNotFoundError. */ it("throws NodeNotFoundError when the destination node is missing", async () => { const { fs } = await makeFS({ devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeFileNode({ inode: 1 })) }], }); expectNodeNotFoundError(() => fs.moveNode(NodePointer.of(0, 1), NodePointer.of(0, 99))); }); /** * Destination is a file → typed NotADirectoryError. */ it("throws NotADirectoryError when the destination is not a directory", async () => { const { fs } = await makeFS({ devices: [ { id: 0, setup: d => { addChild(d, 0, "a", makeFileNode({ inode: 1 })); addChild(d, 0, "b", makeFileNode({ inode: 2 })); }, }, ], }); expectNotADirectoryError(() => fs.moveNode(NodePointer.of(0, 1), NodePointer.of(0, 2))); }); /** * Name collision at the destination → typed AlreadyExistsError. */ it("throws AlreadyExistsError when the destination already has the name", async () => { const { fs } = await makeFS({ devices: [ { id: 0, setup: d => { addChild(d, 0, "src", makeDirectoryNode({ inode: 1 })); addChild(d, 0, "dst", makeDirectoryNode({ inode: 2 })); addChild(d, 1, "f", makeFileNode({ inode: 3 })); addChild(d, 2, "f", makeFileNode({ inode: 4 })); }, }, ], }); expectAlreadyExistsError(() => fs.moveNode(NodePointer.of(0, 3), NodePointer.of(0, 2), "f")); }); /** * New name exceeds maxNameLength → typed InvalidNodeNameError. */ it("throws InvalidNodeNameError when the new name exceeds maxNameLength", async () => { const { fs } = await makeFS({ devices: [ { id: 0, setup: d => { addChild(d, 0, "src", makeDirectoryNode({ inode: 1 })); addChild(d, 0, "dst", makeDirectoryNode({ inode: 2 })); addChild(d, 1, "f", makeFileNode({ inode: 3 })); }, }, ], config: { maxNameLength: 2 }, }); expectInvalidNodeNameError(() => fs.moveNode(NodePointer.of(0, 3), NodePointer.of(0, 2), "abc")); }); /** * Moving a directory into its own descendant must be rejected. */ it("throws DirectoryLoopError when the destination is a descendant of the source", async () => { const { fs } = await makeFS({ devices: [ { id: 0, setup: d => { addChild(d, 0, "a", makeDirectoryNode({ inode: 1 })); addChild(d, 1, "b", makeDirectoryNode({ inode: 2 })); }, }, ], }); expectDirectoryLoopError(() => fs.moveNode(NodePointer.of(0, 1), NodePointer.of(0, 2))); }); /** * Moving a node into itself is also a directory loop. */ it("throws DirectoryLoopError when the source is the destination", async () => { const { fs } = await makeFS({ devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeDirectoryNode({ inode: 1 })) }], }); expectDirectoryLoopError(() => fs.moveNode(NodePointer.of(0, 1), NodePointer.of(0, 1))); }); /** * Moving a directory into its own parent with the *same* name currently * reports AlreadyExists (the name is a child of the destination, which is * the node itself's parent — collision check hits first). Debatable design * (could be a no-op); the test documents the current behavior. */ it("throws AlreadyExistsError when moving a node to the same parent with the same name", async () => { const { fs } = await makeFS({ devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeDirectoryNode({ inode: 1 })) }], }); expectAlreadyExistsError(() => fs.moveNode(NodePointer.of(0, 1), NodePointer.of(0, 0), "a")); }); /** * BUG: cross-device move is a stub. It logs to `console.error`, performs * no mutation, and does not throw. The user has confirmed this is WIP. */ it("BUG: cross-device moveNode only logs an error — performs no mutation", async () => { const { fs, disks } = await makeFS({ devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeFileNode({ inode: 1 })) }, { id: 1 }], }); const log = vi.spyOn(console, "error").mockImplementation(() => {}); fs.moveNode(NodePointer.of(0, 1), NodePointer.of(1, 0)); expect(log).toHaveBeenCalledWith(expect.stringMatching(/cross device/i)); expect(disks.get(0)!.moveNodeEntry).not.toHaveBeenCalled(); expect(disks.get(1)!.moveNodeEntry).not.toHaveBeenCalled(); }); }); // ============================================================================ // writeContent // ============================================================================ describe("FileSystem.writeContent", () => { /** * Happy path: forwards the file's content UUID and the blob to the device. */ it("forwards the file's content UUID and the blob to the device", async () => { const { fs, disks } = await makeFS({ devices: [ { id: 0, setup: d => addChild(d, 0, "f", makeFileNode({ inode: 1, content: "uuid-123" })), }, ], }); const blob = new Blob(["hello"]); fs.writeContent(NodePointer.of(0, 1), blob); expect(disks.get(0)!.writeContent).toHaveBeenCalledWith("uuid-123", blob); }); /** * Missing device → typed DeviceNotFoundError. */ it("throws DeviceNotFoundError when the device is missing", async () => { const { fs } = await makeFS(); await expectDeviceNotFoundError(() => fs.writeContent(NodePointer.of(99, 1), new Blob())); }); /** * Missing node → typed NodeNotFoundError. */ it("throws NodeNotFoundError when the node is missing", async () => { const { fs } = await makeFS(); expectNodeNotFoundError(() => fs.writeContent(NodePointer.of(0, 99), new Blob())); }); /** * Directory target → typed NotAFileError. */ it("throws NotAFileError when the target is a directory", async () => { const { fs } = await makeFS({ devices: [{ id: 0, setup: d => addChild(d, 0, "d", makeDirectoryNode({ inode: 1 })) }], }); await expectNotAFileError(() => fs.writeContent(NodePointer.of(0, 1), new Blob())); }); it("rejects writing content to a symlink with NotAFileError", async () => { const { fs } = await makeFS({ devices: [{ id: 0, setup: d => addChild(d, 0, "l", makeSymlinkNode({ inode: 1 })) }], }); await expectNotAFileError(() => fs.writeContent(NodePointer.of(0, 1), new Blob())); }); }); // ============================================================================ // streamContent // ============================================================================ describe("FileSystem.streamContent", () => { /** * Happy path: forwards the content UUID to the device and returns the stream. */ it("forwards the file's content UUID and returns the device stream", async () => { const { fs, disks } = await makeFS({ devices: [ { id: 0, setup: d => addChild(d, 0, "f", makeFileNode({ inode: 1, content: "uuid-123" })), }, ], }); const stream = fs.streamContent(NodePointer.of(0, 1)); expect(disks.get(0)!.streamContent).toHaveBeenCalledWith("uuid-123"); expect(stream).toBeInstanceOf(ReadableStream); }); /** * Missing device → typed DeviceNotFoundError. */ it("throws DeviceNotFoundError when the device is missing", async () => { const { fs } = await makeFS(); await expectDeviceNotFoundError(() => fs.streamContent(NodePointer.of(99, 1))); }); /** * Missing node → typed NodeNotFoundError. */ it("throws NodeNotFoundError when the node is missing", async () => { const { fs } = await makeFS(); expectNodeNotFoundError(() => fs.streamContent(NodePointer.of(0, 99))); }); /** * Directory target → typed NotAFileError. */ it("throws NotAFileError when the target is a directory", async () => { const { fs } = await makeFS({ devices: [{ id: 0, setup: d => addChild(d, 0, "d", makeDirectoryNode({ inode: 1 })) }], }); await expectNotAFileError(() => fs.streamContent(NodePointer.of(0, 1))); }); /** * EXPECTED-TO-FAIL: same symlink hole as `writeContent`. */ it("should reject streaming from a symlink with NotAFileError", async () => { const { fs } = await makeFS({ devices: [{ id: 0, setup: d => addChild(d, 0, "l", makeSymlinkNode({ inode: 1 })) }], }); expectNotAFileError(() => fs.streamContent(NodePointer.of(0, 1))); }); }); // ============================================================================ // modifyNode // ============================================================================ describe("FileSystem.modifyNode", () => { /** * Happy path: forwards metadata to `writeNodeEntry` with the node's inode. */ it("forwards metadata to the device with the node's inode", async () => { const { fs, disks } = await makeFS({ devices: [{ id: 0, setup: d => addChild(d, 0, "f", makeFileNode({ inode: 1 })) }], }); fs.modifyNode(NodePointer.of(0, 1), { mode: 0o600, owner: 7, group: 8 }); expect(disks.get(0)!.writeNodeEntry).toHaveBeenCalledWith(1, { mode: 0o600, owner: 7, group: 8 }); }); /** * Missing device → typed DeviceNotFoundError. */ it("throws DeviceNotFoundError when the device is missing", async () => { const { fs } = await makeFS(); await expectDeviceNotFoundError(() => fs.modifyNode(NodePointer.of(99, 1), { mode: 0 })); }); /** * Missing node → typed NodeNotFoundError. */ it("throws NodeNotFoundError when the node is missing", async () => { const { fs } = await makeFS(); expectNodeNotFoundError(() => fs.modifyNode(NodePointer.of(0, 99), { mode: 0 })); }); /** * Directory target → typed NotAFileError (arguably odd, but currently the * contract — directories are rejected; metadata edits on directories aren't * routed through this method today). */ it("throws NotAFileError when the target is a directory", async () => { const { fs } = await makeFS({ devices: [{ id: 0, setup: d => addChild(d, 0, "d", makeDirectoryNode({ inode: 1 })) }], }); await expectNotAFileError(() => fs.modifyNode(NodePointer.of(0, 1), { mode: 0 })); }); /** * EXPECTED-TO-FAIL: symlink hole again. Metadata on the symlink node itself * is currently forwarded to `writeNodeEntry`, which may be intentional * (chmod on a symlink) but is inconsistent with the directory rejection. * Flagging as a hole to be resolved. */ it("should reject modifying a symlink with NotAFileError (or document symlink semantics)", async () => { const { fs } = await makeFS({ devices: [{ id: 0, setup: d => addChild(d, 0, "l", makeSymlinkNode({ inode: 1 })) }], }); await expectNotAFileError(() => fs.modifyNode(NodePointer.of(0, 1), { mode: 0o700 })); }); }); // ============================================================================ // canRead / canWrite / canExecute // ============================================================================ /** * Reference implementation of the Unix permission model *as currently written* * (primary gid only, no supplementary group support). Used by the fast-check * property test as a regression guard against bit-constant typos. */ function referenceCan( bit: "read" | "write" | "execute", mode: number, node: { owner: number; group: number }, user: UserInfo, ): boolean { if (user.uid === 0) return true; const owner = { read: 0o400, write: 0o200, execute: 0o100 }[bit]; const group = { read: 0o040, write: 0o020, execute: 0o010 }[bit]; const other = { read: 0o004, write: 0o002, execute: 0o001 }[bit]; if (user.uid === node.owner) return (mode & owner) !== 0; if (user.gid === node.group) return (mode & group) !== 0; return (mode & other) !== 0; } describe("FileSystem.canRead / canWrite / canExecute", () => { /** * Root bypass: uid 0 may do anything, regardless of mode. */ it("uid 0 bypasses mode bits for all three checks", async () => { const { fs, disks } = await makeFS(); const root = makeUser({ uid: 0 }); for (const mode of [0, 0o777, 0o400, 0o040, 0o004]) { disks.get(0)!._nodes.set(1, makeFileNode({ inode: 1, mode })); expect(fs.canRead(NodePointer.of(0, 1), root)).toBe(true); expect(fs.canWrite(NodePointer.of(0, 1), root)).toBe(true); expect(fs.canExecute(NodePointer.of(0, 1), root)).toBe(true); } }); /** * Missing node → typed NodeNotFoundError. */ it("throws NodeNotFoundError when the node is missing", async () => { const { fs } = await makeFS(); const user = makeUser(); await expectNodeNotFoundError(() => fs.canRead(NodePointer.of(0, 99), user)); await expectNodeNotFoundError(() => fs.canWrite(NodePointer.of(0, 99), user)); await expectNodeNotFoundError(() => fs.canExecute(NodePointer.of(0, 99), user)); }); /** * EXPECTED-TO-FAIL: supplementary groups (`UserInfo.group`) are not * considered. In Unix, a user is a member of `node.group` if it is either * their primary gid OR present in the supplementary group list. The current * implementation only checks the primary gid, so a user in a supplementary * group cannot access a file whose group matches that supplementary group. * This documents the hole — likely to be fixed by adding * `user.group.includes(node.group)` to the group branch of each `can*`. */ it("should honor supplementary groups (UserInfo.group) in addition to primary gid", async () => { const { fs, disks } = await makeFS(); disks.get(0)!._nodes.set(1, makeFileNode({ inode: 1, mode: 0o040, owner: 999, group: 42 })); const user = makeUser({ uid: 1000, gid: 1000, group: [42, 99] }); // User is not owner, primary gid is 1000, but supplementary group contains 42. // Correct Unix: `canRead` is true. expect(fs.canRead(NodePointer.of(0, 1), user)).toBe(true); }); }); // ============================================================================ // fromPtr / toPtr // ============================================================================ describe("fromPtr / toPtr", () => { /** * Invalid formats must throw. (Example-based because the failure mode is * a specific regex, not a property over generated strings.) */ it.each(["", ":", "abc", "1:", ":1", "1.5:2", "-1:2", "1 :2", "1: 2", "1:2abc", "1:2 ", " 1:2"])( "throws on invalid pointer %j", bad => { expect(() => NodePointer.parse(bad)).toThrow(/Invalid node pointer format/); }, ); }); // ============================================================================ // Integration // ============================================================================ describe("FileSystem integration", () => { /** * A lifecycle that exercises every mutating method and asserts the sequence * of calls reaching the underlying device in the expected order. */ it("drives the underlying device through a typical file lifecycle", async () => { const { fs, disks } = await makeFS(); const disk = disks.get(0)!; const root = NodePointer.of(0, 0); fs.createNode(root, "hello.txt", { type: NodeType.File, mode: 0o644, owner: 1, group: 1, content: new Blob(["hi"]), size: 2, }); expect(disk.createNodeEntry).toHaveBeenLastCalledWith( 0, "hello.txt", expect.objectContaining({ type: NodeType.File }), ); // Simulate the device having created the node. addChild(disk, 0, "hello.txt", makeFileNode({ inode: 1, content: "uuid-1" })); fs.modifyNode(NodePointer.of(0, 1), { mode: 0o600 }); expect(disk.writeNodeEntry).toHaveBeenLastCalledWith(1, { mode: 0o600 }); fs.writeContent(NodePointer.of(0, 1), new Blob(["updated"])); expect(disk.writeContent).toHaveBeenLastCalledWith("uuid-1", expect.any(Blob)); fs.moveNode(NodePointer.of(0, 1), root, "renamed.txt"); expect(disk.moveNodeEntry).toHaveBeenLastCalledWith(0, 0, "hello.txt", "renamed.txt"); fs.deleteNode(NodePointer.of(0, 1)); expect(disk.unlinkNodeEntry).toHaveBeenLastCalledWith(0, "hello.txt"); }); });