@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/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] : [];
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":"c59d4f248e1599698741db0825cd16c3ed970e9b","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 {
@@ -93,13 +93,27 @@ function entryBytes(entry: Entry): Uint8Array {
93
93
  return (entry.bytes ??= encoder.encode(entry.name));
94
94
  }
95
95
 
96
- function encodeEntry(output: Uint8Array, view: DataView, offset: number, entry: Entry): number {
96
+ const MAX_TAGGED_RAW_COOKIE = (1n << 48n) - 1n;
97
+
98
+ function encodeEntry(
99
+ output: Uint8Array,
100
+ view: DataView,
101
+ offset: number,
102
+ entry: Entry,
103
+ cookieTag?: bigint,
104
+ ): number {
97
105
  const bytes = entryBytes(entry);
98
106
  const remaining = output.length - offset;
99
107
  const header = remaining < 24 ? new Uint8Array(24) : output;
100
108
  const headerView = remaining < 24 ? new DataView(header.buffer) : view;
101
109
  const start = remaining < 24 ? 0 : offset;
102
- headerView.setBigUint64(start, entry.cookie, true);
110
+ let wireCookie = entry.cookie;
111
+ if (cookieTag && entry.cookie >= 3n) {
112
+ if (entry.cookie > MAX_TAGGED_RAW_COOKIE)
113
+ throw new FilesystemError(61, "directory cookies exhausted");
114
+ wireCookie = (cookieTag << 48n) | entry.cookie;
115
+ }
116
+ headerView.setBigUint64(start, wireCookie, true);
103
117
  headerView.setBigUint64(start + 8, BigInt(entry.ino), true);
104
118
  headerView.setUint32(start + 16, bytes.length, true);
105
119
  headerView.setUint8(
@@ -177,8 +191,17 @@ export class DirectoryPages {
177
191
  }
178
192
  return size;
179
193
  }
180
- page(cookie: bigint, byteLength: number, ino: number, parent: number): Uint8Array {
194
+ page(
195
+ cookie: bigint,
196
+ byteLength: number,
197
+ ino: number,
198
+ parent: number,
199
+ cookieTag?: bigint,
200
+ maxBytes?: number,
201
+ hardCapBytes?: number,
202
+ ): Uint8Array {
181
203
  if (!byteLength) return new Uint8Array();
204
+ const limit = maxBytes !== undefined ? Math.min(byteLength, maxBytes) : byteLength;
182
205
  const entries: Entry[] = [];
183
206
  let size = 0;
184
207
  const append = (entry: Entry) => {
@@ -195,11 +218,22 @@ export class DirectoryPages {
195
218
  cookie: 2n,
196
219
  bytes: new Uint8Array([46, 46]),
197
220
  });
198
- if (size < byteLength) size = this.appendEntries(entries, cookie, byteLength, size);
199
- const output = new Uint8Array(Math.min(byteLength, size));
221
+ if (size < byteLength) {
222
+ const scanLimit = maxBytes !== undefined ? limit + 1 : byteLength;
223
+ size = this.appendEntries(entries, cookie, scanLimit, size);
224
+ }
225
+ const actual = Math.min(byteLength, size);
226
+ if (maxBytes !== undefined && actual > maxBytes) {
227
+ const overHardCap = hardCapBytes !== undefined && actual > hardCapBytes;
228
+ throw new FilesystemError(
229
+ overHardCap ? 22 : 6,
230
+ overHardCap ? "directory page exceeds maximum transfer size" : "download budget exhausted",
231
+ );
232
+ }
233
+ const output = new Uint8Array(actual);
200
234
  const view = new DataView(output.buffer);
201
235
  let used = 0;
202
- for (const entry of entries) used = encodeEntry(output, view, used, entry);
236
+ for (const entry of entries) used = encodeEntry(output, view, used, entry, cookieTag);
203
237
  return output;
204
238
  }
205
239
  }
package/fs/guest-watch.ts CHANGED
@@ -59,6 +59,7 @@ function failure(errno: number): GuestWatchRead {
59
59
  export class GuestWatchTable implements GuestWatchReadiness {
60
60
  private watches = new MapConstructor<number, Watch>();
61
61
  private nextId = 1;
62
+ private revocationNotified = false;
62
63
 
63
64
  constructor(private readonly fs: WatchFileSystem) {}
64
65
 
@@ -75,7 +76,8 @@ export class GuestWatchTable implements GuestWatchReadiness {
75
76
  }
76
77
 
77
78
  pending(): boolean {
78
- return !this.fs.revoked && this.hasPending(false);
79
+ if (this.fs.revoked) return !!this.fs.remote && !this.revocationNotified && this.active;
80
+ return this.hasPending(false);
79
81
  }
80
82
 
81
83
  /** A read may return records, end or an error; never consumes watch state. */
@@ -146,9 +148,12 @@ export class GuestWatchTable implements GuestWatchReadiness {
146
148
  }
147
149
 
148
150
  private refill(watch: Watch): GuestWatchRead | undefined {
149
- if (this.fs.revoked) return failure(ECANCELED);
151
+ if (this.fs.revoked) {
152
+ if (this.fs.remote) this.revocationNotified = true;
153
+ return failure(ECANCELED);
154
+ }
150
155
  const generation = atomicsLoad(this.fs.cells, 3);
151
- if (generation === watch.observed) return failure(EAGAIN);
156
+ if (!this.fs.remote && generation === watch.observed) return failure(EAGAIN);
152
157
  // Set before the call: a commit after the service drains moves the counter again. A failed
153
158
  // call drained nothing, so the watch stays pending for the retry.
154
159
  const previous = watch.observed;
@@ -89,6 +89,7 @@ export async function isWorkspace(database: IDBDatabase): Promise<boolean> {
89
89
  key === 0 ||
90
90
  key === 1 ||
91
91
  key === "epoch" ||
92
+ key === "lastExclusiveEpoch" ||
92
93
  key === "active" ||
93
94
  key === "identity" ||
94
95
  key === "format",