a lot of mess, keep working on VDisk for now.
This commit is contained in:
Vendored
+1
-1
@@ -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>/**"]
|
||||||
|
|||||||
@@ -1,6 +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 { TreeNodeType, type FileNode, type TreeNode } from "@core/filesystem/treenode";
|
import { TreeNodeType, type FileNode, type TreeNode } 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";
|
||||||
|
|||||||
@@ -1,6 +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 { TreeNodeType, type DirectoryNode, type TreeNode } from "@core/filesystem/treenode";
|
import { TreeNodeType, type DirectoryNode, type TreeNode } 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";
|
||||||
|
|||||||
@@ -1,6 +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 { TreeNodeType } from "@core/filesystem/treenode";
|
import { TreeNodeType } from "@core/filesystem/node";
|
||||||
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";
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { TreeNodeType } from "./treenode";
|
import type { TreeNodeType } from "./node";
|
||||||
|
|
||||||
export type FileSystemError =
|
export type FileSystemError =
|
||||||
NotADirectoryError | AlreadyExistsError | NodeNotFoundError | IllegalMutationError | FileSystemInitializationError;
|
NotADirectoryError | AlreadyExistsError | NodeNotFoundError | IllegalMutationError | FileSystemInitializationError;
|
||||||
|
|||||||
@@ -10,13 +10,31 @@ import type {
|
|||||||
NodeNotFoundError,
|
NodeNotFoundError,
|
||||||
NotADirectoryError,
|
NotADirectoryError,
|
||||||
} from "./errors";
|
} from "./errors";
|
||||||
import { TreeNodeType, type DirectoryNode, type FileNode, type TreeNode } from "./treenode";
|
import {
|
||||||
import type { IDataStore, NodeHash, ShadowHash } from "./vdisk";
|
type DirectoryNode,
|
||||||
|
type FileNode,
|
||||||
|
type NodeEntry,
|
||||||
|
type NodeHash,
|
||||||
|
type NodePointer,
|
||||||
|
type ShadowHash,
|
||||||
|
} from "./node";
|
||||||
|
import type { IDataStore } from "./vdisk";
|
||||||
|
|
||||||
|
export interface FileSystemConfig {
|
||||||
|
maxPathLength: number;
|
||||||
|
maxSymlinkDepth: number;
|
||||||
|
maxNameLength: number;
|
||||||
|
}
|
||||||
|
|
||||||
export class FileSystem {
|
export class FileSystem {
|
||||||
private _SysVDisk: number = 0;
|
private readonly _maxNameLength: number;
|
||||||
private _Mounts: Map<number, number> = new Map();
|
private readonly _maxPathLength: number;
|
||||||
|
private readonly _maxSymlinkDepth: number;
|
||||||
|
|
||||||
|
private _SysPartitionID: number = 0;
|
||||||
|
private _Mounts: Map<NodePointer, { tinode: number; tdevice_id: number }> = new Map();
|
||||||
private _VDiskManager: VDiskManager = new VDiskManager();
|
private _VDiskManager: VDiskManager = new VDiskManager();
|
||||||
|
private _EntryCache: Map<NodePointer, NodeEntry>;
|
||||||
|
|
||||||
private constructor(store: IDataStore[], base: NodeHash[], overlay: ShadowHash[], id: number[]) {
|
private constructor(store: IDataStore[], base: NodeHash[], overlay: ShadowHash[], id: number[]) {
|
||||||
for (let i = 0; i < id.length; i++) {
|
for (let i = 0; i < id.length; i++) {
|
||||||
@@ -26,18 +44,33 @@ export class FileSystem {
|
|||||||
}
|
}
|
||||||
this._VDiskManager.registerVDisk(store[i]!, base[i], overlay[i], id[i]);
|
this._VDiskManager.registerVDisk(store[i]!, base[i], overlay[i], id[i]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this._EntryCache = this.buildNodeEntryCache();
|
||||||
}
|
}
|
||||||
|
|
||||||
private resolveNode(inode: number): TreeNode | undefined {
|
private updateDentryCache(key: NodePointer, entry: NodeEntry): void {}
|
||||||
const node = this._OverlayFS.get(inode);
|
|
||||||
|
private resolveNode(ptr: NodePointer): TreeNode | undefined {
|
||||||
|
const dev = this._VDiskManager.getVDisk(ptr[1]);
|
||||||
|
if (!dev) return undefined;
|
||||||
|
|
||||||
|
const node = dev.overlay.get(ptr[0]);
|
||||||
if (node) return node;
|
if (node) return node;
|
||||||
if (node === null) return undefined;
|
if (node === null) return undefined;
|
||||||
|
|
||||||
return this._BaseFS.get(inode);
|
return dev.base.get(ptr[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static init(store: IDataStore, base: NodeHash, overlay: ShadowHash, index: number): FileSystem {
|
public static init(store: IDataStore[], base: NodeHash[], overlay: ShadowHash[], index: number[]): FileSystem {
|
||||||
if (base.get(0) === undefined) {
|
if (store.length === 0 || base.length === 0 || index.length === 0) {
|
||||||
|
throw {
|
||||||
|
type: "FileSystemInitializationError",
|
||||||
|
message: "File System tried to initialized without a base hashmap and store",
|
||||||
|
timestamp: Date.now(),
|
||||||
|
} satisfies FileSystemInitializationError;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (base[0]!.get(0) === undefined) {
|
||||||
throw {
|
throw {
|
||||||
type: "FileSystemInitializationError",
|
type: "FileSystemInitializationError",
|
||||||
message: "File System failed to initialize because root node is undefined or not assigned to inode 0",
|
message: "File System failed to initialize because root node is undefined or not assigned to inode 0",
|
||||||
@@ -45,7 +78,7 @@ export class FileSystem {
|
|||||||
} satisfies FileSystemInitializationError;
|
} satisfies FileSystemInitializationError;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (base.get(0)?.type !== TreeNodeType.Directory) {
|
if (base[0]!.get(0)?.type !== TreeNodeType.Directory) {
|
||||||
throw {
|
throw {
|
||||||
type: "FileSystemInitializationError",
|
type: "FileSystemInitializationError",
|
||||||
message: "File System failed to initialize because root node is not a directory",
|
message: "File System failed to initialize because root node is not a directory",
|
||||||
@@ -57,66 +90,71 @@ export class FileSystem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public getRoot(): DirectoryNode {
|
public getRoot(): DirectoryNode {
|
||||||
const node = this.resolveNode(0);
|
const node = this.resolveNode([0, this._SysPartitionID]);
|
||||||
if (node === undefined) throw new Error("FileSystem corrupted! INode 0 did not resolve properly.");
|
if (node === undefined || node.type !== TreeNodeType.Directory)
|
||||||
|
throw new Error("System partitions root inode did not resolve properly.");
|
||||||
return node as DirectoryNode;
|
return node as DirectoryNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
public getNode(inode: number): TreeNode | undefined {
|
public getSysPartitionID(): number {
|
||||||
return this.resolveNode(inode);
|
return this._SysPartitionID;
|
||||||
}
|
}
|
||||||
|
|
||||||
public exists(inode: number): boolean {
|
public getNode(ptr: NodePointer): TreeNode | undefined {
|
||||||
return this.resolveNode(inode) !== undefined;
|
return this.resolveNode(ptr);
|
||||||
}
|
}
|
||||||
|
|
||||||
public isFile(inode: number): boolean {
|
public exists(ptr: NodePointer): boolean {
|
||||||
const node = this.resolveNode(inode);
|
return this.resolveNode(ptr) !== undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public isFile(ptr: NodePointer): boolean {
|
||||||
|
const node = this.resolveNode(ptr);
|
||||||
|
|
||||||
if (node === undefined) {
|
if (node === undefined) {
|
||||||
throw {
|
throw {
|
||||||
type: "NodeNotFound",
|
type: "NodeNotFound",
|
||||||
message: `Node under inode ${inode} not found`,
|
message: `Node under inode ${ptr[0]} not found`,
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
inode: inode,
|
inode: ptr[0],
|
||||||
} satisfies NodeNotFoundError;
|
} satisfies NodeNotFoundError;
|
||||||
}
|
}
|
||||||
|
|
||||||
return node.type === TreeNodeType.File ? true : false;
|
return node.type === TreeNodeType.File ? true : false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public isDirectory(inode: number): boolean {
|
public isDirectory(ptr: NodePointer): boolean {
|
||||||
const node = this.resolveNode(inode);
|
const node = this.resolveNode(ptr);
|
||||||
|
|
||||||
if (node === undefined) {
|
if (node === undefined) {
|
||||||
throw {
|
throw {
|
||||||
type: "NodeNotFound",
|
type: "NodeNotFound",
|
||||||
message: `Node under inode ${inode} not found`,
|
message: `Node under inode ${ptr[0]} not found`,
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
inode: inode,
|
inode: ptr[0],
|
||||||
} satisfies NodeNotFoundError;
|
} satisfies NodeNotFoundError;
|
||||||
}
|
}
|
||||||
|
|
||||||
return node.type === TreeNodeType.Directory ? true : false;
|
return node.type === TreeNodeType.Directory ? true : false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* public isSymlink(inode: number): boolean {
|
public isSymlink(ptr: NodePointer): boolean {
|
||||||
const node = this.resolveNode(inode);
|
const node = this.resolveNode(ptr);
|
||||||
|
|
||||||
if (node === undefined) {
|
if (node === undefined) {
|
||||||
throw {
|
throw {
|
||||||
type: "NodeNotFound",
|
type: "NodeNotFound",
|
||||||
message: `Node under inode ${inode} not found`,
|
message: `Node under inode ${ptr[0]} not found`,
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
inode: inode,
|
inode: ptr[0],
|
||||||
} satisfies NodeNotFoundError;
|
} satisfies NodeNotFoundError;
|
||||||
}
|
}
|
||||||
|
|
||||||
return node.type === TreeNodeType.Symlink ? true : false;
|
return node.type === TreeNodeType.Symlink ? true : false;
|
||||||
} */
|
}
|
||||||
|
|
||||||
public moveNode(sourceInode: number, destinationInode: number, name?: string): FileSystem {
|
public moveNode(source: NodePointer, destination: NodePointer, name?: string): FileSystem {
|
||||||
if (sourceInode === 0) {
|
if (source[0] === 0) {
|
||||||
throw {
|
throw {
|
||||||
type: "IllegalMutation",
|
type: "IllegalMutation",
|
||||||
message: `Attempt at illegal mutation of node under inode 0 (root)`,
|
message: `Attempt at illegal mutation of node under inode 0 (root)`,
|
||||||
@@ -124,20 +162,18 @@ export class FileSystem {
|
|||||||
} satisfies IllegalMutationError;
|
} satisfies IllegalMutationError;
|
||||||
}
|
}
|
||||||
|
|
||||||
const sourceNode = this.resolveNode(sourceInode);
|
const sourceNode = this.resolveNode(source);
|
||||||
const destinationNode = this.resolveNode(destinationInode);
|
const destinationNode = this.resolveNode(destination);
|
||||||
|
|
||||||
if (sourceNode === undefined) {
|
if (sourceNode === undefined) {
|
||||||
throw {
|
throw {
|
||||||
type: "NodeNotFound",
|
type: "NodeNotFound",
|
||||||
message: `Source node under inode ${sourceInode} not found`,
|
message: `Source node under inode ${source[0]} not found`,
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
inode: sourceInode,
|
inode: source[0],
|
||||||
} satisfies NodeNotFoundError;
|
} satisfies NodeNotFoundError;
|
||||||
}
|
}
|
||||||
|
|
||||||
const nodeName = name ?? sourceNode.name;
|
|
||||||
|
|
||||||
if (destinationNode === undefined) {
|
if (destinationNode === undefined) {
|
||||||
throw {
|
throw {
|
||||||
type: "NodeNotFound",
|
type: "NodeNotFound",
|
||||||
@@ -177,6 +213,8 @@ export class FileSystem {
|
|||||||
} satisfies DirectoryLoopError;
|
} satisfies DirectoryLoopError;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const nodeName = name ?? sourceNode;
|
||||||
|
|
||||||
let newNode: TreeNode;
|
let newNode: TreeNode;
|
||||||
|
|
||||||
if (sourceNode.type === TreeNodeType.File) {
|
if (sourceNode.type === TreeNodeType.File) {
|
||||||
|
|||||||
@@ -1,7 +1,18 @@
|
|||||||
export type TreeNode = FileNode | DirectoryNode;
|
export type Node = FileNode | DirectoryNode | SymlinkNode;
|
||||||
|
|
||||||
|
export type NodeHash = ReadonlyMap<number, Node>;
|
||||||
|
export type ShadowHash = ReadonlyMap<number, Node | null>;
|
||||||
|
|
||||||
|
export type NodePointer = string;
|
||||||
|
|
||||||
|
export interface NodeEntry {
|
||||||
|
pinode: number;
|
||||||
|
pdevice_id: number;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface FileNode {
|
export interface FileNode {
|
||||||
readonly type: TreeNodeType.File;
|
readonly type: NodeType.File;
|
||||||
readonly inode: number;
|
readonly inode: number;
|
||||||
readonly link_count: number;
|
readonly link_count: number;
|
||||||
readonly mode: number;
|
readonly mode: number;
|
||||||
@@ -11,11 +22,11 @@ export interface FileNode {
|
|||||||
readonly ctime: number;
|
readonly ctime: number;
|
||||||
readonly atime: number;
|
readonly atime: number;
|
||||||
readonly content: string;
|
readonly content: string;
|
||||||
readonly device_id: number;
|
readonly size: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DirectoryNode {
|
export interface DirectoryNode {
|
||||||
readonly type: TreeNodeType.Directory;
|
readonly type: NodeType.Directory;
|
||||||
readonly inode: number;
|
readonly inode: number;
|
||||||
readonly link_count: number;
|
readonly link_count: number;
|
||||||
readonly mode: number;
|
readonly mode: number;
|
||||||
@@ -24,12 +35,11 @@ export interface DirectoryNode {
|
|||||||
readonly mtime: number;
|
readonly mtime: number;
|
||||||
readonly ctime: number;
|
readonly ctime: number;
|
||||||
readonly atime: number;
|
readonly atime: number;
|
||||||
readonly content: ReadonlyMap<string, number>;
|
readonly children: Map<string, number>;
|
||||||
readonly device_id: number;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SymlinkNode {
|
export interface SymlinkNode {
|
||||||
readonly type: TreeNodeType.Symlink;
|
readonly type: NodeType.Symlink;
|
||||||
readonly inode: number;
|
readonly inode: number;
|
||||||
readonly link_count: number;
|
readonly link_count: number;
|
||||||
readonly mode: number;
|
readonly mode: number;
|
||||||
@@ -38,27 +48,11 @@ export interface SymlinkNode {
|
|||||||
readonly mtime: number;
|
readonly mtime: number;
|
||||||
readonly ctime: number;
|
readonly ctime: number;
|
||||||
readonly atime: number;
|
readonly atime: number;
|
||||||
readonly content: string;
|
readonly target: string;
|
||||||
readonly device_id: number;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DeviceNode {
|
export enum NodeType {
|
||||||
readonly type: TreeNodeType.Device;
|
|
||||||
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: number; // Device-ID
|
|
||||||
readonly device_id: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum TreeNodeType {
|
|
||||||
File = 0,
|
File = 0,
|
||||||
Directory = 1,
|
Directory = 1,
|
||||||
Symlink = 2,
|
Symlink = 2,
|
||||||
Device = 3,
|
|
||||||
}
|
}
|
||||||
+272
-12
@@ -1,18 +1,278 @@
|
|||||||
import type { ReadableStream } from "@core/util/stream";
|
import { NodeType, type DirectoryNode, type Node, type NodeEntry, type NodeHash, type NodePointer } from "./node";
|
||||||
import type { TreeNode } from "./treenode";
|
|
||||||
|
|
||||||
export type NodeHash = ReadonlyMap<number, TreeNode>;
|
export interface VDiskConfig {
|
||||||
export type ShadowHash = ReadonlyMap<number, TreeNode | null>;
|
id: number;
|
||||||
|
label: number;
|
||||||
|
index: number;
|
||||||
|
base: NodeHash;
|
||||||
|
dataC: DataConfig;
|
||||||
|
//metaC: MetaConfig;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DataConfig {
|
||||||
|
chunkSize: number;
|
||||||
|
cacheSize: number;
|
||||||
|
cacheTTL: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
//export interface MetaConfig {}
|
||||||
|
|
||||||
export interface IDataStore {
|
export interface IDataStore {
|
||||||
put(data: Uint8Array | ReadableStream): Promise<string>;
|
read(uuid: string): Promise<Uint8Array>;
|
||||||
get(hash: string): Promise<ReadableStream>;
|
stream(uuid: string): null; // Stream
|
||||||
delete(hash: string): Promise<void>;
|
put(uuid: string, blob: Blob): Promise<void>;
|
||||||
|
delete(uuid: string): Promise<void>;
|
||||||
|
has(uuid: string): Promise<boolean>;
|
||||||
|
list(): Promise<string[]>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface VDisk {
|
export interface IMetaStore {
|
||||||
readonly id: number;
|
loadAll(): Promise<Map<number, Node | null>>;
|
||||||
readonly store: IDataStore;
|
write(inode: number, node: Node): Promise<void>;
|
||||||
readonly base: NodeHash;
|
delete(inode: number): Promise<void>;
|
||||||
readonly overlay: ShadowHash;
|
}
|
||||||
|
|
||||||
|
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 _iIndex: number;
|
||||||
|
private _rIndex: ReadonlyMap<NodePointer, ReadonlyArray<NodeEntry>>;
|
||||||
|
private _overlay: Map<number, Node | null>;
|
||||||
|
private _metaStore: IMetaStore;
|
||||||
|
|
||||||
|
private _rIndexInvalid: boolean;
|
||||||
|
|
||||||
|
private _isWritable(): void {
|
||||||
|
if (this._readonly) throw Error(`The ${this._label} device under id - ${this._id} is marked readonly`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _putNode(inode: number, node: Node | null): void {
|
||||||
|
this._overlay.set(inode, node);
|
||||||
|
}
|
||||||
|
|
||||||
|
public getNode(inode: number): Node | undefined {
|
||||||
|
const node = this._overlay.get(inode);
|
||||||
|
if (node) return node;
|
||||||
|
if (node === null) return undefined;
|
||||||
|
|
||||||
|
return this._base.get(inode);
|
||||||
|
}
|
||||||
|
|
||||||
|
public createNodeEntry(
|
||||||
|
pinode: number,
|
||||||
|
name: string,
|
||||||
|
data:
|
||||||
|
| { type: NodeType.File; mode: number; owner: number; group: number; content: string; size: number }
|
||||||
|
| { type: NodeType.Directory; mode: number; owner: number; group: number }
|
||||||
|
| { type: NodeType.Symlink; mode: number; owner: number; group: number; target: string },
|
||||||
|
): number {
|
||||||
|
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;
|
||||||
|
|
||||||
|
let node: Node;
|
||||||
|
switch (data.type) {
|
||||||
|
case NodeType.File:
|
||||||
|
node = { ...base, type: NodeType.File, content: data.content, size: data.size };
|
||||||
|
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): void {
|
||||||
|
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): void {
|
||||||
|
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): void {
|
||||||
|
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 }): void {
|
||||||
|
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> {}
|
||||||
|
|
||||||
|
public streamContent(uuid: string): Stream {}
|
||||||
|
|
||||||
|
public writeContent(uuid: string, blob: Blob): Promise<void> {
|
||||||
|
this.isWritable();
|
||||||
|
}
|
||||||
|
|
||||||
|
public deleteContent(uuid: string): Promise<void> {
|
||||||
|
this.isWritable();
|
||||||
|
}
|
||||||
|
|
||||||
|
public hasContent(uuid: string): Promise<boolean> {}
|
||||||
|
|
||||||
|
public loadOverlay(): Promise<void> {}
|
||||||
|
|
||||||
|
public createOverlayEntry(inode: number, node: Node | null): Promise<void> {
|
||||||
|
this.isWritable();
|
||||||
|
}
|
||||||
|
|
||||||
|
public invalidateRIndex(): void {
|
||||||
|
this._rIndexInvalid = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public getIndex(): ReadonlyMap<NodePointer, ReadonlyArray<NodeEntry>> {}
|
||||||
|
|
||||||
|
// public sweepOrphans(): Promise<void> {}
|
||||||
|
// public sweepDangling(): Promise<void> {}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
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 type { NodeNotFoundError, NotADirectoryError } from "../filesystem/errors";
|
||||||
import { TreeNodeType, type DirectoryNode, type TreeNode } from "../filesystem/treenode";
|
import { TreeNodeType, type DirectoryNode, type NodeEntry, type NodePointer, type TreeNode } from "../filesystem/node";
|
||||||
|
|
||||||
/*
|
/*
|
||||||
/home/grzegorz/Documents/homework
|
/home/grzegorz/Documents/homework
|
||||||
@@ -9,29 +9,55 @@ import { TreeNodeType, type DirectoryNode, type TreeNode } from "../filesystem/t
|
|||||||
""
|
""
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export function resolvePath(state: ShellState, path: string): string {
|
export function resolvePath(state: ShellState, path: string): NodeEntry {
|
||||||
const session = getCurrentSession(state);
|
const session = getCurrentSession(state);
|
||||||
const isAbsolute = path.startsWith("/"); // true
|
const isAbsolute = path.startsWith("/"); // true
|
||||||
|
|
||||||
const normalizedPath: string = path.replace(/^\/+|\/+$/g, ""); // home/grzegorz/Documents/homework
|
const normalizedPath: string = path.replace(/^\/+|\/+$/g, ""); // home/grzegorz/Documents/homework
|
||||||
const pathComponents: string[] = normalizedPath.split("/").filter(name => name.length > 0); // ["home", "grzegorz", "Documents", "homework"]
|
const pathComponents: string[] = normalizedPath.split("/").filter(name => name.length > 0); // ["home", "grzegorz", "Documents", "homework"]
|
||||||
|
let currentVD: number = state.filesystem.getSysPartitionID();
|
||||||
|
|
||||||
// Fix to dynamically get the root inode VV
|
// Fix to dynamically get the root inode VV
|
||||||
if (pathComponents.length === 0 && isAbsolute) return 0;
|
if (pathComponents.length === 0 && isAbsolute) return [0, currentVD];
|
||||||
// Move behaviour into cd built-in
|
// Move behaviour into cd built-in
|
||||||
if (pathComponents.length === 0) return session.cwd;
|
if (pathComponents.length === 0) return [session.cwd, currentVD];
|
||||||
|
|
||||||
let currentNode =
|
let currentNode = isAbsolute === true ? state.filesystem.getRoot() : state.filesystem.getNode(session.cwd)!;
|
||||||
isAbsolute === true ? state.filesystem.getRoot() : (state.filesystem.getNode(session.cwd) as DirectoryNode);
|
|
||||||
|
|
||||||
if (!currentNode) return -1;
|
if (!currentNode) {
|
||||||
|
throw Error("Current working directory does not exist in the filesystem! Is the userdata corrupted?");
|
||||||
|
}
|
||||||
|
|
||||||
for (let i = 0; i < pathComponents.length; i++) {
|
for (let i = 0; i < pathComponents.length; i++) {
|
||||||
|
// Null assertion because by this point the array cannot be empty
|
||||||
const name: string = pathComponents[i]!;
|
const name: string = pathComponents[i]!;
|
||||||
if (name === ".") continue;
|
|
||||||
|
|
||||||
if (name === "..") {
|
if (state.filesystem.isFile(currentNode.inode) && !(i === pathComponents.length - 1))
|
||||||
currentNode = state.filesystem.getNode(currentNode.parent) as DirectoryNode;
|
throw {
|
||||||
|
type: "NotADirectory",
|
||||||
|
message: `${name} is not a directory`,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
inode: currentNode.inode,
|
||||||
|
nodeType: TreeNodeType.File,
|
||||||
|
} satisfies NotADirectoryError;
|
||||||
|
|
||||||
|
if (currentNode.type === TreeNodeType.Device) {
|
||||||
|
currentVD = currentNode.target_id;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentNode.type === TreeNodeType.Symlink) {
|
||||||
|
const ptr: NodePointer = resolvePath(state, currentNode.target);
|
||||||
|
currentNode = state.filesystem.getNode(ptr)!;
|
||||||
|
|
||||||
|
if (!currentNode) {
|
||||||
|
throw {
|
||||||
|
type: "NodeNotFound",
|
||||||
|
message: `${name} not found`,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
inode: ptr[0],
|
||||||
|
} satisfies NodeNotFoundError;
|
||||||
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,23 +71,15 @@ export function resolvePath(state: ShellState, path: string): string {
|
|||||||
if (!inode)
|
if (!inode)
|
||||||
throw {
|
throw {
|
||||||
type: "NodeNotFound",
|
type: "NodeNotFound",
|
||||||
message: `Child node in ${currentNode.name} under name ${name} not found`,
|
message: `${name} not found`,
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
inode: currentNode.inode,
|
inode: currentNode.inode,
|
||||||
} satisfies NodeNotFoundError;
|
} satisfies NodeNotFoundError;
|
||||||
if (state.filesystem.isFile(inode) && !(i === pathComponents.length - 1))
|
|
||||||
throw {
|
|
||||||
type: "NotADirectory",
|
|
||||||
message: `Child node ${name} is not a directory`,
|
|
||||||
timestamp: Date.now(),
|
|
||||||
inode: inode,
|
|
||||||
nodeType: TreeNodeType.File,
|
|
||||||
} satisfies NotADirectoryError;
|
|
||||||
|
|
||||||
currentNode = state.filesystem.getNode(inode) as DirectoryNode;
|
currentNode = state.filesystem.getNode(inode) as DirectoryNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
return currentNode.inode;
|
return [currentNode.inode, currentVD];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolveInode(state: ShellState, inode: number): string {
|
export function resolveInode(state: ShellState, inode: number): string {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { FileNode, TreeNode } from "@core/filesystem/treenode";
|
import type { FileNode, TreeNode } from "@core/filesystem/node";
|
||||||
import type { ShellState } from "@core/shell_state";
|
import type { ShellState } from "@core/shell_state";
|
||||||
import { Posix } from "@termos/util/posix";
|
import { Posix } from "@termos/util/posix";
|
||||||
|
|
||||||
|
|||||||
+374
-101
@@ -1,131 +1,404 @@
|
|||||||
export class ReadableStream {
|
export type StreamItem =
|
||||||
private _threshold: number;
|
{ ok: true; done: false; value: Uint8Array } | { ok: true; done: true } | { ok: false; done: true; error: unknown };
|
||||||
private _buffer: Uint8Array[] = [];
|
|
||||||
private _state: "idle" | "open" | "waiting" | "closed" | "errored" = "idle";
|
|
||||||
private _pending: ((value: Uint8Array | null) => void) | null = null;
|
|
||||||
private _byteLength: number = 0;
|
|
||||||
private _error: Error | null = null;
|
|
||||||
|
|
||||||
// Default - 32 chunks of 64KB -> Buffer of 2MB
|
export type StreamState = "open" | "closed" | "failed" | "cancelled";
|
||||||
constructor(threshold: number = 1024 * 64 * 32) {
|
|
||||||
this._threshold = threshold;
|
export class StreamCancelled extends Error {
|
||||||
|
constructor(cause?: unknown) {
|
||||||
|
super("stream cancelled", { cause });
|
||||||
|
this.name = "StreamCancelled";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StreamOptions {
|
||||||
|
/** Maximum bytes buffered before producers block. Default: 2 MiB. */
|
||||||
|
byteThreshold?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Writable {
|
||||||
|
push(chunk: Uint8Array): Promise<void>;
|
||||||
|
close(): void;
|
||||||
|
fail(error: unknown): void;
|
||||||
|
cancel(cause?: unknown): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Readable extends AsyncIterable<StreamItem> {
|
||||||
|
read(): Promise<StreamItem>;
|
||||||
|
drain(): Promise<Uint8Array[]>;
|
||||||
|
pipeTo(sink: Writable): Promise<void>;
|
||||||
|
cancel(cause?: unknown): void;
|
||||||
|
readonly state: StreamState;
|
||||||
|
readonly error: unknown;
|
||||||
|
readonly bufferedBytes: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// === Internal core (shared by every class) ===
|
||||||
|
|
||||||
|
const DEFAULT_BYTE_THRESHOLD = 2 * 1024 * 1024;
|
||||||
|
|
||||||
|
type Waiter = (item: StreamItem) => void;
|
||||||
|
type ParkedPush = {
|
||||||
|
chunk: Uint8Array;
|
||||||
|
resolve: () => void;
|
||||||
|
reject: (error: unknown) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
class StreamCore {
|
||||||
|
readonly byteThreshold: number;
|
||||||
|
|
||||||
|
#buffer: Uint8Array[] = [];
|
||||||
|
#bufferedBytes = 0;
|
||||||
|
#waiters: Waiter[] = [];
|
||||||
|
#pendingPushes: ParkedPush[] = [];
|
||||||
|
#state: StreamState = "open";
|
||||||
|
#error: unknown = null;
|
||||||
|
|
||||||
|
constructor(options: StreamOptions = {}) {
|
||||||
|
this.byteThreshold = options.byteThreshold ?? DEFAULT_BYTE_THRESHOLD;
|
||||||
}
|
}
|
||||||
|
|
||||||
public push(chunk: Uint8Array): boolean {
|
get state(): StreamState {
|
||||||
if (this._state === "closed" || this._state === "errored") {
|
return this.#state;
|
||||||
return false;
|
}
|
||||||
|
get error(): unknown {
|
||||||
|
return this.#error;
|
||||||
|
}
|
||||||
|
get bufferedBytes(): number {
|
||||||
|
return this.#bufferedBytes;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this._pending) {
|
// --- Write side ---
|
||||||
const pending = this._pending;
|
|
||||||
this._pending = null;
|
|
||||||
|
|
||||||
pending(chunk);
|
async push(chunk: Uint8Array): Promise<void> {
|
||||||
|
if (this.#state !== "open") throw new Error(`cannot push: stream is ${this.#state}`);
|
||||||
|
|
||||||
this._state = this._buffer.length > 0 ? "open" : "idle";
|
const waiter = this.#waiters.shift();
|
||||||
return true;
|
if (waiter) {
|
||||||
|
waiter({ ok: true, done: false, value: chunk });
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this._buffer.push(chunk);
|
if (this.#bufferedBytes + chunk.byteLength <= this.byteThreshold) {
|
||||||
this._byteLength += chunk.byteLength;
|
this.#buffer.push(chunk);
|
||||||
this._state = "open";
|
this.#bufferedBytes += chunk.byteLength;
|
||||||
|
return;
|
||||||
return this._byteLength < this._threshold;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public close(): void {
|
await new Promise<void>((resolve, reject) => {
|
||||||
if (this._state === "errored") return;
|
this.#pendingPushes.push({ chunk, resolve, reject });
|
||||||
this._state = "closed";
|
|
||||||
|
|
||||||
if (this._pending) {
|
|
||||||
this._pending(null);
|
|
||||||
this._pending = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public error(err: Error): void {
|
|
||||||
this._error = err;
|
|
||||||
this._state = "errored";
|
|
||||||
if (this._pending) {
|
|
||||||
this._pending(null);
|
|
||||||
this._pending = null;
|
|
||||||
}
|
|
||||||
this._buffer = [];
|
|
||||||
this._byteLength = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
public read(): Promise<Uint8Array | null> {
|
|
||||||
if ((this._state = "errored")) {
|
|
||||||
return Promise.reject(this._error || new Error("Stream encountered an error"));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this._buffer.length > 0) {
|
|
||||||
const chunk: Uint8Array = this._buffer.shift()!;
|
|
||||||
this._byteLength -= chunk.byteLength;
|
|
||||||
|
|
||||||
if (this._buffer.length === 0) {
|
|
||||||
this._state = "idle";
|
|
||||||
}
|
|
||||||
|
|
||||||
return Promise.resolve(chunk);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((this._state = "closed")) {
|
|
||||||
return Promise.resolve(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
this._state = "waiting";
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
this._pending = resolve;
|
|
||||||
|
|
||||||
if (this._error) {
|
|
||||||
reject(this._error);
|
|
||||||
this._pending = null;
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public pipe(writable: WritableStream): Promise<void> {
|
close(): void {
|
||||||
return new Promise(async (resolve, reject) => {
|
this.#terminate("closed");
|
||||||
|
}
|
||||||
|
fail(error: unknown): void {
|
||||||
|
this.#terminate("failed", error);
|
||||||
|
}
|
||||||
|
cancel(cause?: unknown): void {
|
||||||
|
this.#terminate("cancelled", new StreamCancelled(cause));
|
||||||
|
}
|
||||||
|
|
||||||
|
#terminate(state: Exclude<StreamState, "open">, error: unknown = null): void {
|
||||||
|
if (this.#state !== "open") return;
|
||||||
|
this.#state = state;
|
||||||
|
this.#error = error;
|
||||||
|
|
||||||
|
const terminal: StreamItem = state === "closed" ? { ok: true, done: true } : { ok: false, done: true, error };
|
||||||
|
|
||||||
|
for (const waiter of this.#waiters.splice(0)) waiter(terminal);
|
||||||
|
for (const pending of this.#pendingPushes.splice(0)) pending.reject(error ?? new Error(`stream ${state}`));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Read side ---
|
||||||
|
|
||||||
|
pull(): Promise<StreamItem> {
|
||||||
|
if (this.#buffer.length) {
|
||||||
|
const chunk = this.#buffer.shift()!;
|
||||||
|
this.#bufferedBytes -= chunk.byteLength;
|
||||||
|
this.#promoteParkedPushes();
|
||||||
|
return Promise.resolve({ ok: true, done: false, value: chunk });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.#pendingPushes.length) {
|
||||||
|
const pending = this.#pendingPushes.shift()!;
|
||||||
|
pending.resolve();
|
||||||
|
return Promise.resolve({ ok: true, done: false, value: pending.chunk });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.#state === "open") return new Promise(resolve => this.#waiters.push(resolve));
|
||||||
|
|
||||||
|
return Promise.resolve(
|
||||||
|
this.#state === "closed" ? { ok: true, done: true } : { ok: false, done: true, error: this.#error },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#promoteParkedPushes(): void {
|
||||||
|
while (this.#pendingPushes.length > 0) {
|
||||||
|
const next = this.#pendingPushes[0];
|
||||||
|
if (this.#bufferedBytes + next.chunk.byteLength > this.byteThreshold) break;
|
||||||
|
this.#pendingPushes.shift();
|
||||||
|
this.#buffer.push(next.chunk);
|
||||||
|
this.#bufferedBytes += next.chunk.byteLength;
|
||||||
|
next.resolve();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// === ReadableStream ===
|
||||||
|
|
||||||
|
export class ReadableStream implements Readable {
|
||||||
|
#core: StreamCore;
|
||||||
|
#writableView: WritableStream | null = null;
|
||||||
|
|
||||||
|
constructor(options: StreamOptions | StreamCore = {}) {
|
||||||
|
this.#core = options instanceof StreamCore ? options : new StreamCore(options);
|
||||||
|
}
|
||||||
|
|
||||||
|
read(): Promise<StreamItem> {
|
||||||
|
return this.#core.pull();
|
||||||
|
}
|
||||||
|
|
||||||
|
async drain(): Promise<Uint8Array[]> {
|
||||||
|
const chunks: Uint8Array[] = [];
|
||||||
|
for (;;) {
|
||||||
|
const item = await this.#core.pull();
|
||||||
|
if (item.done) {
|
||||||
|
if (!item.ok) throw item.error;
|
||||||
|
return chunks;
|
||||||
|
}
|
||||||
|
chunks.push(item.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async pipeTo(sink: Writable): Promise<void> {
|
||||||
|
for await (const item of this) {
|
||||||
|
if (item.done) {
|
||||||
|
item.ok ? sink.close() : sink.fail(item.error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await sink.push(item.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cancel(cause?: unknown): void {
|
||||||
|
this.#core.cancel(cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Symbol.asyncIterator](): AsyncIterator<StreamItem> {
|
||||||
|
let terminalYielded = false;
|
||||||
|
return {
|
||||||
|
next: async () => {
|
||||||
|
const item = await this.#core.pull();
|
||||||
|
if (!item.done) return { done: false, value: item };
|
||||||
|
if (terminalYielded) return { done: true, value: undefined };
|
||||||
|
terminalYielded = true;
|
||||||
|
return { done: false, value: item };
|
||||||
|
},
|
||||||
|
return: async () => {
|
||||||
|
this.#core.cancel("consumer stopped iterating");
|
||||||
|
return { done: true, value: undefined };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
get state(): StreamState {
|
||||||
|
return this.#core.state;
|
||||||
|
}
|
||||||
|
get error(): unknown {
|
||||||
|
return this.#core.error;
|
||||||
|
}
|
||||||
|
get bufferedBytes(): number {
|
||||||
|
return this.#core.bufferedBytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
get writable(): WritableStream {
|
||||||
|
return (this.#writableView ??= new WritableStream(this.#core));
|
||||||
|
}
|
||||||
|
|
||||||
|
static fromAsyncIterable(source: AsyncIterable<Uint8Array>, options: StreamOptions = {}): ReadableStream {
|
||||||
|
const stream = new ReadableStream(options);
|
||||||
|
const sink = stream.writable;
|
||||||
|
(async () => {
|
||||||
try {
|
try {
|
||||||
for await (const chunk of this) {
|
for await (const chunk of source) await sink.push(chunk);
|
||||||
await writable.write(chunk);
|
sink.close();
|
||||||
|
} catch (error) {
|
||||||
|
sink.fail(error);
|
||||||
}
|
}
|
||||||
await writable.close();
|
})();
|
||||||
resolve();
|
return stream;
|
||||||
} catch (err) {
|
|
||||||
reject(err);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async *[Symbol.asyncIterator](): AsyncIterator<Uint8Array> {
|
static fromBlob(blob: Blob, options: StreamOptions & { chunkSize?: number } = {}): ReadableStream {
|
||||||
while (true) {
|
const { chunkSize = 1 << 16, ...streamOptions } = options;
|
||||||
const chunk = await this.read();
|
const stream = new ReadableStream(streamOptions);
|
||||||
if (chunk === null) break;
|
const sink = stream.writable;
|
||||||
yield chunk;
|
(async () => {
|
||||||
|
try {
|
||||||
|
for (let offset = 0; offset < blob.size; offset += chunkSize) {
|
||||||
|
const slice = blob.slice(offset, offset + chunkSize);
|
||||||
|
await sink.push(new Uint8Array(await slice.arrayBuffer()));
|
||||||
}
|
}
|
||||||
|
sink.close();
|
||||||
|
} catch (error) {
|
||||||
|
sink.fail(error);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return stream;
|
||||||
}
|
}
|
||||||
|
|
||||||
public get byteLength(): number {
|
async toBlob(type?: string): Promise<Blob> {
|
||||||
return this._byteLength;
|
return new Blob(await this.drain(), type ? { type } : undefined);
|
||||||
}
|
}
|
||||||
|
|
||||||
public get isFull(): boolean {
|
[Symbol.asyncDispose](): Promise<void> {
|
||||||
return this._byteLength >= this._threshold;
|
if (this.#core.state === "open") this.#core.cancel("disposed");
|
||||||
}
|
return Promise.resolve();
|
||||||
|
|
||||||
public get state(): string {
|
|
||||||
return this._state;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class WritableStream {
|
// === WritableStream ===
|
||||||
write(chunk: Uint8Array): void {}
|
|
||||||
|
|
||||||
close(): void {}
|
export class WritableStream implements Writable {
|
||||||
|
#core: StreamCore;
|
||||||
|
#readableView: ReadableStream | null = null;
|
||||||
|
|
||||||
|
constructor(options: StreamOptions | StreamCore = {}) {
|
||||||
|
this.#core = options instanceof StreamCore ? options : new StreamCore(options);
|
||||||
|
}
|
||||||
|
|
||||||
|
push(chunk: Uint8Array): Promise<void> {
|
||||||
|
return this.#core.push(chunk);
|
||||||
|
}
|
||||||
|
close(): void {
|
||||||
|
this.#core.close();
|
||||||
|
}
|
||||||
|
fail(error: unknown): void {
|
||||||
|
this.#core.fail(error);
|
||||||
|
}
|
||||||
|
cancel(cause?: unknown): void {
|
||||||
|
this.#core.cancel(cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
get state(): StreamState {
|
||||||
|
return this.#core.state;
|
||||||
|
}
|
||||||
|
get error(): unknown {
|
||||||
|
return this.#core.error;
|
||||||
|
}
|
||||||
|
get bufferedBytes(): number {
|
||||||
|
return this.#core.bufferedBytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
get readable(): ReadableStream {
|
||||||
|
return (this.#readableView ??= new ReadableStream(this.#core));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Symbol.asyncDispose](): Promise<void> {
|
||||||
|
if (this.#core.state === "open") this.#core.cancel("disposed");
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class DuplexStream {}
|
// === DuplexStream ===
|
||||||
|
|
||||||
export class TransformStream {}
|
export class DuplexStream implements Readable, Writable {
|
||||||
|
readonly readable: ReadableStream;
|
||||||
|
readonly writable: WritableStream;
|
||||||
|
|
||||||
|
constructor(options: StreamOptions = {}) {
|
||||||
|
const core = new StreamCore(options);
|
||||||
|
this.readable = new ReadableStream(core);
|
||||||
|
this.writable = new WritableStream(core);
|
||||||
|
}
|
||||||
|
|
||||||
|
push(chunk: Uint8Array): Promise<void> {
|
||||||
|
return this.writable.push(chunk);
|
||||||
|
}
|
||||||
|
close(): void {
|
||||||
|
this.writable.close();
|
||||||
|
}
|
||||||
|
fail(error: unknown): void {
|
||||||
|
this.writable.fail(error);
|
||||||
|
}
|
||||||
|
cancel(cause?: unknown): void {
|
||||||
|
this.writable.cancel(cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
read(): Promise<StreamItem> {
|
||||||
|
return this.readable.read();
|
||||||
|
}
|
||||||
|
drain(): Promise<Uint8Array[]> {
|
||||||
|
return this.readable.drain();
|
||||||
|
}
|
||||||
|
pipeTo(sink: Writable): Promise<void> {
|
||||||
|
return this.readable.pipeTo(sink);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Symbol.asyncIterator](): AsyncIterator<StreamItem> {
|
||||||
|
return this.readable[Symbol.asyncIterator]();
|
||||||
|
}
|
||||||
|
|
||||||
|
get state(): StreamState {
|
||||||
|
return this.writable.state;
|
||||||
|
}
|
||||||
|
get error(): unknown {
|
||||||
|
return this.writable.error;
|
||||||
|
}
|
||||||
|
get bufferedBytes(): number {
|
||||||
|
return this.writable.bufferedBytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Symbol.asyncDispose](): Promise<void> {
|
||||||
|
if (this.state === "open") this.cancel("disposed");
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// === TransformStream ===
|
||||||
|
|
||||||
|
export type TransformFn = (
|
||||||
|
chunk: Uint8Array,
|
||||||
|
) => Uint8Array | Uint8Array[] | void | Promise<Uint8Array | Uint8Array[] | void>;
|
||||||
|
|
||||||
|
export class TransformStream {
|
||||||
|
readonly readable: ReadableStream;
|
||||||
|
readonly writable: Writable;
|
||||||
|
#sink: WritableStream;
|
||||||
|
|
||||||
|
constructor(transform: TransformFn, options: StreamOptions = {}) {
|
||||||
|
this.readable = new ReadableStream(options);
|
||||||
|
this.#sink = this.readable.writable;
|
||||||
|
const sink = this.#sink;
|
||||||
|
|
||||||
|
this.writable = {
|
||||||
|
async push(chunk: Uint8Array): Promise<void> {
|
||||||
|
try {
|
||||||
|
const result = await transform(chunk);
|
||||||
|
if (result == null) return;
|
||||||
|
for (const output of Array.isArray(result) ? result : [result]) {
|
||||||
|
await sink.push(output);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
sink.fail(error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
close(): void {
|
||||||
|
sink.close();
|
||||||
|
},
|
||||||
|
fail(error: unknown): void {
|
||||||
|
sink.fail(error);
|
||||||
|
},
|
||||||
|
cancel(cause?: unknown): void {
|
||||||
|
sink.cancel(cause);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
[Symbol.asyncDispose](): Promise<void> {
|
||||||
|
if (this.readable.state === "open") this.#sink.cancel("disposed");
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { FileSystem } from "@core/filesystem/filesystem";
|
import type { FileSystem } from "@core/filesystem/filesystem";
|
||||||
import { TreeNodeType, type TreeNode } from "@core/filesystem/treenode";
|
import { TreeNodeType, type TreeNode } from "@core/filesystem/node";
|
||||||
|
|
||||||
export function dnTraverseTree(fs: FileSystem, root: number): number[] {
|
export function dnTraverseTree(fs: FileSystem, root: number): number[] {
|
||||||
if (fs.getNode(root) === undefined) return [];
|
if (fs.getNode(root) === undefined) return [];
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import type { IDataStore, NodeHash, ShadowHash, VDisk } from "@core/filesystem/vdisk";
|
import type { IDataStore, NodeHash, ShadowHash, VDisk } from "@core/filesystem/vdisk";
|
||||||
|
|
||||||
|
//export interface VDiskManagerConfig {}
|
||||||
|
|
||||||
export class VDiskManager {
|
export class VDiskManager {
|
||||||
private _VDiskHash: Map<number, VDisk> = new Map();
|
private _VDiskHash: Map<number, VDisk> = new Map();
|
||||||
|
|
||||||
|
|||||||
+2
-2
File diff suppressed because one or more lines are too long
+44
-49
@@ -1,92 +1,87 @@
|
|||||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
import {
|
||||||
import { z } from "zod";
|
TreeNodeType,
|
||||||
import { TreeNodeType, type DirectoryNode, type FileNode, type TreeNode } from "../core/filesystem/treenode";
|
type DirectoryNode,
|
||||||
|
type FileNode,
|
||||||
const FileNodeSchema = z.object({
|
type NodeEntry,
|
||||||
inode: z.number(),
|
type NodePointer,
|
||||||
name: z.string(),
|
type TreeNode,
|
||||||
mode: z.number(),
|
} from "../core/filesystem/node";
|
||||||
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): {
|
||||||
|
dev_list: number[];
|
||||||
|
map: ReadonlyMap<number, TreeNode>;
|
||||||
|
cache: Map<NodePointer, NodeEntry>;
|
||||||
|
} {
|
||||||
const raw = JSON.parse(json);
|
const raw = JSON.parse(json);
|
||||||
const validated = TreeNodeSchema.parse(raw);
|
//const validated = TreeNodeSchema.parse(raw);
|
||||||
|
|
||||||
const map = new Map<number, TreeNode>();
|
const map = new Map<number, TreeNode>();
|
||||||
|
const cache = new Map<NodePointer, NodeEntry>();
|
||||||
|
|
||||||
// prettier-ignore
|
// prettier-ignore
|
||||||
function parseNode(tree: any, parent: number): void { // eslint-disable-line @typescript-eslint/no-explicit-any
|
function parseObj(obj: any): number[] { // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||||
|
const result: number[] = [];
|
||||||
|
for (const dev of obj.dev) {
|
||||||
|
const id = dev.id;
|
||||||
|
result.push(id);
|
||||||
|
|
||||||
|
const tree = dev.tree;
|
||||||
|
|
||||||
|
parseNode(tree, tree.inode, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
const deviceList: number[] = parseObj(raw);
|
||||||
|
|
||||||
|
// prettier-ignore
|
||||||
|
function parseNode(tree: any, parent: number, dev_id: number): void { // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||||
if (tree.type === "directory") {
|
if (tree.type === "directory") {
|
||||||
const children: Record<string, number> = {};
|
const prt = [tree.inode, dev_id];
|
||||||
|
const children: Map<string, number> = new Map();
|
||||||
|
|
||||||
for (const child of tree.children) {
|
for (const child of tree.children) {
|
||||||
parseNode(child, tree.inode);
|
parseNode(child, tree.inode, dev_id);
|
||||||
children[child.name] = child.inode;
|
children.set(child.name, child.inode);
|
||||||
}
|
}
|
||||||
|
|
||||||
const directoryNode: DirectoryNode = {
|
const directoryNode: DirectoryNode = {
|
||||||
type: TreeNodeType.Directory,
|
type: TreeNodeType.Directory,
|
||||||
inode: tree.inode,
|
inode: tree.inode,
|
||||||
name: tree.name,
|
link_count: tree.link_count,
|
||||||
parent,
|
|
||||||
mode: tree.mode,
|
mode: tree.mode,
|
||||||
owner: tree.owner,
|
owner: tree.owner,
|
||||||
group: tree.group,
|
group: tree.group,
|
||||||
mtime: tree.mtime,
|
mtime: tree.mtime,
|
||||||
ctime: tree.ctime,
|
ctime: tree.ctime,
|
||||||
atime: tree.atime,
|
atime: tree.atime,
|
||||||
children,
|
content: children,
|
||||||
|
device_id: dev_id,
|
||||||
};
|
};
|
||||||
map.set(tree.inode, Object.freeze(directoryNode));
|
map.set(tree.inode, Object.freeze(directoryNode));
|
||||||
} else {
|
} else {
|
||||||
const fileNode: FileNode = {
|
const fileNode: FileNode = {
|
||||||
type: TreeNodeType.File,
|
type: TreeNodeType.File,
|
||||||
inode: tree.inode,
|
inode: tree.inode,
|
||||||
name: tree.name,
|
|
||||||
parent,
|
|
||||||
mode: tree.mode,
|
mode: tree.mode,
|
||||||
|
link_count: tree.link_count,
|
||||||
owner: tree.owner,
|
owner: tree.owner,
|
||||||
group: tree.group,
|
group: tree.group,
|
||||||
mtime: tree.mtime,
|
mtime: tree.mtime,
|
||||||
ctime: tree.ctime,
|
ctime: tree.ctime,
|
||||||
atime: tree.atime,
|
atime: tree.atime,
|
||||||
content: createImmutableBuffer(Uint8Array.from(tree.content)),
|
content: tree.content,
|
||||||
|
device_id: dev_id,
|
||||||
};
|
};
|
||||||
map.set(tree.inode, Object.freeze(fileNode));
|
map.set(tree.inode, Object.freeze(fileNode));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
parseNode(validated, validated.inode);
|
|
||||||
const base: ReadonlyMap<number, TreeNode> = map;
|
const base: ReadonlyMap<number, TreeNode> = map;
|
||||||
|
|
||||||
return base;
|
return { map: base, cache: new Map() };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { FileSystem } from "@core/filesystem/filesystem";
|
import type { FileSystem } from "@core/filesystem/filesystem";
|
||||||
import { TreeNodeType } from "@core/filesystem/treenode";
|
import { TreeNodeType } from "@core/filesystem/node";
|
||||||
|
|
||||||
export function printTree(fs: FileSystem, root: number): string {
|
export function printTree(fs: FileSystem, root: number): string {
|
||||||
const rootNode = fs.getNode(root);
|
const rootNode = fs.getNode(root);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { FileSystem } from "@core/filesystem/filesystem";
|
import { FileSystem } from "@core/filesystem/filesystem";
|
||||||
import { TreeNodeType, type DirectoryNode, type FileNode, type TreeNode } from "@core/filesystem/treenode";
|
import { TreeNodeType, type DirectoryNode, type FileNode, type TreeNode } from "@core/filesystem/node";
|
||||||
import type { UserInfo } from "@core/session_manager";
|
import type { UserInfo } from "@core/session_manager";
|
||||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
||||||
import {
|
import {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import type {
|
|||||||
NodeNotFoundError,
|
NodeNotFoundError,
|
||||||
NotADirectoryError,
|
NotADirectoryError,
|
||||||
} from "@core/filesystem/errors";
|
} from "@core/filesystem/errors";
|
||||||
import type { TreeNodeType } from "@core/filesystem/treenode";
|
import type { TreeNodeType } from "@core/filesystem/node";
|
||||||
import { expect } from "vitest";
|
import { expect } from "vitest";
|
||||||
|
|
||||||
export function expectThrows(fn: () => unknown, expectedShape: Record<string, unknown>) {
|
export function expectThrows(fn: () => unknown, expectedShape: Record<string, unknown>) {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { FileSystem } from "@core/filesystem/filesystem";
|
import { FileSystem } from "@core/filesystem/filesystem";
|
||||||
import { TreeNodeType, type DirectoryNode, type FileNode, type TreeNode } from "@core/filesystem/treenode";
|
import { TreeNodeType, type DirectoryNode, type FileNode, type TreeNode } from "@core/filesystem/node";
|
||||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
||||||
|
|
||||||
export interface FixtureNode {
|
export interface FixtureNode {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { FileSystem } from "@core/filesystem/filesystem";
|
import { FileSystem } from "@core/filesystem/filesystem";
|
||||||
import type { TreeNode } from "@core/filesystem/treenode";
|
import type { TreeNode } from "@core/filesystem/node";
|
||||||
import type { GroupInfo, UserInfo } from "@core/session_manager";
|
import type { GroupInfo, UserInfo } from "@core/session_manager";
|
||||||
import { createInitialShellState, type ShellState } from "@core/shell_state";
|
import { createInitialShellState, type ShellState } from "@core/shell_state";
|
||||||
import { deserializeFileSystem } from "@shell/serializer";
|
import { deserializeFileSystem } from "@shell/serializer";
|
||||||
|
|||||||
Reference in New Issue
Block a user