@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.
Files changed (48) hide show
  1. package/browser/filesystem-backend.ts +26 -5
  2. package/browser/fs-worker.ts +5 -2
  3. package/browser/shared-fs.ts +93 -10
  4. package/core/filesystem.ts +2 -0
  5. package/dist/browser/filesystem-backend.js +19 -2
  6. package/dist/browser/fs-worker.js +7 -2
  7. package/dist/browser/shared-fs.js +77 -8
  8. package/dist/fs/client.js +82 -21
  9. package/dist/fs/directory-pages.js +22 -7
  10. package/dist/fs/guest-watch.js +9 -3
  11. package/dist/fs/idle-database.js +1 -1
  12. package/dist/fs/idle-owner.js +35 -4
  13. package/dist/fs/indexeddb.js +322 -63
  14. package/dist/fs/memory.js +18 -9
  15. package/dist/fs/multitab-backend.js +5065 -0
  16. package/dist/fs/multitab-protocol.js +301 -0
  17. package/dist/fs/opfs.js +21 -0
  18. package/dist/fs/persistent.js +70 -1
  19. package/dist/fs/protocol.js +1 -1
  20. package/dist/fs/service.js +266 -86
  21. package/dist/fs/shared.js +45 -0
  22. package/dist/fs/vfs.js +26 -8
  23. package/dist/fs/watch-ring.js +7 -3
  24. package/dist/proc/command-stdio.js +56 -1
  25. package/dist/runtime.js +4 -2
  26. package/dist/tooling/program/program-transformer.json +1 -1
  27. package/fs/backend.ts +36 -0
  28. package/fs/client.ts +81 -19
  29. package/fs/directory-pages.ts +40 -6
  30. package/fs/guest-watch.ts +8 -3
  31. package/fs/idle-database.ts +1 -0
  32. package/fs/idle-owner.ts +48 -12
  33. package/fs/indexeddb.ts +396 -78
  34. package/fs/memory.ts +33 -9
  35. package/fs/multitab-backend.ts +6870 -0
  36. package/fs/multitab-protocol.ts +655 -0
  37. package/fs/opfs.ts +21 -0
  38. package/fs/persistent.ts +70 -1
  39. package/fs/protocol.ts +1 -1
  40. package/fs/service.ts +314 -109
  41. package/fs/shared.ts +45 -0
  42. package/fs/storage.ts +3 -0
  43. package/fs/vfs.ts +44 -15
  44. package/fs/watch-ring.ts +5 -2
  45. package/package.json +1 -1
  46. package/proc/command-stdio.ts +72 -2
  47. package/runtime.ts +12 -3
  48. package/tooling/program/program-transformer.json +1 -1
package/fs/shared.ts CHANGED
@@ -80,6 +80,9 @@ const REGISTERED_SLOTS = 11;
80
80
  const PHYSICAL_HINT = 27;
81
81
  const TABLE_HINT = 28;
82
82
  const PINNED_PAGES = 29;
83
+ export const CLIENT_MODE = 30;
84
+ export const CLIENT_MODE_NO_DIRECT_IO = 1;
85
+ export const CLIENT_MODE_NO_CLIENT_CACHE = 2;
83
86
  const MODE = 12;
84
87
  const FILE_SIZE = 1;
85
88
  // File times are unsigned 64-bit nanoseconds in two words each, starting on an even word.
