Author SHA1 Message Date
ChaosMaker 031f8f7726 Merge branch 'master' of ssh://git.gornodox.dev:2222/ChaosMaker/termos
Merge new filesystem to master
2026-11-17 20:49:09 +01:00
ChaosMaker ed8c27677c - package.json tweaks
- `README.md` edits
2026-11-17 20:40:58 +01:00
ChaosMaker f4a74f67cf - Prepare for build and release 2026-11-17 20:03:19 +01:00
ChaosMaker 2f25e44681 - Fixed output formatting error in ls.ts
- Added an exported `Termos` object entry point
- Defined a basic config for the entry point
- Wrote a self contained initialization function for parsin the config into a returned `Shell` instance
- Adjusted `dev.ts` to use the said entry point
2026-11-16 12:16:49 +01:00
ChaosMaker d4ec6b0c49 - Added a safety check in serializer.ts to look for fields containing undefined
- Updated the fs json to contain the new result from the fixed serializer that parses the link counts
- Updated ls to use proper link counts and sizes in the long format (apart from dir sizes which remain at arbitrary 4096)
2026-11-14 10:49:51 +01:00
ChaosMaker de1ce64226 - Fixed cat command
- Moved device config initialization to `serializer.ts`
- Minor bugfixes
- Added `read()` to `filesystem.ts`
2026-11-13 04:15:28 +01:00
ChaosMaker d5566aa494 - Fixed a buged while condition inside path_resolver.ts
- Fixed `NodePointer` class to work with by reference comparison (maps use that) so the reverse index can look up entries properly`. `NodePointer` now caches every pointer created so logic can use reference comparison
2026-11-11 05:21:03 +01:00
ChaosMaker cb9cd7a67a new tree json pasted 2026-11-10 17:15:18 +01:00
ChaosMaker b161e42b3f - Fixed ls (mostly)
- Fixed sorting
- Many minor changes

(need to fix the json serializer to include size in its results *the C++ one*)
2026-11-10 16:19:10 +01:00
ChaosMaker 492f1ba372 - Fixed sort.ts
- Fixed `cd`
2026-11-10 13:13:38 +01:00
ChaosMaker 00200b4c75 - Fixed all of path_resolver.ts functions
- `resolveInode` functions now `resolvePointer`
- Fixed all resolve pointer -> path functions
2026-11-10 12:02:21 +01:00
ChaosMaker 584e594726 - Downward tree traversal fixed (untested - might have bugs)
- Moved filesystem mockups to a separate file
- Tree visualizer now has support for symlinks and mountpoints
2026-11-10 09:08:15 +01:00
ChaosMaker 4fa284de13 - Fixed resolvePath
- Added symlink resolution
- Added mount resolution
- Fixed filesystem not awaiting for disks to be mounted
(now `FileSystem.init()` needs to be called with `await`)
- Removed old test fixture files
- Added a feature-full `resolvePath`test suite

*all tests passing green*
2026-11-10 08:04:57 +01:00
ChaosMaker dd804f6f14 Virtual FileSystem fixed - (Needs unit testing)! 2026-11-09 05:10:44 +01:00
ChaosMaker 832fc6c759 - filesystem move node method fixed
- upTraversalTree fixed

- who tf knows what else
2026-10-30 06:13:34 +01:00
ChaosMaker 2a6e6c57c3 - filesystem fixes
- tree traversal up fixes
2026-09-21 04:44:10 +02:00
ChaosMaker f2b5f86a6c 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
2026-09-20 12:40:38 +02:00
ChaosMaker 933b1fc5e8 - vdisk done?
- vdiskman done?
2026-09-19 06:27:12 +02:00
ChaosMaker 849e0e61f5 a lot of mess, keep working on VDisk for now. 2026-09-17 10:32:31 +02:00
ChaosMaker d642ee6258 Update README.md 2026-09-12 02:02:30 +02:00
ChaosMaker 9c5bd71a5c - moved index code to dev.ts
- some work i dont know about or dont remember ¯\_(ツ)_/¯
2026-09-11 22:50:08 +02:00
ChaosMaker ec13299e95 some bs work, not finished (reference notes board on email for info) 2026-09-09 10:43:37 +02:00
ChaosMaker e2ade5de29 Bugfixes
- chunking fixed
- bug with recursive ls looping fixed
- bug with empty directories on ls -a failing fixed
2026-09-06 02:48:11 +02:00
ChaosMaker b75e691a0b Bugfixes and improvements
- ls fixed
- fixed a bug where ~ wouldnt resolve properly
- temporarily increased the process chunking treshold, because chunking breaks formatting
- added clear
- added pwd
2026-09-06 00:26:09 +02:00
ChaosMaker 776a93e21b Revert "more things broken for now"
This reverts commit 6cc9727091.
2026-09-03 23:22:17 +02:00
ChaosMaker 6cc9727091 more things broken for now
- shell now uses the path env variable
- commands run based on permission of the bin file
2026-09-03 12:27:32 +02:00
ChaosMaker 2715e5e28e Shell update
- changed shell init code to synchronous with guaranteed returns
- Shell.Instance now a normal method not a getter
2026-09-03 11:45:19 +02:00
ChaosMaker 8a349330b0 - initial changes to data shapes
- ls command needs fixing
2026-09-03 11:15:05 +02:00
50 changed files with 7400 additions and 5164 deletions
+1 -1
View File
@@ -19,7 +19,7 @@
"type": "node", "type": "node",
"request": "launch", "request": "launch",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/tsx", "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/tsx",
"runtimeArgs": ["src/index.ts"], "runtimeArgs": ["src/dev.ts"],
"cwd": "${workspaceFolder}", "cwd": "${workspaceFolder}",
"console": "integratedTerminal", "console": "integratedTerminal",
"skipFiles": ["<node_internals>/**"] "skipFiles": ["<node_internals>/**"]
+4
View File
@@ -0,0 +1,4 @@
{
"typescript.validate.enable": true,
"typescript.tsserver.experimental.enableProjectDiagnostics": true
}
+6 -4
View File
@@ -11,19 +11,21 @@ It doesnt implement a website friendly interface on its own. Thats one of the de
## Prerequisites ## Prerequisites
- [Node.js](https://nodejs.org/) installed (version 26.2.0 or higher) - [Node.js](https://nodejs.org/) installed (version 22 or higher)
- [pnpm](https://pnpm.io/) installed (version 12 or higher)
## Installation ## Installation
> [!NOTE] > [!NOTE]
> If youre using Windows or MacOS as your operating system then the installation process might be different. > If youre using Windows or MacOS as your operating system then the installation process might be different.
> Refer to [this website][ref1] on how to install nodejs on your operating system. > Refer to [this website][ref1] on how to install nodejs on your operating system
> and [this website][ref2] for pnpm accordingly.
[ref1]: https://nodejs.org/en/download [ref1]: https://nodejs.org/en/download
[ref2]: https://pnpm.io/installation
```bash ```bash
wget https://git.gornodox.dev/ChaosMaker/termos/archive/unstable-async.zip git clone https://git.gornodox.dev/ChaosMaker/termos.git
unzip -d termos unstable-async.zip
cd termos cd termos
npm install npm install
``` ```
-3287
View File
File diff suppressed because it is too large Load Diff
+29 -5
View File
@@ -1,16 +1,35 @@
{ {
"name": "termos", "name": "termos",
"version": "0.0.1", "version": "0.1.0",
"description": "Emulation library for a unix-like operating-system written in pure typescript", "description": "Emulation library for a unix-like operating-system written in pure typescript",
"main": "index.ts", "files": [
"dist"
],
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"default": "./dist/index.js"
}
},
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"scripts": { "scripts": {
"test": "eslint . && vitest", "test": "eslint . && vitest",
"dev": "npx tsx src/index.ts" "dev": "pnpx tsx src/dev.ts",
"build": "tsup src/index.ts --format esm --dts --clean"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "ssh://git@git.gornodox.dev:2222/ChaosMaker/termos.git" "url": "ssh://git@git.gornodox.dev:2222/ChaosMaker/termos.git"
}, },
"devEngines": {
"packageManager": {
"name": "pnpm",
"version": "12^",
"onFail": "warn"
}
},
"keywords": [], "keywords": [],
"author": "gornodox", "author": "gornodox",
"license": "ISC", "license": "ISC",
@@ -28,10 +47,15 @@
"vite-tsconfig-paths": "^6.1.1", "vite-tsconfig-paths": "^6.1.1",
"vitest": "^4.1.10" "vitest": "^4.1.10"
}, },
"dependencies": { "peerDependenciesMeta": {
"zod": "^4.4.3" "@types/node": {
"optional": true
}
}, },
"allowScripts": { "allowScripts": {
"esbuild@0.28.1": true "esbuild@0.28.1": true
},
"dependencies": {
"tsup": "^9.0.0"
} }
} }
+2699
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -0,0 +1,2 @@
allowBuilds:
esbuild: true
+18 -9
View File
@@ -1,11 +1,20 @@
export interface TermosConfig { export interface TermosConfig {
serverAddress: string; groups: string[];
dbName: string; users: {
idbName: string; username: string;
groups: string[];
home: string;
}[];
general: {
user: string;
serverAddress?: string;
dbName?: string;
idbName?: string;
};
filesystem: {
json: string;
maxNameLength?: number;
maxPathLength?: number;
maxSymlinkDepth?: number;
};
} }
export const defaultConfig: TermosConfig = {
serverAddress: "",
dbName: "termos",
idbName: "cache",
};
+1 -6
View File
@@ -3,12 +3,7 @@ import type { Result } from "./result";
import type { ShellState } from "./shell_state"; import type { ShellState } from "./shell_state";
import type { ShellError } from "./util/errors"; import type { ShellError } from "./util/errors";
export type CommandFn = ( export type CommandFn = (io: CommandIO, state: ShellState, args: string[]) => Promise<CommandOutput<ShellError>>;
io: CommandIO,
state: ShellState,
flags: string[],
args: string[],
) => Promise<CommandOutput<ShellError>>;
export interface CommandDescriptor { export interface CommandDescriptor {
fn: CommandFn; fn: CommandFn;
+4
View File
@@ -1,8 +1,10 @@
import type { CommandDescriptor } from "./command"; import type { CommandDescriptor } from "./command";
import { descriptor as cat } from "./commands/cat"; import { descriptor as cat } from "./commands/cat";
import { descriptor as cd } from "./commands/cd"; import { descriptor as cd } from "./commands/cd";
import { descriptor as clear } from "./commands/clear";
import { descriptor as echo } from "./commands/echo"; import { descriptor as echo } from "./commands/echo";
import { descriptor as ls } from "./commands/ls"; import { descriptor as ls } from "./commands/ls";
import { descriptor as pwd } from "./commands/pwd";
import { descriptor as testasync } from "./commands/testasync"; import { descriptor as testasync } from "./commands/testasync";
const reg = new Map<string, CommandDescriptor>(); const reg = new Map<string, CommandDescriptor>();
@@ -12,6 +14,8 @@ reg.set(cd.name, cd);
reg.set(testasync.name, testasync); reg.set(testasync.name, testasync);
reg.set(ls.name, ls); reg.set(ls.name, ls);
reg.set(cat.name, cat); reg.set(cat.name, cat);
reg.set(pwd.name, pwd);
reg.set(clear.name, clear);
Object.freeze(reg); Object.freeze(reg);
export const COMMAND_REGISTRY: ReadonlyMap<string, CommandDescriptor> = reg; export const COMMAND_REGISTRY: ReadonlyMap<string, CommandDescriptor> = reg;
+1 -7
View File
@@ -6,13 +6,7 @@ import type { ShellError } from "@core/util/errors";
export const COMMAND_NAME = ""; export const COMMAND_NAME = "";
//Need to implement escape sequences async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
async function main(
io: CommandIO,
state: ShellState,
flags: string[],
args: string[],
): Promise<CommandOutput<ShellError>> {
const result: ResultSuccess = createSuccessResult(COMMAND_NAME); const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
return { return {
+21 -17
View File
@@ -1,6 +1,7 @@
import type { CommandDescriptor, CommandOutput } from "@core/command"; import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { CommandIO } from "@core/command_io"; import type { CommandIO } from "@core/command_io";
import { TreeNodeType, type FileNode, type TreeNode } from "@core/filesystem/treenode"; import type { FileSystemCorruptionError } from "@core/filesystem/errors";
import { type NodePointer } from "@core/filesystem/node";
import { createErrorResult, createSuccessResult, type ResultSuccess } from "@core/result"; import { createErrorResult, createSuccessResult, type ResultSuccess } from "@core/result";
import { getCurrentSession } from "@core/session_manager"; import { getCurrentSession } from "@core/session_manager";
import type { ShellState } from "@core/shell_state"; import type { ShellState } from "@core/shell_state";
@@ -10,15 +11,12 @@ import { resolvePath } from "@core/util/path_resolver";
export const COMMAND_NAME = "cat"; export const COMMAND_NAME = "cat";
//Need to implement escape sequences //Need to implement escape sequences
async function main( async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
io: CommandIO,
state: ShellState,
flags: string[],
args: string[],
): Promise<CommandOutput<ShellError>> {
for (const arg of args) { for (const arg of args) {
const inode = resolvePath(state, arg); let ptr: NodePointer;
if (inode === -1) { try {
ptr = resolvePath(state, arg);
} catch (e) {
return { return {
state, state,
result: createErrorResult( result: createErrorResult(
@@ -30,15 +28,20 @@ async function main(
} satisfies CommandOutput<PathResolutionError>; } satisfies CommandOutput<PathResolutionError>;
} }
// Casting to TreeNode because the resolvePath already ensures the inode is correct; if (!state.filesystem.isFile(ptr)) {
const node = state.filesystem.getNode(inode) as TreeNode; const entries = state.filesystem.getNodeEntries(ptr);
if (!entries) {
if (node.type != TreeNodeType.File) { throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing. FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
return { return {
state, state,
result: createErrorResult( result: createErrorResult(
"PathResolutionError", "PathResolutionError",
`${node.name} is a directory`, `${entries[0]!.name} is a directory`,
{ path: arg }, { path: arg },
COMMAND_NAME, COMMAND_NAME,
), ),
@@ -47,15 +50,16 @@ async function main(
const session = getCurrentSession(state); const session = getCurrentSession(state);
if (!state.filesystem.canRead(inode, session.user)) { if (!state.filesystem.canRead(ptr, session.user)) {
return { return {
state, state,
result: createErrorResult("PermissionDenied", "Permission denied", { resource: arg }, COMMAND_NAME), result: createErrorResult("PermissionDenied", "Permission denied", { resource: arg }, COMMAND_NAME),
} satisfies CommandOutput<PermissionDeniedError>; } satisfies CommandOutput<PermissionDeniedError>;
} }
node as FileNode; const content = await state.filesystem.read(ptr);
io.writeStdout(node.content.toArray());
io.writeStdout(content);
} }
const result: ResultSuccess = createSuccessResult(COMMAND_NAME); const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
+11 -14
View File
@@ -1,5 +1,6 @@
import type { CommandDescriptor, CommandOutput } from "@core/command"; import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { CommandIO } from "@core/command_io"; import type { CommandIO } from "@core/command_io";
import type { NodePointer } from "@core/filesystem/node";
import { createErrorResult, createSuccessResult } from "@core/result"; import { createErrorResult, createSuccessResult } from "@core/result";
import { getCurrentSession } from "@core/session_manager"; import { getCurrentSession } from "@core/session_manager";
import { ShellState, withCwd } from "@core/shell_state"; import { ShellState, withCwd } from "@core/shell_state";
@@ -13,12 +14,7 @@ import { resolvePath } from "@core/util/path_resolver";
export const COMMAND_NAME = "cd"; export const COMMAND_NAME = "cd";
async function main( async function main(__io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
__io: CommandIO,
state: ShellState,
__flags: string[],
args: string[],
): Promise<CommandOutput<ShellError>> {
if (args.length > 1) { if (args.length > 1) {
return { return {
state, state,
@@ -31,16 +27,17 @@ async function main(
} satisfies CommandOutput<InvalidArgumentsError>; } satisfies CommandOutput<InvalidArgumentsError>;
} }
let inode: number; let ptr: NodePointer;
const session = getCurrentSession(state); const session = getCurrentSession(state);
if (args[0] === undefined) { if (args[0] === undefined) {
inode = session.user.home; ptr = session.user.home;
} else if (args[0] === "-") { } else if (args[0] === "-") {
inode = session.pwd; ptr = session.pwd;
} else { } else {
inode = resolvePath(state, args[0]); try {
if (inode === -1) { ptr = resolvePath(state, args[0]);
} catch (e) {
return { return {
state, state,
result: createErrorResult( result: createErrorResult(
@@ -53,21 +50,21 @@ async function main(
} }
} }
if (state.filesystem.isFile(inode)) { if (state.filesystem.isFile(ptr)) {
return { return {
state, state,
result: createErrorResult("PathResolutionError", "Not a directory", { path: args[0]! }, COMMAND_NAME), result: createErrorResult("PathResolutionError", "Not a directory", { path: args[0]! }, COMMAND_NAME),
} satisfies CommandOutput<PathResolutionError>; } satisfies CommandOutput<PathResolutionError>;
} }
if (!state.filesystem.canExecute(inode, session.user)) { if (!state.filesystem.canExecute(ptr, session.user)) {
return { return {
state, state,
result: createErrorResult("PermissionDenied", "Permission denied", { resource: args[0]! }, COMMAND_NAME), result: createErrorResult("PermissionDenied", "Permission denied", { resource: args[0]! }, COMMAND_NAME),
} satisfies CommandOutput<PermissionDeniedError>; } satisfies CommandOutput<PermissionDeniedError>;
} }
const returnState = withCwd(state, inode); const returnState = withCwd(state, ptr);
return { return {
state: returnState, state: returnState,
+23
View File
@@ -0,0 +1,23 @@
import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { CommandIO } from "@core/command_io";
import { createSuccessResult, type ResultSuccess } from "@core/result";
import type { ShellState } from "@core/shell_state";
import type { ShellError } from "@core/util/errors";
export const COMMAND_NAME = "clear";
async function main(io: CommandIO, state: ShellState, __args: string[]): Promise<CommandOutput<ShellError>> {
io.writeStdout(new TextEncoder().encode("\x1b[2J\x1b[0;0H"));
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
return {
state: state,
result,
};
}
export const descriptor: CommandDescriptor = {
fn: main,
name: COMMAND_NAME,
};
+1 -6
View File
@@ -7,12 +7,7 @@ import type { ShellError } from "@core/util/errors";
export const COMMAND_NAME = "echo"; export const COMMAND_NAME = "echo";
//Need to implement escape sequences //Need to implement escape sequences
async function main( async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
io: CommandIO,
state: ShellState,
__flags: string[],
args: string[],
): Promise<CommandOutput<ShellError>> {
const joined = args.join(" "); const joined = args.join(" ");
const encoded = new TextEncoder().encode(joined + "\n"); const encoded = new TextEncoder().encode(joined + "\n");
+378 -202
View File
@@ -1,70 +1,241 @@
import type { CommandDescriptor, CommandOutput } from "@core/command"; import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { CommandIO } from "@core/command_io"; import type { CommandIO } from "@core/command_io";
import { TreeNodeType, type DirectoryNode, type TreeNode } from "@core/filesystem/treenode"; import { NodePointer, NodeType, type DirectoryNode, type FileNode, type Node } from "@core/filesystem/node";
import { createErrorResult, createSuccessResult } from "@core/result"; import { createErrorResult, createSuccessResult } from "@core/result";
import { getCurrentSession } from "@core/session_manager"; import { getCurrentSession } from "@core/session_manager";
import type { ShellState } from "@core/shell_state"; import type { ShellState } from "@core/shell_state";
import type { ShellError } from "@core/util/errors"; import type { ShellError } from "@core/util/errors";
import { resolvePath } from "@core/util/path_resolver"; import { resolvePath } from "@core/util/path_resolver";
import { SortTreeNodeBy, sortTreeNodes } from "@core/util/sort"; import { SortNodeBy, sortNodes } from "@core/util/sort";
import { concatUint8Arrays } from "@termos/util/concat";
import { convertToUnit } from "@termos/util/format_unit"; import { convertToUnit } from "@termos/util/format_unit";
export const COMMAND_NAME = "ls"; export const COMMAND_NAME = "ls";
async function main( interface DirEntry {
io: CommandIO, name: string;
state: ShellState, ptr: NodePointer;
flags: string[], }
args: string[],
): Promise<CommandOutput<ShellError>> { async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
const entries: { inode: number; path: string }[] = []; const entries: { ptr: NodePointer; path: string }[] = [];
const paths: string[] = [];
const e = new TextEncoder(); const e = new TextEncoder();
const vars = flags.filter(
// Match at least 1 character between each side of a singular = character
f =>
f.match(/\w+[=]{1}\w+/g) &&
// Check if descriptors flags array contains an object with the name as the flags key and has takesValue set to true
descriptor.flags?.some(flag => flag.name === f.split("=")[0] && flag.takesValue === true),
);
const fSet = new Set(flags.filter(f => descriptor.flags?.some(flag => flag.name === f) && !vars.includes(f))); let options = {
all: false,
almostAll: false,
long: false,
noSort: false,
noOwner: false,
noGroup: false,
sortBy: SortNodeBy.NAME,
humanReadable: false,
f: false,
x: false,
timestamp: "atime",
reverse: false,
recursive: false,
quoteName: false,
appendIndicator: false,
numericUidGid: false,
literal: false,
inode: false,
si: false,
dereference: false,
fullTime: false,
};
if (fSet.size + vars.length < flags.length) { for (let arg of args) {
return { let val;
state, if (arg.startsWith("--")) {
result: createErrorResult("UsageError", `Invalid options`, {}, COMMAND_NAME), arg = arg.slice(2);
};
if (arg.match(/\w+[=]{1}\w+/g)) {
const flag = arg.split("=")[0];
val = arg.split("=")[1] ?? "";
if (flag === "time" && isValidTimestamp(val)) {
options.timestamp = val;
continue;
}
if (flag === "sort" && isValidSortMethod(val)) {
options.sortBy = val as SortNodeBy;
continue;
}
return {
state,
result: createErrorResult("UsageError", `Invalid options`, {}, COMMAND_NAME),
};
}
switch (arg) {
case "all":
options.all = true;
break;
case "almost-all":
options.almostAll = true;
break;
case "no-group":
options.noGroup = true;
break;
case "human-readable":
options.humanReadable = true;
break;
case "reverse":
options.reverse = true;
break;
case "recursive":
options.recursive = true;
break;
case "quote-name":
options.quoteName = true;
break;
case "numeric-uid-gid":
options.numericUidGid = true;
break;
case "inode":
options.inode = true;
break;
case "dereference":
options.dereference = true;
break;
case "literal":
options.literal = true;
break;
case "si":
options.si = true;
options.humanReadable = true;
break;
case "full-time":
options.fullTime = true;
break;
case "help":
// handled separately
break;
default:
return {
state,
result: createErrorResult("UsageError", `Invalid options`, {}, COMMAND_NAME),
};
break;
}
} else if (arg.startsWith("-")) {
arg = arg.slice(1);
for (const c of arg) {
switch (c) {
case "l":
options.long = true;
break;
case "a":
options.all = true;
break;
case "A":
options.almostAll = true;
break;
case "c":
options.timestamp = "ctime";
break;
case "U":
options.noSort = true;
break;
case "g":
options.noOwner = true;
options.long = true;
break;
case "G":
options.noGroup = true;
break;
case "h":
options.humanReadable = true;
break;
case "f":
options.f = true;
options.noSort = true;
options.all = true;
break;
case "x":
options.x = true;
break;
case "X":
options.sortBy = SortNodeBy.EXTENSION;
break;
case "u":
options.timestamp = "atime";
break;
case "t":
options.sortBy = options.timestamp as SortNodeBy;
break;
case "S":
options.sortBy = SortNodeBy.SIZE;
break;
case "r":
options.reverse = true;
break;
case "R":
options.recursive = true;
break;
case "Q":
options.quoteName = true;
break;
case "p":
options.appendIndicator = true;
break;
case "o":
options.noGroup = true;
options.long = true;
break;
case "n":
options.numericUidGid = true;
break;
case "N":
options.literal = true;
break;
case "i":
options.inode = true;
break;
case "L":
options.dereference = true;
break;
case "m":
// -m: comma separated list (not in options yet)
break;
default:
return {
state,
result: createErrorResult("UsageError", `Invalid options`, {}, COMMAND_NAME),
};
}
}
} else {
paths.push(arg);
}
} }
const session = getCurrentSession(state); const session = getCurrentSession(state);
const timeVar = vars.find(f => f.startsWith("time"))?.split("=")[1];
const sortVar = vars.find(f => f.startsWith("sort"))?.split("=")[1];
let sortBy: SortTreeNodeBy = sortVar && isValidSortMethod(sortVar) ? sortVar : SortTreeNodeBy.NAME; if (paths.length === 0) {
let timestamp: SortTreeNodeBy.ATIME | SortTreeNodeBy.MTIME | SortTreeNodeBy.CTIME = entries.push({ ptr: session.cwd, path: "." });
timeVar && isValidTimestamp(timeVar) ? timeVar : SortTreeNodeBy.ATIME;
if (args.length === 0) {
entries.push({ inode: session.cwd, path: "." });
} else { } else {
for (const arg of args) { for (const path of paths) {
const inode = resolvePath(state, arg); const ptr = resolvePath(state, path);
if (inode === -1) { if (!state.filesystem.exists(ptr)) {
return { return {
state, state,
result: createErrorResult( result: createErrorResult(
"PathResolutionError", "PathResolutionError",
`No such file or directory`, `No such file or directory`,
{ path: arg }, { path },
COMMAND_NAME, COMMAND_NAME,
), ),
}; };
} }
entries.push({ inode: inode, path: arg }); entries.push({ ptr, path });
} }
} }
if (fSet.has("l") || fSet.has("g") || fSet.has("o")) { if (options.long) {
for (const entry of entries) { for (const entry of entries) {
listDirEntries(entry); listDirEntries(entry);
} }
@@ -74,196 +245,201 @@ async function main(
} }
io.writeStdout(e.encode(`No support for short format yet\n`)); io.writeStdout(e.encode(`No support for short format yet\n`));
} }
io.writeStdout(e.encode("\n"));
return { return {
state, state,
result: createSuccessResult(COMMAND_NAME), result: createSuccessResult(COMMAND_NAME),
}; };
function listDirEntries(entry: { inode: number; path: string }): void { function listDirEntries(entry: { ptr: NodePointer; path: string }): void {
const node = state.filesystem.getNode(entry.inode) as DirectoryNode; const node = state.filesystem.getNode(entry.ptr) as DirectoryNode;
// This method of evaluating flags is faulty, it doesnt respect order; if (options.recursive) io.writeStdout(e.encode(`${entry.path}:\n`));
if (fSet.has("t")) sortBy = timestamp;
if (fSet.has("S")) sortBy = SortTreeNodeBy.SIZE;
if (fSet.has("X")) sortBy = SortTreeNodeBy.EXTENSION;
if (fSet.has("R") || fSet.has("recursive")) io.writeStdout(e.encode(`${entry.path}:\n`));
io.writeStdout(e.encode(`total ${Object.entries(node.children).length}\n`)); io.writeStdout(e.encode(`total ${Object.entries(node.children).length}\n`));
let children: TreeNode[] = Object.entries(node.children).map(c => state.filesystem.getNode(c[1])!); let children: DirEntry[] = Array.from(node.children.entries()).map(([name, inode]) => ({
if (!fSet.has("f") || !fSet.has("U")) name,
children = sortTreeNodes(state, children, fSet.has("r") || fSet.has("reverse"), sortBy); ptr: NodePointer.of(entry.ptr.device, inode),
}));
if (!options.noSort) children = sortNodes(state, children, options.reverse, options.sortBy);
if (fSet.has("a") || fSet.has("A") || fSet.has("all") || fSet.has("almost-all") || fSet.has("f")) if (!options.all && !options.almostAll) {
children = children.filter(c => !c.name.startsWith(".")); children = children.filter(c => !c.name.startsWith("."));
if (fSet.has("l") || fSet.has("g") || fSet.has("o")) {
longMode(io, state, children, fSet);
io.writeStdout(e.encode("\n"));
} }
if (fSet.has("R") || fSet.has("recursive")) { if (options.long) {
for (const child of children) { longMode(io, state, children);
if (child.type === TreeNodeType.Directory) { if (options.recursive) io.writeStdout(e.encode("\n"));
}
if (options.recursive) {
for (const c of children) {
if (c.name.match(/^[.]{1,2}$/)) continue;
const child = state.filesystem.getNode(c.ptr)!;
if (child.type === NodeType.Directory) {
let path; let path;
if (entry.path === "/") { if (entry.path === "/") {
path = "/" + child.name; path = "/" + c.name;
} else if (entry.path.endsWith("/")) { } else if (entry.path.endsWith("/")) {
path = entry.path + child.name; path = entry.path + c.name;
} else path = entry.path + "/" + child.name; } else path = entry.path + "/" + c.name;
listDirEntries({ inode: child.inode, path }); listDirEntries({ ptr: c.ptr, path });
} }
} }
} }
} }
function longMode(io: CommandIO, state: ShellState, children: DirEntry[]): void {
const e = new TextEncoder();
const buff: Uint8Array[] = [];
const nodes: DirEntry[] = [...children];
// Calculate the string size of the biggerst node in the array;
// Sets 4 length for directories because the arbitrary size is 4096 later in the code
const maxInodeWidth = Math.max(...nodes.map(c => c.ptr.inode.toString().length));
const maxSizeWidth = Math.max(
...nodes.map(c =>
state.filesystem.getNode(c.ptr)!.type === NodeType.File
? (state.filesystem.getNode(c.ptr) as FileNode).size.toString().length
: 4,
),
);
const maxLinksWidth = Math.max(
...nodes.map((c): number => {
const node = state.filesystem.getNode(c.ptr)!;
const o = node.link_count.toString().length;
return o;
}),
);
const namePadding = nodes.every(c => !c.name.includes(" "));
for (const n of nodes) {
const node = state.filesystem.getNode(n.ptr)!;
if (options.inode) {
const inode = node.inode.toString().padStart(maxInodeWidth, " ");
buff.push(e.encode(inode + " "));
}
// Mode
const mode: string = parseMode(node.mode);
switch (node.type) {
case NodeType.Directory:
buff.push(e.encode("d" + mode + " "));
break;
case NodeType.File:
buff.push(e.encode("-" + mode + " "));
break;
}
//Link count
const linkCount = node.link_count.toString().padStart(maxLinksWidth, " ") + " ";
buff.push(e.encode(linkCount));
// owner group
if (options.noGroup) {
buff.push(e.encode(`${state.users.get(node.owner)?.username} `));
} else if (options.noOwner) {
buff.push(e.encode(`${state.groups.get(node.group)?.groupname} `));
} else if (options.numericUidGid) {
buff.push(e.encode(`${node.owner} ${node.group} `));
} else {
buff.push(
e.encode(`${state.users.get(node.owner)?.username} ${state.groups.get(node.group)?.groupname} `),
);
}
//Size
// Holy abomination, pad the stringified bytesize number with whitespaces so the actual length of the string matches across all rows
// Sets the folder size to an arbitrary 4096, could change it later to smth else
let size;
if (options.humanReadable) {
const bytes = node.type === NodeType.File ? node.size : 4096;
size = convertToUnit(bytes, 1, options.si ? 1000 : 1024);
} else {
size =
node.type === NodeType.File
? `${node.size.toString().padStart(maxSizeWidth, " ")} `
: `${"4096".padStart(maxSizeWidth, " ")} `;
}
buff.push(e.encode(size));
//Timestamp
const date = getDateTimestamp(node, options.timestamp);
if (options.fullTime) {
buff.push(
// Month + 1 because January is 0
e.encode(
`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()} `,
),
);
} else {
buff.push(
// Month + 1 because January is 0
e.encode(`${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()} `),
);
}
//Name
if (options.quoteName) {
buff.push(
e.encode(
`"${node.type === NodeType.Directory ? n.name + '"' + (options.appendIndicator ? "/" : "") : n.name + '"'}\n`,
),
);
} else {
const unpadded = `${n.name.includes(" ") && !options.literal ? "'" + n.name + "'" : n.name}`;
const name = `${!namePadding ? (unpadded.includes(" ") ? unpadded : " " + unpadded) : unpadded}`;
buff.push(
e.encode(
`${node.type === NodeType.Directory ? name + (options.appendIndicator ? "/" : "") : name}\n`,
),
);
}
}
const out = concatUint8Arrays(buff);
io.writeStdout(out);
}
function getDateTimestamp(node: Node, ts: string): Date {
if (ts === "atime") return new Date(node.atime);
if (ts === "ctime") return new Date(node.ctime);
if (ts === "mtime") return new Date(node.mtime);
return new Date();
}
function parseMode(mode: number) {
const owner = (mode >> 6) & 7;
const group = (mode >> 3) & 7;
const other = mode & 7;
const map = (bits: number) => {
let s = "";
s += bits & 4 ? "r" : "-";
s += bits & 2 ? "w" : "-";
s += bits & 1 ? "x" : "-";
return s;
};
return map(owner) + map(group) + map(other);
}
function isValidSortMethod(value: string): value is SortNodeBy {
return Object.values(SortNodeBy).includes(value as SortNodeBy);
}
function isValidTimestamp(value: string): value is SortNodeBy.ATIME | SortNodeBy.MTIME | SortNodeBy.CTIME {
return Object.values(SortNodeBy).includes(value as SortNodeBy.ATIME | SortNodeBy.MTIME | SortNodeBy.CTIME);
}
} }
//function normalMode(io: CommandIO, state: ShellState, flags: string[], args: string[]): void {} //function normalMode(io: CommandIO, state: ShellState, flags: string[], args: string[]): void {}
function longMode(io: CommandIO, state: ShellState, nodes: TreeNode[], flags: Set<string>): void {
const e = new TextEncoder();
if (flags.has("a") || flags.has("all") || flags.has("f")) {
const cwdNode = state.filesystem.getNode(nodes[0]!.parent)!;
const parentNode = state.filesystem.getNode(cwdNode.parent)!;
const parent: TreeNode = { ...parentNode, name: ".." };
nodes.unshift(parent);
const cwd: TreeNode = { ...cwdNode, name: "." };
nodes.unshift(cwd);
}
// Calculate the string size of the biggerst node in the array;
// Sets 4 length for directories because the arbitrary size is 4096 later in the code
const maxInodeWidth = Math.max(...nodes.map(c => c.inode.toString().length));
const maxSizeWidth = Math.max(
...nodes.map(c => (c.type === TreeNodeType.File ? c.content.byteSize().toString().length : 4)),
);
const maxChildrenWidth = Math.max(
...nodes.map(c =>
c.type === TreeNodeType.Directory ? Object.entries(c.children).length.toString().length : 2,
),
);
for (const node of nodes) {
if (flags.has("i") || flags.has("inode")) {
const inode = node.inode.toString().padStart(maxInodeWidth, " ");
io.writeStdout(e.encode(inode + " "));
}
const mode: string = parseMode(node.mode);
switch (node.type) {
case TreeNodeType.Directory:
io.writeStdout(e.encode("d" + mode + " "));
break;
case TreeNodeType.File:
io.writeStdout(e.encode("-" + mode + " "));
break;
}
const childAmnt =
node.type === TreeNodeType.Directory
? `${Object.entries(node.children).length.toString().padStart(maxChildrenWidth, " ")} `
: `${"10".padStart(maxChildrenWidth, " ")} `;
io.writeStdout(e.encode(childAmnt));
if (flags.has("o") || flags.has("G") || flags.has("no-group")) {
io.writeStdout(e.encode(`${state.users.get(node.owner)?.username} `));
} else if (flags.has("g")) {
io.writeStdout(e.encode(`${state.groups.get(node.group)?.groupname} `));
} else if (flags.has("n") || flags.has("numeric-uid-gid")) {
io.writeStdout(e.encode(`${node.owner} ${node.group} `));
} else {
io.writeStdout(
e.encode(`${state.users.get(node.owner)?.username} ${state.groups.get(node.group)?.groupname} `),
);
}
// Holy abomination, pad the stringified bytesize number with whitespaces so the actual length of the string matches across all rows
// Sets the folder size to an arbitrary 4096, could change it later to smth else
let size;
if (flags.has("h") || flags.has("human-readable")) {
const bytes = node.type === TreeNodeType.File ? node.content.byteSize() : 4096;
size = convertToUnit(bytes, 1, flags.has("si") ? 1000 : 1024);
} else {
size =
node.type === TreeNodeType.File
? `${node.content.byteSize().toString().padStart(maxSizeWidth, " ")} `
: `${"4096".padStart(maxSizeWidth, " ")} `;
}
io.writeStdout(e.encode(size));
// for now only mtime, need a helper function for all the formatting later on
const mtime = new Date(node.mtime);
if (flags.has("full-time")) {
io.writeStdout(
// Month + 1 because January is 0
e.encode(
`${mtime.getFullYear()}-${mtime.getMonth() + 1}-${mtime.getDate()} ${mtime.getHours()}:${mtime.getMinutes()} `,
),
);
} else {
io.writeStdout(
// Month + 1 because January is 0
e.encode(`${mtime.getMonth() + 1}-${mtime.getDate()} ${mtime.getHours()}:${mtime.getMinutes()} `),
);
}
const appendSlash = flags.has("p");
if (flags.has("Q") || flags.has("quote-name")) {
io.writeStdout(
e.encode(
`"${node.type === TreeNodeType.Directory ? node.name + '"' + (appendSlash ? "/" : "") : node.name + '"'}\n`,
),
);
} else if (!flags.has("N") || !flags.has("literal")) {
io.writeStdout(
e.encode(
`${node.type === TreeNodeType.Directory ? node.name + (appendSlash ? "/" : "") : node.name}\n`,
),
);
} else {
const name = `${node.name.includes(" ") ? "'" + node.name + "'" : node.name}`;
io.writeStdout(
e.encode(`${node.type === TreeNodeType.Directory ? name + (appendSlash ? "/" : "") : name}\n`),
);
}
}
}
function parseMode(mode: number) {
const owner = (mode >> 6) & 7;
const group = (mode >> 3) & 7;
const other = mode & 7;
const map = (bits: number) => {
let s = "";
s += bits & 4 ? "r" : "-";
s += bits & 2 ? "w" : "-";
s += bits & 1 ? "x" : "-";
return s;
};
return map(owner) + map(group) + map(other);
}
function isValidSortMethod(value: string): value is SortTreeNodeBy {
return Object.values(SortTreeNodeBy).includes(value as SortTreeNodeBy);
}
function isValidTimestamp(value: string): value is SortTreeNodeBy.ATIME | SortTreeNodeBy.MTIME | SortTreeNodeBy.CTIME {
return Object.values(SortTreeNodeBy).includes(
value as SortTreeNodeBy.ATIME | SortTreeNodeBy.MTIME | SortTreeNodeBy.CTIME,
);
}
export const descriptor: CommandDescriptor = { export const descriptor: CommandDescriptor = {
fn: main, fn: main,
flags: [ flags: [
+41
View File
@@ -0,0 +1,41 @@
import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { CommandIO } from "@core/command_io";
import { createErrorResult, createSuccessResult, type ResultSuccess } from "@core/result";
import { getCurrentSession } from "@core/session_manager";
import type { ShellState } from "@core/shell_state";
import type { InvalidArgumentsError, ShellError } from "@core/util/errors";
import { resolvePointer } from "@core/util/path_resolver";
export const COMMAND_NAME = "pwd";
//Need to implement escape sequences
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
if (args.length > 0) {
return {
state,
result: createErrorResult(
"InvalidArguments",
`Expected aruments 0, got ${args.length}.`,
{ expected: "pwd", actual: `pwd ${args.toString().replace(/[,]/g, " ")}` },
COMMAND_NAME,
),
} satisfies CommandOutput<InvalidArgumentsError>;
}
const session = getCurrentSession(state);
const path = resolvePointer(state, session.cwd);
io.writeStdout(new TextEncoder().encode(path));
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
return {
state: state,
result,
};
}
export const descriptor: CommandDescriptor = {
fn: main,
name: COMMAND_NAME,
};
+1 -6
View File
@@ -8,12 +8,7 @@ import { createImmutableBuffer } from "@core/util/immutable_buffer";
const COMMAND_NAME = "async"; const COMMAND_NAME = "async";
async function main( async function main(io: CommandIO, state: ShellState, __args: string[]): Promise<CommandOutput<ShellError>> {
io: CommandIO,
state: ShellState,
__flags: string[],
__args: string[],
): Promise<CommandOutput<ShellError>> {
while (true) { while (true) {
const out = await io.getSignal(); const out = await io.getSignal();
+1 -7
View File
@@ -1,6 +1,5 @@
import type { CommandDescriptor, CommandOutput } from "@core/command"; import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { CommandIO } from "@core/command_io"; import type { CommandIO } from "@core/command_io";
import { TreeNodeType } from "@core/filesystem/treenode";
import { createSuccessResult, type ResultSuccess } from "@core/result"; import { createSuccessResult, type ResultSuccess } from "@core/result";
import { getCurrentSession } from "@core/session_manager"; import { getCurrentSession } from "@core/session_manager";
import type { ShellState } from "@core/shell_state"; import type { ShellState } from "@core/shell_state";
@@ -10,12 +9,7 @@ import { resolvePath } from "@core/util/path_resolver";
export const COMMAND_NAME = "touch"; export const COMMAND_NAME = "touch";
//Need to implement escape sequences //Need to implement escape sequences
async function main( async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
io: CommandIO,
state: ShellState,
flags: string[],
args: string[],
): Promise<CommandOutput<ShellError>> {
for (const arg of args) { for (const arg of args) {
const inode = resolvePath(state, arg); const inode = resolvePath(state, arg);
const session = getCurrentSession(state); const session = getCurrentSession(state);
+40 -3
View File
@@ -1,4 +1,4 @@
import type { TreeNodeType } from "./treenode"; import type { NodePointer, NodeType } from "./node";
export type FileSystemError = export type FileSystemError =
NotADirectoryError | AlreadyExistsError | NodeNotFoundError | IllegalMutationError | FileSystemInitializationError; NotADirectoryError | AlreadyExistsError | NodeNotFoundError | IllegalMutationError | FileSystemInitializationError;
@@ -14,7 +14,15 @@ export interface NotADirectoryError {
message: string; message: string;
timestamp: number; timestamp: number;
type: "NotADirectory"; type: "NotADirectory";
nodeType: TreeNodeType; nodeType: NodeType;
}
export interface NotAFileError {
inode: number;
message: string;
timestamp: number;
type: "NotAFile";
nodeType: NodeType;
} }
export interface AlreadyExistsError { export interface AlreadyExistsError {
@@ -28,7 +36,21 @@ export interface AlreadyExistsError {
export interface NodeNotFoundError { export interface NodeNotFoundError {
type: "NodeNotFound"; type: "NodeNotFound";
message: string; message: string;
inode: number; pointer: NodePointer;
timestamp: number;
}
export interface DeviceNotFoundError {
type: "DeviceNotFound";
message: string;
device_id: number;
timestamp: number;
}
export interface MountPointNotFoundError {
type: "MountPointNotFound";
message: string;
pointer: NodePointer;
timestamp: number; timestamp: number;
} }
@@ -45,3 +67,18 @@ export interface DirectoryLoopError {
descendantInode: number; descendantInode: number;
ancestorInode: number; ancestorInode: number;
} }
export interface InvalidNodeNameError {
type: "InvalidNodeName";
message: string;
timestamp: number;
pointer: NodePointer;
attemptedName: string;
}
export interface FileSystemCorruptionError {
type: "FileSystemCorruption";
message: string;
timestamp: number;
override?: {};
}
File diff suppressed because it is too large Load Diff
+120
View File
@@ -0,0 +1,120 @@
export type Node = FileNode | DirectoryNode | SymlinkNode;
export type NodeHash = ReadonlyMap<number, Node>;
export type ShadowHash = ReadonlyMap<number, Node | null>;
export class NodePointer {
private static readonly _cache = new Map<string, NodePointer>();
private readonly _device_id: number;
private readonly _inode: number;
private constructor(device_id: number, inode: number) {
this._device_id = device_id;
this._inode = inode;
}
static of(device_id: number, inode: number): NodePointer {
const key = `${device_id}:${inode}`;
let p = NodePointer._cache.get(key);
if (!p) {
p = new NodePointer(device_id, inode);
NodePointer._cache.set(key, p);
}
return p;
}
static parse(s: string): NodePointer {
const m = /^(\d+):(\d+)$/.exec(s);
if (!m) throw new Error(`Invalid NodePointer: ${s}`);
let p = NodePointer._cache.get(s);
if (!p) {
p = new NodePointer(Number(m[1]), Number(m[2]));
NodePointer._cache.set(s, p);
}
return p;
}
get device(): number {
return this._device_id;
}
get inode(): number {
return this._inode;
}
toString(): string {
return `${this._device_id}:${this.inode}`;
}
equals(other: NodePointer): boolean {
return this._device_id === other._device_id && this.inode === other.inode;
}
}
//export type NodePointer = `${string}:${string}`;
export interface NodeEntry {
readonly pinode: number;
readonly pdevice_id: number;
readonly name: string;
}
export interface FileNode {
readonly type: NodeType.File;
readonly inode: number;
readonly link_count: number;
readonly mode: number;
readonly owner: number;
readonly group: number;
readonly mtime: number;
readonly ctime: number;
readonly atime: number;
readonly content: string;
readonly size: number;
}
export interface DirectoryNode {
readonly type: NodeType.Directory;
readonly inode: number;
readonly link_count: number;
readonly mode: number;
readonly owner: number;
readonly group: number;
readonly mtime: number;
readonly ctime: number;
readonly atime: number;
readonly children: Map<string, number>;
}
export interface SymlinkNode {
readonly type: NodeType.Symlink;
readonly inode: number;
readonly link_count: number;
readonly mode: number;
readonly owner: number;
readonly group: number;
readonly mtime: number;
readonly ctime: number;
readonly atime: number;
readonly target: string;
}
export enum NodeType {
File = 0,
Directory = 1,
Symlink = 2,
}
/* export function toPtr({ device_id, inode }: { device_id: number; inode: number }): NodePointer {
return `${device_id}:${inode}`;
}
export function fromPtr(ptr: NodePointer): { device_id: number; inode: number } {
if (!ptr.match(/^\d+[:]\d+$/)) {
//TODO: Make typed
throw new Error("Invalid node pointer format");
}
const arr = ptr.split(":");
return {
device_id: Number(arr[0]),
inode: Number(arr[1]),
};
} */
-51
View File
@@ -1,51 +0,0 @@
import type { ImmutableBuffer } from "@core/util/immutable_buffer";
export type TreeNode = FileNode | DirectoryNode;
export interface FileNode {
readonly type: TreeNodeType.File;
readonly inode: number;
readonly name: string;
readonly parent: number;
readonly mode: number;
readonly owner: number;
readonly group: number;
readonly mtime: number;
readonly ctime: number;
readonly atime: number;
readonly content: ImmutableBuffer;
}
export interface DirectoryNode {
readonly type: TreeNodeType.Directory;
readonly inode: number;
readonly name: string;
readonly parent: number;
readonly mode: number;
readonly owner: number;
readonly group: number;
readonly mtime: number;
readonly ctime: number;
readonly atime: number;
readonly children: Readonly<Record<string, number>>;
}
/* export interface SymlinkNode {
readonly type: TreeNodeType.Symlink;
readonly inode: number;
readonly name: string;
readonly parent: number;
readonly mode: number;
readonly owner: number;
readonly group: number;
readonly mtime: number;
readonly ctime: number;
readonly atime: number;
readonly target: string;
} */
export enum TreeNodeType {
File = 0,
Directory = 1,
//Symlink = 2,
}
+447
View File
@@ -0,0 +1,447 @@
import type { Blob } from "node:buffer";
import { Readable } from "node:stream";
import { blob } from "node:stream/consumers";
import { NodePointer, NodeType, type DirectoryNode, type Node, type NodeEntry, type NodeHash } 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;
label: string;
index: number;
readonly: boolean;
size: number;
base: NodeHash;
dataC: DataConfig;
}
export interface DataConfig {
chunkSize: number;
cacheSize: number;
cacheTTL: number;
}
export interface IDataStore {
read(uuid: string): Promise<Uint8Array>;
stream(uuid: string): Readable;
put(uuid: string, blob: Blob): Promise<void>;
delete(uuid: string): Promise<void>;
has(uuid: string): Promise<boolean>;
list(): Promise<string[]>;
}
export interface IMetaStore {
loadAll(): Promise<Map<number, Node | null>>;
write(entries: Array<[number, Node | null]>): Promise<void>;
delete(entries: Array<number>): Promise<void>;
}
export class VDisk {
private readonly _id: number;
private readonly _label: string;
private readonly _readonly: boolean;
private readonly _totalSize: number;
private readonly _base: NodeHash;
private readonly _dataStore: IDataStore;
private readonly _metaStore: IMetaStore;
private _iIndex: number;
private _rIndex: ReadonlyMap<NodePointer, ReadonlyArray<NodeEntry>>;
private _overlay: Map<number, Node | null>;
private _pending: Map<number, Node | null> | null;
private _rIndexInvalid: boolean;
private _flush: Promise<void>;
private constructor(config: VDiskConfig, data: IDataStore, meta: IMetaStore) {
this._id = config.id;
this._label = config.label;
this._readonly = config.readonly;
this._totalSize = config.size;
this._base = config.base;
this._iIndex = config.index;
this._dataStore = data;
this._metaStore = meta;
this._overlay = new Map();
this._rIndex = new Map();
this._rIndexInvalid = false;
this._pending = null;
this._flush = Promise.resolve();
}
private async _batch<T>(fn: () => T): Promise<T> {
if (this._pending) {
console.error("Nested batch not ok");
}
this._pending = new Map();
let result: T;
try {
result = fn();
} catch (err) {
this._pending = null;
throw err;
}
const pending = this._pending;
this._pending = null;
for (const [inode, node] of pending) {
this._overlay.set(inode, node);
}
const entries = Array.from(pending.entries());
const next = this._flush.then(() => this._metaStore.write(entries));
this._flush = next.catch(() => {});
await next;
return result;
}
private _isWritable(): void {
if (this._readonly) throw Error(`The ${this._label} device under id - ${this._id} is marked readonly`);
}
private _buildReverseIndex(): Map<NodePointer, NodeEntry[]> {
const index: Map<NodePointer, NodeEntry[]> = new Map();
const stack: [number, number, number, string][] = [];
const root = this.getNode(0) as DirectoryNode;
for (const [name, inode] of root.children) {
if (name === "." || name === "..") continue;
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 = NodePointer.of(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) {
if (name === "." || name === "..") continue;
stack.push([cinode, inode, pdevice_id, name]);
}
}
}
return index;
}
private _putNode(inode: number, node: Node | null): void {
if (!this._pending)
throw new Error(
"_putNode called outside of batch. This is not a BUG. Every mutation must be wrapped in a _batch call",
);
this._pending.set(inode, node);
}
public static async open(config: VDiskConfig, data: IDataStore, meta: IMetaStore): Promise<VDisk> {
const vdisk = new VDisk(config, data, meta);
await vdisk.loadOverlay();
vdisk._rIndex = vdisk._buildReverseIndex();
return vdisk;
}
public getNode(inode: number): Node | undefined {
if (this._pending && this._pending.has(inode)) {
return this._pending.get(inode) ?? undefined;
}
const node = this._overlay.get(inode);
if (node) return node;
if (node === null) return undefined;
return this._base.get(inode);
}
public async createNodeEntry(
pinode: number,
name: string,
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 },
): Promise<number> {
return this._batch(async () => {
this._isWritable();
const index = ++this._iIndex;
const time = Date.now();
const link_count = data.type === NodeType.Directory ? 2 : 1;
const base = {
inode: index,
link_count,
type: data.type,
mode: data.mode,
owner: data.owner,
group: data.group,
mtime: time,
ctime: time,
atime: time,
};
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: 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() };
break;
case NodeType.Symlink:
node = { ...base, type: NodeType.Symlink, target: data.target };
break;
}
const children = new Map(pnode.children);
children.set(name, index);
const parent = {
...pnode,
children,
link_count: pnode.link_count + (data.type === NodeType.Directory ? 1 : 0),
mtime: time,
ctime: time,
};
this._putNode(index, node);
this._putNode(pinode, parent);
this.invalidateRIndex();
return index;
});
}
public linkNodeEntry(pinode: number, name: string, tinode: number): Promise<void> {
return this._batch(() => {
this._isWritable();
const pnode = this.getNode(pinode) as DirectoryNode;
const tnode = this.getNode(tinode) as Node;
const time = Date.now();
const children = new Map(pnode.children);
children.set(name, tnode.inode);
const parent = { ...pnode, children, mtime: time, ctime: time };
const target = { ...tnode, link_count: tnode.link_count + 1, ctime: time };
this._putNode(tinode, target);
this._putNode(pinode, parent);
this.invalidateRIndex();
});
}
public unlinkNodeEntry(inode: number, name: string): Promise<void> {
return this._batch(() => {
this._isWritable();
const pnode = this.getNode(inode) as DirectoryNode;
const tinode = pnode.children.get(name)!;
const tnode = this.getNode(tinode) as Node;
const time = Date.now();
const children = new Map(pnode.children);
children.delete(name);
const parent = { ...pnode, children, mtime: time, ctime: time };
const link_count = tnode.link_count - 1;
const wasLast = link_count === 0;
this._putNode(inode, parent);
this._putNode(tinode, wasLast ? null : { ...tnode, link_count, ctime: Date.now() });
this.invalidateRIndex();
});
}
public moveNodeEntry(pinode: number, dinode: number, tname: string, dname?: string): Promise<void> {
return this._batch(() => {
this._isWritable();
const pnode = this.getNode(pinode) as DirectoryNode;
const dnode = this.getNode(dinode) as DirectoryNode;
const tinode = pnode.children.get(tname)!;
const tnode = this.getNode(tinode)!;
const name = dname ?? tname;
const isDir = tnode.type === NodeType.Directory;
const time = Date.now();
if (pinode === dinode) {
const pchildren = new Map(pnode.children);
pchildren.delete(tname);
pchildren.set(name, tinode);
const parent = { ...pnode, children: pchildren, mtime: time, ctime: time };
const target = { ...tnode, ctime: time };
this._putNode(pinode, parent);
this._putNode(tinode, target);
this.invalidateRIndex();
return;
}
const pchildren = new Map(pnode.children);
pchildren.delete(tname);
const dchildren = new Map(dnode.children);
dchildren.set(name, tinode);
const parent = {
...pnode,
children: pchildren,
mtime: time,
ctime: time,
link_count: pnode.link_count - (isDir ? 1 : 0),
};
const target = { ...tnode, ctime: time };
const destination = {
...dnode,
children: dchildren,
mtime: time,
ctime: time,
link_count: dnode.link_count + (isDir ? 1 : 0),
};
this._putNode(pinode, parent);
this._putNode(tinode, target);
this._putNode(dinode, destination);
this.invalidateRIndex();
});
}
public writeNodeEntry(inode: number, data: { mode?: number; owner?: number; group?: number }): Promise<void> {
return this._batch(() => {
this._isWritable();
const node = this.getNode(inode)!;
const newNode: Node = {
...node,
mode: data.mode ?? node.mode,
owner: data.owner ?? node.owner,
group: data.group ?? node.group,
ctime: Date.now(),
};
this._putNode(inode, newNode);
});
}
public readContent(uuid: string): Promise<Uint8Array> {
return this._dataStore.read(uuid);
}
public streamContent(uuid: string): Readable {
return this._dataStore.stream(uuid);
}
public async writeContent(uuid: string, blob: Blob): Promise<void> {
this._isWritable();
await this._dataStore.put(uuid, blob);
}
public async deleteContent(uuid: string): Promise<void> {
this._isWritable();
await this._dataStore.delete(uuid);
}
public hasContent(uuid: string): Promise<boolean> {
return this._dataStore.has(uuid);
}
public async loadOverlay(): Promise<void> {
const overlay = await this._metaStore.loadAll();
this._overlay = new Map(overlay);
}
// public sweepOrphans(): Promise<void> {}
// public sweepDangling(): Promise<void> {}
public invalidateRIndex(): void {
this._rIndexInvalid = true;
}
public getIndex(): ReadonlyMap<NodePointer, ReadonlyArray<NodeEntry>> {
if (this._rIndexInvalid) {
this._rIndex = this._buildReverseIndex();
this._rIndexInvalid = false;
}
return this._rIndex;
}
public get ID(): number {
return this._id;
}
public get Label(): string {
return this._label;
}
public get IsReadonly(): boolean {
return this._readonly;
}
public get ByteSize(): number {
return this._totalSize;
}
}
View File
+4 -3
View File
@@ -1,3 +1,4 @@
import type { NodePointer } from "./filesystem/node";
import { type HistoryState } from "./history_state"; import { type HistoryState } from "./history_state";
import { createShellState, type ShellState } from "./shell_state"; import { createShellState, type ShellState } from "./shell_state";
import { createShellError, type LoginError, type UserNotFoundError } from "./util/errors"; import { createShellError, type LoginError, type UserNotFoundError } from "./util/errors";
@@ -13,15 +14,15 @@ export interface UserInfo {
readonly uid: number; readonly uid: number;
readonly gid: number; readonly gid: number;
readonly group: readonly number[]; readonly group: readonly number[];
readonly home: number; readonly home: NodePointer;
} }
export interface SessionState { export interface SessionState {
readonly user: UserInfo; readonly user: UserInfo;
readonly envVars: ReadonlyMap<string, string>; readonly envVars: ReadonlyMap<string, string>;
readonly history: HistoryState; readonly history: HistoryState;
readonly cwd: number; readonly cwd: NodePointer;
readonly pwd: number; readonly pwd: NodePointer;
readonly exitCode: number; readonly exitCode: number;
} }
+3 -2
View File
@@ -1,4 +1,5 @@
import type { FileSystem } from "./filesystem/filesystem"; import type { FileSystem } from "./filesystem/filesystem";
import type { NodePointer } from "./filesystem/node";
import { addHistoryEntry } from "./history_state"; import { addHistoryEntry } from "./history_state";
import type { GroupInfo, UserInfo } from "./session_manager"; import type { GroupInfo, UserInfo } from "./session_manager";
import { createInitialSessionState, getCurrentSession, type SessionState } from "./session_manager"; import { createInitialSessionState, getCurrentSession, type SessionState } from "./session_manager";
@@ -38,14 +39,14 @@ export function createShellState(
}); });
} }
export function withCwd(state: ShellState, inode: number): ShellState { export function withCwd(state: ShellState, ptr: NodePointer): ShellState {
const session = getCurrentSession(state); const session = getCurrentSession(state);
const newSession = Object.freeze({ const newSession = Object.freeze({
user: session.user, user: session.user,
envVars: Object.freeze(session.envVars), envVars: Object.freeze(session.envVars),
history: Object.freeze(session.history), history: Object.freeze(session.history),
cwd: inode, cwd: ptr,
pwd: session.cwd, pwd: session.cwd,
exitCode: session.exitCode, exitCode: session.exitCode,
} satisfies SessionState); } satisfies SessionState);
+1 -52
View File
@@ -6,13 +6,7 @@ interface UnclosedQuoteError {
timestamp: number; timestamp: number;
} }
interface ParsedCommand { export function tokenize(input: string): string[] {
command: string;
flags: string[];
args: string[];
}
function tokenize(input: string): string[] {
enum State { enum State {
Normal, Normal,
SingleQuote, SingleQuote,
@@ -98,48 +92,3 @@ function tokenize(input: string): string[] {
flushBuffer(); flushBuffer();
return tokens; return tokens;
} }
export function parseCommand(input: string): ParsedCommand {
const tokens = tokenize(input);
const command = tokens[0] ?? "";
const flags: string[] = [];
const args: string[] = [];
let pastEndOfOptions = false;
for (let i = 1; i < tokens.length; i++) {
const token = tokens[i]!;
if (pastEndOfOptions) {
args.push(token);
continue;
}
if (token === "--") {
pastEndOfOptions = true;
continue;
}
if (token.startsWith("--")) {
flags.push(token.slice(2));
continue;
} else if (token.startsWith("-")) {
if (token.includes("=")) {
flags.push(token.slice(1));
continue;
}
for (const char of token.slice(1)) {
flags.push(char);
}
continue;
} else {
args.push(token);
continue;
}
}
return {
command,
flags,
args,
};
}
+205 -47
View File
@@ -1,70 +1,228 @@
import type { FileSystemCorruptionError, NodeNotFoundError, NotADirectoryError } from "@core/filesystem/errors";
import { NodePointer, NodeType, type Node } from "@core/filesystem/node";
import { getCurrentSession } from "@core/session_manager"; import { getCurrentSession } from "@core/session_manager";
import type { ShellState } from "@core/shell_state"; import type { ShellState } from "@core/shell_state";
import type { NodeNotFoundError, NotADirectoryError } from "../filesystem/errors";
import { TreeNodeType, type DirectoryNode, type TreeNode } from "../filesystem/treenode";
export function resolvePath(state: ShellState, path: string): number { export function resolvePath(state: ShellState, path: string): NodePointer {
let linkDepth = 0;
const maxDepth = state.filesystem.maxSymlinkDepth;
const session = getCurrentSession(state); const session = getCurrentSession(state);
const isAbsolute = path.startsWith("/"); const isAbsolute = path.startsWith("/");
const normalizedPath: string = path.replace(/^\/+|\/+$/g, ""); const pathComponents: string[] = path.split("/").filter(c => c.length > 0);
const pathComponents: string[] = normalizedPath.split("/").filter(name => name.length > 0);
if (pathComponents.length === 0 && isAbsolute) return 0; let currentDeviceId: number;
if (pathComponents.length === 0) return session.cwd; let currentNode: Node;
let currentNode = isAbsolute if (isAbsolute) {
? state.filesystem.getRoot() currentDeviceId = 0;
: (state.filesystem.getNode(session.cwd) as DirectoryNode); currentNode = state.filesystem.getRoot();
} else if (!isAbsolute && pathComponents[0] === "~") {
const home = session.user.home;
currentDeviceId = home.device;
currentNode = state.filesystem.getNode(session.user.home)!;
if (!currentNode) {
throw {
type: "NodeNotFound",
message: `[Panic] ${session.user.username}'s home directory does not exist!`,
timestamp: Date.now(),
pointer: session.user.home,
} satisfies NodeNotFoundError;
}
pathComponents.shift();
if (!currentNode) return -1; if (currentNode.type === NodeType.Symlink) {
if (++linkDepth > maxDepth) throw new Error("Symlink max depth - aborting!");
const target = currentNode.target;
if (target.startsWith("/")) {
currentDeviceId = 0;
currentNode = state.filesystem.getRoot();
} else {
const entries = state.filesystem.getNodeEntries(session.user.home);
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
currentDeviceId = entries[0].pdevice_id;
currentNode = state.filesystem.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
}
pathComponents.unshift(...target.split("/").filter(c => c.length > 0));
}
} else {
currentDeviceId = session.cwd.device;
currentNode = state.filesystem.getNode(session.cwd)!;
if (!currentNode) {
throw {
type: "NodeNotFound",
message: "[Panic] Current working directory does not exist!",
timestamp: Date.now(),
pointer: session.cwd,
} satisfies NodeNotFoundError;
}
}
while (pathComponents.length > 0) {
const name = pathComponents.shift()!;
for (let i = 0; i < pathComponents.length; i++) {
const name = pathComponents[i]!;
if (name === ".") continue; if (name === ".") continue;
if (name === "..") { if (name === "..") {
currentNode = state.filesystem.getNode(currentNode.parent) as DirectoryNode; if (state.filesystem.isMountTarget(NodePointer.of(currentDeviceId, currentNode.inode))) {
const mount = state.filesystem.getMountPoint(NodePointer.of(currentDeviceId, currentNode.inode));
if (!mount) {
throw {
type: "FileSystemCorruption",
message: "Mount registry entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
const entries = state.filesystem.getNodeEntries(mount);
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
currentDeviceId = entries[0].pdevice_id;
currentNode = state.filesystem.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
continue;
}
if (currentNode.inode === 0) continue;
const entries = state.filesystem.getNodeEntries(NodePointer.of(currentDeviceId, currentNode.inode));
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
currentDeviceId = entries[0].pdevice_id;
currentNode = state.filesystem.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
continue; continue;
} }
const inode = currentNode.children[name]; if (currentNode.type !== NodeType.Directory) {
if (!inode)
throw {
type: "NodeNotFound",
message: `Child node in ${currentNode.name} under name ${name} not found`,
timestamp: Date.now(),
inode: currentNode.inode,
} satisfies NodeNotFoundError;
if (state.filesystem.isFile(inode) && !(i === pathComponents.length - 1))
throw { throw {
type: "NotADirectory", type: "NotADirectory",
message: `Child node ${name} is not a directory`, message: "Not a directory",
timestamp: Date.now(), timestamp: Date.now(),
inode: inode, inode: currentNode.inode,
nodeType: TreeNodeType.File, nodeType: currentNode.type,
} satisfies NotADirectoryError; } satisfies NotADirectoryError;
}
currentNode = state.filesystem.getNode(inode) as DirectoryNode; const childInode = currentNode.children.get(name);
if (childInode === undefined) {
throw {
type: "NodeNotFound",
message: `${name} not found`,
timestamp: Date.now(),
pointer: NodePointer.of(currentDeviceId, currentNode.inode),
} satisfies NodeNotFoundError;
}
let childPtr = NodePointer.of(currentDeviceId, childInode);
if (state.filesystem.isMountPoint(childPtr)) {
const mount = state.filesystem.getMountTarget(childPtr)!;
childPtr = mount;
currentDeviceId = mount.device;
}
let child = state.filesystem.getNode(childPtr);
if (!child) {
throw {
type: "NodeNotFound",
message: `Node under ${childPtr} not found (probable dangling orphan)`,
timestamp: Date.now(),
pointer: childPtr,
} satisfies NodeNotFoundError;
}
if (child.type === NodeType.Symlink) {
// Change to typed error later on
if (++linkDepth > maxDepth) throw new Error("Symlink max depth - aborting!");
const target = child.target;
if (target.startsWith("/")) {
currentDeviceId = 0;
currentNode = state.filesystem.getRoot();
} else {
const entries = state.filesystem.getNodeEntries(childPtr);
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
currentDeviceId = entries[0].pdevice_id;
currentNode = state.filesystem.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
}
pathComponents.unshift(...target.split("/").filter(c => c.length > 0));
continue;
}
currentNode = child;
} }
return currentNode.inode; return NodePointer.of(currentDeviceId, currentNode.inode);
} }
export function resolveInode(state: ShellState, inode: number): string { export function resolvePointer(state: ShellState, pointer: NodePointer): string {
const node = state.filesystem.getNode(inode); const node = state.filesystem.getNode(pointer);
const components: string[] = []; const components: string[] = [];
if (node === undefined) return ""; if (node === undefined) return "";
let currentInode = inode; let ptr = pointer;
while (currentInode !== 0) { // TODO: Change while statements condition to not be hardcoded
const node = state.filesystem.getNode(currentInode) as TreeNode; while (!ptr.equals(NodePointer.of(0, 0))) {
if (!node) break; if (state.filesystem.isMountTarget(ptr)) {
const mount = state.filesystem.getMountPoint(ptr);
if (!mount) {
throw {
type: "FileSystemCorruption",
message: "Mount registry entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
components.push(node.name); const entries = state.filesystem.getNodeEntries(mount);
currentInode = node.parent; if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
components.push(entries[0].name);
ptr = NodePointer.of(entries[0].pdevice_id, entries[0].pinode);
continue;
}
const entries = state.filesystem.getNodeEntries(ptr);
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
components.push(entries[0].name);
ptr = NodePointer.of(entries[0].pdevice_id, entries[0].pinode);
} }
if (components.length === 0) { if (components.length === 0) {
components.push("/"); components.push("/");
@@ -77,9 +235,9 @@ export function resolveInode(state: ShellState, inode: number): string {
return result; return result;
} }
export function resolveInodeToHome(state: ShellState, inode: number): string { export function resolvePointerToHome(state: ShellState, ptr: NodePointer): string {
const home = resolveInode(state, getCurrentSession(state).user.home); const home = resolvePointer(state, getCurrentSession(state).user.home);
let result = resolveInode(state, inode); let result = resolvePointer(state, ptr);
if (result.startsWith(home)) { if (result.startsWith(home)) {
result = `~${result.slice(home.length)}`; result = `~${result.slice(home.length)}`;
@@ -88,9 +246,9 @@ export function resolveInodeToHome(state: ShellState, inode: number): string {
return result; return result;
} }
export function resolveInodeToCwd(state: ShellState, inode: number): string { export function resolvePointerToCwd(state: ShellState, ptr: NodePointer): string {
const cwd = resolveInode(state, getCurrentSession(state).cwd); const cwd = resolvePointer(state, getCurrentSession(state).cwd);
let result = resolveInode(state, inode); let result = resolvePointer(state, ptr);
if (result.startsWith(cwd)) { if (result.startsWith(cwd)) {
result = `.${result.slice(cwd.length)}`; result = `.${result.slice(cwd.length)}`;
@@ -99,9 +257,9 @@ export function resolveInodeToCwd(state: ShellState, inode: number): string {
return result; return result;
} }
export function resolveInodeRelative(state: ShellState, inode: number, relative: number): string { export function resolvePointerRelative(state: ShellState, ptr: NodePointer, relative: NodePointer): string {
const rel = resolveInode(state, relative); const rel = resolvePointer(state, relative);
let result = resolveInode(state, inode); let result = resolvePointer(state, ptr);
if (result.startsWith(rel)) { if (result.startsWith(rel)) {
result = `.${result.slice(rel.length)}`; result = `.${result.slice(rel.length)}`;
+55 -47
View File
@@ -1,8 +1,8 @@
import type { FileNode, TreeNode } from "@core/filesystem/treenode"; import { FileNode, NodePointer } from "@core/filesystem/node";
import type { ShellState } from "@core/shell_state"; import type { ShellState } from "@core/shell_state";
import { Posix } from "@termos/util/posix"; import { Posix } from "@termos/util/posix";
export enum SortTreeNodeBy { export enum SortNodeBy {
NAME = "name", NAME = "name",
INODE = "inode", INODE = "inode",
SIZE = "size", SIZE = "size",
@@ -13,50 +13,46 @@ export enum SortTreeNodeBy {
CTIME = "ctime", CTIME = "ctime",
} }
export function sortTreeNodes<T extends TreeNode | number>( export function sortNodes<T extends { name: string; ptr: NodePointer }>(
state: ShellState, state: ShellState,
arr: T[], arr: T[],
r: boolean = false, r: boolean = false,
by: SortTreeNodeBy = SortTreeNodeBy.NAME, by: SortNodeBy = SortNodeBy.NAME,
): T[] { ): T[] {
if (arr.length === 0) return []; if (arr.length === 0) return [];
const nodes: TreeNode[] = []; nodeQS(arr, r, by, 0, arr.length - 1, state);
return arr;
if (typeof arr[0] === "number") {
for (const e of arr as number[]) {
const node = state.filesystem.getNode(e);
if (!node) continue;
nodes.push(node);
}
} else {
nodes.push(...(arr as TreeNode[]));
}
nodeQS(nodes, r, by, 0, nodes.length - 1);
if (typeof arr[0] === "number") {
return nodes.map(n => n.inode) as T[];
} else {
return nodes as T[];
}
} }
function nodeQS(arr: TreeNode[], r: boolean, by: SortTreeNodeBy, start: number, end: number): void { function nodeQS(
arr: { name: string; ptr: NodePointer }[],
r: boolean,
by: SortNodeBy,
start: number,
end: number,
state: ShellState,
): void {
if (end <= start) return; if (end <= start) return;
const pivot = partitionNodeArray(arr, r, by, start, end); const pivot = partitionNodeArray(arr, r, by, start, end, state);
nodeQS(arr, r, by, start, pivot - 1); nodeQS(arr, r, by, start, pivot - 1, state);
nodeQS(arr, r, by, pivot + 1, end); nodeQS(arr, r, by, pivot + 1, end, state);
} }
function partitionNodeArray(part: TreeNode[], r: boolean, by: SortTreeNodeBy, start: number, end: number): number { function partitionNodeArray(
part: { name: string; ptr: NodePointer }[],
r: boolean,
by: SortNodeBy,
start: number,
end: number,
state: ShellState,
): number {
const pivot = part[end]; const pivot = part[end];
let i = start - 1; let i = start - 1;
for (let j = start; j <= end; j++) { for (let j = start; j <= end; j++) {
if (compareTreeNode(part[j]!, pivot!, by, r) < 0) { if (compareNode(part[j]!, pivot!, by, r, state) < 0) {
i++; i++;
const temp = part[i]!; const temp = part[i]!;
part[i] = part[j]!; part[i] = part[j]!;
@@ -72,11 +68,17 @@ function partitionNodeArray(part: TreeNode[], r: boolean, by: SortTreeNodeBy, st
return i; return i;
} }
function compareTreeNode(a: TreeNode, b: TreeNode, by: SortTreeNodeBy, r: boolean): number { function compareNode(
a: { name: string; ptr: NodePointer },
b: { name: string; ptr: NodePointer },
by: SortNodeBy,
r: boolean,
state: ShellState,
): number {
switch (by) { switch (by) {
case SortTreeNodeBy.NAME: { case SortNodeBy.NAME: {
const A: string = a.name.startsWith(".") ? a.name.slice(1) : a.name; const A: string = a.name;
const B: string = b.name.startsWith(".") ? b.name.slice(1) : b.name; const B: string = b.name;
const min = Math.min(A.length, B.length); const min = Math.min(A.length, B.length);
for (let i = 0; i < min; i++) { for (let i = 0; i < min; i++) {
@@ -91,23 +93,27 @@ function compareTreeNode(a: TreeNode, b: TreeNode, by: SortTreeNodeBy, r: boolea
return r ? B.length - A.length : A.length - B.length; return r ? B.length - A.length : A.length - B.length;
} }
case SortTreeNodeBy.MTIME: case SortNodeBy.MTIME:
case SortTreeNodeBy.ATIME: case SortNodeBy.ATIME:
case SortTreeNodeBy.CTIME: { case SortNodeBy.CTIME: {
const A: number = a[by]; const nodeA = state.filesystem.getNode(a.ptr)!;
const B: number = b[by]; const nodeB = state.filesystem.getNode(b.ptr)!;
const A: number = nodeA[by];
const B: number = nodeB[by];
return r ? A - B : B - A; return r ? A - B : B - A;
} }
case SortTreeNodeBy.SIZE: { case SortNodeBy.SIZE: {
const A: number = (a as FileNode).content.byteSize(); const nodeA = state.filesystem.getNode(a.ptr)!;
const B: number = (b as FileNode).content.byteSize(); const nodeB = state.filesystem.getNode(b.ptr)!;
const A: number = (nodeA as FileNode).size;
const B: number = (nodeB as FileNode).size;
return r ? A - B : B - A; return r ? A - B : B - A;
} }
case SortTreeNodeBy.EXTENSION: { case SortNodeBy.EXTENSION: {
const A: string = a.name.split(".").pop() ?? ""; const A: string = a.name.split(".").pop() ?? "";
const B: string = b.name.split(".").pop() ?? ""; const B: string = b.name.split(".").pop() ?? "";
const min = Math.min(A.length, B.length); const min = Math.min(A.length, B.length);
@@ -124,12 +130,14 @@ function compareTreeNode(a: TreeNode, b: TreeNode, by: SortTreeNodeBy, r: boolea
return r ? B.length - A.length : A.length - B.length; return r ? B.length - A.length : A.length - B.length;
} }
case SortTreeNodeBy.INODE: { case SortNodeBy.INODE: {
return r ? a.inode - b.inode : b.inode - a.inode; return r ? a.ptr.inode - b.ptr.inode : b.ptr.inode - a.ptr.inode;
} }
case SortTreeNodeBy.TYPE: { case SortNodeBy.TYPE: {
return r ? b.type - a.type : a.type - b.type; const nodeA = state.filesystem.getNode(a.ptr)!;
const nodeB = state.filesystem.getNode(a.ptr)!;
return r ? nodeB.type - nodeA.type : nodeA.type - nodeB.type;
} }
} }
} }
+62
View File
@@ -0,0 +1,62 @@
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();
public loadAll(): Promise<Map<number, Node | null>> {
return Promise.resolve(this._data);
}
public write(entries: Array<[number, Node | null]>): Promise<void> {
for (const [inode, node] of entries) {
this._data.set(inode, node);
}
return Promise.resolve();
}
public delete(entries: number[]): Promise<void> {
for (const inode of entries) {
this._data.delete(inode);
}
return Promise.resolve();
}
}
export class MemDataStore implements IDataStore {
private _data: Map<string, Blob> = new Map();
public async read(uuid: string): Promise<Uint8Array> {
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): Readable {
const blob = this._data.get(uuid);
if (!blob) throw new Error("Content missing - " + uuid);
return Readable.from(blob.stream());
}
public put(uuid: string, blob: Blob): Promise<void> {
this._data.set(uuid, blob);
return Promise.resolve();
}
public delete(uuid: string): Promise<void> {
this._data.delete(uuid);
return Promise.resolve();
}
public has(uuid: string): Promise<boolean> {
return Promise.resolve(this._data.has(uuid));
}
public list(): Promise<string[]> {
return Promise.resolve(Array.from(this._data.keys()));
}
}
+23 -21
View File
@@ -1,42 +1,44 @@
import type { FileSystem } from "@core/filesystem/filesystem"; import type { FileSystem } from "@core/filesystem/filesystem";
import { TreeNodeType, type TreeNode } from "@core/filesystem/treenode"; import { NodePointer, NodeType, type NodeEntry } from "@core/filesystem/node";
export function dnTraverseTree(fs: FileSystem, root: number): number[] { export function dnTraverseTree(fs: FileSystem, root: NodePointer): NodePointer[] {
if (fs.getNode(root) === undefined) return []; if (fs.getNode(root) === undefined) return [];
const result: number[] = []; const result: NodePointer[] = [];
const stack: number[] = []; const stack: NodePointer[] = [];
stack.push(root); stack.push(root);
while (stack.length > 0) { while (stack.length > 0) {
const node = fs.getNode(stack.pop() as number); const ptr = stack.pop()!;
if (node === undefined) continue; const node = fs.getNode(ptr);
if (!node) continue;
result.push(node.inode); result.push(ptr);
if (node.type === TreeNodeType.Directory) { if (node.type === NodeType.Directory) {
const children = Object.values(node.children); const children = Array.from(node.children.values());
for (let i = children.length - 1; i >= 0; i--) { for (let i = children.length - 1; i >= 0; i--) {
stack.push(children[i] as number); const child = children[i]!;
const pointer = NodePointer.of(ptr.device, child);
stack.push(pointer);
} }
} }
} }
return result; return result;
} }
export function upTraverseTree(fs: FileSystem, inode: number): number[] { export function upTraverseTree(fs: FileSystem, ptr: NodePointer): NodePointer[] {
if (fs.getNode(inode) === undefined) return []; if (fs.getNode(ptr) === undefined) return [];
const result: number[] = []; const result: NodePointer[] = [ptr];
result.push(inode); let currentPtr = ptr;
let currentInode = inode; while (currentPtr.inode !== 0) {
while (currentInode !== 0) { const entries = fs.getNodeEntries(currentPtr);
const node = fs.getNode(currentInode) as TreeNode; if (!entries || entries.length === 0) throw new Error(`No reverse-index entry found for ${currentPtr}`);
if (!node) break;
result.push(node.parent); const parent = entries[0] as NodeEntry;
currentInode = node.parent; currentPtr = NodePointer.of(parent.pdevice_id, parent.pinode);
result.push(currentPtr);
} }
return result; return result;
+45
View File
@@ -0,0 +1,45 @@
import { IDataStore, IMetaStore, VDisk, VDiskConfig } from "@core/filesystem/vdisk";
export class VDiskManager {
private _disks: Map<number, VDisk>;
constructor() {
this._disks = new Map();
}
public async registerDisk(config: VDiskConfig, data: IDataStore, meta: IMetaStore): Promise<VDisk> {
if (this._disks.has(config.id)) {
throw new Error("Disk of this id already exists");
}
const vd = await VDisk.open(config, data, meta);
this._disks.set(config.id, vd);
return vd;
}
public getDisk(id: number): VDisk | undefined {
const vd = this._disks.get(id);
return vd;
}
public hasDisk(id: number): boolean {
return this._disks.has(id);
}
public listDisk(): VDisk[] {
return Array.from(this._disks.values());
}
public listID(): number[] {
return Array.from(this._disks.keys());
}
public unregisterDisk(id: number): void {
if (!this._disks.has(id)) {
throw new Error("Disk of this id doesnt exist");
}
this._disks.delete(id);
}
}
+60
View File
File diff suppressed because one or more lines are too long
+188
View File
@@ -0,0 +1,188 @@
import type { FileSystemCorruptionError, NodeNotFoundError, NotADirectoryError } from "@core/filesystem/errors";
import { FileSystem } from "@core/filesystem/filesystem";
import { NodePointer, NodeType, type Node } from "@core/filesystem/node";
import type { GroupInfo, UserInfo } from "@core/session_manager";
import { createInitialShellState, type ShellState } from "@core/shell_state";
import { deserializeFileSystem } from "@shell/serializer";
import { Shell } from "@shell/shell";
import type { TermosConfig } from "./config";
async function getShell(config: TermosConfig): Promise<Shell> {
// TODO: Validate json schema
const devices = deserializeFileSystem(config.filesystem.json);
const fs = await FileSystem.init(devices);
const users: Map<number, UserInfo> = new Map();
const groups: Map<number, GroupInfo> = new Map();
const reverseGroups: Map<string, number> = new Map();
const reverseUsers: Map<string, number> = new Map();
if (config.users.length === 0) throw new Error("System needs to have at least one user");
if (config.groups.length === 0) throw new Error("System needs to have at least one user group");
for (let i = 1000; i < config.groups.length + 1000; i++) {
const group = config.groups[i - 1000]!;
reverseGroups.set(group, i);
const members: number[] = [];
for (let i = 1000; i < config.users.length + 1000; i++) {
const user = config.users[i - 1000]!;
if (user.groups.some(g => g === group)) {
members.push(i);
}
}
groups.set(i, { groupname: group, gid: i, members });
}
for (let i = 1000; i < config.users.length + 1000; i++) {
const user = config.users[i - 1000]!;
if (user.groups.length === 0) throw new Error("User must belong to at least one user group");
const gid = reverseGroups.get(user.groups[0]!);
if (!gid) throw new Error("User is a member of an undefined group");
const groups: number[] = [];
for (const group of user.groups) {
if (group === "sudoers") continue;
const gid = reverseGroups.get(group);
if (!gid) throw new Error("User is a member of an undefined group");
groups.push(gid);
}
reverseUsers.set(user.username, i);
users.set(i, { username: user.username, uid: i, gid, group: groups, home: resPath(user.home) });
}
const uid = reverseUsers.get(config.general.user);
if (!uid) throw new Error("Tried to initialize termos with an undefined user");
const user = users.get(uid)!;
const state: ShellState = createInitialShellState(fs, users, groups, user);
return new Shell(state);
function resPath(path: string) {
let linkDepth = 0;
const maxDepth = fs.maxSymlinkDepth;
const pathComponents: string[] = path.split("/").filter(c => c.length > 0);
let currentDeviceId: number = 0;
let currentNode: Node = fs.getRoot();
while (pathComponents.length > 0) {
const name = pathComponents.shift()!;
if (name === ".") continue;
if (name === "..") {
if (fs.isMountTarget(NodePointer.of(currentDeviceId, currentNode.inode))) {
const mount = fs.getMountPoint(NodePointer.of(currentDeviceId, currentNode.inode));
if (!mount) {
throw {
type: "FileSystemCorruption",
message: "Mount registry entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
const entries = fs.getNodeEntries(mount);
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
currentDeviceId = entries[0].pdevice_id;
currentNode = fs.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
continue;
}
if (currentNode.inode === 0) continue;
const entries = fs.getNodeEntries(NodePointer.of(currentDeviceId, currentNode.inode));
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
currentDeviceId = entries[0].pdevice_id;
currentNode = fs.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
continue;
}
if (currentNode.type !== NodeType.Directory) {
throw {
type: "NotADirectory",
message: "Not a directory",
timestamp: Date.now(),
inode: currentNode.inode,
nodeType: currentNode.type,
} satisfies NotADirectoryError;
}
const childInode = currentNode.children.get(name);
if (childInode === undefined) {
throw {
type: "NodeNotFound",
message: `${name} not found`,
timestamp: Date.now(),
pointer: NodePointer.of(currentDeviceId, currentNode.inode),
} satisfies NodeNotFoundError;
}
let childPtr = NodePointer.of(currentDeviceId, childInode);
if (fs.isMountPoint(childPtr)) {
const mount = fs.getMountTarget(childPtr)!;
childPtr = mount;
currentDeviceId = mount.device;
}
let child = fs.getNode(childPtr);
if (!child) {
throw {
type: "NodeNotFound",
message: `Node under ${childPtr} not found (probable dangling orphan)`,
timestamp: Date.now(),
pointer: childPtr,
} satisfies NodeNotFoundError;
}
if (child.type === NodeType.Symlink) {
if (++linkDepth > maxDepth) throw new Error("Symlink max depth - aborting!");
const target = child.target;
if (target.startsWith("/")) {
currentDeviceId = 0;
currentNode = fs.getRoot();
} else {
const entries = fs.getNodeEntries(childPtr);
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
currentDeviceId = entries[0].pdevice_id;
currentNode = fs.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
}
pathComponents.unshift(...target.split("/").filter(c => c.length > 0));
continue;
}
currentNode = child;
}
return NodePointer.of(currentDeviceId, currentNode.inode);
}
}
export const Termos = {
getShell,
};
+1 -85
View File
@@ -1,85 +1 @@
/* import { defaultConfig, TermosConfig } from "./config"; export { Termos } from "./entry";
let config: TermosConfig = { ...defaultConfig };
namespace Termos {
export function init(config: Partial<TermosConfig>) {
config = { ...defaultConfig, ...config };
console.log("termos initialized");
}
}
*/
import { FileSystem } from "@core/filesystem/filesystem";
import type { TreeNode } from "@core/filesystem/treenode";
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 { printTree } from "./util/tree_visualizer";
const rawJson = `{"atime": 1786341244,"children": [{"atime": 1786341264,"children": [{"atime": 1786341330,"children": [],"content": null,"ctime": 1786341330,"group": 1000,"inode": 2,"mode": 493,"mtime": 1786341330,"name": "subdir1","owner": 1000,"parent": 1,"type": "directory"}],"content": null,"ctime": 1786341330,"group": 1000,"inode": 1,"mode": 493,"mtime": 1786341330,"name": "folder1","owner": 1000,"parent": 0,"type": "directory"},{"atime": 1786341269,"children": [{"atime": 1786341344,"children": [],"content": null,"ctime": 1786341344,"group": 1000,"inode": 4,"mode": 493,"mtime": 1786341344,"name": "subdir2","owner": 1000,"parent": 3,"type": "directory"},{"atime": 1786341345,"children": [{"atime": 1786341356,"children": [],"content": [],"ctime": 1786341356,"group": 1000,"inode": 6,"mode": 420,"mtime": 1786341356,"name": "empty-foo","owner": 1000,"parent": 5,"type": "regular"}],"content": null,"ctime": 1786341356,"group": 1000,"inode": 5,"mode": 493,"mtime": 1786341356,"name": "subdir3","owner": 1000,"parent": 3,"type": "directory"}],"content": null,"ctime": 1786341345,"group": 1000,"inode": 3,"mode": 493,"mtime": 1786341345,"name": "folder2","owner": 1000,"parent": 0,"type": "directory"},{"atime": 1786341312,"children": [],"content": [72,101,108,108,111,44,32,87,111,114,108,100,33,10],"ctime": 1786341312,"group": 1000,"inode": 7,"mode": 420,"mtime": 1786341312,"name": "some-file","owner": 1000,"parent": 0,"type": "regular"}],"content": null,"ctime": 1786341312,"group": 1000,"inode": 0,"mode": 493,"mtime": 1786341312,"name": "root","owner": 1000,"parent": 0,"type": "directory"}`;
const base = deserializeFileSystem(rawJson);
const overlay: ReadonlyMap<number, TreeNode | null> = new Map();
const fs = FileSystem.init(base, overlay, base.size - 1);
console.log(printTree(fs, 0));
const users: Map<number, UserInfo> = new Map();
const groups: Map<number, GroupInfo> = new Map();
const user: UserInfo = {
username: "root",
uid: 1000,
gid: 1000, // <- PRIMARY GID
group: [1000], // <- GROUPS ARRAY
home: 3,
};
const group: GroupInfo = {
groupname: "root",
gid: 1000,
members: [1000], // <- UID
};
users.set(1000, user);
groups.set(1000, group);
const state: ShellState = createInitialShellState(fs, users, groups, user);
await Shell.init(state);
//console.log(resolveInode(Shell.Instance?.State!, 6));
//console.log(resolveInode(Shell.Instance?.State!, 6, true));
//console.log(sortTreeNodes(Shell.Instance?.State!, dnTraverseTree(Shell.Instance?.State.filesystem!, 0)));
Shell.Instance?.on("result", payload => {
const decoded = new TextDecoder().decode(payload.result.stdout.toArray());
process.stdout.write(decoded + "\n");
process.stdout.write(resolveInodeToHome(payload.state, getCurrentSession(payload.state).cwd) + "\n> ");
});
/*
Cant do it like this because commands also use the stdout event right before returning a result so e.g. echo will print twice
Need to use this only if a continuous process is running
*/
/* Shell.Instance?.on("stdout", payload => {
const decoded = new TextDecoder().decode(payload.data);
process.stdout.write(decoded + "\n");
}); */
//console.clear();
process.stdout.write(resolveInodeToHome(state, getCurrentSession(state).cwd) + "\n> ");
process.stdin.on("data", async data => {
if (Shell.Instance?.BoundPID !== null) {
Shell.Instance?.sendInput(data.toString().trim());
return;
}
const input = data.toString().trim();
await Shell.Instance?.execute(input);
});
//export { Termos };
+3 -4
View File
@@ -23,20 +23,19 @@ export class Process {
readonly CommandDescriptor: CommandDescriptor; readonly CommandDescriptor: CommandDescriptor;
readonly State: ShellState; readonly State: ShellState;
readonly Args: string[]; readonly Args: string[];
readonly Flags: string[];
constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]) { constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, args: string[]) {
this.PID = pid; this.PID = pid;
this.State = state; this.State = state;
this.Name = descriptor.name; this.Name = descriptor.name;
this.CommandDescriptor = descriptor; this.CommandDescriptor = descriptor;
this.Flags = flags;
this.Args = args; this.Args = args;
// Check if positive later and throw an error if so // Check if positive later and throw an error if so
this._MaxChunkByteSize = 1024; this._MaxChunkByteSize = 1024;
this._EventEmitter = new EventEmitter<ShellEventMap>(); this._EventEmitter = new EventEmitter<ShellEventMap>();
} }
// WARNING, CHUNKING OUTPUT BREAKS FORMATING
private writeToOutput(chunks: Uint8Array[], eventType: "stdout" | "stderr", data: Uint8Array): void { private writeToOutput(chunks: Uint8Array[], eventType: "stdout" | "stderr", data: Uint8Array): void {
if (this._Settled) return; if (this._Settled) return;
@@ -68,7 +67,7 @@ export class Process {
}, },
}; };
const promise = this.CommandDescriptor.fn(io, this.State, this.Flags, this.Args); const promise = this.CommandDescriptor.fn(io, this.State, this.Args);
promise promise
.then(output => { .then(output => {
+4 -4
View File
@@ -1,6 +1,6 @@
import type { CommandDescriptor } from "@core/command"; import type { CommandDescriptor } from "@core/command";
import type { ShellState } from "@core/shell_state"; import type { ShellState } from "@core/shell_state";
import type { Signal } from "@core/signal"; import { SIGNAL_MAP, type Signal } from "@core/signal";
import { EventEmitter } from "./event_emitter"; import { EventEmitter } from "./event_emitter";
import { Process } from "./process"; import { Process } from "./process";
import type { ShellEventMap } from "./shell"; import type { ShellEventMap } from "./shell";
@@ -11,9 +11,9 @@ export class ProcessManager {
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter(); private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
public createProcess(state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]): number { public createProcess(state: ShellState, descriptor: CommandDescriptor, args: string[]): number {
const pid = ++this._PIDIndex; const pid = ++this._PIDIndex;
const process = new Process(pid, state, descriptor, flags, args); const process = new Process(pid, state, descriptor, args);
this._Processes.set(pid, process); this._Processes.set(pid, process);
process.on("stdout", payload => this._EventEmitter.emit("stdout", payload)); process.on("stdout", payload => this._EventEmitter.emit("stdout", payload));
@@ -51,7 +51,7 @@ export class ProcessManager {
} }
//Make global signals an enum later //Make global signals an enum later
process.sendSignal({ type: "SIGKILL" } satisfies Signal); process.sendSignal({ type: SIGNAL_MAP.SIGKILL } satisfies Signal);
} }
public on<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void { public on<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
+122 -76
View File
@@ -1,92 +1,138 @@
import { createImmutableBuffer } from "@core/util/immutable_buffer"; import type { IDataStore, IMetaStore, VDiskConfig } from "@core/filesystem/vdisk";
import { z } from "zod"; import { MemDataStore, MemMetaStore } from "@core/util/temp_mem_stores";
import { TreeNodeType, type DirectoryNode, type FileNode, type TreeNode } from "../core/filesystem/treenode"; import { Blob } from "node:buffer";
import { randomUUID } from "node:crypto";
const FileNodeSchema = z.object({ import { NodeType, type DirectoryNode, type FileNode, type Node, type SymlinkNode } from "../core/filesystem/node";
inode: z.number(),
name: z.string(),
mode: z.number(),
parent: z.number(),
owner: z.number(),
group: z.number(),
mtime: z.number(),
ctime: z.number(),
atime: z.number(),
type: z.literal("regular"),
content: z.array(z.number()),
});
const DirectoryNodeSchema = z.object({
inode: z.number(),
name: z.string(),
mode: z.number(),
parent: z.number(),
owner: z.number(),
group: z.number(),
mtime: z.number(),
ctime: z.number(),
atime: z.number(),
type: z.literal("directory"),
//eslint-ignore
children: z.array(z.lazy((): any => TreeNodeSchema)), // eslint-disable-line @typescript-eslint/no-explicit-any
});
const TreeNodeSchema = z.union([FileNodeSchema, DirectoryNodeSchema]);
/* export function serializeFileSystem(map: ReadonlyMap<number, TreeNode | null>): string { /* export function serializeFileSystem(map: ReadonlyMap<number, TreeNode | null>): string {
} */ } */
export function deserializeFileSystem(json: string): ReadonlyMap<number, TreeNode> { export function deserializeFileSystem(json: string): { dstore: IDataStore; mstore: IMetaStore; config: VDiskConfig }[] {
const raw = JSON.parse(json); const raw = JSON.parse(json);
const validated = TreeNodeSchema.parse(raw);
const map = new Map<number, TreeNode>();
// prettier-ignore // prettier-ignore
function parseNode(tree: any, parent: number): void { // eslint-disable-line @typescript-eslint/no-explicit-any function parseNode(tree: any, parent: number, store: MemDataStore, map: Map<number, Node>): void { // eslint-disable-line @typescript-eslint/no-explicit-any
if (tree.type === "directory") { if(tree === null || tree.type === undefined) {
const children: Record<string, number> = {}; 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;
}
for (const child of tree.children) { switch(tree.type) {
parseNode(child, tree.inode); case "directory": {
children[child.name] = child.inode; const children: Map<string, number> = new Map();
for (const child of tree.children) {
parseNode(child, tree.inode, store, map);
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,
};
if(Object.values(directoryNode).some(e => e === undefined))
throw new Error(`Serialization failed, object contains undefined fields - ${directoryNode}`);
children.set('..', parent);
children.set('.', tree.inode);
map.set(tree.inode, Object.freeze(directoryNode));
break;
} }
case "regular": {
const uuid = randomUUID();
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: uuid,
size: tree.size,
};
const directoryNode: DirectoryNode = { if(Object.values(fileNode).some(e => e === undefined))
type: TreeNodeType.Directory, throw new Error(`Serialization failed, object contains undefined fields - ${fileNode}`);
inode: tree.inode,
name: tree.name, const buff: Uint8Array<ArrayBuffer> = Uint8Array.from(tree.content);
parent, store.put(uuid, new Blob([buff]));
mode: tree.mode, map.set(tree.inode, Object.freeze(fileNode));
owner: tree.owner, break;
group: tree.group, }
mtime: tree.mtime, case "symlink": {
ctime: tree.ctime, const symlinkNode: SymlinkNode = {
atime: tree.atime, type: NodeType.Symlink,
children, inode: tree.inode,
}; mode: tree.mode,
map.set(tree.inode, Object.freeze(directoryNode)); link_count: tree.link_count,
} else { owner: tree.owner,
const fileNode: FileNode = { group: tree.group,
type: TreeNodeType.File, mtime: tree.mtime,
inode: tree.inode, ctime: tree.ctime,
name: tree.name, atime: tree.atime,
parent, target: tree.target,
mode: tree.mode, };
owner: tree.owner,
group: tree.group, if(Object.values(symlinkNode).some(e => e === undefined))
mtime: tree.mtime, throw new Error(`Serialization failed, object contains undefined fields - ${symlinkNode}`);
ctime: tree.ctime,
atime: tree.atime, map.set(tree.inode, Object.freeze(symlinkNode));
content: createImmutableBuffer(Uint8Array.from(tree.content)), break;
}; }
map.set(tree.inode, Object.freeze(fileNode)); default:
throw new Error(`Unknown node type in JSON ${tree.type}`);
} }
} }
parseNode(validated, validated.inode); const result: { dstore: IDataStore; mstore: IMetaStore; config: VDiskConfig }[] = [];
const base: ReadonlyMap<number, TreeNode> = map; for (const dev of raw.dev) {
const map = new Map();
const data = new MemDataStore();
const meta = new MemMetaStore();
parseNode(dev.tree, dev.tree.inode, data, map);
return base; const config: VDiskConfig = {
id: dev.id,
label: `disk-${dev.id}`,
index: 0,
readonly: false,
size: 1024 * 1024 * 1024 * 8, //8 GiB
base: map,
dataC: {
chunkSize: 1024 * 8, //8 KiB
cacheSize: 1024 * 1024 * 64, //64 MiB
cacheTTL: 1000 * 60, // 1 min
},
};
result.push({ dstore: data, mstore: meta, config });
}
return result;
} }
+13 -50
View File
@@ -5,13 +5,11 @@ import { withExitCode, withHistory, type ShellState } from "@core/shell_state";
import { SIGNAL_MAP } from "@core/signal"; import { SIGNAL_MAP } from "@core/signal";
import type { ShellError } from "@core/util/errors"; import type { ShellError } from "@core/util/errors";
import { createImmutableBuffer } from "@core/util/immutable_buffer"; import { createImmutableBuffer } from "@core/util/immutable_buffer";
import { parseCommand } from "@core/util/parser"; import { tokenize } from "@core/util/parser";
import { EventEmitter } from "./event_emitter"; import { EventEmitter } from "./event_emitter";
import { ProcessManager } from "./process_manager"; import { ProcessManager } from "./process_manager";
export class Shell { export class Shell {
static #Instance: Shell;
static #Promise: Promise<Shell> | null = null;
private _State: Readonly<ShellState>; private _State: Readonly<ShellState>;
private _ProcessManager: ProcessManager = new ProcessManager(); private _ProcessManager: ProcessManager = new ProcessManager();
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter(); private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
@@ -19,7 +17,7 @@ export class Shell {
public BoundPID: number | null = null; public BoundPID: number | null = null;
private constructor(state: ShellState) { constructor(state: ShellState) {
this._State = Object.freeze(state); this._State = Object.freeze(state);
//Temporary solution for sigint keybind //Temporary solution for sigint keybind
@@ -43,51 +41,22 @@ export class Shell {
}); });
} }
static async init(initialState: ShellState): Promise<Shell> {
if (Shell.#Instance) {
console.warn("Shell already initialized");
return this.#Instance;
}
if (Shell.#Promise) return Shell.#Promise;
Shell.#Promise = (async () => {
try {
Shell.#Instance = new Shell(initialState);
return Shell.#Instance;
} finally {
Shell.#Promise = null;
}
})();
return Shell.#Promise;
}
public async execute(input: string): Promise<void> { public async execute(input: string): Promise<void> {
let parsed; const parsed = tokenize(input);
try {
parsed = parseCommand(input);
} catch {
const result = createErrorResult("ParseError", `Parsing error - ${input}`, {});
this._State = withExitCode(this._State, result.error.exitCode); if (!parsed[0]) return;
this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
return;
}
if (parsed.command === "") return;
this._State = withHistory(this._State, input); this._State = withHistory(this._State, input);
const command = COMMAND_REGISTRY.get(parsed.command); const command = COMMAND_REGISTRY.get(parsed[0]);
if (!command) { if (!command) {
const encoded = new TextEncoder().encode(`Command ${parsed.command} not found`); const encoded = new TextEncoder().encode(`Command ${parsed[0]} not found`);
const result = createErrorResult( const result = createErrorResult(
"CommandNotFound", "CommandNotFound",
`Command ${parsed.command} not found`, `Command ${parsed[0]} not found`,
{ command: parsed.command }, { command: parsed[0] },
parsed.command, parsed[0],
createImmutableBuffer(encoded), createImmutableBuffer(encoded),
createImmutableBuffer(new Uint8Array()), createImmutableBuffer(new Uint8Array()),
); );
@@ -102,7 +71,7 @@ export class Shell {
"PermissionDenied", "PermissionDenied",
`Permission Denied`, `Permission Denied`,
{ resource: `Execution of the ${command.name} command` }, { resource: `Execution of the ${command.name} command` },
parsed.command, parsed[0],
); );
this._State = withExitCode(this._State, result.error.exitCode); this._State = withExitCode(this._State, result.error.exitCode);
@@ -110,7 +79,9 @@ export class Shell {
return; return;
} }
const pid = this._ProcessManager.createProcess(this._State, command, parsed.flags, parsed.args); parsed.shift();
const pid = this._ProcessManager.createProcess(this._State, command, parsed);
this.BoundPID = pid; this.BoundPID = pid;
} }
@@ -132,14 +103,6 @@ export class Shell {
return this._State; return this._State;
} }
public static get Instance(): Shell | undefined {
if (!Shell.#Instance) {
console.error("Shell has not been initialised yet. Call `await Shell.init()` first.");
return;
}
return Shell.#Instance;
}
public on<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void { public on<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
return this._EventEmitter.on(type, handler); return this._EventEmitter.on(type, handler);
} }
-74
View File
@@ -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;
}
*/
+76 -33
View File
@@ -1,61 +1,104 @@
import type { FileSystem } from "@core/filesystem/filesystem"; import type { FileSystem } from "@core/filesystem/filesystem";
import { TreeNodeType } from "@core/filesystem/treenode"; import { NodePointer, NodeType, type SymlinkNode } from "@core/filesystem/node";
export function printTree(fs: FileSystem, root: number): string { type Frame = {
ptr: NodePointer;
name: string;
prefix: string;
isLast: boolean;
};
function getSortedChildren(fs: FileSystem, ptr: NodePointer): Array<{ name: string; ptr: NodePointer }> {
const node = fs.getNode(ptr);
if (!node || node.type !== NodeType.Directory) return [];
const entries = Array.from(node.children.entries());
entries.sort(([a], [b]) => a.localeCompare(b));
return entries.map(([name, inode]) => ({
name,
ptr: NodePointer.of(ptr.device, inode),
}));
}
function mountSuffix(fs: FileSystem, ptr: NodePointer): string {
if (!fs.isMountPoint(ptr)) return "";
const target = fs.getMountPoint(ptr);
if (!target) return " -> [mount: target missing]";
return ` -> ${target.toString()}`;
}
function symlinkSuffix(node: { type: NodeType; target?: string }): string {
return node.type === NodeType.Symlink ? ` -> ${(node as SymlinkNode).target}` : "";
}
export function printTree(fs: FileSystem, root: NodePointer, rootLabel = "/"): string {
const rootNode = fs.getNode(root); const rootNode = fs.getNode(root);
if (rootNode === undefined) return ""; if (rootNode === undefined) return "";
const lines: string[] = []; const lines: string[] = [];
const rootSuffix = mountSuffix(fs, root) + symlinkSuffix(rootNode);
lines.push(rootNode.name + ` (${rootNode.inode})`); lines.push(`${rootLabel} ${root.toString()}${rootSuffix}`);
type Frame = {
inode: number;
prefix: string;
isLast: boolean;
};
const stack: Frame[] = []; const stack: Frame[] = [];
const rootChildren = getSortedChildren(fs, root);
const getSorterChildren = (inode: number): number[] => {
const node = fs.getNode(inode);
if (!node || node.type !== TreeNodeType.Directory) return [];
const entries = Object.entries(node.children);
entries.sort(([a], [b]) => a.localeCompare(b));
return entries.map(([, childInode]) => childInode) as number[];
};
const rootChildren = getSorterChildren(root);
for (let i = rootChildren.length - 1; i >= 0; i--) { for (let i = rootChildren.length - 1; i >= 0; i--) {
const childInode: number = rootChildren[i] as number; const child = rootChildren[i]!;
if (child.name.startsWith(".")) continue;
const isLast = i === rootChildren.length - 1; const isLast = i === rootChildren.length - 1;
stack.push({ ptr: child.ptr, name: child.name, prefix: "", isLast });
stack.push({ inode: childInode, prefix: "", isLast });
} }
while (stack.length > 0) { while (stack.length > 0) {
const frame = stack.pop()!; const frame = stack.pop()!;
const node = fs.getNode(frame.inode); const node = fs.getNode(frame.ptr);
if (!node) continue; if (!node) continue;
const name = node.name;
const connector = frame.isLast ? "└── " : "├── "; const connector = frame.isLast ? "└── " : "├── ";
lines.push(frame.prefix + connector + name + ` (${node.inode})`); const suffix = mountSuffix(fs, frame.ptr) + symlinkSuffix(node);
lines.push(`${frame.prefix}${connector}${frame.name} ${frame.ptr.toString()}${suffix}`);
if (node.type === TreeNodeType.Directory) { if (node.type === NodeType.Directory && !fs.isMountPoint(frame.ptr)) {
const childPrefix = frame.prefix + (frame.isLast ? " " : "│ "); const childPrefix = frame.prefix + (frame.isLast ? " " : "│ ");
const children = getSorterChildren(frame.inode); const children = getSortedChildren(fs, frame.ptr);
for (let i = children.length - 1; i >= 0; i--) { for (let i = children.length - 1; i >= 0; i--) {
const childInode = children[i] as number; const child = children[i]!;
if (child.name.startsWith(".")) continue;
const childIsLast = i === children.length - 1; const childIsLast = i === children.length - 1;
stack.push({
stack.push({ inode: childInode, prefix: childPrefix, isLast: childIsLast }); ptr: child.ptr,
name: child.name,
prefix: childPrefix,
isLast: childIsLast,
});
} }
} }
} }
return lines.join("\n"); return lines.join("\n");
} }
export function printDeviceTree(fs: FileSystem, deviceId: number, rootLabel?: string): string {
return printTree(fs, NodePointer.of(deviceId, 0), rootLabel ?? `disk-${deviceId}:/`);
}
export function printAllDeviceTrees(fs: FileSystem, deviceIds?: number[]): string {
const ids =
deviceIds ??
(() => {
const mgr = (fs as unknown as { _VDiskManager?: { listID(): number[] } })._VDiskManager;
if (!mgr) {
throw new Error(
"printAllDeviceTrees: FileSystem has no public device list — pass deviceIds explicitly",
);
}
return mgr.listID();
})();
return ids
.slice()
.sort((a, b) => a - b)
.map(id => printDeviceTree(fs, id))
.join("\n\n");
}
File diff suppressed because it is too large Load Diff
+677 -56
View File
@@ -1,73 +1,694 @@
import { resolveInode, resolvePath } from "@core/util/path_resolver"; // @tests/core/util/path_resolver.test.ts (adjust)
import { toPtr, type NodePointer } from "@core/filesystem/node";
import { resolvePath } from "@core/util/path_resolver";
import { expectNodeNotFoundError, expectNotADirectoryError } from "@tests/helpers/error_matchers"; import { expectNodeNotFoundError, expectNotADirectoryError } from "@tests/helpers/error_matchers";
import { Fixture7Depth } from "@tests/helpers/state_fixture"; import { makeFS, makeShellState, makeTree, makeUser } from "@tests/helpers/filesystems_fixture";
import { describe, expect, test } from "vitest"; import fc from "fast-check";
import { describe, expect, it } from "vitest";
const state = Fixture7Depth.State; // ============================================================================
const fs = state.filesystem; // Path normalization
// ============================================================================
describe("resolvePath", () => { describe("resolvePath — path normalization", () => {
test("returns an inode from an absolute path", () => { /**
const path = "/d1/d2/d3/d4/"; * `/` is the root of device 0; no traversal is needed.
const result = resolvePath(fs, 1, path); */
it("resolves '/' to the root of device 0", async () => {
expect(result).toBeDefined(); const fs = await makeFS([makeTree().build()]);
expect(fs.getNode(result as number)!.name).toBe("d4"); expect(resolvePath(makeShellState(fs), "/")).toEqual({ device_id: 0, inode: 0 });
}); });
test("returns an inode from a relative path", () => { /**
const path = "./d2/d3/d4/"; * Redundant leading slashes are stripped by the normalizer.
const result = resolvePath(fs, 1, path); */
it("resolves '/', '//', and '///' identically", async () => {
expect(result).toBeDefined(); const fs = await makeFS([makeTree().build()]);
expect(fs.getNode(result as number)!.name).toBe("d4"); const state = makeShellState(fs);
for (const p of ["/", "//", "///"]) {
expect(resolvePath(state, p)).toEqual({ device_id: 0, inode: 0 });
}
}); });
test("returns an inode from a relative parent path", () => { /**
const path = "../d1/d2/d3/d4/"; * Empty path returns the current working directory without traversal.
const result = resolvePath(fs, 1, path); */
it("resolves an empty string to the current working directory", async () => {
expect(result).toBeDefined(); const t = makeTree();
expect(fs.getNode(result as number)!.name).toBe("d4"); const work = t.addDir(0, "work");
const fs = await makeFS([t.build()]);
const state = makeShellState(fs, { cwd: toPtr({ device_id: 0, inode: work }) });
expect(resolvePath(state, "")).toEqual({ device_id: 0, inode: work });
}); });
test("returns inode 0", () => { /**
const path = "/"; * Property: leading, trailing, and interior redundant slashes never change
const result = resolvePath(fs, 1, path); * the resolved pointer.
*/
it("resolves identically regardless of redundant slashes", async () => {
const t = makeTree();
const a = t.addDir(0, "a");
t.addFile(a, "b");
const fs = await makeFS([t.build()]);
const state = makeShellState(fs);
const expected = resolvePath(state, "/a/b");
expect(result).toBeDefined(); fc.assert(
expect(result).toBe(0); fc.property(
expect(fs.getNode(result as number)!.name).toBe("root"); fc.integer({ min: 0, max: 5 }),
}); fc.integer({ min: 0, max: 5 }),
fc.integer({ min: 1, max: 4 }),
test("returns inode 1 (cwd)", () => { (lead, trail, mid) => {
const path = ""; const path = "/".repeat(lead) + "a" + "/".repeat(mid) + "b" + "/".repeat(trail);
const result = resolvePath(fs, 1, path); expect(resolvePath(state, path)).toEqual(expected);
},
expect(result).toBeDefined(); ),
expect(result).toBe(1); );
expect(fs.getNode(result as number)!.name).toBe("d1");
});
test("throws because of a nonexistent path", () => {
expectNodeNotFoundError(() => resolvePath(fs, 1, "/d3"));
});
test("throws because of file path component", () => {
expectNotADirectoryError(() => resolvePath(fs, 6, "./deep_file.txt/d8"));
});
test("throws because of a nonexistent cwd inode (technicaly should never happen)", () => {
expectNodeNotFoundError(() => resolvePath(fs, 69, "/d3"));
}); });
}); });
describe("resolveInode", () => { // ============================================================================
test("returns an the path from the d4 node", () => { // Absolute paths
expect(resolveInode(state, 4, true)).toBe("/d1/d2/d3/d4"); // ============================================================================
describe("resolvePath — absolute paths", () => {
/**
* Single-component absolute path resolves to the child's pointer.
*/
it("resolves '/name' to the child node of root", async () => {
const t = makeTree();
const foo = t.addFile(0, "foo");
const fs = await makeFS([t.build()]);
expect(resolvePath(makeShellState(fs), "/foo")).toEqual({ device_id: 0, inode: foo });
}); });
test("returns an empty string from a non existent inode", () => { /**
expect(resolveInode(state, 999)).toBe(""); * Nested paths traverse each directory in turn.
*/
it("resolves a nested path '/a/b' to the final child", async () => {
const t = makeTree();
const a = t.addDir(0, "a");
const b = t.addFile(a, "b");
const fs = await makeFS([t.build()]);
expect(resolvePath(makeShellState(fs), "/a/b")).toEqual({ device_id: 0, inode: b });
});
/**
* Deeper paths traverse more levels.
*/
it("resolves a deep path '/a/b/c/d' to the final child", async () => {
const t = makeTree();
const a = t.addDir(0, "a");
const b = t.addDir(a, "b");
const c = t.addDir(b, "c");
const d = t.addFile(c, "d");
const fs = await makeFS([t.build()]);
expect(resolvePath(makeShellState(fs), "/a/b/c/d")).toEqual({ device_id: 0, inode: d });
});
/**
* Trailing slash is stripped and resolves the same as without it.
*/
it("resolves '/a/b/' to the same pointer as '/a/b'", async () => {
const t = makeTree();
const a = t.addDir(0, "a");
t.addFile(a, "b");
const fs = await makeFS([t.build()]);
const state = makeShellState(fs);
expect(resolvePath(state, "/a/b/")).toEqual(resolvePath(state, "/a/b"));
});
/**
* Missing top-level component raises a typed NodeNotFound.
*/
it("throws NodeNotFound when the first component does not exist", async () => {
const fs = await makeFS([makeTree().build()]);
await expectNodeNotFoundError(() => resolvePath(makeShellState(fs), "/missing"));
});
/**
* Missing intermediate component raises a typed NodeNotFound.
*/
it("throws NodeNotFound when an intermediate component does not exist", async () => {
const t = makeTree();
t.addDir(0, "a");
const fs = await makeFS([t.build()]);
await expectNodeNotFoundError(() => resolvePath(makeShellState(fs), "/a/missing/b"));
});
/**
* Descending through a file at a non-final position is rejected with
* NotADirectory (this one works — the isFile check fires because `a` is
* not the last component).
*/
it("throws NotADirectory when traversing through a file at a non-final position", async () => {
const t = makeTree();
t.addFile(0, "a");
const fs = await makeFS([t.build()]);
await expectNotADirectoryError(() => resolvePath(makeShellState(fs), "/a/b/c"));
});
/**
* EXPECTED-TO-FAIL: descending through a file at the final position should
* also throw NotADirectory. Current implementation skips the isFile check
* on the last iteration and then crashes on `(file as Directory).children`.
*/
it("should throw NotADirectory when descending through a file at the final position", async () => {
const t = makeTree();
t.addFile(0, "a");
const fs = await makeFS([t.build()]);
await expectNotADirectoryError(() => resolvePath(makeShellState(fs), "/a/b"));
});
});
// ============================================================================
// Relative paths
// ============================================================================
describe("resolvePath — relative paths", () => {
/**
* A single relative component resolves against cwd.
*/
it("resolves a relative path from a device-0 cwd", async () => {
const t = makeTree();
const work = t.addDir(0, "work");
const file = t.addFile(work, "file");
const fs = await makeFS([t.build()]);
const state = makeShellState(fs, { cwd: toPtr({ device_id: 0, inode: work }) });
expect(resolvePath(state, "file")).toEqual({ device_id: 0, inode: file });
});
/**
* Multi-component relative paths traverse from cwd.
*/
it("resolves a multi-component relative path from cwd", async () => {
const t = makeTree();
const work = t.addDir(0, "work");
const sub = t.addDir(work, "sub");
const leaf = t.addFile(sub, "leaf");
const fs = await makeFS([t.build()]);
const state = makeShellState(fs, { cwd: toPtr({ device_id: 0, inode: work }) });
expect(resolvePath(state, "sub/leaf")).toEqual({ device_id: 0, inode: leaf });
});
/**
* Missing relative component raises a typed NodeNotFound.
*/
it("throws NodeNotFound for a missing relative component", async () => {
const fs = await makeFS([makeTree().build()]);
await expectNodeNotFoundError(() => resolvePath(makeShellState(fs), "nope"));
});
});
// ============================================================================
// ~ expansion
// ============================================================================
describe("resolvePath — '~' expansion", () => {
/**
* `~` expands to the user's home directory (home on device 0).
*/
it("expands '~' to the user's home directory", async () => {
const t = makeTree();
const home = t.addDir(0, "home");
const fs = await makeFS([t.build()]);
const user = makeUser(toPtr({ device_id: 0, inode: home }));
const state = makeShellState(fs, { user });
expect(resolvePath(state, "~")).toEqual({ device_id: 0, inode: home });
});
/**
* `~/name` expands home first, then resolves `name` beneath it.
*/
it("expands '~/name' to a child of home", async () => {
const t = makeTree();
const home = t.addDir(0, "home");
const file = t.addFile(home, "file");
const fs = await makeFS([t.build()]);
const user = makeUser(toPtr({ device_id: 0, inode: home }));
const state = makeShellState(fs, { user });
expect(resolvePath(state, "~/file")).toEqual({ device_id: 0, inode: file });
});
/**
* EXPECTED-TO-FAIL: `~` expansion never touches `currentVD`, so a home on
* device 1 resolves the first component but then reads subsequent children
* from device 0 — usually crashing on a missing inode.
*/
it("should resolve '~/file' when home lives on device 1", async () => {
const t0 = makeTree();
const t1 = makeTree();
const home = t1.addDir(0, "home");
const file = t1.addFile(home, "file");
const fs = await makeFS([t0.build(), t1.build()]);
const user = makeUser(toPtr({ device_id: 1, inode: home }));
const state = makeShellState(fs, { user });
expect(resolvePath(state, "~/file")).toEqual({ device_id: 1, inode: file });
});
});
// ============================================================================
// Symlink resolution
// ============================================================================
describe("resolvePath — symlink resolution", () => {
/**
* Absolute symlink targets resolve from device 0's root.
*/
it("follows an absolute symlink target", async () => {
const t = makeTree();
const real = t.addDir(0, "real");
const leaf = t.addFile(real, "leaf");
t.addSymlink(0, "link", "/real/leaf");
const fs = await makeFS([t.build()]);
expect(resolvePath(makeShellState(fs), "/link")).toEqual({ device_id: 0, inode: leaf });
});
});
// ============================================================================
// Mount points
// ============================================================================
describe("resolvePath — mount points", () => {
/**
* EXPECTED-TO-FAIL: mount redirect must fire on the child before descent.
* `/mnt` alone should return the mounted device's root, not the mountpoint
* directory on the parent device.
*/
it("should resolve '/mnt' to the mounted device's root", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
expect(resolvePath(makeShellState(fs), "/mnt")).toEqual({ device_id: 1, inode: 0 });
});
/**
* EXPECTED-TO-FAIL: `/mnt/file` should descend through the mount and land
* on `/file` on device 1 — the trailing component must not be consumed by
* the redirect.
*/
it("should resolve '/mnt/file' to '/file' on the mounted device", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const file = t1.addFile(0, "file");
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
expect(resolvePath(makeShellState(fs), "/mnt/file")).toEqual({ device_id: 1, inode: file });
});
/**
* EXPECTED-TO-FAIL: deep paths through a mount must traverse the mounted
* device for every subsequent component.
*/
it("should resolve '/mnt/sub/leaf' to '/sub/leaf' on the mounted device", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const sub = t1.addDir(0, "sub");
const leaf = t1.addFile(sub, "leaf");
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
expect(resolvePath(makeShellState(fs), "/mnt/sub/leaf")).toEqual({ device_id: 1, inode: leaf });
});
/**
* A non-mountpoint directory resolves to itself on the parent device —
* `/a` is not a mount, so no redirect.
*/
it("resolves a non-mountpoint directory to itself on the parent device", async () => {
const t0 = makeTree();
const a = t0.addDir(0, "a"); // /a = device 0:1 (not a mountpoint)
const mnt = t0.addDir(0, "mnt"); // /mnt = device 0:2 (the mountpoint)
const t1 = makeTree();
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(
toPtr({ device_id: 0, inode: mnt }), // "0:2" — the mountpoint
toPtr({ device_id: 1, inode: 0 }),
);
const state = makeShellState(fs);
// /a is not a mountpoint → resolves to itself on device 0
expect(resolvePath(state, "/a")).toEqual({ device_id: 0, inode: a });
// /mnt IS a mountpoint → redirects to device 1's root
// (this is already covered by the /mnt tests; include for contrast or drop)
expect(resolvePath(state, "/mnt")).toEqual({ device_id: 1, inode: 0 });
});
/**
* EXPECTED-TO-FAIL: nested mount at `/a/b` should redirect to dev1's sub.
*/
it("should resolve '/a/b' (nested mount) to the mounted device's sub", async () => {
const t0 = makeTree();
const a = t0.addDir(0, "a");
const b = t0.addDir(a, "b");
const t1 = makeTree();
const sub = t1.addDir(0, "sub");
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: b }), toPtr({ device_id: 1, inode: sub }));
expect(resolvePath(makeShellState(fs), "/a/b")).toEqual({ device_id: 1, inode: sub });
});
/**
* EXPECTED-TO-FAIL: continuation of the nested case — `/a/b/leaf` should
* land on dev1's leaf through the mounted sub.
*/
it("should resolve '/a/b/leaf' through a nested mount", async () => {
const t0 = makeTree();
const a = t0.addDir(0, "a");
const b = t0.addDir(a, "b");
const t1 = makeTree();
const sub = t1.addDir(0, "sub");
const leaf = t1.addFile(sub, "leaf");
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: b }), toPtr({ device_id: 1, inode: sub }));
expect(resolvePath(makeShellState(fs), "/a/b/leaf")).toEqual({ device_id: 1, inode: leaf });
});
/**
* EXPECTED-TO-FAIL: two independent mounts must redirect independently.
*/
it("should resolve multiple independent mounts", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const other = t0.addDir(0, "other");
const t1 = makeTree();
const file = t1.addFile(0, "file");
const sub = t1.addDir(0, "sub");
const leaf = t1.addFile(sub, "leaf");
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
fs.mount(toPtr({ device_id: 0, inode: other }), toPtr({ device_id: 1, inode: sub }));
const state = makeShellState(fs);
expect(resolvePath(state, "/mnt/file")).toEqual({ device_id: 1, inode: file });
expect(resolvePath(state, "/other/leaf")).toEqual({ device_id: 1, inode: leaf });
});
});
// ============================================================================
// Symlinks across mount points
// ============================================================================
describe("resolvePath — symlinks across mount points", () => {
/**
* EXPECTED-TO-FAIL: symlink whose target lands on another device must
* return the target's device id in the result. Without threading, the loop
* terminates with currentNode from dev1 but currentVD still 0.
*/
it("should thread the target's device into currentVD after a symlink→mount hop", async () => {
const t0 = makeTree();
t0.addSymlink(0, "link", "/mnt");
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
expect(resolvePath(makeShellState(fs), "/link")).toEqual({ device_id: 1, inode: 0 });
});
/**
* EXPECTED-TO-FAIL: full traversal through the symlink and across the
* mount. Verifies not only the final pointer is right, but that the loop
* can continue descending on the mounted device.
*/
it("should resolve through a symlink→mount hop and continue on the mounted device", async () => {
const t0 = makeTree();
t0.addSymlink(0, "link", "/mnt");
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const file = t1.addFile(0, "file");
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
expect(resolvePath(makeShellState(fs), "/link/file")).toEqual({ device_id: 1, inode: file });
});
});
// ============================================================================
// Integration
// ============================================================================
describe("resolvePath — integration", () => {
/**
* Full traversal across multiple levels with a file terminus.
*/
it("resolves a multi-level path through directories to a file", async () => {
const t = makeTree();
const varInode = t.addDir(0, "var");
const logInode = t.addDir(varInode, "log");
const appLog = t.addFile(logInode, "app.log");
const fs = await makeFS([t.build()]);
expect(resolvePath(makeShellState(fs), "/var/log/app.log")).toEqual({ device_id: 0, inode: appLog });
});
});
// ============================================================================
// Known bugs — each test asserts *current* behavior and goes red on the fix.
// ============================================================================
describe("resolvePath — known bugs", () => {
/**
* BUG: symlink depth overflow throws a raw `Error`, not a typed error.
* Same setup as above; asserts the thrown object isn't a discriminated
* union member (no `type` field).
*
* Fix: throw a typed `SymlinkLoopError` (or similar) from `errors.ts`.
*/
it("BUG: symlink depth overflow throws a raw Error, not a typed one", async () => {
const t = makeTree();
const sNames = Array.from({ length: 41 }, (_, i) => `s${i + 1}`);
t.addFile(0, "target");
for (let i = 0; i < 40; i++) {
t.addSymlink(0, sNames[i]!, `/${sNames[i + 1]}`);
}
t.addSymlink(0, sNames[40]!, "/target");
const fs = await makeFS([t.build()]);
let thrown: unknown = undefined;
try {
resolvePath(makeShellState(fs), "/s1");
} catch (e) {
thrown = e;
}
expect(thrown).toBeInstanceOf(Error);
expect(thrown).not.toHaveProperty("type");
// ^ BUG: no `type` discriminant. Correct: typed (e.g. SymlinkLoop).
});
/**
* BUG: a malformed cwd pointer is not validated; `fromPtr(session.cwd)`
* throws a raw `Error("Invalid node pointer format")`, not a typed one.
* Same "untyped" class as the symlink-depth bug.
*
* Fix: wrap `fromPtr` calls in a typed try/catch, or add a validating
* parse (e.g. `tryFromPtr`) that returns `undefined` on failure.
*/
it("BUG: malformed cwd throws a raw Error from fromPtr", async () => {
const fs = await makeFS([makeTree().build()]);
const state = makeShellState(fs, {
cwd: "garbage" as NodePointer,
});
expect(() => resolvePath(state, "foo")).toThrow(/Invalid node pointer format/);
});
/**
* BUG: same as above, for `session.user.home` when expanding `~`.
*/
it("BUG: malformed home pointer throws a raw Error from fromPtr", async () => {
const fs = await makeFS([makeTree().build()]);
const user = makeUser("garbage" as NodePointer);
const state = makeShellState(fs, { user });
expect(() => resolvePath(state, "~")).toThrow(/Invalid node pointer format/);
});
});
describe("resolvePath — '..' across mount boundaries", () => {
/**
* BASIC CASE. Mount `/mnt` (device 0) → device 1's root. From inside the
* mount (at `1:0`), `..` must exit through the reverse mount index to
* `/mnt`'s parent (`/`) — not stay put via the `inode === 0` shortcut.
*
* This is the direct fix target: the `..` branch must check
* `getMountSource(currentPtr)` *before* the `inode === 0` shortcut.
*/
it("'..' from a mount root returns to the mountpoint's parent", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const fs = await makeFS([t0.build(), makeTree().build()]);
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
const atMountedRoot = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) });
expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: 0 });
});
/**
* NON-ROOT MOUNTPOINT. Mount `/home/user/mnt` → device 1's root. `..` from
* the mounted root must land on `/home/user` (device 0), *not* `/`.
* Catches a fix that hardcodes "go to root on mount exit".
*/
it("'..' from a non-root mount returns to the mountpoint's immediate parent", async () => {
const t0 = makeTree();
const home = t0.addDir(0, "home");
const user = t0.addDir(home, "user");
const mnt = t0.addDir(user, "mnt");
const fs = await makeFS([t0.build(), makeTree().build()]);
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
const atMountedRoot = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) });
expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: user });
});
/**
* INSIDE-MOUNT `..`. A subdirectory of the mounted device is *not* the
* mount root, so `..` from `1:sub` must stay inside device 1 (regular
* reverse-index walk), not exit the mount. Catches a fix that exits the
* mount on every `..` inside the mounted device instead of only at its
* root.
*/
it("'..' from inside a mount (not at its root) stays inside the mount", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const sub = t1.addDir(0, "sub");
const fs = await makeFS([t0.build(), t1.build()]);
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
const atSub = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: sub }) });
expect(resolvePath(atSub, "..")).toEqual({ device_id: 1, inode: 0 });
});
/**
* MULTI-STEP `..`. From `/mnt/sub/leaf`, three consecutive `..` should
* produce `/mnt/sub` → `/mnt` → `/`. Exercises both the in-mount walk and
* the final mount exit in one flow. Catches a fix that only handles the
* "already at mount root" case but breaks when coming from deeper.
*/
it("multi-step '..' walks from deep inside a mount out to the parent device", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const sub = t1.addDir(0, "sub");
const leaf = t1.addFile(sub, "leaf");
const fs = await makeFS([t0.build(), t1.build()]);
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
// Sanity: full descent lands at `1:leaf`
expect(resolvePath(makeShellState(fs), "/mnt/sub/leaf")).toEqual({ device_id: 1, inode: leaf });
// One `..` up: /mnt/sub
const atLeaf = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: leaf }) });
expect(resolvePath(atLeaf, "..")).toEqual({ device_id: 1, inode: sub });
// Another `..`: /mnt's content = dev1 root
const atSub = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: sub }) });
expect(resolvePath(atSub, "..")).toEqual({ device_id: 1, inode: 0 });
// Final `..`: exit the mount → /
const atMountedRoot = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) });
expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: 0 });
});
/**
* INDEPENDENT MOUNTS AT DIFFERENT DEPTHS. Mount A at `/a` (dev0 → dev1)
* and Mount B at `/b/nested` (dev0 → dev2). `..` from dev1's root must go
* to `/` (parent of `/a`), while `..` from dev2's root must go to `/b`
* (parent of `/b/nested`).
*
* Catches a fix that collapses the reverse index to a single entry — e.g.,
* if `getMountSource` returns the *first* mount's mountpoint for any
* target, or if `mount()` overwrites the wrong entry.
*/
it("'..' from different mounts returns to each mountpoint's own parent", async () => {
const t0 = makeTree();
const a = t0.addDir(0, "a");
const b = t0.addDir(0, "b");
const nested = t0.addDir(b, "nested");
const fs = await makeFS([t0.build(), makeTree().build(), makeTree().build()]);
await fs.mount(toPtr({ device_id: 0, inode: a }), toPtr({ device_id: 1, inode: 0 })); // /a → dev1
await fs.mount(toPtr({ device_id: 0, inode: nested }), toPtr({ device_id: 2, inode: 0 })); // /b/nested → dev2
// `..` from dev1's root → parent of `/a` = `/`
const atDev1Root = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) });
expect(resolvePath(atDev1Root, "..")).toEqual({ device_id: 0, inode: 0 });
// `..` from dev2's root → parent of `/b/nested` = `/b`
const atDev2Root = makeShellState(fs, { cwd: toPtr({ device_id: 2, inode: 0 }) });
expect(resolvePath(atDev2Root, "..")).toEqual({ device_id: 0, inode: b });
});
/**
* MOUNT NESTED IN A MOUNTED DEVICE'S TREE. The most realistic cross-device
* scenario:
*
* dev0: /mnt (0:1)
* dev1: / (1:0)
* /b (1:2) ← mountpoint of B
* dev2: / (2:0)
*
* Mount A: 0:1 → 1:0 (/mnt shows dev1)
* Mount B: 1:2 → 2:0 (/mnt/b shows dev2)
*
* From `/mnt/b` (dev2 root), `..` must exit B's mount to `/mnt/b`'s parent
* in the *mounted* device 1 (`1:0`), not skip straight to device 0. A
* second `..` then exits A's mount to `/`.
*
* This is the true "chained mount exit" case. Each `..` handles exactly
* one mount; the reverse index for `1:2` (B's mountpoint) lands on `1:0`
* (dev1 root), which is itself a mount target of A. The second `..` then
* exits A. Both steps go through the same `getMountSource` branch.
*/
it("'..' walks out of a mount nested inside another mount's device tree", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const b = t1.addDir(0, "b");
const fs = await makeFS([t0.build(), t1.build(), makeTree().build()]);
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 })); // /mnt → dev1
await fs.mount(toPtr({ device_id: 1, inode: b }), toPtr({ device_id: 2, inode: 0 })); // /mnt/b → dev2
// Sanity: /mnt/b resolves to dev2 root
expect(resolvePath(makeShellState(fs), "/mnt/b")).toEqual({ device_id: 2, inode: 0 });
// `..` from dev2 root → exit B's mount → parent of `1:b` = `1:0` (dev1 root)
const atDev2Root = makeShellState(fs, { cwd: toPtr({ device_id: 2, inode: 0 }) });
expect(resolvePath(atDev2Root, "..")).toEqual({ device_id: 1, inode: 0 });
// `..` from dev1 root → exit A's mount → parent of `0:mnt` = `/`
const atDev1Root = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) });
expect(resolvePath(atDev1Root, "..")).toEqual({ device_id: 0, inode: 0 });
});
/**
* ROUND TRIP. `cd /mnt`, `cd ..`, `cd mnt` should land back at `{1:0}`.
* Catches a fix that mutates mount state (e.g., a stale `currentDeviceId`
* that leaks across calls) or that resolves `/mnt` differently after a
* `..` exit.
*/
it("entering and exiting a mount via resolvePath round-trips", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const fs = await makeFS([t0.build(), makeTree().build()]);
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
// Start at /, enter /mnt
const fromRoot = makeShellState(fs);
expect(resolvePath(fromRoot, "/mnt")).toEqual({ device_id: 1, inode: 0 });
// `..` from mounted root → /
const atMnt = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) });
expect(resolvePath(atMnt, "..")).toEqual({ device_id: 0, inode: 0 });
// `mnt` again from / → back to mounted root
const atRoot = makeShellState(fs, { cwd: toPtr({ device_id: 0, inode: 0 }) });
expect(resolvePath(atRoot, "mnt")).toEqual({ device_id: 1, inode: 0 });
}); });
}); });
File diff suppressed because one or more lines are too long
+84 -15
View File
@@ -1,17 +1,23 @@
// @core/filesystem/errors.test-util.ts (adjust path to match yours)
import type { import type {
AlreadyExistsError, AlreadyExistsError,
DeviceNotFoundError,
DirectoryLoopError, DirectoryLoopError,
FileSystemCorruptionError,
FileSystemInitializationError,
IllegalMutationError, IllegalMutationError,
InvalidNodeNameError,
NodeNotFoundError, NodeNotFoundError,
NotADirectoryError, NotADirectoryError,
NotAFileError,
} from "@core/filesystem/errors"; } from "@core/filesystem/errors";
import type { TreeNodeType } from "@core/filesystem/treenode"; import type { NodeType } from "@core/filesystem/node";
import { expect } from "vitest"; import { expect } from "vitest";
export function expectThrows(fn: () => unknown, expectedShape: Record<string, unknown>) { export async function expectThrows(fn: () => unknown, expectedShape: Record<string, unknown>) {
let thrown: unknown; let thrown: unknown;
try { try {
fn(); await fn();
} catch (e) { } catch (e) {
thrown = e; thrown = e;
} }
@@ -20,19 +26,19 @@ export function expectThrows(fn: () => unknown, expectedShape: Record<string, un
expect(thrown).toMatchObject(expectedShape); expect(thrown).toMatchObject(expectedShape);
} }
export function expectNotADirectoryError(fn: () => unknown, overrides?: Partial<NotADirectoryError>) { export async function expectNotADirectoryError(fn: () => unknown, overrides?: Partial<NotADirectoryError>) {
expectThrows(fn, { return await expectThrows(fn, {
type: "NotADirectory", type: "NotADirectory",
inode: expect.any(Number) as number, inode: expect.any(Number) as number,
message: expect.any(String) as string, message: expect.any(String) as string,
timestamp: expect.any(Number) as number, timestamp: expect.any(Number) as number,
nodeType: expect.any(Number) as TreeNodeType, nodeType: expect.any(Number) as NodeType,
...overrides, ...overrides,
}); });
} }
export function expectAlreadyExistsError(fn: () => unknown, overrides?: Partial<AlreadyExistsError>) { export async function expectAlreadyExistsError(fn: () => unknown, overrides?: Partial<AlreadyExistsError>) {
expectThrows(fn, { return await expectThrows(fn, {
type: "AlreadyExists", type: "AlreadyExists",
parentInode: expect.any(Number) as number, parentInode: expect.any(Number) as number,
name: expect.any(String) as string, name: expect.any(String) as string,
@@ -42,18 +48,23 @@ export function expectAlreadyExistsError(fn: () => unknown, overrides?: Partial<
}); });
} }
export function expectNodeNotFoundError(fn: () => unknown, overrides?: Partial<NodeNotFoundError>) { /**
expectThrows(fn, { * FIXED: `NodeNotFoundError` has `pointer: NodePointer` (a string), not `inode: number`.
* The previous version asserted `inode: expect.any(Number)` and would have failed
* against every real thrown `NodeNotFoundError`.
*/
export async function expectNodeNotFoundError(fn: () => unknown, overrides?: Partial<NodeNotFoundError>) {
return await expectThrows(fn, {
type: "NodeNotFound", type: "NodeNotFound",
inode: expect.any(Number) as number, pointer: expect.any(String) as string,
message: expect.any(String) as string, message: expect.any(String) as string,
timestamp: expect.any(Number) as number, timestamp: expect.any(Number) as number,
...overrides, ...overrides,
}); });
} }
export function expectIllegalMutationError(fn: () => unknown, overrides?: Partial<IllegalMutationError>) { export async function expectIllegalMutationError(fn: () => unknown, overrides?: Partial<IllegalMutationError>) {
expectThrows(fn, { return await expectThrows(fn, {
type: "IllegalMutation", type: "IllegalMutation",
message: expect.any(String) as string, message: expect.any(String) as string,
timestamp: expect.any(Number) as number, timestamp: expect.any(Number) as number,
@@ -61,8 +72,8 @@ export function expectIllegalMutationError(fn: () => unknown, overrides?: Partia
}); });
} }
export function expectDirectoryLoopError(fn: () => void, overrides?: Partial<DirectoryLoopError>) { export async function expectDirectoryLoopError(fn: () => void, overrides?: Partial<DirectoryLoopError>) {
expectThrows(fn, { return await expectThrows(fn, {
type: "DirectoryLoop", type: "DirectoryLoop",
descendantInode: expect.any(Number) as number, descendantInode: expect.any(Number) as number,
ancestorInode: expect.any(Number) as number, ancestorInode: expect.any(Number) as number,
@@ -71,3 +82,61 @@ export function expectDirectoryLoopError(fn: () => void, overrides?: Partial<Dir
...overrides, ...overrides,
}); });
} }
// ---- NEW helpers below ----
export async function expectDeviceNotFoundError(fn: () => unknown, overrides?: Partial<DeviceNotFoundError>) {
return await expectThrows(fn, {
type: "DeviceNotFound",
device_id: expect.any(Number) as number,
message: expect.any(String) as string,
timestamp: expect.any(Number) as number,
...overrides,
});
}
export async function expectNotAFileError(fn: () => unknown, overrides?: Partial<NotAFileError>) {
return await expectThrows(fn, {
type: "NotAFile",
inode: expect.any(Number) as number,
message: expect.any(String) as string,
timestamp: expect.any(Number) as number,
nodeType: expect.any(Number) as NodeType,
...overrides,
});
}
export async function expectFileSystemInitializationError(
fn: () => unknown,
overrides?: Partial<FileSystemInitializationError>,
) {
return await expectThrows(fn, {
type: "FileSystemInitializationError",
message: expect.any(String) as string,
timestamp: expect.any(Number) as number,
...overrides,
});
}
export async function expectInvalidNodeNameError(fn: () => unknown, overrides?: Partial<InvalidNodeNameError>) {
return await expectThrows(fn, {
type: "InvalidNodeName",
pointer: expect.any(String) as string,
attemptedName: expect.any(String) as string,
message: expect.any(String) as string,
timestamp: expect.any(Number) as number,
...overrides,
});
}
export async function expectFileSystemCorruptionError(
fn: () => unknown,
overrides?: Partial<FileSystemCorruptionError>,
) {
return await expectThrows(fn, {
type: "FileSystemCorruption",
message: expect.any(String) as string,
timestamp: expect.any(Number) as number,
...overrides,
});
}
+170 -59
View File
@@ -1,71 +1,182 @@
import { FileSystem } from "@core/filesystem/filesystem"; // ============================================================================
import { TreeNodeType, type DirectoryNode, type FileNode, type TreeNode } from "@core/filesystem/treenode"; // Node fixtures
import { createImmutableBuffer } from "@core/util/immutable_buffer"; // ============================================================================
export interface FixtureNode { import { FileSystem } from "@core/filesystem/filesystem";
inode: number; import {
name: string; NodeType,
type: "File" | "Dir"; toPtr,
children: FixtureNode[]; type DirectoryNode,
content?: string; type FileNode,
mode?: number; type Node,
owner?: number; type NodePointer,
group?: number; type SymlinkNode,
mtime?: number; } from "@core/filesystem/node";
ctime?: number; import { DefaultVDiskConfig } from "@core/filesystem/vdisk";
atime?: number; import type { SessionState, UserInfo } from "@core/session_manager";
import type { ShellState } from "@core/shell_state";
import { MemDataStore, MemMetaStore } from "@core/util/temp_mem_stores";
export function makeDir(inode: number, children: Record<string, number> = {}): DirectoryNode {
return {
type: NodeType.Directory,
inode,
link_count: 2,
mode: 0o755,
owner: 0,
group: 0,
mtime: 0,
ctime: 0,
atime: 0,
children: new Map(Object.entries(children)),
};
} }
export function buildTestFS(tree: FixtureNode): FileSystem { export function makeFile(inode: number): FileNode {
const map = new Map<number, TreeNode>(); return {
type: NodeType.File,
inode,
link_count: 1,
mode: 0o644,
owner: 0,
group: 0,
mtime: 0,
ctime: 0,
atime: 0,
content: `uuid-${inode}`,
size: 0,
};
}
function parse(node: FixtureNode, parent: number): void { export function makeSymlink(inode: number, target: string): SymlinkNode {
if (node.type === "Dir") { return {
for (const child of node.children) { type: NodeType.Symlink,
parse(child, node.inode); inode,
} link_count: 1,
mode: 0o777,
owner: 0,
group: 0,
mtime: 0,
ctime: 0,
atime: 0,
target,
};
}
const children: Record<string, number> = {}; export function makeUser(home: NodePointer = toPtr({ device_id: 0, inode: 0 })): UserInfo {
for (const child of node.children) { return {
children[child.name] = child.inode; username: "test",
} uid: 1000,
gid: 1000,
group: [],
home,
};
}
const directoryNode: DirectoryNode = { // ============================================================================
type: TreeNodeType.Directory, // Tree builder — auto-assigns inodes, validates before use
inode: node.inode, // ============================================================================
name: node.name,
parent: parent, export interface TreeBuilder {
mode: node.mode ?? 0o777, addDir(parentInode: number, name: string): number;
owner: node.owner ?? 0, addFile(parentInode: number, name: string): number;
group: node.group ?? 0, addSymlink(parentInode: number, name: string, target: string): number;
mtime: node.mtime ?? Date.now(), build(): Map<number, Node>;
ctime: node.ctime ?? Date.now(), }
atime: node.atime ?? Date.now(),
children: children, export function makeTree(): TreeBuilder {
}; const nodes = new Map<number, Node>([[0, makeDir(0)]]);
map.set(node.inode, Object.freeze(directoryNode)); let nextInode = 1;
} else {
const fileNode: FileNode = { function attach(parentInode: number, name: string, childInode: number): void {
type: TreeNodeType.File, const parent = nodes.get(parentInode);
inode: node.inode, if (!parent || parent.type !== NodeType.Directory) {
name: node.name, throw new Error(`Parent inode ${parentInode} is not a directory`);
parent: parent,
mode: node.mode ?? 0o777,
owner: node.owner ?? 0,
group: node.group ?? 0,
mtime: node.mtime ?? Date.now(),
ctime: node.ctime ?? Date.now(),
atime: node.atime ?? Date.now(),
content: createImmutableBuffer(new TextEncoder().encode(node.content)),
};
map.set(node.inode, Object.freeze(fileNode));
} }
const children = new Map(parent.children);
children.set(name, childInode);
nodes.set(parentInode, { ...parent, children });
} }
parse(tree, 0); function add(node: Node, parentInode: number, name: string): number {
attach(parentInode, name, node.inode);
nodes.set(node.inode, node);
return node.inode;
}
const base: ReadonlyMap<number, TreeNode> = map; return {
const overlay: ReadonlyMap<number, TreeNode | null> = new Map(); addDir(parentInode, name) {
return add(makeDir(nextInode++), parentInode, name);
},
addFile(parentInode, name) {
return add(makeFile(nextInode++), parentInode, name);
},
addSymlink(parentInode, name, target) {
return add(makeSymlink(nextInode++, target), parentInode, name);
},
build() {
for (const [key, node] of nodes) {
if (node.inode !== key) {
throw new Error(`inode mismatch: key=${key}, node.inode=${node.inode}`);
}
if (node.type === NodeType.Directory) {
for (const [cname, cinode] of node.children) {
if (!nodes.has(cinode)) {
throw new Error(`dangling child '${cname}' → inode ${cinode}`);
}
}
}
}
return nodes;
},
};
}
return FileSystem.init(base, overlay, base.size - 1); // ============================================================================
// FileSystem builder — real VDisk stack, one device per base map
// ============================================================================
export async function makeFS(bases: Map<number, Node>[]): Promise<FileSystem> {
const devices = bases.map((base, id) => ({
dstore: new MemDataStore(),
mstore: new MemMetaStore(),
config: {
...DefaultVDiskConfig(id),
base,
index: Math.max(0, ...base.keys()),
},
}));
const fs = FileSystem.init(devices);
// `FileSystem.init` does not await `registerDisk` (see the init suite BUG);
// flush a macrotask so every disk is registered before the first resolve.
await new Promise(r => setImmediate(r));
return fs;
}
// ============================================================================
// Shell state fixture
// ============================================================================
export function makeShellState(
fs: FileSystem,
opts: { cwd?: NodePointer; home?: NodePointer; user?: UserInfo } = {},
): ShellState {
const cwd = opts.cwd ?? toPtr({ device_id: 0, inode: 0 });
const user = opts.user ?? makeUser(opts.home);
const session = {
user,
envVars: new Map<string, string>(),
history: [],
cwd,
pwd: cwd,
exitCode: 0,
} as unknown as SessionState;
return {
filesystem: fs,
users: new Map(),
groups: new Map(),
sessionStack: [session],
} as unknown as ShellState;
} }
-91
View File
@@ -1,91 +0,0 @@
import { FileSystem } from "@core/filesystem/filesystem";
import type { TreeNode } from "@core/filesystem/treenode";
import type { GroupInfo, UserInfo } from "@core/session_manager";
import { createInitialShellState, type ShellState } from "@core/shell_state";
import { deserializeFileSystem } from "@shell/serializer";
import { buildTestFS } from "./filesystems_fixture";
import { depth7Tree } from "./tree_fixture";
export class Fixture {
/*
root (0)
├── folder1 (1)
│ └── subdir1 (2)
├── folder2 (3)
│ ├── subdir2 (4)
│ └── subdir3 (5)
│ └── empty-foo (6)
└── some-file (7)
*/
static rawJson = `{"atime": 1786341244,"children": [{"atime": 1786341264,"children": [{"atime": 1786341330,"children": [],"content": null,"ctime": 1786341330,"group": 1000,"inode": 2,"mode": 493,"mtime": 1786341330,"name": "subdir1","owner": 1000,"parent": 1,"type": "directory"}],"content": null,"ctime": 1786341330,"group": 1000,"inode": 1,"mode": 493,"mtime": 1786341330,"name": "folder1","owner": 1000,"parent": 0,"type": "directory"},{"atime": 1786341269,"children": [{"atime": 1786341344,"children": [],"content": null,"ctime": 1786341344,"group": 1000,"inode": 4,"mode": 493,"mtime": 1786341344,"name": "subdir2","owner": 1000,"parent": 3,"type": "directory"},{"atime": 1786341345,"children": [{"atime": 1786341356,"children": [],"content": [],"ctime": 1786341356,"group": 1000,"inode": 6,"mode": 420,"mtime": 1786341356,"name": "empty-foo","owner": 1000,"parent": 5,"type": "regular"}],"content": null,"ctime": 1786341356,"group": 1000,"inode": 5,"mode": 493,"mtime": 1786341356,"name": "subdir3","owner": 1000,"parent": 3,"type": "directory"}],"content": null,"ctime": 1786341345,"group": 1000,"inode": 3,"mode": 493,"mtime": 1786341345,"name": "folder2","owner": 1000,"parent": 0,"type": "directory"},{"atime": 1786341312,"children": [],"content": [72,101,108,108,111,44,32,87,111,114,108,100,33,10],"ctime": 1786341312,"group": 1000,"inode": 7,"mode": 420,"mtime": 1786341312,"name": "some-file","owner": 1000,"parent": 0,"type": "regular"}],"content": null,"ctime": 1786341312,"group": 1000,"inode": 0,"mode": 493,"mtime": 1786341312,"name": "root","owner": 1000,"parent": 0,"type": "directory"}`;
static user: UserInfo = {
username: "root",
uid: 0,
gid: 0, // <- PRIMARY GID
group: [0], // <- GROUPS ARRAY
home: 0,
};
static user2: UserInfo = {
username: "user",
uid: 1000,
gid: 1000,
group: [1000],
home: 1,
};
static nopass: UserInfo = {
username: "no pass",
uid: 1001,
gid: 1000,
group: [1000],
home: 2,
};
static group: GroupInfo = {
groupname: "root",
gid: 0,
members: [0], // <- UID
};
static group2: GroupInfo = {
groupname: "user",
gid: 1000,
members: [1000, 1001], // <- UID
};
public static get State(): ShellState {
const rawJson = `{"atime": 1786341244,"children": [{"atime": 1786341264,"children": [{"atime": 1786341330,"children": [],"content": null,"ctime": 1786341330,"group": 1000,"inode": 2,"mode": 493,"mtime": 1786341330,"name": "subdir1","owner": 1000,"parent": 1,"type": "directory"}],"content": null,"ctime": 1786341330,"group": 1000,"inode": 1,"mode": 493,"mtime": 1786341330,"name": "folder1","owner": 1000,"parent": 0,"type": "directory"},{"atime": 1786341269,"children": [{"atime": 1786341344,"children": [],"content": null,"ctime": 1786341344,"group": 1000,"inode": 4,"mode": 493,"mtime": 1786341344,"name": "subdir2","owner": 1000,"parent": 3,"type": "directory"},{"atime": 1786341345,"children": [{"atime": 1786341356,"children": [],"content": [],"ctime": 1786341356,"group": 1000,"inode": 6,"mode": 420,"mtime": 1786341356,"name": "empty-foo","owner": 1000,"parent": 5,"type": "regular"}],"content": null,"ctime": 1786341356,"group": 1000,"inode": 5,"mode": 493,"mtime": 1786341356,"name": "subdir3","owner": 1000,"parent": 3,"type": "directory"}],"content": null,"ctime": 1786341345,"group": 1000,"inode": 3,"mode": 493,"mtime": 1786341345,"name": "folder2","owner": 1000,"parent": 0,"type": "directory"},{"atime": 1786341312,"children": [],"content": [72,101,108,108,111,44,32,87,111,114,108,100,33,10],"ctime": 1786341312,"group": 1000,"inode": 7,"mode": 420,"mtime": 1786341312,"name": "some-file","owner": 1000,"parent": 0,"type": "regular"}],"content": null,"ctime": 1786341312,"group": 1000,"inode": 0,"mode": 493,"mtime": 1786341312,"name": "root","owner": 1000,"parent": 0,"type": "directory"}`;
const base = deserializeFileSystem(rawJson);
const overlay: ReadonlyMap<number, TreeNode | null> = new Map();
const fs = FileSystem.init(base, overlay, base.size - 1);
const users: Map<number, UserInfo> = new Map();
const groups: Map<number, GroupInfo> = new Map();
users.set(0, Fixture.user);
users.set(1000, Fixture.user2);
users.set(1001, Fixture.nopass);
groups.set(0, Fixture.group);
groups.set(1000, Fixture.group2);
return createInitialShellState(fs, users, groups, Fixture.user);
}
}
export class Fixture7Depth extends Fixture {
public static get State(): ShellState {
const fs = buildTestFS(depth7Tree);
const users: Map<number, UserInfo> = new Map();
const groups: Map<number, GroupInfo> = new Map();
users.set(0, Fixture7Depth.user);
users.set(1000, Fixture7Depth.user2);
groups.set(0, Fixture7Depth.group);
groups.set(1000, Fixture7Depth.group2);
return createInitialShellState(fs, users, groups, Fixture7Depth.user);
}
}
-58
View File
@@ -1,58 +0,0 @@
import type { FixtureNode } from "./filesystems_fixture";
export const depth7Tree: FixtureNode = {
inode: 0,
name: "root",
type: "Dir",
children: [
{
inode: 1,
name: "d1",
type: "Dir",
children: [
{
inode: 2,
name: "d2",
type: "Dir",
children: [
{
inode: 3,
name: "d3",
type: "Dir",
children: [
{
inode: 4,
name: "d4",
type: "Dir",
children: [
{
inode: 5,
name: "d5",
type: "Dir",
children: [
{
inode: 6,
name: "d6",
type: "Dir",
children: [
{
inode: 7,
name: "deep_file.txt",
type: "File",
content: "Deepest node at depth 7",
children: [],
},
],
},
],
},
],
},
],
},
],
},
],
},
],
};
+9
View File
@@ -0,0 +1,9 @@
import { defineConfig } from "tsup";
export default defineConfig({
entry: ["src/index.ts", "!src/dev.ts", "!src/**/*.test.ts", "!src/**/*.spec.ts"],
format: ["esm"],
dts: true,
clean: true,
sourcemap: true,
});