@waffle-os/runtime 0.0.147 → 0.0.148
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/browser/filesystem-backend.ts +26 -5
- package/browser/fs-worker.ts +5 -2
- package/browser/shared-fs.ts +93 -10
- package/core/filesystem.ts +2 -0
- package/dist/browser/filesystem-backend.js +19 -2
- package/dist/browser/fs-worker.js +7 -2
- package/dist/browser/shared-fs.js +77 -8
- package/dist/fs/client.js +82 -21
- package/dist/fs/directory-pages.js +22 -7
- package/dist/fs/guest-watch.js +9 -3
- package/dist/fs/idle-database.js +1 -1
- package/dist/fs/idle-owner.js +35 -4
- package/dist/fs/indexeddb.js +322 -63
- package/dist/fs/memory.js +18 -9
- package/dist/fs/multitab-backend.js +5065 -0
- package/dist/fs/multitab-protocol.js +301 -0
- package/dist/fs/opfs.js +21 -0
- package/dist/fs/persistent.js +70 -1
- package/dist/fs/protocol.js +1 -1
- package/dist/fs/service.js +266 -86
- package/dist/fs/shared.js +45 -0
- package/dist/fs/vfs.js +26 -8
- package/dist/fs/watch-ring.js +7 -3
- package/dist/proc/command-stdio.js +56 -1
- package/dist/runtime.js +4 -2
- package/dist/tooling/program/program-transformer.json +1 -1
- package/fs/backend.ts +36 -0
- package/fs/client.ts +81 -19
- package/fs/directory-pages.ts +40 -6
- package/fs/guest-watch.ts +8 -3
- package/fs/idle-database.ts +1 -0
- package/fs/idle-owner.ts +48 -12
- package/fs/indexeddb.ts +396 -78
- package/fs/memory.ts +33 -9
- package/fs/multitab-backend.ts +6870 -0
- package/fs/multitab-protocol.ts +655 -0
- package/fs/opfs.ts +21 -0
- package/fs/persistent.ts +70 -1
- package/fs/protocol.ts +1 -1
- package/fs/service.ts +314 -109
- package/fs/shared.ts +45 -0
- package/fs/storage.ts +3 -0
- package/fs/vfs.ts +44 -15
- package/fs/watch-ring.ts +5 -2
- package/package.json +1 -1
- package/proc/command-stdio.ts +72 -2
- package/runtime.ts +12 -3
- package/tooling/program/program-transformer.json +1 -1
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
import { FilesystemError, pack } from "./protocol.js";
|
|
2
|
+
|
|
3
|
+
/** Maximum payload bytes in a single BroadcastChannel RPC frame. */
|
|
4
|
+
export const MAX_FRAME_BYTES = 1024 * 1024;
|
|
5
|
+
/** Minimum sender-side frame credit grant per admitted peer. */
|
|
6
|
+
export const MIN_PEER_FRAMES = 2;
|
|
7
|
+
/** Minimum sender-side byte credit grant per admitted peer (guarantees any valid <= 1 MiB frame). */
|
|
8
|
+
export const MIN_PEER_BYTES = 1024 * 1024;
|
|
9
|
+
/** Global Host wire-credit frame pool across all attached peers (supports up to 16 peers). */
|
|
10
|
+
export const MAX_HOST_FRAMES = 64;
|
|
11
|
+
/** Global Host wire-credit byte pool across all attached peers (16 MiB). */
|
|
12
|
+
export const MAX_HOST_WIRE_BYTES = 16 * 1024 * 1024;
|
|
13
|
+
/** Default target grant per peer when global pool headroom allows. */
|
|
14
|
+
export const DEFAULT_PEER_FRAMES = 4;
|
|
15
|
+
/** Default target byte grant per peer when global pool headroom allows (2 MiB). */
|
|
16
|
+
export const DEFAULT_PEER_BYTES = 2 * MAX_FRAME_BYTES;
|
|
17
|
+
/** Global Host staged upload pool cap across all peers (32 MiB). */
|
|
18
|
+
export const MAX_STAGED_UPLOAD_BYTES = 32 * 1024 * 1024;
|
|
19
|
+
/** Global Host staged download pool cap across all peers (32 MiB). */
|
|
20
|
+
export const MAX_STAGED_DOWNLOAD_BYTES = 32 * 1024 * 1024;
|
|
21
|
+
/** Max concurrent staged uploads per peer. */
|
|
22
|
+
export const MAX_CONCURRENT_UPLOADS_PER_PEER = 4;
|
|
23
|
+
/** Max concurrent staged downloads per peer. */
|
|
24
|
+
export const MAX_CONCURRENT_DOWNLOADS_PER_PEER = 4;
|
|
25
|
+
/** Hard per-session cap on pending settlement items (unpins + watchAcks + watchCloses). */
|
|
26
|
+
export const MAX_PENDING_SETTLEMENTS = 1024;
|
|
27
|
+
/** Flush threshold for Host immediate batched settlement confirmations. */
|
|
28
|
+
export const SETTLEMENT_BATCH_SIZE = 32;
|
|
29
|
+
/** Maximum settlement entries piggybacked on a single heartbeat ping/pong. */
|
|
30
|
+
export const PONG_SETTLEMENT_LIMIT = 256;
|
|
31
|
+
/** Maximum 16-bit local directory cookie epoch before EOVERFLOW (never wraps). */
|
|
32
|
+
export const DIR_EPOCH_MAX = 0xffffn;
|
|
33
|
+
/** Low 48-bit mask for untagged MemFS/DirectoryPages cookies. */
|
|
34
|
+
const COOKIE_LOW_MASK = 0xffffffffffffn;
|
|
35
|
+
/** Slab granularity (64 KiB) for incremental bounded wire-encoding budget reservations. */
|
|
36
|
+
const WIRE_BUDGET_SLAB_BYTES = 64 * 1024;
|
|
37
|
+
|
|
38
|
+
export interface MultiTabTimings {
|
|
39
|
+
readonly leaseDurationMs: number;
|
|
40
|
+
readonly leaseRenewMs: number;
|
|
41
|
+
readonly leaseClockSafetyMs: number;
|
|
42
|
+
readonly heartbeatIntervalMs: number;
|
|
43
|
+
readonly heartbeatTimeoutMs: number;
|
|
44
|
+
readonly confirmGraceMs: number;
|
|
45
|
+
readonly attachRetryMs: number;
|
|
46
|
+
readonly waitPollMs: number;
|
|
47
|
+
readonly recoverTimeoutMs: number;
|
|
48
|
+
readonly drainGraceMs: number;
|
|
49
|
+
readonly attachIdleTimeoutMs: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const DEFAULT_MULTITAB_TIMINGS: MultiTabTimings = Object.freeze({
|
|
53
|
+
leaseDurationMs: 1200,
|
|
54
|
+
leaseRenewMs: 400,
|
|
55
|
+
leaseClockSafetyMs: 200,
|
|
56
|
+
heartbeatIntervalMs: 800,
|
|
57
|
+
heartbeatTimeoutMs: 2400,
|
|
58
|
+
confirmGraceMs: 400,
|
|
59
|
+
attachRetryMs: 300,
|
|
60
|
+
waitPollMs: 150,
|
|
61
|
+
recoverTimeoutMs: 2000,
|
|
62
|
+
drainGraceMs: 150,
|
|
63
|
+
attachIdleTimeoutMs: 2400 * 3,
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
export function resolveMultiTabTimings(overrides?: Partial<MultiTabTimings>): MultiTabTimings {
|
|
67
|
+
if (!overrides) return DEFAULT_MULTITAB_TIMINGS;
|
|
68
|
+
const heartbeatTimeoutMs =
|
|
69
|
+
overrides.heartbeatTimeoutMs ?? DEFAULT_MULTITAB_TIMINGS.heartbeatTimeoutMs;
|
|
70
|
+
return Object.freeze({
|
|
71
|
+
...DEFAULT_MULTITAB_TIMINGS,
|
|
72
|
+
...overrides,
|
|
73
|
+
attachIdleTimeoutMs: overrides.attachIdleTimeoutMs ?? heartbeatTimeoutMs * 3,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export type MultiTabImplementation = "indexeddb" | "opfs-memory";
|
|
78
|
+
|
|
79
|
+
export function multitabScope(implementation: MultiTabImplementation, name: string): string {
|
|
80
|
+
return `${implementation}:${encodeURIComponent(name)}`;
|
|
81
|
+
}
|
|
82
|
+
export function controlChannelName(scope: string): string {
|
|
83
|
+
return `waffle:multitab:v1:ctrl:${scope}`;
|
|
84
|
+
}
|
|
85
|
+
export function peerChannelName(scope: string, hostTerm: bigint, peerId: string): string {
|
|
86
|
+
return `waffle:multitab:v1:peer:${scope}:${hostTerm.toString(16)}:${peerId}`;
|
|
87
|
+
}
|
|
88
|
+
export function electionLockName(scope: string): string {
|
|
89
|
+
return `waffle:multitab:v1:host:${scope}`;
|
|
90
|
+
}
|
|
91
|
+
export function attachClaimPrefix(scope: string): string {
|
|
92
|
+
return `waffle:multitab:v1:attach-claim:${scope}:`;
|
|
93
|
+
}
|
|
94
|
+
export function attachClaimLockName(scope: string, attemptId: string, mode: string): string {
|
|
95
|
+
return `${attachClaimPrefix(scope)}${attemptId}:${mode}`;
|
|
96
|
+
}
|
|
97
|
+
export function parseAttachClaimAttemptId(scope: string, lockName: string): string | undefined {
|
|
98
|
+
const prefix = attachClaimPrefix(scope);
|
|
99
|
+
if (!lockName.startsWith(prefix)) return undefined;
|
|
100
|
+
const rest = lockName.slice(prefix.length);
|
|
101
|
+
const sep = rest.indexOf(":");
|
|
102
|
+
return sep > 0 ? rest.slice(0, sep) : undefined;
|
|
103
|
+
}
|
|
104
|
+
export function aliveLockPrefix(scope: string): string {
|
|
105
|
+
return `waffle:multitab:v1:alive:${scope}:`;
|
|
106
|
+
}
|
|
107
|
+
export function aliveLockName(scope: string, attemptId: string): string {
|
|
108
|
+
return `${aliveLockPrefix(scope)}${attemptId}`;
|
|
109
|
+
}
|
|
110
|
+
export function peerAliveLockName(scope: string, peerId: string): string {
|
|
111
|
+
return `waffle:multitab:v1:peer-alive:${scope}:${peerId}`;
|
|
112
|
+
}
|
|
113
|
+
export function recoverLockName(scope: string): string {
|
|
114
|
+
return `waffle:multitab:v1:recover:${scope}`;
|
|
115
|
+
}
|
|
116
|
+
export function storageLockNameFor(implementation: MultiTabImplementation, name: string): string {
|
|
117
|
+
return implementation === "indexeddb"
|
|
118
|
+
? `bun-wasm:filesystem:indexeddb:${name}`
|
|
119
|
+
: `bun-wasm:filesystem:${name}`;
|
|
120
|
+
}
|
|
121
|
+
export function maintenanceLockNameFor(name: string): string {
|
|
122
|
+
return `bun-wasm:filesystem:indexeddb-maintenance:${name}`;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function formatTerm(term: bigint): string {
|
|
126
|
+
return term.toString(16);
|
|
127
|
+
}
|
|
128
|
+
export function parseTerm(value: unknown): bigint | undefined {
|
|
129
|
+
if (typeof value !== "string" || !/^[0-9a-f]+$/i.test(value)) return undefined;
|
|
130
|
+
try {
|
|
131
|
+
return BigInt(`0x${value}`);
|
|
132
|
+
} catch {
|
|
133
|
+
return undefined;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Error carrying an explicit confirmed-release outcome for worker -> page propagation. */
|
|
138
|
+
export class MultiTabReleaseError extends Error {
|
|
139
|
+
readonly released: boolean;
|
|
140
|
+
readonly errno?: number;
|
|
141
|
+
constructor(message: string, released: boolean, cause?: unknown, code?: number) {
|
|
142
|
+
super(message);
|
|
143
|
+
this.name = "MultiTabReleaseError";
|
|
144
|
+
this.released = released;
|
|
145
|
+
if (cause !== undefined) this.cause = cause;
|
|
146
|
+
if (code !== undefined) this.errno = code;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function describeReason(reason: unknown, fallback = "Filesystem storage failure"): string {
|
|
151
|
+
if (reason instanceof Error && reason.message) return reason.message;
|
|
152
|
+
if (typeof reason === "string" && reason.length) return reason;
|
|
153
|
+
try {
|
|
154
|
+
const text = String(reason);
|
|
155
|
+
return text.length ? text : fallback;
|
|
156
|
+
} catch {
|
|
157
|
+
return fallback;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function wrapReleaseError(
|
|
162
|
+
reason: unknown,
|
|
163
|
+
released: boolean,
|
|
164
|
+
fallback = "Filesystem disposal failed",
|
|
165
|
+
): MultiTabReleaseError {
|
|
166
|
+
const code = reason instanceof FilesystemError ? reason.errno : undefined;
|
|
167
|
+
return new MultiTabReleaseError(describeReason(reason, fallback), released, reason, code);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Copy any SharedArrayBuffer-backed or sub-ranged Uint8Array into a plain unshared ArrayBuffer. */
|
|
171
|
+
export function unsharedBytes(bytes: Uint8Array): Uint8Array<ArrayBuffer> {
|
|
172
|
+
if (
|
|
173
|
+
bytes.buffer instanceof ArrayBuffer &&
|
|
174
|
+
!(bytes.buffer as { resizable?: boolean }).resizable &&
|
|
175
|
+
bytes.byteOffset === 0 &&
|
|
176
|
+
bytes.byteLength === bytes.buffer.byteLength
|
|
177
|
+
)
|
|
178
|
+
return bytes as Uint8Array<ArrayBuffer>;
|
|
179
|
+
const copy = new Uint8Array(bytes.byteLength);
|
|
180
|
+
copy.set(bytes);
|
|
181
|
+
return copy;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const PURE_STATELESS_READ_OPS = new Set<string>([
|
|
185
|
+
"readFile",
|
|
186
|
+
"lookup",
|
|
187
|
+
"listFiles",
|
|
188
|
+
"resolvePath",
|
|
189
|
+
"stat",
|
|
190
|
+
"permissions",
|
|
191
|
+
"read",
|
|
192
|
+
"readdir",
|
|
193
|
+
"readlink",
|
|
194
|
+
"resolve",
|
|
195
|
+
"readdirPage",
|
|
196
|
+
]);
|
|
197
|
+
|
|
198
|
+
export function isReplayableRead(operation: string, args: readonly unknown[]): boolean {
|
|
199
|
+
if (!PURE_STATELESS_READ_OPS.has(operation)) return false;
|
|
200
|
+
if (operation === "readdirPage") {
|
|
201
|
+
const cookie = args[1];
|
|
202
|
+
if (typeof cookie === "bigint" && cookie >= 3n) return false;
|
|
203
|
+
}
|
|
204
|
+
return true;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Validate a client's directory cookie against currentDirEpoch and strip the high 16-bit tag. */
|
|
208
|
+
export function validateAndStripDirCookie(wireCookie: bigint, currentDirEpoch: bigint): bigint {
|
|
209
|
+
if (wireCookie < 0n) throw new FilesystemError(28, "invalid directory cookie");
|
|
210
|
+
if (wireCookie <= 2n) return wireCookie;
|
|
211
|
+
const tag = wireCookie >> 48n;
|
|
212
|
+
if (tag !== currentDirEpoch) throw new FilesystemError(8, "stale directory cookie");
|
|
213
|
+
return wireCookie & COOKIE_LOW_MASK;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
type HostPhaseAdvertisement = "opening" | "waiting-storage" | "retiring";
|
|
217
|
+
export type HostHealthState = "ready" | "draining" | "failed";
|
|
218
|
+
|
|
219
|
+
export interface PeerCreditLimit {
|
|
220
|
+
readonly frames: number;
|
|
221
|
+
readonly bytes: number;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export type ControlMessage =
|
|
225
|
+
| { readonly kind: "discover"; readonly fromPeerId: string }
|
|
226
|
+
| {
|
|
227
|
+
readonly kind: "host-status";
|
|
228
|
+
readonly attemptId: string;
|
|
229
|
+
readonly clientId: string;
|
|
230
|
+
readonly phase: HostPhaseAdvertisement;
|
|
231
|
+
readonly hostTerm?: string;
|
|
232
|
+
}
|
|
233
|
+
| {
|
|
234
|
+
readonly kind: "host-ready";
|
|
235
|
+
readonly attemptId: string;
|
|
236
|
+
readonly clientId: string;
|
|
237
|
+
readonly hostTerm: string;
|
|
238
|
+
readonly workspaceId: string;
|
|
239
|
+
readonly storageEpoch: number;
|
|
240
|
+
readonly lastExclusiveEpoch: number;
|
|
241
|
+
}
|
|
242
|
+
| {
|
|
243
|
+
readonly kind: "host-draining";
|
|
244
|
+
readonly attemptId: string;
|
|
245
|
+
readonly hostTerm: string;
|
|
246
|
+
}
|
|
247
|
+
| {
|
|
248
|
+
readonly kind: "host-stepping-down";
|
|
249
|
+
readonly attemptId: string;
|
|
250
|
+
readonly hostTerm: string;
|
|
251
|
+
}
|
|
252
|
+
| {
|
|
253
|
+
readonly kind: "host-failed";
|
|
254
|
+
readonly attemptId: string;
|
|
255
|
+
readonly clientId: string;
|
|
256
|
+
readonly hostTerm: string;
|
|
257
|
+
readonly workspaceId: string;
|
|
258
|
+
readonly message?: string;
|
|
259
|
+
}
|
|
260
|
+
| {
|
|
261
|
+
readonly kind: "cooperative-step-down";
|
|
262
|
+
readonly targetAttemptId: string;
|
|
263
|
+
readonly targetTerm: string;
|
|
264
|
+
}
|
|
265
|
+
| {
|
|
266
|
+
readonly kind: "external-takeover";
|
|
267
|
+
readonly attemptId: string;
|
|
268
|
+
readonly hostTerm: string;
|
|
269
|
+
readonly workspaceId: string;
|
|
270
|
+
readonly lastExclusiveEpoch: number;
|
|
271
|
+
readonly affectedEpoch: number;
|
|
272
|
+
}
|
|
273
|
+
| {
|
|
274
|
+
readonly kind: "workspace-replaced";
|
|
275
|
+
readonly workspaceId: string;
|
|
276
|
+
readonly expectedWorkspaceId: string;
|
|
277
|
+
}
|
|
278
|
+
| {
|
|
279
|
+
readonly kind: "attach";
|
|
280
|
+
readonly peerId: string;
|
|
281
|
+
readonly sessionId: string;
|
|
282
|
+
readonly hostTerm: string;
|
|
283
|
+
readonly targetAttemptId?: string;
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
export interface WirePinnedHandle {
|
|
287
|
+
readonly remoteHandle: number;
|
|
288
|
+
readonly fileId: bigint;
|
|
289
|
+
readonly pinToken: number;
|
|
290
|
+
readonly unlinked?: boolean;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export interface WireResolveResult {
|
|
294
|
+
readonly parent?: WirePinnedHandle;
|
|
295
|
+
readonly node?: WirePinnedHandle;
|
|
296
|
+
readonly name: string;
|
|
297
|
+
readonly trailingSlash: boolean;
|
|
298
|
+
readonly terminalDot: boolean;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
export type PeerMessage =
|
|
302
|
+
| {
|
|
303
|
+
readonly kind: "attached";
|
|
304
|
+
readonly hostTerm: string;
|
|
305
|
+
readonly sessionId: string;
|
|
306
|
+
readonly creditLimit: PeerCreditLimit;
|
|
307
|
+
}
|
|
308
|
+
| {
|
|
309
|
+
readonly kind: "attach-rejected";
|
|
310
|
+
readonly hostTerm: string;
|
|
311
|
+
readonly sessionId: string;
|
|
312
|
+
readonly errno: number;
|
|
313
|
+
readonly message?: string;
|
|
314
|
+
}
|
|
315
|
+
| {
|
|
316
|
+
readonly kind: "credit-limit";
|
|
317
|
+
readonly hostTerm: string;
|
|
318
|
+
readonly sessionId: string;
|
|
319
|
+
readonly creditLimit: PeerCreditLimit;
|
|
320
|
+
}
|
|
321
|
+
| {
|
|
322
|
+
readonly kind: "req";
|
|
323
|
+
readonly hostTerm: string;
|
|
324
|
+
readonly sessionId: string;
|
|
325
|
+
readonly reqId: number;
|
|
326
|
+
readonly op: string;
|
|
327
|
+
readonly args: unknown[];
|
|
328
|
+
readonly data?: Uint8Array;
|
|
329
|
+
readonly uploadId?: string;
|
|
330
|
+
readonly totalBytes?: number;
|
|
331
|
+
readonly responseCookieTag?: string;
|
|
332
|
+
}
|
|
333
|
+
| {
|
|
334
|
+
readonly kind: "chunk-put";
|
|
335
|
+
readonly hostTerm: string;
|
|
336
|
+
readonly sessionId: string;
|
|
337
|
+
readonly reqId: number;
|
|
338
|
+
readonly uploadId: string;
|
|
339
|
+
readonly offset: number;
|
|
340
|
+
readonly totalBytes: number;
|
|
341
|
+
readonly chunk: Uint8Array;
|
|
342
|
+
}
|
|
343
|
+
| {
|
|
344
|
+
readonly kind: "chunk-get";
|
|
345
|
+
readonly hostTerm: string;
|
|
346
|
+
readonly sessionId: string;
|
|
347
|
+
readonly reqId: number;
|
|
348
|
+
readonly downloadId: string;
|
|
349
|
+
readonly offset: number;
|
|
350
|
+
readonly length: number;
|
|
351
|
+
}
|
|
352
|
+
| {
|
|
353
|
+
readonly kind: "res";
|
|
354
|
+
readonly hostTerm: string;
|
|
355
|
+
readonly sessionId: string;
|
|
356
|
+
readonly reqId: number;
|
|
357
|
+
readonly ok: boolean;
|
|
358
|
+
readonly value?: unknown;
|
|
359
|
+
readonly data?: Uint8Array;
|
|
360
|
+
readonly packed?: boolean;
|
|
361
|
+
readonly binary?: boolean;
|
|
362
|
+
readonly errno?: number;
|
|
363
|
+
readonly message?: string;
|
|
364
|
+
readonly retry?: true;
|
|
365
|
+
readonly creditFrames?: number;
|
|
366
|
+
readonly creditBytes?: number;
|
|
367
|
+
readonly chunkedId?: string;
|
|
368
|
+
readonly totalBytes?: number;
|
|
369
|
+
readonly firstChunk?: Uint8Array;
|
|
370
|
+
readonly ackId?: number;
|
|
371
|
+
}
|
|
372
|
+
| {
|
|
373
|
+
readonly kind: "ping";
|
|
374
|
+
readonly hostTerm: string;
|
|
375
|
+
readonly sessionId: string;
|
|
376
|
+
readonly pingId: number;
|
|
377
|
+
readonly latestAckedWakeSeq: number;
|
|
378
|
+
readonly pendingWatchAcks?: readonly (readonly [number, boolean])[];
|
|
379
|
+
readonly pendingUnpins?: readonly number[];
|
|
380
|
+
readonly pendingWatchCloses?: readonly number[];
|
|
381
|
+
}
|
|
382
|
+
| {
|
|
383
|
+
readonly kind: "pong";
|
|
384
|
+
readonly hostTerm: string;
|
|
385
|
+
readonly sessionId: string;
|
|
386
|
+
readonly pingId: number;
|
|
387
|
+
readonly activeReqIds: readonly number[];
|
|
388
|
+
readonly latestWakeSeq: number;
|
|
389
|
+
readonly settledWatchAcks?: readonly number[];
|
|
390
|
+
readonly settledUnpins?: readonly number[];
|
|
391
|
+
readonly settledWatchCloses?: readonly number[];
|
|
392
|
+
readonly creditLimit: PeerCreditLimit;
|
|
393
|
+
readonly hostState: HostHealthState;
|
|
394
|
+
}
|
|
395
|
+
| {
|
|
396
|
+
readonly kind: "watch-wake";
|
|
397
|
+
readonly hostTerm: string;
|
|
398
|
+
readonly sessionId: string;
|
|
399
|
+
readonly wakeSeq: number;
|
|
400
|
+
}
|
|
401
|
+
| {
|
|
402
|
+
readonly kind: "watch-wake-ack";
|
|
403
|
+
readonly hostTerm: string;
|
|
404
|
+
readonly sessionId: string;
|
|
405
|
+
readonly wakeSeq: number;
|
|
406
|
+
}
|
|
407
|
+
| {
|
|
408
|
+
readonly kind: "watch-ack";
|
|
409
|
+
readonly hostTerm: string;
|
|
410
|
+
readonly sessionId: string;
|
|
411
|
+
readonly ackId: number;
|
|
412
|
+
readonly accepted: boolean;
|
|
413
|
+
}
|
|
414
|
+
| {
|
|
415
|
+
readonly kind: "unpin";
|
|
416
|
+
readonly hostTerm: string;
|
|
417
|
+
readonly sessionId: string;
|
|
418
|
+
readonly pinToken: number;
|
|
419
|
+
}
|
|
420
|
+
| {
|
|
421
|
+
readonly kind: "watch-close";
|
|
422
|
+
readonly hostTerm: string;
|
|
423
|
+
readonly sessionId: string;
|
|
424
|
+
readonly hostWatchId: number;
|
|
425
|
+
}
|
|
426
|
+
| {
|
|
427
|
+
readonly kind: "settled";
|
|
428
|
+
readonly hostTerm: string;
|
|
429
|
+
readonly sessionId: string;
|
|
430
|
+
readonly watchAcks?: readonly number[];
|
|
431
|
+
readonly unpins?: readonly number[];
|
|
432
|
+
readonly watchCloses?: readonly number[];
|
|
433
|
+
}
|
|
434
|
+
| {
|
|
435
|
+
readonly kind: "detach";
|
|
436
|
+
readonly hostTerm: string;
|
|
437
|
+
readonly sessionId: string;
|
|
438
|
+
};
|
|
439
|
+
|
|
440
|
+
function isObject(value: unknown): value is Record<string, unknown> {
|
|
441
|
+
return typeof value === "object" && value !== null;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
export function isControlMessage(value: unknown): value is ControlMessage {
|
|
445
|
+
if (!isObject(value) || typeof value.kind !== "string") return false;
|
|
446
|
+
switch (value.kind) {
|
|
447
|
+
case "discover":
|
|
448
|
+
return typeof value.fromPeerId === "string";
|
|
449
|
+
case "host-status":
|
|
450
|
+
return (
|
|
451
|
+
typeof value.attemptId === "string" &&
|
|
452
|
+
typeof value.clientId === "string" &&
|
|
453
|
+
(value.phase === "opening" ||
|
|
454
|
+
value.phase === "waiting-storage" ||
|
|
455
|
+
value.phase === "retiring")
|
|
456
|
+
);
|
|
457
|
+
case "host-ready":
|
|
458
|
+
return (
|
|
459
|
+
typeof value.attemptId === "string" &&
|
|
460
|
+
typeof value.clientId === "string" &&
|
|
461
|
+
typeof value.hostTerm === "string" &&
|
|
462
|
+
typeof value.workspaceId === "string" &&
|
|
463
|
+
typeof value.storageEpoch === "number" &&
|
|
464
|
+
typeof value.lastExclusiveEpoch === "number"
|
|
465
|
+
);
|
|
466
|
+
case "host-draining":
|
|
467
|
+
case "host-stepping-down":
|
|
468
|
+
return typeof value.attemptId === "string" && typeof value.hostTerm === "string";
|
|
469
|
+
case "host-failed":
|
|
470
|
+
return (
|
|
471
|
+
typeof value.attemptId === "string" &&
|
|
472
|
+
typeof value.clientId === "string" &&
|
|
473
|
+
typeof value.hostTerm === "string" &&
|
|
474
|
+
typeof value.workspaceId === "string"
|
|
475
|
+
);
|
|
476
|
+
case "cooperative-step-down":
|
|
477
|
+
return typeof value.targetAttemptId === "string" && typeof value.targetTerm === "string";
|
|
478
|
+
case "external-takeover":
|
|
479
|
+
return (
|
|
480
|
+
typeof value.attemptId === "string" &&
|
|
481
|
+
typeof value.hostTerm === "string" &&
|
|
482
|
+
typeof value.workspaceId === "string" &&
|
|
483
|
+
typeof value.lastExclusiveEpoch === "number" &&
|
|
484
|
+
typeof value.affectedEpoch === "number"
|
|
485
|
+
);
|
|
486
|
+
case "workspace-replaced":
|
|
487
|
+
return typeof value.workspaceId === "string" && typeof value.expectedWorkspaceId === "string";
|
|
488
|
+
case "attach":
|
|
489
|
+
return (
|
|
490
|
+
typeof value.peerId === "string" &&
|
|
491
|
+
typeof value.sessionId === "string" &&
|
|
492
|
+
typeof value.hostTerm === "string"
|
|
493
|
+
);
|
|
494
|
+
default:
|
|
495
|
+
return false;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function isValidCreditLimit(value: unknown): value is PeerCreditLimit {
|
|
500
|
+
return (
|
|
501
|
+
isObject(value) &&
|
|
502
|
+
typeof value.frames === "number" &&
|
|
503
|
+
Number.isInteger(value.frames) &&
|
|
504
|
+
value.frames >= 0 &&
|
|
505
|
+
typeof value.bytes === "number" &&
|
|
506
|
+
Number.isInteger(value.bytes) &&
|
|
507
|
+
value.bytes >= 0
|
|
508
|
+
);
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
export function isPeerMessage(value: unknown): value is PeerMessage {
|
|
512
|
+
if (
|
|
513
|
+
!isObject(value) ||
|
|
514
|
+
typeof value.kind !== "string" ||
|
|
515
|
+
typeof value.hostTerm !== "string" ||
|
|
516
|
+
typeof value.sessionId !== "string"
|
|
517
|
+
)
|
|
518
|
+
return false;
|
|
519
|
+
switch (value.kind) {
|
|
520
|
+
case "attached":
|
|
521
|
+
case "credit-limit":
|
|
522
|
+
return isValidCreditLimit(value.creditLimit);
|
|
523
|
+
case "attach-rejected":
|
|
524
|
+
return typeof value.errno === "number";
|
|
525
|
+
case "req":
|
|
526
|
+
return (
|
|
527
|
+
typeof value.reqId === "number" && typeof value.op === "string" && Array.isArray(value.args)
|
|
528
|
+
);
|
|
529
|
+
case "chunk-put":
|
|
530
|
+
return (
|
|
531
|
+
typeof value.reqId === "number" &&
|
|
532
|
+
typeof value.uploadId === "string" &&
|
|
533
|
+
typeof value.offset === "number" &&
|
|
534
|
+
typeof value.totalBytes === "number" &&
|
|
535
|
+
value.chunk instanceof Uint8Array
|
|
536
|
+
);
|
|
537
|
+
case "chunk-get":
|
|
538
|
+
return (
|
|
539
|
+
typeof value.reqId === "number" &&
|
|
540
|
+
typeof value.downloadId === "string" &&
|
|
541
|
+
typeof value.offset === "number" &&
|
|
542
|
+
typeof value.length === "number"
|
|
543
|
+
);
|
|
544
|
+
case "res":
|
|
545
|
+
return typeof value.reqId === "number" && typeof value.ok === "boolean";
|
|
546
|
+
case "ping":
|
|
547
|
+
return typeof value.pingId === "number" && typeof value.latestAckedWakeSeq === "number";
|
|
548
|
+
case "pong":
|
|
549
|
+
return (
|
|
550
|
+
typeof value.pingId === "number" &&
|
|
551
|
+
Array.isArray(value.activeReqIds) &&
|
|
552
|
+
typeof value.latestWakeSeq === "number" &&
|
|
553
|
+
isValidCreditLimit(value.creditLimit) &&
|
|
554
|
+
(value.hostState === "ready" ||
|
|
555
|
+
value.hostState === "draining" ||
|
|
556
|
+
value.hostState === "failed")
|
|
557
|
+
);
|
|
558
|
+
case "watch-wake":
|
|
559
|
+
case "watch-wake-ack":
|
|
560
|
+
return typeof value.wakeSeq === "number";
|
|
561
|
+
case "watch-ack":
|
|
562
|
+
return typeof value.ackId === "number" && typeof value.accepted === "boolean";
|
|
563
|
+
case "unpin":
|
|
564
|
+
return typeof value.pinToken === "number";
|
|
565
|
+
case "watch-close":
|
|
566
|
+
return typeof value.hostWatchId === "number";
|
|
567
|
+
case "settled":
|
|
568
|
+
case "detach":
|
|
569
|
+
return true;
|
|
570
|
+
default:
|
|
571
|
+
return false;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
const wireEncoder = new TextEncoder();
|
|
576
|
+
|
|
577
|
+
/** Incremental wire-byte builder that charges actual UTF-8 encoded JSON bytes in 64 KiB slabs
|
|
578
|
+
* against the Host's staged download budget BEFORE allocating the final contiguous buffer. */
|
|
579
|
+
export class BoundedWireBuilder {
|
|
580
|
+
private readonly chunks: Uint8Array[] = [];
|
|
581
|
+
private totalBytes = 0;
|
|
582
|
+
private reservedBytes = 0;
|
|
583
|
+
private finished = false;
|
|
584
|
+
constructor(
|
|
585
|
+
private readonly hardCapBytes: number,
|
|
586
|
+
private readonly reserveSlab: (deltaBytes: number) => boolean,
|
|
587
|
+
private readonly releaseAll: (bytes: number) => void,
|
|
588
|
+
) {}
|
|
589
|
+
appendText(text: string): void {
|
|
590
|
+
this.appendBytes(wireEncoder.encode(text));
|
|
591
|
+
}
|
|
592
|
+
appendPacked(value: unknown): void {
|
|
593
|
+
this.appendBytes(pack(value));
|
|
594
|
+
}
|
|
595
|
+
appendBytes(chunk: Uint8Array): void {
|
|
596
|
+
if (!chunk.byteLength) return;
|
|
597
|
+
const nextTotal = this.totalBytes + chunk.byteLength;
|
|
598
|
+
if (nextTotal > this.hardCapBytes) {
|
|
599
|
+
this.abort();
|
|
600
|
+
throw new FilesystemError(22, "wire response exceeds download cap");
|
|
601
|
+
}
|
|
602
|
+
if (nextTotal > this.reservedBytes) {
|
|
603
|
+
const target = Math.min(
|
|
604
|
+
this.hardCapBytes,
|
|
605
|
+
Math.ceil(nextTotal / WIRE_BUDGET_SLAB_BYTES) * WIRE_BUDGET_SLAB_BYTES,
|
|
606
|
+
);
|
|
607
|
+
const delta = target - this.reservedBytes;
|
|
608
|
+
if (!this.reserveSlab(delta)) {
|
|
609
|
+
this.abort();
|
|
610
|
+
throw new FilesystemError(6, "staged download pool exhausted");
|
|
611
|
+
}
|
|
612
|
+
this.reservedBytes = target;
|
|
613
|
+
}
|
|
614
|
+
this.chunks.push(chunk);
|
|
615
|
+
this.totalBytes = nextTotal;
|
|
616
|
+
}
|
|
617
|
+
/** Assemble the exact wire buffer and return the currently reserved budget bytes. */
|
|
618
|
+
finish(): { bytes: Uint8Array<ArrayBuffer>; reservedBytes: number } {
|
|
619
|
+
this.finished = true;
|
|
620
|
+
const out = new Uint8Array(this.totalBytes);
|
|
621
|
+
let offset = 0;
|
|
622
|
+
for (const chunk of this.chunks) {
|
|
623
|
+
out.set(chunk, offset);
|
|
624
|
+
offset += chunk.byteLength;
|
|
625
|
+
}
|
|
626
|
+
this.chunks.length = 0;
|
|
627
|
+
return { bytes: out, reservedBytes: this.reservedBytes };
|
|
628
|
+
}
|
|
629
|
+
abort(): void {
|
|
630
|
+
if (this.finished) return;
|
|
631
|
+
this.finished = true;
|
|
632
|
+
this.chunks.length = 0;
|
|
633
|
+
if (this.reservedBytes > 0) {
|
|
634
|
+
const bytes = this.reservedBytes;
|
|
635
|
+
this.reservedBytes = 0;
|
|
636
|
+
this.releaseAll(bytes);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
export interface BroadcastChannelLike {
|
|
642
|
+
onmessage: ((event: MessageEvent) => void) | null;
|
|
643
|
+
onmessageerror: ((event: MessageEvent) => void) | null;
|
|
644
|
+
postMessage(message: unknown): void;
|
|
645
|
+
close(): void;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
export interface LockManagerLike {
|
|
649
|
+
request<T>(
|
|
650
|
+
name: string,
|
|
651
|
+
optionsOrCallback: LockOptions | ((lock: Lock | null) => T | Promise<T>),
|
|
652
|
+
callback?: (lock: Lock | null) => T | Promise<T>,
|
|
653
|
+
): Promise<T>;
|
|
654
|
+
query(): Promise<LockManagerSnapshot>;
|
|
655
|
+
}
|
package/fs/opfs.ts
CHANGED
|
@@ -173,6 +173,7 @@ export class OpfsStorage implements StorageBackend {
|
|
|
173
173
|
private handles = new Map<string, SyncAccess>();
|
|
174
174
|
private owned = new Map<SyncAccess, AccessOwnership>();
|
|
175
175
|
private failedClose?: FailedClose;
|
|
176
|
+
private terminalFailureListener?: (reason: unknown) => void;
|
|
176
177
|
private peakHandles = 0;
|
|
177
178
|
private garbage = new Set<string>();
|
|
178
179
|
private needsOrphanSweep = true;
|
|
@@ -581,6 +582,20 @@ export class OpfsStorage implements StorageBackend {
|
|
|
581
582
|
const result = this.closeResult(access);
|
|
582
583
|
if (result.kind === "failed-close") throw result.reason;
|
|
583
584
|
}
|
|
585
|
+
isTerminallyFailed(): boolean {
|
|
586
|
+
return this.failedClose !== undefined;
|
|
587
|
+
}
|
|
588
|
+
terminalFailureReason(): unknown {
|
|
589
|
+
return this.failedClose?.reason;
|
|
590
|
+
}
|
|
591
|
+
setTerminalFailureListener(listener: (reason: unknown) => void): void {
|
|
592
|
+
this.terminalFailureListener = listener;
|
|
593
|
+
if (this.failedClose !== undefined) {
|
|
594
|
+
try {
|
|
595
|
+
listener(this.failedClose.reason);
|
|
596
|
+
} catch {}
|
|
597
|
+
}
|
|
598
|
+
}
|
|
584
599
|
private closeResult(access: SyncAccess): CloseOutcome {
|
|
585
600
|
const previous = this.owned.get(access);
|
|
586
601
|
if (previous?.kind === "failed-close") return previous;
|
|
@@ -589,8 +604,14 @@ export class OpfsStorage implements StorageBackend {
|
|
|
589
604
|
} catch (reason) {
|
|
590
605
|
const failure: FailedClose = { kind: "failed-close", reason };
|
|
591
606
|
this.owned.set(access, failure);
|
|
607
|
+
const first = this.failedClose === undefined;
|
|
592
608
|
this.failedClose ??= failure;
|
|
593
609
|
this.closed = true;
|
|
610
|
+
if (first) {
|
|
611
|
+
try {
|
|
612
|
+
this.terminalFailureListener?.(reason);
|
|
613
|
+
} catch {}
|
|
614
|
+
}
|
|
594
615
|
return failure;
|
|
595
616
|
}
|
|
596
617
|
this.owned.delete(access);
|