@@ -282,6 +285,48 @@ export class SharedFilesystemState {
282
285
  readerPinBytes(): number {
283
286
  return this.pageReaders ? this.cells[PINNED_PAGES]! * DATA_PAGE_BYTES : 0;
284
287
  }
288
+ setClientMode(mode: number): void {
289
+ Atomics.store(this.cells, CLIENT_MODE, mode | 0);
290
+ }
291
+ isDirectDisabled(): boolean {
292
+ return (Atomics.load(this.cells, CLIENT_MODE) & CLIENT_MODE_NO_DIRECT_IO) !== 0;
293
+ }
294
+ isClientCacheDisabled(): boolean {
295
+ return (Atomics.load(this.cells, CLIENT_MODE) & CLIENT_MODE_NO_CLIENT_CACHE) !== 0;
296
+ }
297
+ /** Reset all per-mount filesystem state in place across Host remount/demotion while preserving
298
+ * tab-lifetime header invariants (`MAGIC`, `maxSegments`, owner/probe words, `WATCH_OFFSET`,
299
+ * `watch.cells[3]`, `CLIENT_MODE`) and reusing tab-lifetime segments at their exact indexes. */
300
+ resetForRemount(retainedSegments: readonly (SharedArrayBuffer | undefined)[] = []): void {
301
+ Atomics.store(this.cells, GLOBAL_LOCK, 0);
302
+ Atomics.store(this.cells, USED_PAGES, 0);
303
+ for (let i = 7; i <= 25; i++) Atomics.store(this.cells, i, 0);
304
+ Atomics.store(this.cells, PHYSICAL_HINT, 0);
305
+ Atomics.store(this.cells, TABLE_HINT, 0);
306
+ Atomics.store(this.cells, PINNED_PAGES, 0);
307
+ for (let i = 32; i < HEADER_WORDS; i++) Atomics.store(this.cells, i, 0);
308
+ this.owners.fill(0);
309
+ this.slots.fill(0);
310
+ this.tableOwners.fill(0);
311
+ this.pages.fill(0);
312
+ this.firstBytes.fill(0);
313
+ this.pageViews.length = 0;
314
+ this.pendingSegments.length = 0;
315
+ this.staged.clear();
316
+ this.serviceMutation = false;
317
+ this.globalOwner = undefined;
318
+ this.globalDepth = 0;
319
+ this.fileOwnsGlobal.clear();
320
+ this.currentOwner = undefined;
321
+ this.segments.length = 1;
322
+ this.segments[0] = this.buffer;
323
+ for (let i = 0; i < retainedSegments.length; i++) {
324
+ const seg = retainedSegments[i];
325
+ if (!seg) continue;
326
+ new Uint8Array(seg).fill(0);
327
+ this.segments[i + 1] = seg;
328
+ }
329
+ }
285
330
  private releaseVersionPages(pages: Uint32Array): void {
286
331
  this.globalLock(undefined, this.lockOwner, false, "release");
287
332
  try {
package/fs/storage.ts CHANGED
@@ -108,6 +108,9 @@ export interface StorageBackend {
108
108
  /** Make the selected immutable payloads durable; omitted means all outstanding payloads. */
109
109
  flush(keys?: readonly string[]): Promise<void>;
110
110
  close(): Promise<void>;
111
+ isTerminallyFailed?(): boolean;
112
+ terminalFailureReason?(): unknown;
113
+ setTerminalFailureListener?(listener: (reason: unknown) => void): void;
111
114
  }
112
115
 
113
116
  export interface ChecksummedRecord {
package/fs/vfs.ts CHANGED
@@ -3,7 +3,7 @@ import type { VfsImplementation } from "./vfs-internal.js";
3
3
 
4
4
  /** @public Product guarantees, independent of the browser's physical storage adapter. */
5
5
  export type VfsMode = "fast" | "safe" | "memory";
6
- export type VfsWhenBusy = "takeover" | "wait";
6
+ export type VfsWhenBusy = "takeover" | "wait" | "attach";
7
7
  export type VfsSelection =
8
8
  | { mode?: "fast" | "safe"; whenBusy?: VfsWhenBusy }
9
9
  | { mode: "memory"; whenBusy?: never };
@@ -42,13 +42,13 @@ export interface VfsDescriptor {
42
42
  readonly fsync: "targeted-file-checkpoint" | "volatile-ordering-only";
43
43
  readonly targetedFlush: "selected-payloads-and-namespace" | "volatile-ordering-only";
44
44
  };
45
- readonly multiTab: "exclusive-owner" | "isolated";
45
+ readonly multiTab: "exclusive-owner" | "shared-host" | "isolated";
46
46
  readonly supportedWhenBusy: readonly VfsWhenBusy[];
47
47
  readonly defaultWhenBusy?: VfsWhenBusy;
48
48
  readonly requirements: readonly string[];
49
49
  readonly worker: "dedicated";
50
50
  readonly serviceMayAwait: true;
51
- readonly directSharedMemory: { readonly reads: true; readonly mutations: true };
51
+ readonly directSharedMemory: { readonly reads: boolean; readonly mutations: boolean };
52
52
  readonly format: { readonly id: string; readonly location: string } | null;
53
53
  readonly unsupportedSettings: readonly string[];
54
54
  readonly lifecycle: readonly ("opening" | "waiting" | "ready" | "failed" | "disposed")[];
@@ -79,7 +79,7 @@ const descriptors: Record<VfsImplementation, VfsDescriptor> = {
79
79
  ...persistent,
80
80
  implementation: "indexeddb",
81
81
  displayName: "FAST (IndexedDB checkpoints)",
82
- supportedWhenBusy: Object.freeze(["takeover", "wait"] as const),
82
+ supportedWhenBusy: Object.freeze(["takeover", "wait", "attach"] as const),
83
83
  defaultWhenBusy: "takeover",
84
84
  requirements: Object.freeze(requirements.concat(["IndexedDB", "Web Locks"])),
85
85
  format: Object.freeze({
@@ -92,7 +92,7 @@ const descriptors: Record<VfsImplementation, VfsDescriptor> = {
92
92
  ...persistent,
93
93
  implementation: "opfs-memory",
94
94
  displayName: "FAST (OPFS checkpoints)",
95
- supportedWhenBusy: Object.freeze(["wait"] as const),
95
+ supportedWhenBusy: Object.freeze(["wait", "attach"] as const),
96
96
  defaultWhenBusy: "wait",
97
97
  requirements: Object.freeze(requirements.concat(["OPFS", "sync-access-handles", "Web Locks"])),
98
98
  format: Object.freeze({
@@ -124,6 +124,24 @@ const descriptors: Record<VfsImplementation, VfsDescriptor> = {
124
124
  }),
125
125
  };
126
126
 
127
+ const attachDirectSharedMemory = Object.freeze({ reads: false, mutations: false });
128
+ const attachDescriptors: Partial<Record<VfsImplementation, VfsDescriptor>> = {
129
+ indexeddb: Object.freeze({
130
+ ...descriptors.indexeddb,
131
+ multiTab: "shared-host",
132
+ directSharedMemory: attachDirectSharedMemory,
133
+ requirements: Object.freeze(descriptors.indexeddb.requirements.concat(["BroadcastChannel"])),
134
+ }),
135
+ "opfs-memory": Object.freeze({
136
+ ...descriptors["opfs-memory"],
137
+ multiTab: "shared-host",
138
+ directSharedMemory: attachDirectSharedMemory,
139
+ requirements: Object.freeze(
140
+ descriptors["opfs-memory"].requirements.concat(["BroadcastChannel"]),
141
+ ),
142
+ }),
143
+ };
144
+
127
145
  /** FAST preserves the existing IndexedDB workspace in every browser until a migration wins. */
128
146
  export function getVfsDescriptor(mode: string = "fast"): VfsDescriptor {
129
147
  if (mode === "fast") return descriptors.indexeddb;
@@ -147,10 +165,15 @@ export function resolveVfs(
147
165
  const whenBusy = options.whenBusy;
148
166
  if (whenBusy === undefined) return { descriptor, whenBusy: descriptor.defaultWhenBusy };
149
167
  if (
150
- (whenBusy === "wait" || whenBusy === "takeover") &&
168
+ (whenBusy === "wait" || whenBusy === "takeover" || whenBusy === "attach") &&
151
169
  descriptor.supportedWhenBusy.includes(whenBusy)
152
- )
153
- return { descriptor, whenBusy };
170
+ ) {
171
+ const resolved =
172
+ whenBusy === "attach"
173
+ ? (attachDescriptors[descriptor.implementation] ?? descriptor)
174
+ : descriptor;
175
+ return { descriptor: resolved, whenBusy };
176
+ }
154
177
  throw new VfsError(
155
178
  "INVALID_VFS_SETTINGS",
156
179
  descriptor.implementation,
@@ -181,16 +204,22 @@ function overrideDescriptor(selected: VfsDescriptor, implementation: unknown): V
181
204
  }
182
205
 
183
206
  /** No probe or storage mutation: only verify the APIs needed by the existing implementation. */
184
- export function requireVfsCapabilities(name: VfsImplementation): void {
207
+ export function requireVfsCapabilities(name: VfsImplementation, whenBusy?: VfsWhenBusy): void {
185
208
  if (name === "memory") return;
186
209
  const locks = globalThis.navigator?.locks;
187
210
  const hasStorage = name === "indexeddb" ? !!globalThis.indexedDB : hasOpfs();
188
- if (locks && hasStorage) return;
189
- throw new VfsError(
190
- "UNSUPPORTED_VFS_CAPABILITY",
191
- name,
192
- `${name} requires ${name === "indexeddb" ? "IndexedDB" : "OPFS sync access handles"} and Web Locks in a dedicated worker`,
193
- );
211
+ if (!locks || !hasStorage)
212
+ throw new VfsError(
213
+ "UNSUPPORTED_VFS_CAPABILITY",
214
+ name,
215
+ `${name} requires ${name === "indexeddb" ? "IndexedDB" : "OPFS sync access handles"} and Web Locks in a dedicated worker`,
216
+ );
217
+ if (whenBusy === "attach" && typeof globalThis.BroadcastChannel !== "function")
218
+ throw new VfsError(
219
+ "UNSUPPORTED_VFS_CAPABILITY",
220
+ name,
221
+ `${name} with whenBusy: "attach" requires BroadcastChannel in a dedicated worker`,
222
+ );
194
223
  }
195
224
  function hasOpfs(): boolean {
196
225
  return (
package/fs/watch-ring.ts CHANGED
@@ -36,9 +36,12 @@ export function validWatchName(name: string, maximum = WATCH_NAME_BYTES): boolea
36
36
  return true;
37
37
  }
38
38
 
39
- export function wakeFilesystemWatch(buffer: SharedArrayBuffer): void {
39
+ export function wakeFilesystemWatch(buffer: SharedArrayBuffer, advance = false): void {
40
40
  const offset = Atomics.load(new Int32Array(buffer, POINTER * 4, 1), 0);
41
- if (offset) Atomics.notify(new Int32Array(buffer, offset, 4), 3);
41
+ if (!offset) return;
42
+ const cells = new Int32Array(buffer, offset, 4);
43
+ if (advance) Atomics.add(cells, 3, 1);
44
+ Atomics.notify(cells, 3);
42
45
  }
43
46
 
44
47
  /** Appends and reads own the filesystem's global mutation lock. Waiting never does. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@waffle-os/runtime",
3
- "version": "0.0.147",
3
+ "version": "0.0.148",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/ShaulLavo/waffle.git",
@@ -1,8 +1,8 @@
1
1
  import { atomicsWaitAsync } from "./intrinsics.js";
2
2
  import type { DescriptorTable, Resource } from "../core/descriptors.js";
3
- import { withFileOffset, shareFileResource } from "../core/open-file.js";
3
+ import { claimFileOffset, withFileOffset, shareFileResource } from "../core/open-file.js";
4
4
  import { FilesystemClient } from "../fs/client.js";
5
- import type { FilesystemConnection } from "../fs/protocol.js";
5
+ import { errno, type FilesystemConnection } from "../fs/protocol.js";
6
6
  import { CommandStdioError, type CommandInput, type CommandOutput } from "./command.js";
7
7
 
8
8
  const READ = 1n << 1n;
@@ -96,6 +96,9 @@ export class CommandStdio {
96
96
  private async transfer(fd: number, bytes: Uint8Array, writing: boolean): Promise<number> {
97
97
  for (;;) {
98
98
  const resource = this.resource(fd, writing ? WRITE : READ);
99
+ if (resource.kind === "file" && this.filesystem?.shared.isDirectDisabled()) {
100
+ return await this.transferAsyncFile(resource, bytes, writing);
101
+ }
99
102
  const words = this.notifications(resource);
100
103
  const observed = words.map((word) => Atomics.load(word, 0));
101
104
  const count =
@@ -113,6 +116,73 @@ export class CommandStdio {
113
116
  }
114
117
  }
115
118
 
119
+ private async runAsyncFileLease(
120
+ filesystem: FilesystemClient,
121
+ resource: Extract<Resource, { kind: "file" }>,
122
+ lease: { readonly position: number; readonly append: boolean; commit(next: number): void },
123
+ bytes: Uint8Array,
124
+ writing: boolean,
125
+ ): Promise<number> {
126
+ if (writing && lease.append) {
127
+ const result: { written: number; offset: number } = await filesystem.asyncCall(
128
+ "append",
129
+ [resource.handle],
130
+ bytes,
131
+ );
132
+ lease.commit(result.offset);
133
+ this.check();
134
+ return result.written;
135
+ }
136
+ if (writing) {
137
+ const written: number = await filesystem.asyncCall(
138
+ "write",
139
+ [resource.handle, lease.position],
140
+ bytes,
141
+ );
142
+ if (written > 0) lease.commit(lease.position + written);
143
+ this.check();
144
+ return written;
145
+ }
146
+ const read: Uint8Array = await filesystem.asyncCall("read", [
147
+ resource.handle,
148
+ bytes.length,
149
+ lease.position,
150
+ ]);
151
+ bytes.set(read, 0);
152
+ if (read.length > 0) lease.commit(lease.position + read.length);
153
+ this.check();
154
+ return read.length;
155
+ }
156
+
157
+ private async transferAsyncFile(
158
+ resource: Extract<Resource, { kind: "file" }>,
159
+ bytes: Uint8Array,
160
+ writing: boolean,
161
+ ): Promise<number> {
162
+ const filesystem = this.filesystem;
163
+ if (!filesystem)
164
+ throw new CommandStdioError("EBADF", "File descriptor has no filesystem connection");
165
+ shareFileResource(resource, filesystem.connection);
166
+ for (;;) {
167
+ this.check();
168
+ const claim = claimFileOffset(resource);
169
+ if (claim.kind === "failed") throw stdioError(-claim.errno);
170
+ if (claim.kind === "busy") {
171
+ await this.wait([claim.word], [claim.observed]);
172
+ continue;
173
+ }
174
+ const { lease } = claim;
175
+ try {
176
+ return await this.runAsyncFileLease(filesystem, resource, lease, bytes, writing);
177
+ } catch (error) {
178
+ if (error instanceof CommandStdioError) throw error;
179
+ throw stdioError(-errno(error));
180
+ } finally {
181
+ lease.release();
182
+ }
183
+ }
184
+ }
185
+
116
186
  private notifications(resource: Resource): Int32Array[] {
117
187
  if (resource.kind !== "file")
118
188
  return resource.kind === "directory"
package/runtime.ts CHANGED
@@ -103,7 +103,12 @@ export interface RuntimeConsumer {
103
103
  /** Filesystem authority is borrowed. Only the page runtime can close its service. */
104
104
  export type RuntimeFilesystem = Omit<
105
105
  SharedFilesystem,
106
- "client" | "dispose" | "attachSocketScope" | "connectObserved"
106
+ | "client"
107
+ | "dispose"
108
+ | "attachSocketScope"
109
+ | "connectObserved"
110
+ | "beginRuntimeDispose"
111
+ | "ownershipRetained"
107
112
  >;
108
113
  export type RuntimeSupervisor = Omit<
109
114
  ProcessSupervisor,
@@ -946,7 +951,10 @@ export function createRuntime(options: RuntimeOptions = {}): Runtime {
946
951
  // A controller may be awaiting an adapter's launch handle when suspension wins.
947
952
  // Its late handle and asynchronous stop still belong to this page, not the next owner.
948
953
  while (launching.size) await Promise.allSettled(Array.from(launching));
949
- if (!pendingStartup) await attempt(() => filesystem.drain());
954
+ if (!pendingStartup) {
955
+ filesystem.beginRuntimeDispose();
956
+ await attempt(() => filesystem.drain());
957
+ }
950
958
  // Keep the backend and relays alive while every admitted filesystem request fences.
951
959
  const failuresBeforeFences = failures.length;
952
960
  await Promise.all(
@@ -992,7 +1000,8 @@ export function createRuntime(options: RuntimeOptions = {}): Runtime {
992
1000
  consumers.clear();
993
1001
  const failuresBeforeFilesystemClose = failures.length;
994
1002
  await attempt(() => filesystem.dispose());
995
- if (failures.length !== failuresBeforeFilesystemClose) throwFailures();
1003
+ if (failures.length !== failuresBeforeFilesystemClose && filesystem.ownershipRetained())
1004
+ throwFailures();
996
1005
  reservations.dispose();
997
1006
  restoreControlAllocator();
998
1007
  adapters.clear();
@@ -1 +1 @@
1
- {"commit":"4151b800bf27e8211403d0da3e32358cd9fd4c9a","buildToolsSha256":"b617652c1601f8722bb85c3a688a1fca4985b53f2c2066c10c76c2e693081137","optimizerSourceSha256":"34c4a040f3cf639f039823880822c6541c384c9b4eaa116d27dda8d9cb5c9f9e"}
1
+ {"commit":"c59d4f248e1599698741db0825cd16c3ed970e9b","buildToolsSha256":"b617652c1601f8722bb85c3a688a1fca4985b53f2c2066c10c76c2e693081137","optimizerSourceSha256":"34c4a040f3cf639f039823880822c6541c384c9b4eaa116d27dda8d9cb5c9f9e"}