@waffle-os/runtime 0.0.147 → 0.0.149

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 (58) hide show
  1. package/browser/filesystem-backend.ts +26 -5
  2. package/browser/fs-worker.ts +5 -2
  3. package/browser/process-broker.ts +6 -3
  4. package/browser/run-command.ts +18 -7
  5. package/browser/shared-fs.ts +93 -10
  6. package/core/filesystem.ts +2 -0
  7. package/dist/browser/filesystem-backend.js +19 -2
  8. package/dist/browser/fs-worker.js +7 -2
  9. package/dist/browser/process-broker.js +3 -2
  10. package/dist/browser/run-command.js +8 -2
  11. package/dist/browser/shared-fs.js +77 -8
  12. package/dist/fs/client.js +82 -21
  13. package/dist/fs/directory-pages.js +22 -7
  14. package/dist/fs/guest-watch.js +9 -3
  15. package/dist/fs/idle-database.js +1 -1
  16. package/dist/fs/idle-owner.js +35 -4
  17. package/dist/fs/indexeddb.js +322 -63
  18. package/dist/fs/memory.js +18 -9
  19. package/dist/fs/multitab-backend.js +5065 -0
  20. package/dist/fs/multitab-protocol.js +301 -0
  21. package/dist/fs/opfs.js +21 -0
  22. package/dist/fs/persistent.js +70 -1
  23. package/dist/fs/protocol.js +1 -1
  24. package/dist/fs/service.js +266 -86
  25. package/dist/fs/shared.js +45 -0
  26. package/dist/fs/vfs.js +26 -8
  27. package/dist/fs/watch-ring.js +7 -3
  28. package/dist/proc/command-stdio.js +56 -1
  29. package/dist/proc/registry.js +8 -8
  30. package/dist/proc/start-command.js +10 -0
  31. package/dist/proc/supervisor.js +4 -4
  32. package/dist/runtime.js +4 -2
  33. package/dist/tooling/program/program-transformer.json +1 -1
  34. package/fs/backend.ts +36 -0
  35. package/fs/client.ts +81 -19
  36. package/fs/directory-pages.ts +40 -6
  37. package/fs/guest-watch.ts +8 -3
  38. package/fs/idle-database.ts +1 -0
  39. package/fs/idle-owner.ts +48 -12
  40. package/fs/indexeddb.ts +396 -78
  41. package/fs/memory.ts +33 -9
  42. package/fs/multitab-backend.ts +6870 -0
  43. package/fs/multitab-protocol.ts +655 -0
  44. package/fs/opfs.ts +21 -0
  45. package/fs/persistent.ts +70 -1
  46. package/fs/protocol.ts +1 -1
  47. package/fs/service.ts +314 -109
  48. package/fs/shared.ts +45 -0
  49. package/fs/storage.ts +3 -0
  50. package/fs/vfs.ts +44 -15
  51. package/fs/watch-ring.ts +5 -2
  52. package/package.json +1 -1
  53. package/proc/command-stdio.ts +72 -2
  54. package/proc/registry.ts +13 -19
  55. package/proc/start-command.ts +29 -0
  56. package/proc/supervisor.ts +8 -6
  57. package/runtime.ts +12 -3
  58. package/tooling/program/program-transformer.json +1 -1
