@x-otto/ottofs 0.0.0-stage → 0.4.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -2
- package/dist/index.d.mts +171 -0
- package/dist/index.mjs +360 -0
- package/dist/native-DvvCjSi3.mjs +46 -0
- package/dist/worker.d.mts +1 -0
- package/dist/worker.mjs +34 -0
- package/package.json +21 -4
package/README.md
CHANGED
|
@@ -1,3 +1,53 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @x-otto/ottofs
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
OttoFS 卷的 NAPI 客户端。**凭据不在这里**:对象存储的密钥只存在于 `ottofsd`,本包只持有一枚能力令牌(caps + path prefix + TTL)。
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { OttoVolume, createOttofsBackend } from '@x-otto/ottofs'
|
|
7
|
+
|
|
8
|
+
const volume = OttoVolume.open({
|
|
9
|
+
socket: '/run/user/1000/ottofs/vol.sock',
|
|
10
|
+
token: process.env.OTTOFS_TOKEN, // hex,来自 `ottofs token issue`
|
|
11
|
+
nativePath: process.env.OTTOFS_NAPI, // 编译好的 ottofs-napi(.node)
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
const backend = createOttofsBackend(volume) // 程序化调用方用的带版本视图(otto 自己的工具走挂载目录,不用它)
|
|
15
|
+
const receipt = await backend.write('/workspace/a.ts', bytes, { mode: 'atomic' })
|
|
16
|
+
await backend.write('/workspace/a.ts', bytes, { expectedGeneration: receipt.generation })
|
|
17
|
+
await volume.close()
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## 行为约定
|
|
21
|
+
|
|
22
|
+
- **worker 线程**:原生绑定是同步的(刻意不在绑定里藏运行时),默认在 worker 里执行,不阻塞事件循环。`worker: false` 只建议在脚本/测试里用。
|
|
23
|
+
- **错误码**:抛 `OttoFsError`,`code` 是稳定值(`ECONFLICT`/`EACCES`/`EBADTOKEN`/`EDQUOT`/`EIO`…)。
|
|
24
|
+
- **版本号**:`write` 返回 `generation`,带上 `expectedGeneration` 再写即可把「覆盖别人改动」变成显式 `ECONFLICT`。
|
|
25
|
+
- **原子写**:默认 `atomic`(同目录临时文件 + fsync + rename);`inplace` 需显式指定。
|
|
26
|
+
- **会话**:`session()` 返回字符串(u64 装不进 JS 的 Number)。
|
|
27
|
+
|
|
28
|
+
## 怎么试
|
|
29
|
+
|
|
30
|
+
一条命令(会自己 format 一个临时卷、起 daemon、签一个 10 分钟令牌、跑示例、收尾):
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pnpm --filter @x-otto/ottofs demo # TS 示例
|
|
34
|
+
pnpm --filter @x-otto/ottofs demo --ui # 再加一个 Ink 面板
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
单独用某一半:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pnpm --filter @x-otto/ottofs build:native # cargo build ottofs-napi → native/ottofs.node
|
|
41
|
+
pnpm --filter @x-otto/ottofs build # tsdown → dist/
|
|
42
|
+
node packages/ottofs/examples/basic.ts # 需要 OTTOFS_SOCKET / OTTOFS_TOKEN
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`native/ottofs.node` 存在时无需指定路径;否则用 `nativePath` 或 `OTTOFS_NAPI`。
|
|
46
|
+
|
|
47
|
+
## 和 Rust 的关系
|
|
48
|
+
|
|
49
|
+
这个包**不链接** Rust,只在运行时加载一个 `ottofs-napi` 编出来的 cdylib(`.node`)。
|
|
50
|
+
|
|
51
|
+
- 为什么:真正的文件系统在 Rust 侧(`ottofs/` 的 core/meta/chunk/vfs),凭据与卷都在 daemon 进程里;JS 侧只是**客户端**。把 Rust 做成 npm 的构建期依赖,会让每个消费者和 CI 都必须装 Rust 工具链。
|
|
52
|
+
- 现在怎么做:`build:native` 调 cargo 把产物复制到 `native/ottofs.node`,`OttoVolume.open()` 按 `nativePath → OTTOFS_NAPI → native/ottofs.node` 的顺序查找。
|
|
53
|
+
- 还没做的:**预编译产物分发**(按平台放 `optionalDependencies` 里)。所以现在 `npm i @x-otto/ottofs` 单独装是不完整的——要么本机有 Rust 跑 `build:native`,要么拿到对应平台的 `.node`。这是打包层面的缺口,不是设计选择。
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
//#region src/types.d.ts
|
|
2
|
+
/** Stable error codes surfaced by the daemon; the native layer prefixes them. */
|
|
3
|
+
type FsErrorCode = 'EACCES' | 'EBADTOKEN' | 'EBADFRAME' | 'EBADREQUEST' | 'ECONFLICT' | 'EDQUOT' | 'EEXPIREDTOKEN' | 'EINTERNAL' | 'EINTR' | 'EIO' | 'ENOENT' | 'EROFS' | 'ETIMEDOUT';
|
|
4
|
+
interface VolumeOptions {
|
|
5
|
+
/** Path to the daemon's unix socket. */
|
|
6
|
+
socket: string;
|
|
7
|
+
/** Hex capability token from `ottofs token issue`. Never an S3 credential. */
|
|
8
|
+
token: string;
|
|
9
|
+
/**
|
|
10
|
+
* Path to the compiled `ottofs-napi` binary (`.node`). Resolved from
|
|
11
|
+
* `OTTOFS_NAPI` when omitted.
|
|
12
|
+
*/
|
|
13
|
+
nativePath?: string;
|
|
14
|
+
/** Run native calls on a worker thread. Default true. */
|
|
15
|
+
worker?: boolean;
|
|
16
|
+
unref?: boolean;
|
|
17
|
+
}
|
|
18
|
+
interface Stat {
|
|
19
|
+
inode: number;
|
|
20
|
+
size: number;
|
|
21
|
+
mode: number;
|
|
22
|
+
isDir: boolean;
|
|
23
|
+
generation?: number;
|
|
24
|
+
}
|
|
25
|
+
interface Entry {
|
|
26
|
+
name: string;
|
|
27
|
+
inode: number;
|
|
28
|
+
isDir: boolean;
|
|
29
|
+
}
|
|
30
|
+
interface WriteReceipt {
|
|
31
|
+
inode: number;
|
|
32
|
+
bytes: number;
|
|
33
|
+
/** Path-scoped version; pass it back as `expectedGeneration` to detect conflicts. */
|
|
34
|
+
generation: number;
|
|
35
|
+
}
|
|
36
|
+
interface Usage {
|
|
37
|
+
/** Bytes in use. */
|
|
38
|
+
bytes: number;
|
|
39
|
+
/** Inodes in use. */
|
|
40
|
+
inodes: number;
|
|
41
|
+
/** Configured capacity; 0 means unlimited. */
|
|
42
|
+
capacity: number;
|
|
43
|
+
/** Configured inode limit; 0 means unlimited. */
|
|
44
|
+
inodeLimit: number;
|
|
45
|
+
}
|
|
46
|
+
interface WriteOptions {
|
|
47
|
+
mode?: 'atomic' | 'inplace';
|
|
48
|
+
expectedGeneration?: number;
|
|
49
|
+
}
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region src/errors.d.ts
|
|
52
|
+
/** Error raised by an OttoFS operation, carrying a stable machine code. */
|
|
53
|
+
declare class OttoFsError extends Error {
|
|
54
|
+
readonly code: FsErrorCode;
|
|
55
|
+
constructor(code: FsErrorCode, message: string);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* The native layer reports errors as `CODE: detail`. Parsing on this side keeps
|
|
59
|
+
* the Rust shape untouched while giving callers something they can switch on.
|
|
60
|
+
*/
|
|
61
|
+
declare function toError(error: unknown): OttoFsError;
|
|
62
|
+
//#endregion
|
|
63
|
+
//#region src/attribution-bridge.d.ts
|
|
64
|
+
declare const OTTOFS_FEATURE_ATTRIBUTION = 1;
|
|
65
|
+
interface AttributionOwnerChange {
|
|
66
|
+
readonly type: 'registered' | 'unregistered';
|
|
67
|
+
readonly ownerId: string;
|
|
68
|
+
readonly domain: string;
|
|
69
|
+
readonly pid?: number;
|
|
70
|
+
}
|
|
71
|
+
interface AttributionOwnerSummary {
|
|
72
|
+
readonly ownerId: string;
|
|
73
|
+
readonly domain: string;
|
|
74
|
+
readonly pid?: number;
|
|
75
|
+
}
|
|
76
|
+
interface AttributionOwners {
|
|
77
|
+
observe(listener: (change: AttributionOwnerChange) => void): () => void;
|
|
78
|
+
snapshot(): readonly AttributionOwnerSummary[];
|
|
79
|
+
}
|
|
80
|
+
interface AttributionTag {
|
|
81
|
+
readonly session: string;
|
|
82
|
+
readonly turn?: number;
|
|
83
|
+
}
|
|
84
|
+
interface AttributionRegistration {
|
|
85
|
+
readonly sid: number;
|
|
86
|
+
readonly leaderStarttime: number;
|
|
87
|
+
readonly session: string;
|
|
88
|
+
readonly turn?: number;
|
|
89
|
+
readonly job: string;
|
|
90
|
+
}
|
|
91
|
+
interface AttributionVolume {
|
|
92
|
+
features(): Promise<number>;
|
|
93
|
+
attributeRegister(registration: AttributionRegistration): Promise<void>;
|
|
94
|
+
attributeClear(sid: number): Promise<void>;
|
|
95
|
+
}
|
|
96
|
+
interface AttributionBridgeInput {
|
|
97
|
+
readonly owners: AttributionOwners;
|
|
98
|
+
readonly volume: AttributionVolume;
|
|
99
|
+
readonly jobOf?: (ownerId: string) => AttributionTag | undefined;
|
|
100
|
+
readonly starttimeOf?: (pid: number) => number | undefined;
|
|
101
|
+
readonly processGroupAlive?: (pgid: number) => boolean;
|
|
102
|
+
readonly log?: (message: string) => void;
|
|
103
|
+
}
|
|
104
|
+
interface AttributionBridge {
|
|
105
|
+
stop(): void;
|
|
106
|
+
reconcile(): Promise<void>;
|
|
107
|
+
}
|
|
108
|
+
declare function createAttributionBridge(input: AttributionBridgeInput): AttributionBridge;
|
|
109
|
+
//#endregion
|
|
110
|
+
//#region src/volume.d.ts
|
|
111
|
+
/** Worker-backed or in-thread handle to one OttoFS volume session. */
|
|
112
|
+
declare class OttoVolume {
|
|
113
|
+
#private;
|
|
114
|
+
private constructor();
|
|
115
|
+
static open(options: VolumeOptions): OttoVolume;
|
|
116
|
+
get workerBacked(): boolean;
|
|
117
|
+
session(): Promise<string>;
|
|
118
|
+
caps(): Promise<number>;
|
|
119
|
+
features(): Promise<number>;
|
|
120
|
+
attributeRegister(registration: AttributionRegistration): Promise<void>;
|
|
121
|
+
attributeClear(sid: number): Promise<void>;
|
|
122
|
+
stat(path: string): Promise<Stat>;
|
|
123
|
+
readdir(path: string): Promise<Entry[]>;
|
|
124
|
+
read(path: string, offset?: number, length?: number): Promise<Buffer>;
|
|
125
|
+
write(path: string, data: Uint8Array, options?: WriteOptions): Promise<WriteReceipt>;
|
|
126
|
+
mkdir(path: string, mode?: number): Promise<void>;
|
|
127
|
+
unlink(path: string): Promise<void>;
|
|
128
|
+
rename(from: string, to: string): Promise<void>;
|
|
129
|
+
sync(path: string): Promise<void>;
|
|
130
|
+
usage(): Promise<Usage>;
|
|
131
|
+
close(): Promise<void>;
|
|
132
|
+
}
|
|
133
|
+
//#endregion
|
|
134
|
+
//#region src/backend.d.ts
|
|
135
|
+
interface WorkspaceBackend {
|
|
136
|
+
stat(path: string): Promise<Stat>;
|
|
137
|
+
read(path: string, offset?: number, length?: number): Promise<Uint8Array>;
|
|
138
|
+
write(path: string, data: Uint8Array, options?: {
|
|
139
|
+
expectedGeneration?: number;
|
|
140
|
+
mode?: 'atomic' | 'inplace';
|
|
141
|
+
}): Promise<WriteReceipt>;
|
|
142
|
+
list(path: string): Promise<Entry[]>;
|
|
143
|
+
remove(path: string): Promise<void>;
|
|
144
|
+
rename(from: string, to: string): Promise<void>;
|
|
145
|
+
mkdir(path: string, mode?: number): Promise<void>;
|
|
146
|
+
}
|
|
147
|
+
declare function createOttofsBackend(volume: OttoVolume): WorkspaceBackend;
|
|
148
|
+
//#endregion
|
|
149
|
+
//#region src/read-all.d.ts
|
|
150
|
+
interface ReadAllOptions {
|
|
151
|
+
/** Bytes per native call. Defaults to 8 MiB. */
|
|
152
|
+
chunkSize?: number;
|
|
153
|
+
/** Reported after each chunk, so a caller can render progress. */
|
|
154
|
+
onProgress?: (progress: {
|
|
155
|
+
bytesRead: number;
|
|
156
|
+
total: number;
|
|
157
|
+
}) => void;
|
|
158
|
+
signal?: AbortSignal;
|
|
159
|
+
}
|
|
160
|
+
declare const DEFAULT_CHUNK_SIZE: number;
|
|
161
|
+
/**
|
|
162
|
+
* Reads a whole file in bounded chunks.
|
|
163
|
+
*
|
|
164
|
+
* The native layer is synchronous and does not call back into JS, so progress
|
|
165
|
+
* lives here: each chunk is one request, and the callback runs between them.
|
|
166
|
+
* That also gives cancellation a natural place to be checked — without it a
|
|
167
|
+
* large read would hold a worker thread until it finished.
|
|
168
|
+
*/
|
|
169
|
+
declare function readAll(volume: Pick<OttoVolume, 'stat' | 'read'>, path: string, options?: ReadAllOptions): Promise<Buffer>;
|
|
170
|
+
//#endregion
|
|
171
|
+
export { type AttributionBridge, type AttributionBridgeInput, type AttributionOwnerChange, type AttributionOwnerSummary, type AttributionOwners, type AttributionRegistration, type AttributionTag, type AttributionVolume, DEFAULT_CHUNK_SIZE, type Entry, type FsErrorCode, OTTOFS_FEATURE_ATTRIBUTION, OttoFsError, OttoVolume, type ReadAllOptions, type Stat, type Usage, type VolumeOptions, type WorkspaceBackend, type WriteOptions, type WriteReceipt, createAttributionBridge, createOttofsBackend, readAll, toError };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
import { n as OttoFsError, r as toError, t as loadNative } from "./native-DvvCjSi3.mjs";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { Worker } from "node:worker_threads";
|
|
5
|
+
//#region src/volume.ts
|
|
6
|
+
/** Worker-backed or in-thread handle to one OttoFS volume session. */
|
|
7
|
+
var OttoVolume = class OttoVolume {
|
|
8
|
+
#worker;
|
|
9
|
+
#inline;
|
|
10
|
+
#pending = /* @__PURE__ */ new Map();
|
|
11
|
+
#next = 1;
|
|
12
|
+
#closed = false;
|
|
13
|
+
constructor(options) {
|
|
14
|
+
const nativePath = options.nativePath ?? process.env.OTTOFS_NAPI ?? defaultNativePath();
|
|
15
|
+
if (!nativePath) throw new OttoFsError("EINTERNAL", "no native module: pass nativePath, set OTTOFS_NAPI, or run `pnpm build:native`");
|
|
16
|
+
if (options.worker === false) {
|
|
17
|
+
this.#inline = loadNative(nativePath).OttoVolume.open({
|
|
18
|
+
socket: options.socket,
|
|
19
|
+
token: options.token
|
|
20
|
+
});
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
this.#worker = new Worker(resolveWorker(), { workerData: {
|
|
24
|
+
nativePath,
|
|
25
|
+
socket: options.socket,
|
|
26
|
+
token: options.token
|
|
27
|
+
} });
|
|
28
|
+
if (options.unref === true) this.#worker.unref();
|
|
29
|
+
this.#worker.on("message", (reply) => {
|
|
30
|
+
const pending = this.#pending.get(reply.id);
|
|
31
|
+
if (!pending) return;
|
|
32
|
+
this.#pending.delete(reply.id);
|
|
33
|
+
if (reply.ok) pending.resolve(reply.value);
|
|
34
|
+
else pending.reject(toError(new Error(reply.message ?? "unknown error")));
|
|
35
|
+
});
|
|
36
|
+
this.#worker.on("error", (error) => {
|
|
37
|
+
for (const pending of this.#pending.values()) pending.reject(toError(error));
|
|
38
|
+
this.#pending.clear();
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
static open(options) {
|
|
42
|
+
return new OttoVolume(options);
|
|
43
|
+
}
|
|
44
|
+
get workerBacked() {
|
|
45
|
+
return this.#worker !== void 0;
|
|
46
|
+
}
|
|
47
|
+
async session() {
|
|
48
|
+
return String(await this.#call("session", []));
|
|
49
|
+
}
|
|
50
|
+
async caps() {
|
|
51
|
+
return Number(await this.#call("caps", []));
|
|
52
|
+
}
|
|
53
|
+
async features() {
|
|
54
|
+
return Number(await this.#call("features", []));
|
|
55
|
+
}
|
|
56
|
+
async attributeRegister(registration) {
|
|
57
|
+
await this.#call("attributeRegister", [
|
|
58
|
+
registration.sid,
|
|
59
|
+
registration.leaderStarttime,
|
|
60
|
+
registration.session,
|
|
61
|
+
registration.turn ?? null,
|
|
62
|
+
registration.job
|
|
63
|
+
]);
|
|
64
|
+
}
|
|
65
|
+
async attributeClear(sid) {
|
|
66
|
+
await this.#call("attributeClear", [sid]);
|
|
67
|
+
}
|
|
68
|
+
stat(path) {
|
|
69
|
+
return this.#call("stat", [path]);
|
|
70
|
+
}
|
|
71
|
+
readdir(path) {
|
|
72
|
+
return this.#call("readdir", [path]);
|
|
73
|
+
}
|
|
74
|
+
async read(path, offset = 0, length = 64 * 1024 * 1024) {
|
|
75
|
+
const value = await this.#call("read", [
|
|
76
|
+
path,
|
|
77
|
+
offset,
|
|
78
|
+
length
|
|
79
|
+
]);
|
|
80
|
+
return Buffer.isBuffer(value) ? value : Buffer.from(value);
|
|
81
|
+
}
|
|
82
|
+
write(path, data, options = {}) {
|
|
83
|
+
const buffer = Buffer.isBuffer(data) ? data : Buffer.from(data);
|
|
84
|
+
return this.#call("write", [
|
|
85
|
+
path,
|
|
86
|
+
buffer,
|
|
87
|
+
options
|
|
88
|
+
]);
|
|
89
|
+
}
|
|
90
|
+
async mkdir(path, mode = 493) {
|
|
91
|
+
await this.#call("mkdir", [path, mode]);
|
|
92
|
+
}
|
|
93
|
+
async unlink(path) {
|
|
94
|
+
await this.#call("unlink", [path]);
|
|
95
|
+
}
|
|
96
|
+
async rename(from, to) {
|
|
97
|
+
await this.#call("rename", [from, to]);
|
|
98
|
+
}
|
|
99
|
+
async sync(path) {
|
|
100
|
+
await this.#call("sync", [path]);
|
|
101
|
+
}
|
|
102
|
+
usage() {
|
|
103
|
+
return this.#call("usage", []);
|
|
104
|
+
}
|
|
105
|
+
async close() {
|
|
106
|
+
if (this.#closed) return;
|
|
107
|
+
if (this.#inline) {
|
|
108
|
+
this.#closed = true;
|
|
109
|
+
this.#inline.close();
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
if (!this.#worker) {
|
|
113
|
+
this.#closed = true;
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
try {
|
|
117
|
+
await this.#call("close", []);
|
|
118
|
+
} finally {
|
|
119
|
+
this.#closed = true;
|
|
120
|
+
await this.#worker.terminate();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
#call(op, args) {
|
|
124
|
+
if (this.#closed) return Promise.reject(new OttoFsError("EINTERNAL", "volume is closed"));
|
|
125
|
+
if (this.#inline) try {
|
|
126
|
+
const target = this.#inline;
|
|
127
|
+
return Promise.resolve(target[op].apply(this.#inline, args));
|
|
128
|
+
} catch (error) {
|
|
129
|
+
return Promise.reject(toError(error));
|
|
130
|
+
}
|
|
131
|
+
const id = this.#next++;
|
|
132
|
+
return new Promise((resolve, reject) => {
|
|
133
|
+
this.#pending.set(id, {
|
|
134
|
+
resolve,
|
|
135
|
+
reject
|
|
136
|
+
});
|
|
137
|
+
this.#worker.postMessage({
|
|
138
|
+
id,
|
|
139
|
+
op,
|
|
140
|
+
args
|
|
141
|
+
});
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
/**
|
|
146
|
+
* Built output ships worker.mjs; running from source (tsx, --experimental-strip-types)
|
|
147
|
+
* only has worker.ts. Picking whichever exists keeps both usable instead of
|
|
148
|
+
* making the package silently dist-only.
|
|
149
|
+
*/
|
|
150
|
+
/**
|
|
151
|
+
* `pnpm build:native` drops the library here, so the common case needs no
|
|
152
|
+
* configuration at all.
|
|
153
|
+
*/
|
|
154
|
+
function defaultNativePath() {
|
|
155
|
+
const candidate = fileURLToPath(new URL("../native/ottofs.node", import.meta.url));
|
|
156
|
+
return existsSync(candidate) ? candidate : void 0;
|
|
157
|
+
}
|
|
158
|
+
function resolveWorker() {
|
|
159
|
+
for (const candidate of ["./worker.mjs", "./worker.ts"]) {
|
|
160
|
+
const url = new URL(candidate, import.meta.url);
|
|
161
|
+
if (existsSync(url)) return url;
|
|
162
|
+
}
|
|
163
|
+
throw new OttoFsError("EINTERNAL", "worker entry point not found");
|
|
164
|
+
}
|
|
165
|
+
//#endregion
|
|
166
|
+
//#region src/attribution-bridge.ts
|
|
167
|
+
const OTTOFS_FEATURE_ATTRIBUTION = 1;
|
|
168
|
+
const PROCESS_TREE_DOMAIN = "processTree";
|
|
169
|
+
const OWNER_PREFIX = "bash:";
|
|
170
|
+
function messageOf(error) {
|
|
171
|
+
return error instanceof Error ? error.message : String(error);
|
|
172
|
+
}
|
|
173
|
+
function jobIdOf(ownerId) {
|
|
174
|
+
return ownerId.startsWith(OWNER_PREFIX) ? ownerId.slice(5) : ownerId;
|
|
175
|
+
}
|
|
176
|
+
function createAttributionBridge(input) {
|
|
177
|
+
const log = input.log ?? (() => {});
|
|
178
|
+
const pids = /* @__PURE__ */ new Map();
|
|
179
|
+
const pending = /* @__PURE__ */ new Map();
|
|
180
|
+
const skipped = /* @__PURE__ */ new Set();
|
|
181
|
+
let supported;
|
|
182
|
+
let stopped = false;
|
|
183
|
+
let unsubscribe;
|
|
184
|
+
const groupAlive = (sid) => {
|
|
185
|
+
if (input.processGroupAlive === void 0) return false;
|
|
186
|
+
try {
|
|
187
|
+
return input.processGroupAlive(sid);
|
|
188
|
+
} catch (error) {
|
|
189
|
+
log(`attribution: process group probe failed for ${sid}: ${messageOf(error)}`);
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
const supportedNow = async () => {
|
|
194
|
+
if (supported !== void 0) return supported;
|
|
195
|
+
try {
|
|
196
|
+
supported = (await input.volume.features() & 1) === 1;
|
|
197
|
+
} catch (error) {
|
|
198
|
+
log(`attribution: feature probe failed: ${messageOf(error)}`);
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
201
|
+
if (!supported) log("attribution: the daemon does not declare ATTRIBUTION, no registration will be sent");
|
|
202
|
+
return supported;
|
|
203
|
+
};
|
|
204
|
+
const tagOf = (ownerId) => {
|
|
205
|
+
if (input.jobOf === void 0) return { session: "" };
|
|
206
|
+
try {
|
|
207
|
+
return input.jobOf(ownerId);
|
|
208
|
+
} catch (error) {
|
|
209
|
+
log(`attribution: job lookup failed for ${ownerId}: ${messageOf(error)}`);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
const registrationOf = (ownerId, sid) => {
|
|
214
|
+
const tag = tagOf(ownerId);
|
|
215
|
+
if (tag === void 0) return;
|
|
216
|
+
const starttime = input.starttimeOf;
|
|
217
|
+
let leaderStarttime = 0;
|
|
218
|
+
if (starttime !== void 0) try {
|
|
219
|
+
leaderStarttime = starttime(sid) ?? 0;
|
|
220
|
+
} catch (error) {
|
|
221
|
+
log(`attribution: starttime probe failed for ${sid}: ${messageOf(error)}`);
|
|
222
|
+
leaderStarttime = 0;
|
|
223
|
+
}
|
|
224
|
+
return {
|
|
225
|
+
sid,
|
|
226
|
+
leaderStarttime,
|
|
227
|
+
session: tag.session,
|
|
228
|
+
...tag.turn === void 0 ? {} : { turn: tag.turn },
|
|
229
|
+
job: jobIdOf(ownerId)
|
|
230
|
+
};
|
|
231
|
+
};
|
|
232
|
+
const register = async (ownerId, sid) => {
|
|
233
|
+
if (stopped) return;
|
|
234
|
+
if (!await supportedNow()) return;
|
|
235
|
+
const registration = registrationOf(ownerId, sid);
|
|
236
|
+
if (registration === void 0) return;
|
|
237
|
+
try {
|
|
238
|
+
await input.volume.attributeRegister(registration);
|
|
239
|
+
skipped.delete(ownerId);
|
|
240
|
+
pids.set(ownerId, sid);
|
|
241
|
+
pending.delete(ownerId);
|
|
242
|
+
} catch (error) {
|
|
243
|
+
log(`attribution: register failed for ${ownerId} (sid ${sid}): ${messageOf(error)}`);
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
const clear = async (ownerId, sid) => {
|
|
247
|
+
if (stopped) return;
|
|
248
|
+
if (!await supportedNow()) return;
|
|
249
|
+
try {
|
|
250
|
+
await input.volume.attributeClear(sid);
|
|
251
|
+
pending.delete(ownerId);
|
|
252
|
+
pids.delete(ownerId);
|
|
253
|
+
} catch (error) {
|
|
254
|
+
log(`attribution: clear failed for ${ownerId} (sid ${sid}): ${messageOf(error)}`);
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
const release = (ownerId, sid) => {
|
|
258
|
+
if (!pids.has(ownerId)) return;
|
|
259
|
+
if (groupAlive(sid)) {
|
|
260
|
+
pending.set(ownerId, sid);
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
clear(ownerId, sid);
|
|
264
|
+
};
|
|
265
|
+
const handle = (change) => {
|
|
266
|
+
if (stopped || change.domain !== PROCESS_TREE_DOMAIN) return;
|
|
267
|
+
const sid = change.pid ?? pids.get(change.ownerId);
|
|
268
|
+
if (sid === void 0) return;
|
|
269
|
+
if (change.type === "registered") {
|
|
270
|
+
register(change.ownerId, sid);
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
release(change.ownerId, sid);
|
|
274
|
+
};
|
|
275
|
+
const reconcile = async () => {
|
|
276
|
+
if (stopped) return;
|
|
277
|
+
if (!await supportedNow()) return;
|
|
278
|
+
for (const [ownerId, sid] of [...pending]) {
|
|
279
|
+
if (groupAlive(sid)) continue;
|
|
280
|
+
await clear(ownerId, sid);
|
|
281
|
+
}
|
|
282
|
+
let live = [];
|
|
283
|
+
try {
|
|
284
|
+
live = input.owners.snapshot();
|
|
285
|
+
} catch (error) {
|
|
286
|
+
log(`attribution: owner snapshot failed: ${messageOf(error)}`);
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
for (const entry of live) {
|
|
290
|
+
if (entry.domain !== PROCESS_TREE_DOMAIN) continue;
|
|
291
|
+
const sid = entry.pid ?? pids.get(entry.ownerId);
|
|
292
|
+
if (sid === void 0) {
|
|
293
|
+
if (!skipped.has(entry.ownerId)) {
|
|
294
|
+
skipped.add(entry.ownerId);
|
|
295
|
+
log(`attribution: no pid known for ${entry.ownerId}, reconcile skipped it`);
|
|
296
|
+
}
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
299
|
+
await register(entry.ownerId, sid);
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
try {
|
|
303
|
+
unsubscribe = input.owners.observe(handle);
|
|
304
|
+
} catch (error) {
|
|
305
|
+
log(`attribution: owner observation failed: ${messageOf(error)}`);
|
|
306
|
+
}
|
|
307
|
+
return {
|
|
308
|
+
stop() {
|
|
309
|
+
stopped = true;
|
|
310
|
+
unsubscribe?.();
|
|
311
|
+
unsubscribe = void 0;
|
|
312
|
+
},
|
|
313
|
+
reconcile
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
//#endregion
|
|
317
|
+
//#region src/backend.ts
|
|
318
|
+
function createOttofsBackend(volume) {
|
|
319
|
+
return {
|
|
320
|
+
stat: (path) => volume.stat(path),
|
|
321
|
+
read: (path, offset = 0, length = 64 * 1024 * 1024) => volume.read(path, offset, length),
|
|
322
|
+
write: (path, data, options = {}) => volume.write(path, data, options),
|
|
323
|
+
list: (path) => volume.readdir(path),
|
|
324
|
+
remove: (path) => volume.unlink(path),
|
|
325
|
+
rename: (from, to) => volume.rename(from, to),
|
|
326
|
+
mkdir: (path, mode) => volume.mkdir(path, mode)
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
//#endregion
|
|
330
|
+
//#region src/read-all.ts
|
|
331
|
+
const DEFAULT_CHUNK_SIZE = 8 * 1024 * 1024;
|
|
332
|
+
/**
|
|
333
|
+
* Reads a whole file in bounded chunks.
|
|
334
|
+
*
|
|
335
|
+
* The native layer is synchronous and does not call back into JS, so progress
|
|
336
|
+
* lives here: each chunk is one request, and the callback runs between them.
|
|
337
|
+
* That also gives cancellation a natural place to be checked — without it a
|
|
338
|
+
* large read would hold a worker thread until it finished.
|
|
339
|
+
*/
|
|
340
|
+
async function readAll(volume, path, options = {}) {
|
|
341
|
+
const chunkSize = Math.max(1, options.chunkSize ?? 8388608);
|
|
342
|
+
const total = (await volume.stat(path)).size;
|
|
343
|
+
const buffer = Buffer.allocUnsafe(total);
|
|
344
|
+
let bytesRead = 0;
|
|
345
|
+
while (bytesRead < total) {
|
|
346
|
+
options.signal?.throwIfAborted();
|
|
347
|
+
const length = Math.min(chunkSize, total - bytesRead);
|
|
348
|
+
const chunk = await volume.read(path, bytesRead, length);
|
|
349
|
+
if (chunk.length === 0) throw new OttoFsError("EIO", `short read at ${bytesRead} of ${total} bytes: ${path}`);
|
|
350
|
+
buffer.set(chunk, bytesRead);
|
|
351
|
+
bytesRead += chunk.length;
|
|
352
|
+
options.onProgress?.({
|
|
353
|
+
bytesRead,
|
|
354
|
+
total
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
return buffer.subarray(0, bytesRead);
|
|
358
|
+
}
|
|
359
|
+
//#endregion
|
|
360
|
+
export { DEFAULT_CHUNK_SIZE, OTTOFS_FEATURE_ATTRIBUTION, OttoFsError, OttoVolume, createAttributionBridge, createOttofsBackend, readAll, toError };
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
//#region src/errors.ts
|
|
3
|
+
const CODES = [
|
|
4
|
+
"EACCES",
|
|
5
|
+
"EBADTOKEN",
|
|
6
|
+
"EBADFRAME",
|
|
7
|
+
"EBADREQUEST",
|
|
8
|
+
"ECONFLICT",
|
|
9
|
+
"EDQUOT",
|
|
10
|
+
"EEXPIREDTOKEN",
|
|
11
|
+
"EINTERNAL",
|
|
12
|
+
"EINTR",
|
|
13
|
+
"EIO",
|
|
14
|
+
"ENOENT",
|
|
15
|
+
"EROFS",
|
|
16
|
+
"ETIMEDOUT"
|
|
17
|
+
];
|
|
18
|
+
/** Error raised by an OttoFS operation, carrying a stable machine code. */
|
|
19
|
+
var OttoFsError = class extends Error {
|
|
20
|
+
code;
|
|
21
|
+
constructor(code, message) {
|
|
22
|
+
super(message);
|
|
23
|
+
this.name = "OttoFsError";
|
|
24
|
+
this.code = code;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* The native layer reports errors as `CODE: detail`. Parsing on this side keeps
|
|
29
|
+
* the Rust shape untouched while giving callers something they can switch on.
|
|
30
|
+
*/
|
|
31
|
+
function toError(error) {
|
|
32
|
+
if (error instanceof OttoFsError) return error;
|
|
33
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
34
|
+
const [head, ...rest] = message.split(":");
|
|
35
|
+
const candidate = head?.trim();
|
|
36
|
+
if (candidate && CODES.includes(candidate)) return new OttoFsError(candidate, rest.join(":").trim() || message);
|
|
37
|
+
return new OttoFsError("EINTERNAL", message);
|
|
38
|
+
}
|
|
39
|
+
//#endregion
|
|
40
|
+
//#region src/native.ts
|
|
41
|
+
function loadNative(path) {
|
|
42
|
+
if (!path.endsWith(".node")) throw new OttoFsError("EINTERNAL", `native module must be a .node file (got ${path}); copy the built library to *.node first`);
|
|
43
|
+
return createRequire(import.meta.url)(path);
|
|
44
|
+
}
|
|
45
|
+
//#endregion
|
|
46
|
+
export { OttoFsError as n, toError as r, loadNative as t };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { };
|
package/dist/worker.mjs
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { t as loadNative } from "./native-DvvCjSi3.mjs";
|
|
2
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
3
|
+
//#region src/worker.ts
|
|
4
|
+
const data = workerData;
|
|
5
|
+
let volume;
|
|
6
|
+
function get() {
|
|
7
|
+
volume ??= loadNative(data.nativePath).OttoVolume.open({
|
|
8
|
+
socket: data.socket,
|
|
9
|
+
token: data.token
|
|
10
|
+
});
|
|
11
|
+
return volume;
|
|
12
|
+
}
|
|
13
|
+
parentPort?.on("message", (request) => {
|
|
14
|
+
try {
|
|
15
|
+
const target = get();
|
|
16
|
+
const method = target[request.op];
|
|
17
|
+
if (typeof method !== "function") throw new Error(`EBADREQUEST: unknown operation ${request.op}`);
|
|
18
|
+
const value = method.apply(target, request.args);
|
|
19
|
+
parentPort?.postMessage({
|
|
20
|
+
id: request.id,
|
|
21
|
+
ok: true,
|
|
22
|
+
value
|
|
23
|
+
});
|
|
24
|
+
} catch (error) {
|
|
25
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
26
|
+
parentPort?.postMessage({
|
|
27
|
+
id: request.id,
|
|
28
|
+
ok: false,
|
|
29
|
+
message
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
//#endregion
|
|
34
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,23 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@x-otto/ottofs",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.4.0-beta.0",
|
|
4
|
+
"description": "OttoFS 卷的 NAPI 客户端:能力令牌 + 结构化语义(generation/配额/错误码),凭据留在 daemon",
|
|
5
|
+
"files": [
|
|
6
|
+
"dist",
|
|
7
|
+
"native"
|
|
8
|
+
],
|
|
9
|
+
"type": "module",
|
|
10
|
+
"main": "./dist/index.mjs",
|
|
11
|
+
"types": "./dist/index.d.mts",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.mts",
|
|
15
|
+
"import": "./dist/index.mjs"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"dependencies": {},
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"access": "public",
|
|
21
|
+
"tag": "beta"
|
|
22
|
+
}
|
|
23
|
+
}
|