package/dist/fs/vfs.js CHANGED
@@ -34,7 +34,7 @@ const descriptors = {
34
34
  ...persistent,
35
35
  implementation: "indexeddb",
36
36
  displayName: "FAST (IndexedDB checkpoints)",
37
- supportedWhenBusy: Object.freeze(["takeover", "wait"]),
37
+ supportedWhenBusy: Object.freeze(["takeover", "wait", "attach"]),
38
38
  defaultWhenBusy: "takeover",
39
39
  requirements: Object.freeze(requirements.concat(["IndexedDB", "Web Locks"])),
40
40
  format: Object.freeze({
@@ -47,7 +47,7 @@ const descriptors = {
47
47
  ...persistent,
48
48
  implementation: "opfs-memory",
49
49
  displayName: "FAST (OPFS checkpoints)",
50
- supportedWhenBusy: Object.freeze(["wait"]),
50
+ supportedWhenBusy: Object.freeze(["wait", "attach"]),
51
51
  defaultWhenBusy: "wait",
52
52
  requirements: Object.freeze(requirements.concat(["OPFS", "sync-access-handles", "Web Locks"])),
53
53
  format: Object.freeze({
@@ -78,6 +78,21 @@ const descriptors = {
78
78
  lifecycle: Object.freeze(["opening", "ready", "failed", "disposed"])
79
79
  })
80
80
  };
81
+ const attachDirectSharedMemory = Object.freeze({ reads: false, mutations: false });
82
+ const attachDescriptors = {
83
+ indexeddb: Object.freeze({
84
+ ...descriptors.indexeddb,
85
+ multiTab: "shared-host",
86
+ directSharedMemory: attachDirectSharedMemory,
87
+ requirements: Object.freeze(descriptors.indexeddb.requirements.concat(["BroadcastChannel"]))
88
+ }),
89
+ "opfs-memory": Object.freeze({
90
+ ...descriptors["opfs-memory"],
91
+ multiTab: "shared-host",
92
+ directSharedMemory: attachDirectSharedMemory,
93
+ requirements: Object.freeze(descriptors["opfs-memory"].requirements.concat(["BroadcastChannel"]))
94
+ })
95
+ };
81
96
  export function getVfsDescriptor(mode = "fast") {
82
97
  if (mode === "fast")
83
98
  return descriptors.indexeddb;
@@ -93,8 +108,10 @@ export function resolveVfs(options, implementation) {
93
108
  const whenBusy = options.whenBusy;
94
109
  if (whenBusy === undefined)
95
110
  return { descriptor, whenBusy: descriptor.defaultWhenBusy };
96
- if ((whenBusy === "wait" || whenBusy === "takeover") && descriptor.supportedWhenBusy.includes(whenBusy))
97
- return { descriptor, whenBusy };
111
+ if ((whenBusy === "wait" || whenBusy === "takeover" || whenBusy === "attach") && descriptor.supportedWhenBusy.includes(whenBusy)) {
112
+ const resolved = whenBusy === "attach" ? attachDescriptors[descriptor.implementation] ?? descriptor : descriptor;
113
+ return { descriptor: resolved, whenBusy };
114
+ }
98
115
  throw new VfsError("INVALID_VFS_SETTINGS", descriptor.implementation, `${descriptor.implementation} does not support whenBusy: ${String(whenBusy)}`);
99
116
  }
100
117
  function overrideDescriptor(selected, implementation) {
@@ -107,14 +124,15 @@ function overrideDescriptor(selected, implementation) {
107
124
  throw new VfsError("INVALID_VFS_SETTINGS", implementation, "Implementation does not implement the selected mode");
108
125
  return descriptor;
109
126
  }
110
- export function requireVfsCapabilities(name) {
127
+ export function requireVfsCapabilities(name, whenBusy) {
111
128
  if (name === "memory")
112
129
  return;
113
130
  const locks = globalThis.navigator?.locks;
114
131
  const hasStorage = name === "indexeddb" ? !!globalThis.indexedDB : hasOpfs();
115
- if (locks && hasStorage)
116
- return;
117
- throw new VfsError("UNSUPPORTED_VFS_CAPABILITY", name, `${name} requires ${name === "indexeddb" ? "IndexedDB" : "OPFS sync access handles"} and Web Locks in a dedicated worker`);
132
+ if (!locks || !hasStorage)
133
+ throw new VfsError("UNSUPPORTED_VFS_CAPABILITY", name, `${name} requires ${name === "indexeddb" ? "IndexedDB" : "OPFS sync access handles"} and Web Locks in a dedicated worker`);
134
+ if (whenBusy === "attach" && typeof globalThis.BroadcastChannel !== "function")
135
+ throw new VfsError("UNSUPPORTED_VFS_CAPABILITY", name, `${name} with whenBusy: "attach" requires BroadcastChannel in a dedicated worker`);
118
136
  }
119
137
  function hasOpfs() {
120
138
  return typeof globalThis.navigator?.storage?.getDirectory === "function" && typeof FileSystemFileHandle !== "undefined" && typeof FileSystemFileHandle.prototype.createSyncAccessHandle === "function";
@@ -27,10 +27,14 @@ export function validWatchName(name, maximum = WATCH_NAME_BYTES) {
27
27
  }
28
28
  return true;
29
29
  }
30
- export function wakeFilesystemWatch(buffer) {
30
+ export function wakeFilesystemWatch(buffer, advance = false) {
31
31
  const offset = Atomics.load(new Int32Array(buffer, POINTER * 4, 1), 0);
32
- if (offset)
33
- Atomics.notify(new Int32Array(buffer, offset, 4), 3);
32
+ if (!offset)
33
+ return;
34
+ const cells = new Int32Array(buffer, offset, 4);
35
+ if (advance)
36
+ Atomics.add(cells, 3, 1);
37
+ Atomics.notify(cells, 3);
34
38
  }
35
39
 
36
40
  export class WatchRing {
@@ -1,6 +1,7 @@
1
1
  import { atomicsWaitAsync } from "./intrinsics.js";
2
- import { withFileOffset, shareFileResource } from "../core/open-file.js";
2
+ import { claimFileOffset, withFileOffset, shareFileResource } from "../core/open-file.js";
3
3
  import { FilesystemClient } from "../fs/client.js";
4
+ import { errno } from "../fs/protocol.js";
4
5
  import { CommandStdioError } from "./command.js";
5
6
  const READ = 1n << 1n;
6
7
  const WRITE = 1n << 6n;
@@ -88,6 +89,9 @@ export class CommandStdio {
88
89
  async transfer(fd, bytes, writing) {
89
90
  for (;; ) {
90
91
  const resource = this.resource(fd, writing ? WRITE : READ);
92
+ if (resource.kind === "file" && this.filesystem?.shared.isDirectDisabled()) {
93
+ return await this.transferAsyncFile(resource, bytes, writing);
94
+ }
91
95
  const words = this.notifications(resource);
92
96
  const observed = words.map((word) => Atomics.load(word, 0));
93
97
  const count = resource.kind === "file" ? this.file(resource, bytes, writing) : writing ? resource.tryWrite?.([bytes]) : resource.tryRead?.([bytes]);
@@ -103,6 +107,57 @@ export class CommandStdio {
103
107
  await this.wait(words, observed);
104
108
  }
105
109
  }
110
+ async runAsyncFileLease(filesystem, resource, lease, bytes, writing) {
111
+ if (writing && lease.append) {
112
+ const result = await filesystem.asyncCall("append", [resource.handle], bytes);
113
+ lease.commit(result.offset);
114
+ this.check();
115
+ return result.written;
116
+ }
117
+ if (writing) {
118
+ const written = await filesystem.asyncCall("write", [resource.handle, lease.position], bytes);
119
+ if (written > 0)
120
+ lease.commit(lease.position + written);
121
+ this.check();
122
+ return written;
123
+ }
124
+ const read = await filesystem.asyncCall("read", [
125
+ resource.handle,
126
+ bytes.length,
127
+ lease.position
128
+ ]);
129
+ bytes.set(read, 0);
130
+ if (read.length > 0)
131
+ lease.commit(lease.position + read.length);
132
+ this.check();
133
+ return read.length;
134
+ }
135
+ async transferAsyncFile(resource, bytes, writing) {
136
+ const filesystem = this.filesystem;
137
+ if (!filesystem)
138
+ throw new CommandStdioError("EBADF", "File descriptor has no filesystem connection");
139
+ shareFileResource(resource, filesystem.connection);
140
+ for (;; ) {
141
+ this.check();
142
+ const claim = claimFileOffset(resource);
143
+ if (claim.kind === "failed")
144
+ throw stdioError(-claim.errno);
145
+ if (claim.kind === "busy") {
146
+ await this.wait([claim.word], [claim.observed]);
147
+ continue;
148
+ }
149
+ const { lease } = claim;
150
+ try {
151
+ return await this.runAsyncFileLease(filesystem, resource, lease, bytes, writing);
152
+ } catch (error) {
153
+ if (error instanceof CommandStdioError)
154
+ throw error;
155
+ throw stdioError(-errno(error));
156
+ } finally {
157
+ lease.release();
158
+ }
159
+ }
160
+ }
106
161
  notifications(resource) {
107
162
  if (resource.kind !== "file")
108
163
  return resource.kind === "directory" ? [] : resource.notification ? [resource.notification] : [];
@@ -70,8 +70,8 @@ export class ExecutableRegistry {
70
70
  async check(name, cwd = "/", assertActive = () => {}) {
71
71
  return (await this.admit(name, cwd, assertActive, undefined, "access")).entry;
72
72
  }
73
- async resolve(name, cwd = "/", assertActive = () => {}, argv, byteBackedGuestOnly = false) {
74
- const admitted = await this.admit(name, cwd, assertActive, argv, byteBackedGuestOnly ? "byte-backed-guest" : "execute");
73
+ async resolve(name, cwd = "/", assertActive = () => {}, argv, commandPrograms) {
74
+ const admitted = await this.admit(name, cwd, assertActive, argv, commandPrograms ?? "execute");
75
75
  const entry = admitted.entry;
76
76
  assertActive();
77
77
  if ("command" in entry)
@@ -175,8 +175,8 @@ export class ExecutableRegistry {
175
175
  return this.admitScript(target.startsWith("/") ? target : `${dirname(file.path)}/${target}`, cwd, assertActive, argv, mode, depth, seen, symlinks + 1, scriptName);
176
176
  }
177
177
  const resolved = file.path === predicted ? registered : this.entries.get(file.path);
178
- if (mode === "byte-backed-guest")
179
- return this.admitByteBackedGuest(file.kind === "file" ? resolved : undefined, file.path, argv);
178
+ if (mode === "byte-backed" || mode === "guest")
179
+ return this.admitGuest(file.kind === "file" ? resolved : undefined, file.path, argv, mode);
180
180
  const admitted = resolved && !(("command" in resolved) && resolved.command.marker && !await this.matchesMarker(absolute, resolved.command.marker));
181
181
  assertActive();
182
182
  if (admitted && resolved && file.kind === "file")
@@ -210,8 +210,8 @@ export class ExecutableRegistry {
210
210
  }
211
211
  }
212
212
  async admitEntry(entry, path, cwd, assertActive, argv, mode, depth, seen, symlinks, scriptName) {
213
- if (mode === "byte-backed-guest")
214
- return this.admitByteBackedGuest(entry, path, argv);
213
+ if (mode === "byte-backed" || mode === "guest")
214
+ return this.admitGuest(entry, path, argv, mode);
215
215
  if (!entry)
216
216
  throw new ExecutableNotFound(path);
217
217
  if ("script" in entry)
@@ -220,8 +220,8 @@ export class ExecutableRegistry {
220
220
  this.checkCommand(entry.command);
221
221
  return { entry, ...argv ? { argv } : {} };
222
222
  }
223
- admitByteBackedGuest(entry, path, argv) {
224
- if (!entry || "script" in entry || "command" in entry || !entry.interruptible || entry.execution?.kind !== "guest")
223
+ admitGuest(entry, path, argv, programs) {
224
+ if (!entry || "script" in entry || "command" in entry || programs === "byte-backed" && !entry.interruptible || entry.execution?.kind !== "guest")
225
225
  throw new ExecutableNotRunnable(path, false);
226
226
  return { entry, ...argv ? { argv } : {} };
227
227
  }
@@ -16,12 +16,20 @@ function output(value) {
16
16
  throw new TypeError("Command output callback must be a function");
17
17
  return { limitBytes, onChunk };
18
18
  }
19
+ function policies({ programs = "byte-backed", onLeaderExit = "join" }) {
20
+ if (programs !== "byte-backed" && programs !== "guest")
21
+ throw new TypeError('Command programs must be "byte-backed" or "guest"');
22
+ if (onLeaderExit !== "join" && onLeaderExit !== "stop")
23
+ throw new TypeError('Command onLeaderExit must be "join" or "stop"');
24
+ return { programs, onLeaderExit };
25
+ }
19
26
  function snapshot(executable, options) {
20
27
  if (options?.filesystem !== "runtime-root")
21
28
  throw new TypeError('Commands require filesystem: "runtime-root"');
22
29
  if (!path(executable))
23
30
  throw new TypeError("Command executable must be an absolute path");
24
31
  const { args, cwd = "/", env, stdin, stdout, stderr, deadlineMs } = options;
32
+ const { programs, onLeaderExit } = policies(options);
25
33
  if (!path(cwd))
26
34
  throw new TypeError("Command cwd must be an absolute path");
27
35
  if (args !== undefined && !Array.isArray(args))
@@ -42,6 +50,8 @@ function snapshot(executable, options) {
42
50
  throw new RangeError("Command deadline must be between 1 and 2147483647 ms");
43
51
  return {
44
52
  filesystem: "runtime-root",
53
+ programs,
54
+ onLeaderExit,
45
55
  args: argv,
46
56
  cwd,
47
57
  env: Object.fromEntries(entries),
@@ -627,7 +627,7 @@ export class ProcessSupervisor {
627
627
  const executable = await this.options.registry.resolve(image.request.executable, image.request.cwd, () => {
628
628
  if (record.result || record.revoked || readOutcome(record.outcome))
629
629
  throw new Error("process exited before executable admission completed");
630
- }, image.request.argv, this.options.byteBackedGuestOnly?.(record.rootPid));
630
+ }, image.request.argv, this.options.commandPrograms?.(record.rootPid));
631
631
  if (record.result || record.revoked)
632
632
  return;
633
633
  const settled = readOutcome(record.outcome);
@@ -771,7 +771,7 @@ export class ProcessSupervisor {
771
771
  };
772
772
  try {
773
773
  active();
774
- const resolved = await this.options.registry.resolve(replacement.request.executable, replacement.request.cwd, active, replacement.request.argv, this.options.byteBackedGuestOnly?.(record.rootPid));
774
+ const resolved = await this.options.registry.resolve(replacement.request.executable, replacement.request.cwd, active, replacement.request.argv, this.options.commandPrograms?.(record.rootPid));
775
775
  active();
776
776
  if (record.processKind === "thread")
777
777
  throw new ProcessError(ProcessErrno.NOTSUP, "exec requires a sole process leader");
@@ -836,7 +836,7 @@ export class ProcessSupervisor {
836
836
  return image.stopping;
837
837
  const stop = async () => {
838
838
  this.revokeImage(image);
839
- if (this.options.byteBackedGuestOnly?.(record.rootPid))
839
+ if (this.options.commandPrograms?.(record.rootPid))
840
840
  image.descriptors.dispose();
841
841
  else
842
842
  this.disposeDescriptors(image.descriptors);
@@ -1259,7 +1259,7 @@ export class ProcessSupervisor {
1259
1259
  this.safely(hook);
1260
1260
  this.revokeImage(record.image);
1261
1261
  this.disposeDescriptors(record.image.descriptors, (error) => {
1262
- if (!this.options.byteBackedGuestOnly?.(record.rootPid)) {
1262
+ if (!this.options.commandPrograms?.(record.rootPid)) {
1263
1263
  this.report(error);
1264
1264
  return;
1265
1265
  }
package/dist/runtime.js CHANGED
@@ -646,8 +646,10 @@ export function createRuntime(options = {}) {
646
646
  }
647
647
  while (launching.size)
648
648
  await Promise.allSettled(Array.from(launching));
649
- if (!pendingStartup)
649
+ if (!pendingStartup) {
650
+ filesystem.beginRuntimeDispose();
650
651
  await attempt(() => filesystem.drain());
652
+ }
651
653
  const failuresBeforeFences = failures.length;
652
654
  await Promise.all([
653
655
  attempt(() => host?.quiesce()),
@@ -684,7 +686,7 @@ export function createRuntime(options = {}) {
684
686
  consumers.clear();
685
687
  const failuresBeforeFilesystemClose = failures.length;
686
688
  await attempt(() => filesystem.dispose());
687
- if (failures.length !== failuresBeforeFilesystemClose)
689
+ if (failures.length !== failuresBeforeFilesystemClose && filesystem.ownershipRetained())
688
690
  throwFailures();
689
691
  reservations.dispose();
690
692
  restoreControlAllocator();
@@ -1 +1 @@
1
- {"commit":"4151b800bf27e8211403d0da3e32358cd9fd4c9a","buildToolsSha256":"b617652c1601f8722bb85c3a688a1fca4985b53f2c2066c10c76c2e693081137","optimizerSourceSha256":"34c4a040f3cf639f039823880822c6541c384c9b4eaa116d27dda8d9cb5c9f9e"}
1
+ {"commit":"7b0a762d210309fb18e4772f1a1cb50d96602dc1","buildToolsSha256":"b617652c1601f8722bb85c3a688a1fca4985b53f2c2066c10c76c2e693081137","optimizerSourceSha256":"34c4a040f3cf639f039823880822c6541c384c9b4eaa116d27dda8d9cb5c9f9e"}
package/fs/backend.ts CHANGED
@@ -30,6 +30,42 @@ export interface FilesystemBackend {
30
30
  revokeOwner?(owner: number, epoch?: Int32Array): void;
31
31
  takeSharedSegments?(): SharedSegment[];
32
32
  sharedSegments?(): SharedSegment[];
33
+ /** Called by FilesystemService when attaching a connection's shared root buffer. */
34
+ attachShared?(shared: SharedArrayBuffer): void;
35
+ /** Version tag checked on cold-read preparation re-entry alongside the session epoch. */
36
+ readVersion?(): string;
37
+ /** Current dirty-admission change counter for backpressure waits on non-MemoryBackend owners. */
38
+ dirtyChange?(): number | undefined;
39
+ /** Backend-owned watch hooks (used by MultiTabBackend). */
40
+ watchOpen?(
41
+ owner: number,
42
+ handle: FileHandle,
43
+ recursive: boolean,
44
+ cancelled: () => boolean,
45
+ ): number | Promise<number>;
46
+ watchRead?(
47
+ owner: number,
48
+ watchId: number,
49
+ cancelled: () => boolean,
50
+ ):
51
+ | import("./watch-subscriptions.js").HeldWatchBatch
52
+ | Promise<import("./watch-subscriptions.js").HeldWatchBatch>;
53
+ watchClose?(owner: number, watchId: number): void;
54
+ closeWatchOwner?(owner: number): void;
55
+ /** Called in FilesystemService.request() finally after finishResult() to settle provisional pins. */
56
+ settleResult?(operation: string, value: unknown): void;
57
+ /** Latched disposal notification posted before Runtime.dispose() awaits filesystem.drain(). */
58
+ beginDispose?(): void;
59
+ /** Synchronous shutdown hook called by FilesystemService.shutdown() before draining work. */
60
+ beginShutdown?(): void;
61
+ /** Whether this backend supports Unix domain socket scope attachment (defaults to true for MemoryBackend). */
62
+ readonly supportsSockets?: boolean;
63
+ /** Whether async execute/flush/watch rejections are handled client results rather than fatal service shutdown failures. */
64
+ readonly asyncErrorsAreClientResults?: boolean;
65
+ /** Re-verify lease / terminal state before publishing a prepared cold descriptor read. */
66
+ isPreparedReadValid?(): boolean;
67
+ /** Whether a handle is unlinked (used by service capability trimming when not MemoryBackend). */
68
+ isUnlinked?(handle: FileHandle): boolean;
33
69
  /** Select a bounded cold descriptor range before asynchronous storage work. */
34
70
  prepareDescriptorRead?(
35
71
  handle: FileHandle,
package/fs/client.ts CHANGED
@@ -399,6 +399,7 @@ function preparationFailed(completion: FilesystemCompletion | undefined): boolea
399
399
  function clientWatches(
400
400
  cells: () => Int32Array,
401
401
  revoked: () => boolean,
402
+ remote: () => boolean,
402
403
  call: (operation: string, args: unknown[]) => any,
403
404
  ): WatchFileSystem {
404
405
  return {
@@ -408,6 +409,9 @@ function clientWatches(
408
409
  get revoked() {
409
410
  return revoked();
410
411
  },
412
+ get remote() {
413
+ return remote();
414
+ },
411
415
  open: (handle, recursive) => call("watchOpen", [handle, recursive]),
412
416
  read: (id) => call("watchRead", [id]),
413
417
  close: (id) => {
@@ -539,6 +543,7 @@ export class FilesystemClient implements FileSystem {
539
543
  this.watches = clientWatches(
540
544
  () => this.shared.watch.cells,
541
545
  this.revoked,
546
+ () => this.shared.isDirectDisabled(),
542
547
  (operation, args) => this.call(operation, args),
543
548
  );
544
549
  connection.port.onmessage = ({ data }) => {
@@ -944,7 +949,8 @@ export class FilesystemClient implements FileSystem {
944
949
  if (
945
950
  count === 1 &&
946
951
  !this.revoked() &&
947
- ((!this.resident && this.shared.isUnlinked(atomicsLoad(this.capabilities, key))) ||
952
+ (this.shared.isDirectDisabled() ||
953
+ (!this.resident && this.shared.isUnlinked(atomicsLoad(this.capabilities, key))) ||
948
954
  atomicsLoad(this.capabilities, 0) > TRANSIENT_HANDLES)
949
955
  )
950
956
  this.connection.port.postMessage({ trim: true });
@@ -1024,6 +1030,7 @@ export class FilesystemClient implements FileSystem {
1024
1030
  }
1025
1031
  /** The shared slot of a regular file this connection holds open, or 0. */
1026
1032
  private directSlot(handle: FileHandle): number {
1033
+ if (this.shared.isDirectDisabled()) return 0;
1027
1034
  const cached = mapGet(this.fileSlots, handle);
1028
1035
  if (cached !== undefined) return cached;
1029
1036
  if (!mapHas(this.openHandles, handle)) return 0;
@@ -1280,6 +1287,7 @@ export class FilesystemClient implements FileSystem {
1280
1287
  }
1281
1288
  /** Nonblocking runtime_proc I/O. Never retain an iovec across an EAGAIN boundary. */
1282
1289
  tryRead(handle: FileHandle, chunks: readonly Uint8Array[], offset: number): number {
1290
+ if (this.shared.isDirectDisabled()) return -58;
1283
1291
  if (this.resident)
1284
1292
  return this.residentIO(() => this.resident?.client?.tryRead(handle, chunks, offset) ?? -6);
1285
1293
  if (!(offset >= 0)) return -28;
@@ -1315,6 +1323,7 @@ export class FilesystemClient implements FileSystem {
1315
1323
  }
1316
1324
  }
1317
1325
  tryWrite(handle: FileHandle, chunks: readonly Uint8Array[], offset: number): number {
1326
+ if (this.shared.isDirectDisabled()) return -58;
1318
1327
  if (this.resident)
1319
1328
  return this.residentIO(() => this.resident?.client?.tryWrite(handle, chunks, offset) ?? -6);
1320
1329
  if (this.shared.publication) return this.publishedWrite(handle, chunks, offset, true);
@@ -1367,6 +1376,7 @@ export class FilesystemClient implements FileSystem {
1367
1376
  handle: FileHandle,
1368
1377
  chunks: readonly Uint8Array[],
1369
1378
  ): { written: number; offset: number } | number {
1379
+ if (this.shared.isDirectDisabled()) return -58;
1370
1380
  if (this.resident)
1371
1381
  return this.residentIO(() => this.resident?.client?.tryAppend(handle, chunks) ?? -6);
1372
1382
  if (this.shared.publication) return this.publishedAppend(handle, chunks, true);
@@ -1609,6 +1619,8 @@ export class FilesystemClient implements FileSystem {
1609
1619
  // A failed preparation is ready too: retrying the syscall delivers its errno, rather than
1610
1620
  // leaving poll asleep forever. Preserve that completion until the syscall consumes it.
1611
1621
  if (this.revoked()) return { readable: true, writable: true, hangup: true };
1622
+ if (this.shared.isDirectDisabled())
1623
+ return { readable: !writing, writable: writing, hangup: false };
1612
1624
  if (pending?.kind === "read")
1613
1625
  return { readable: pending.completion.ready, writable: false, hangup: false };
1614
1626
  if ((pending && !pending.completion.ready) || (stage && !stage.completion.ready))
@@ -1679,8 +1691,10 @@ export class FilesystemClient implements FileSystem {
1679
1691
  try {
1680
1692
  const epoch = this.version();
1681
1693
  const key = `${directory}\0${Number(followFinal) | (Number(rooted) << 1)}\0${path}`;
1682
- const cached = this.paths.get(key, epoch);
1683
- if (!this.resident && !this.shared.publication && !(epoch & 1) && cached !== undefined)
1694
+ const cacheable =
1695
+ !this.resident && !this.shared.publication && !this.shared.isClientCacheDisabled();
1696
+ const cached = cacheable ? this.paths.get(key, epoch) : undefined;
1697
+ if (cacheable && !(epoch & 1) && cached !== undefined)
1684
1698
  return typeof cached === "number" ? cached : { ...cached };
1685
1699
  return this.#resolveCold(key, [directory, path, followFinal, rooted]);
1686
1700
  } catch (error) {
@@ -1701,23 +1715,27 @@ export class FilesystemClient implements FileSystem {
1701
1715
  epoch: number,
1702
1716
  resolved: ResolvedPath | number,
1703
1717
  ): ResolvedPath | number {
1704
- this.paths.set(key, resolved, epoch);
1718
+ if (!this.shared.isClientCacheDisabled()) this.paths.set(key, resolved, epoch);
1705
1719
  return typeof resolved === "number" ? resolved : { ...resolved };
1706
1720
  }
1707
1721
  stat(handle: FileHandle): FileStat {
1708
1722
  // Keep the capability's backend pin alive while reading its shared metadata slot.
1709
1723
  this.retain(handle);
1710
1724
  try {
1711
- const direct = this.resident ? undefined : this.shared.stat(handle, this.revoked);
1725
+ const direct =
1726
+ this.resident || this.shared.isDirectDisabled()
1727
+ ? undefined
1728
+ : this.shared.stat(handle, this.revoked);
1712
1729
  if (direct) return direct;
1713
1730
  const epoch = this.version();
1714
- const cached = this.stats.get(handle, epoch);
1715
- if (!this.resident && !this.shared.publication && !(epoch & 1) && cached)
1716
- return { ...cached };
1731
+ const cacheable =
1732
+ !this.resident && !this.shared.publication && !this.shared.isClientCacheDisabled();
1733
+ const cached = cacheable ? this.stats.get(handle, epoch) : undefined;
1734
+ if (cacheable && !(epoch & 1) && cached) return { ...cached };
1717
1735
  const completion = this.submit("stat", [handle]);
1718
1736
  try {
1719
1737
  const stat = completion.wait();
1720
- this.stats.set(handle, stat, completion.epoch);
1738
+ if (cacheable) this.stats.set(handle, stat, completion.epoch);
1721
1739
  return { ...stat };
1722
1740
  } finally {
1723
1741
  completion.release();
@@ -1739,10 +1757,11 @@ export class FilesystemClient implements FileSystem {
1739
1757
  }
1740
1758
  private cachedRead(handle: FileHandle, position: number) {
1741
1759
  const epoch = this.version();
1742
- let cached = this.reads.get(handle);
1760
+ const cacheable =
1761
+ !this.resident && !this.shared.publication && !this.shared.isClientCacheDisabled();
1762
+ let cached = cacheable ? this.reads.get(handle) : undefined;
1743
1763
  if (
1744
- this.resident ||
1745
- this.shared.publication ||
1764
+ !cacheable ||
1746
1765
  epoch & 1 ||
1747
1766
  cached?.epoch !== epoch ||
1748
1767
  position < cached.offset ||
@@ -1751,8 +1770,10 @@ export class FilesystemClient implements FileSystem {
1751
1770
  const completion = this.submit("read", [handle, PAGE, position]);
1752
1771
  try {
1753
1772
  cached = { offset: position, bytes: completion.wait(), epoch: completion.epoch };
1754
- if (this.reads.size >= 16) this.reads.clear();
1755
- this.reads.set(handle, cached);
1773
+ if (cacheable) {
1774
+ if (this.reads.size >= 16) this.reads.clear();
1775
+ this.reads.set(handle, cached);
1776
+ }
1756
1777
  } finally {
1757
1778
  completion.release();
1758
1779
  }
@@ -1815,6 +1836,7 @@ export class FilesystemClient implements FileSystem {
1815
1836
  return this.tryRead(handle, chunks, offset);
1816
1837
  if (this.resident) return this.workspaceRead(handle, chunks, offset);
1817
1838
  if (!(offset >= 0)) return -28; // EINVAL: positions are never negative.
1839
+ if (this.shared.isDirectDisabled()) return this.readUnloaded(handle, chunks, offset);
1818
1840
  const slot = this.directSlot(handle);
1819
1841
  if (slot) {
1820
1842
  try {
@@ -1863,6 +1885,24 @@ export class FilesystemClient implements FileSystem {
1863
1885
  if (this.shared.publication) return this.publishedWrite(handle, chunks, offset, false);
1864
1886
  if (!(offset >= 0)) return -28; // EINVAL: positions are never negative.
1865
1887
  chunks = fixedWriteSources(chunks);
1888
+ if (this.shared.isDirectDisabled()) {
1889
+ try {
1890
+ let total = 0;
1891
+ for (let i = 0; i < chunks.length; i++) total += chunks[i]!.length;
1892
+ const limit = Math.min(total, 1024 * 1024);
1893
+ const data = new Uint8ArrayConstructor(limit);
1894
+ let at = 0;
1895
+ for (let i = 0; i < chunks.length && at < limit; i++) {
1896
+ const chunk = chunks[i]!;
1897
+ const count = Math.min(chunk.length, limit - at);
1898
+ if (count > 0) typedArraySet(data, chunk.subarray(0, count), at);
1899
+ at += count;
1900
+ }
1901
+ return this.call("write", [handle, offset], data);
1902
+ } catch (error) {
1903
+ return -errno(error);
1904
+ }
1905
+ }
1866
1906
  const slot = this.directSlot(handle);
1867
1907
  if (slot) {
1868
1908
  let total = 0;
@@ -1942,6 +1982,22 @@ export class FilesystemClient implements FileSystem {
1942
1982
  chunks = fixedWriteSources(chunks);
1943
1983
  let total = 0;
1944
1984
  for (let i = 0; i < chunks.length; i++) total += chunks[i]!.length;
1985
+ if (this.shared.isDirectDisabled()) {
1986
+ try {
1987
+ const limit = Math.min(total, 1024 * 1024);
1988
+ const data = new Uint8ArrayConstructor(limit);
1989
+ let at = 0;
1990
+ for (let i = 0; i < chunks.length && at < limit; i++) {
1991
+ const chunk = chunks[i]!;
1992
+ const count = Math.min(chunk.length, limit - at);
1993
+ if (count > 0) typedArraySet(data, chunk.subarray(0, count), at);
1994
+ at += count;
1995
+ }
1996
+ return this.call("append", [handle], data);
1997
+ } catch (error) {
1998
+ return -errno(error);
1999
+ }
2000
+ }
1945
2001
  const fallback = () => {
1946
2002
  const data = new Uint8ArrayConstructor(total);
1947
2003
  let at = 0;
@@ -2083,6 +2139,7 @@ export class FilesystemClient implements FileSystem {
2083
2139
  return this.publishedMetadata({ kind: "resize", handle, size, truncate });
2084
2140
  if (
2085
2141
  !this.shared.publication &&
2142
+ !this.shared.isDirectDisabled() &&
2086
2143
  mapHas(this.openHandles, handle) &&
2087
2144
  this.shared.hasFile(handle)
2088
2145
  ) {
@@ -2120,6 +2177,7 @@ export class FilesystemClient implements FileSystem {
2120
2177
  return this.publishedMetadata({ kind: "setTimes", handle, atime, mtime });
2121
2178
  if (
2122
2179
  !this.shared.publication &&
2180
+ !this.shared.isDirectDisabled() &&
2123
2181
  mapHas(this.openHandles, handle) &&
2124
2182
  this.shared.hasFile(handle)
2125
2183
  ) {
@@ -2186,13 +2244,14 @@ export class FilesystemClient implements FileSystem {
2186
2244
  }
2187
2245
  readdir(handle: FileHandle): DirectoryEntry[] {
2188
2246
  const epoch = this.version();
2189
- const cached = this.readdirs.get(handle, epoch);
2190
- if (!this.resident && !this.shared.publication && !(epoch & 1) && cached)
2191
- return cached.map((entry) => ({ ...entry }));
2247
+ const cacheable =
2248
+ !this.resident && !this.shared.publication && !this.shared.isClientCacheDisabled();
2249
+ const cached = cacheable ? this.readdirs.get(handle, epoch) : undefined;
2250
+ if (cacheable && !(epoch & 1) && cached) return cached.map((entry) => ({ ...entry }));
2192
2251
  const completion = this.submit("readdir", [handle]);
2193
2252
  try {
2194
2253
  const entries = completion.wait() as DirectoryEntry[];
2195
- this.readdirs.set(handle, entries, completion.epoch);
2254
+ if (cacheable) this.readdirs.set(handle, entries, completion.epoch);
2196
2255
  return entries.map((entry) => ({ ...entry }));
2197
2256
  } finally {
2198
2257
  completion.release();
@@ -2219,7 +2278,10 @@ export class FilesystemClient implements FileSystem {
2219
2278
  readlink(handle: FileHandle): string {
2220
2279
  this.retain(handle);
2221
2280
  try {
2222
- const direct = this.resident ? undefined : this.shared.stat(handle, this.revoked);
2281
+ const direct =
2282
+ this.resident || this.shared.isDirectDisabled()
2283
+ ? undefined
2284
+ : this.shared.stat(handle, this.revoked);
2223
2285
  if (direct && direct.kind !== "symlink") throw new FilesystemError(28);
2224
2286
  return this.call("readlink", [handle]);
2225
2287
  } finally {