@waffle-os/runtime 0.0.153 → 0.0.155

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 (61) hide show
  1. package/browser/net/helper.ts +114 -19
  2. package/browser/net/ring.ts +18 -6
  3. package/browser/net/runtime.ts +2 -2
  4. package/browser/notification-relay.ts +105 -18
  5. package/browser/notification-wait.ts +45 -4
  6. package/browser/notification-worker.ts +169 -76
  7. package/browser/preview.ts +15 -2
  8. package/core/filesystem.ts +18 -0
  9. package/core/wasi.ts +75 -4
  10. package/dist/browser/net/helper.js +83 -18
  11. package/dist/browser/net/ring.js +6 -5
  12. package/dist/browser/net/runtime.js +2 -2
  13. package/dist/browser/notification-relay.js +78 -15
  14. package/dist/browser/notification-wait.js +37 -5
  15. package/dist/browser/notification-worker.js +146 -67
  16. package/dist/core/wasi.js +62 -4
  17. package/dist/fs/backend.js +7 -0
  18. package/dist/fs/client.js +75 -17
  19. package/dist/fs/dirty-admission.js +15 -8
  20. package/dist/fs/guest-watch.js +267 -94
  21. package/dist/fs/indexeddb-chunks.js +88 -11
  22. package/dist/fs/indexeddb.js +366 -110
  23. package/dist/fs/memory.js +106 -20
  24. package/dist/fs/multitab-backend.js +291 -74
  25. package/dist/fs/multitab-protocol.js +1 -0
  26. package/dist/fs/persistent.js +70 -16
  27. package/dist/fs/protocol.js +15 -7
  28. package/dist/fs/publication-attachment.js +9 -7
  29. package/dist/fs/service.js +62 -9
  30. package/dist/fs/shared.js +100 -6
  31. package/dist/fs/storage.js +107 -8
  32. package/dist/fs/watch-service.js +97 -2
  33. package/dist/fs/watch-subscriptions.js +121 -8
  34. package/dist/proc/command-stdio.js +1 -1
  35. package/dist/proc/intrinsics/core.js +5 -0
  36. package/dist/proc/intrinsics.js +1 -0
  37. package/dist/tooling/program/program-transformer.json +1 -1
  38. package/fs/backend.ts +17 -0
  39. package/fs/client.ts +99 -16
  40. package/fs/dirty-admission.ts +22 -7
  41. package/fs/guest-watch.ts +299 -103
  42. package/fs/indexeddb-chunks.ts +103 -9
  43. package/fs/indexeddb.ts +477 -121
  44. package/fs/memory.ts +120 -19
  45. package/fs/multitab-backend.ts +440 -95
  46. package/fs/multitab-protocol.ts +1 -0
  47. package/fs/persistent.ts +88 -16
  48. package/fs/protocol.ts +26 -7
  49. package/fs/publication-attachment.ts +9 -7
  50. package/fs/service.ts +62 -7
  51. package/fs/shared.ts +110 -8
  52. package/fs/storage.ts +128 -10
  53. package/fs/watch-service.ts +110 -3
  54. package/fs/watch-subscriptions.ts +115 -7
  55. package/package.json +1 -1
  56. package/proc/command-stdio.ts +1 -1
  57. package/proc/intrinsics/core.ts +7 -0
  58. package/proc/intrinsics.ts +1 -0
  59. package/testing/idle-workspace-cancellation-browser.ts +22 -13
  60. package/testing/indexeddb-storage-browser.ts +564 -1
  61. package/tooling/program/program-transformer.json +1 -1
@@ -192,6 +192,7 @@ const PURE_STATELESS_READ_OPS = new Set<string>([
192
192
  "readdir",
193
193
  "readlink",
194
194
  "resolve",
195
+ "realpath",
195
196
  "readdirPage",
196
197
  ]);
197
198
 
package/fs/persistent.ts CHANGED
@@ -13,7 +13,14 @@ import {
13
13
  import { FilesystemError, PAGE } from "./protocol.js";
14
14
  import type { FileHandle, FileStat } from "../core/index.js";
15
15
  import { MemoryBackend, type LocalMutationPlan, type MemoryBackendSharedRoot } from "./backend.js";
16
- import { MemFS, adoptInodes, type Node, type FileNode, type NamespacePlan } from "./memory.js";
16
+ import {
17
+ MemFS,
18
+ adoptInodes,
19
+ type DirNode,
20
+ type Node,
21
+ type FileNode,
22
+ type NamespacePlan,
23
+ } from "./memory.js";
17
24
  import {
18
25
  storeTime,
19
26
  validatePersistedIndex,
@@ -57,6 +64,9 @@ export class PersistentBackend extends MemoryBackend {
57
64
  private readonly pressure: CheckpointPressure;
58
65
  private nodes = new Map<number, Node>();
59
66
  private byFileId = new Map<bigint, Node>();
67
+ private dirEntryBytes = new WeakMap<DirNode, number>();
68
+ private namespaceBytes = 0;
69
+ private idleChangeSequence: number | undefined;
60
70
  private readonly initialWorkspaceId: string;
61
71
  private readonly initialEra: bigint;
62
72
  private readonly loadedIndex: boolean;
@@ -103,6 +113,7 @@ export class PersistentBackend extends MemoryBackend {
103
113
  this.links.set(node.ino, (this.links.get(node.ino) ?? 0) + 1);
104
114
  if (this.nodes.has(node.ino)) return;
105
115
  this.nodes.set(node.ino, node);
116
+ this.namespaceBytes += this.nodeMetadataBytes(node);
106
117
  if (node.identity) this.byFileId.set(node.identity.id, node);
107
118
  if (node.kind === "dir") for (const child of node.children.values()) visit(child);
108
119
  };
@@ -116,6 +127,11 @@ export class PersistentBackend extends MemoryBackend {
116
127
  }
117
128
  this.committedKeys = new Map(this.keys);
118
129
  } else this.dirty.add(fs.root);
130
+ fs.onDirEntryDelta = (dir, delta) => {
131
+ const existing = this.dirEntryBytes.get(dir);
132
+ if (existing !== undefined) this.dirEntryBytes.set(dir, existing + delta);
133
+ if (this.nodes.has(dir.ino)) this.namespaceBytes += delta;
134
+ };
119
135
  fs.onLinkChange = (node, delta) => this.changeLinks(node, delta);
120
136
  fs.onChange = (node) => {
121
137
  if (!this.detached.has(node)) {
@@ -132,6 +148,12 @@ export class PersistentBackend extends MemoryBackend {
132
148
  get hasLoadedIndex(): boolean {
133
149
  return this.loadedIndex;
134
150
  }
151
+ /**
152
+ * Whether the storage still belongs to this connection's epoch. IndexedDB may answer from an
153
+ * epoch read made by one of its own open commits (see IndexedDBStorage.verifyEpoch). That is
154
+ * sound only because the caller, the multitab lease renewal, confirms it still holds the
155
+ * storage Web Lock first: keep the lock query before this call.
156
+ */
135
157
  async verifyStorageEpoch(signal?: AbortSignal): Promise<boolean> {
136
158
  if ("verifyEpoch" in this.storage && typeof this.storage.verifyEpoch === "function") {
137
159
  return (this.storage as { verifyEpoch(s?: AbortSignal): Promise<boolean> }).verifyEpoch(
@@ -160,10 +182,18 @@ export class PersistentBackend extends MemoryBackend {
160
182
  setTerminalFailureListener(listener: (reason: unknown) => void): void {
161
183
  this.storage.setTerminalFailureListener?.(listener);
162
184
  }
185
+ private hasPendingChanges(): boolean {
186
+ if (this.dirty.size > 0 || this.removed.size > 0 || this.shared.publication) return true;
187
+ return (
188
+ this.idleChangeSequence === undefined ||
189
+ this.shared.changeSequence !== this.idleChangeSequence
190
+ );
191
+ }
163
192
  private startTimer(intervalMs: number): void {
164
193
  if (intervalMs > 0)
165
194
  this.timer = setInterval(() => {
166
- if (!this.stopped && !this.pendingCheckpoints) void this.checkpoint().catch(() => {});
195
+ if (!this.stopped && !this.pendingCheckpoints && this.hasPendingChanges())
196
+ void this.checkpoint().catch(() => {});
167
197
  }, intervalMs);
168
198
  }
169
199
  static async open(
@@ -232,6 +262,7 @@ export class PersistentBackend extends MemoryBackend {
232
262
  else this.links.delete(node.ino);
233
263
  if (delta === 1 && previous === 0) {
234
264
  this.nodes.set(node.ino, node);
265
+ this.namespaceBytes += this.nodeMetadataBytes(node);
235
266
  if (node.identity) this.byFileId.set(node.identity.id, node);
236
267
  this.detached.delete(node);
237
268
  const key = this.detachedKeys.get(node.ino);
@@ -249,6 +280,7 @@ export class PersistentBackend extends MemoryBackend {
249
280
  for (const child of node.children.values()) this.changeLinks(child, 1);
250
281
  } else if (delta === -1 && count === 0) {
251
282
  this.nodes.delete(node.ino);
283
+ this.namespaceBytes -= this.nodeMetadataBytes(node);
252
284
  this.dirty.delete(node);
253
285
  this.detached.add(node);
254
286
  this.removed.add(node.ino);
@@ -486,9 +518,7 @@ export class PersistentBackend extends MemoryBackend {
486
518
  return this.ownWork(load);
487
519
  }
488
520
  private namespaceUnits(): number {
489
- let units = 0;
490
- for (const node of this.nodes.values()) units += this.nodeMetadataBytes(node) * 4;
491
- return units;
521
+ return this.namespaceBytes * 4;
492
522
  }
493
523
  private configureDirty(): void {
494
524
  if (this.dirtyLimits === false) return;
@@ -501,7 +531,10 @@ export class PersistentBackend extends MemoryBackend {
501
531
  override attachShared(...args: Parameters<MemoryBackend["attachShared"]>): void {
502
532
  const previous = this.shared;
503
533
  super.attachShared(...args);
504
- if (previous !== this.shared) this.configureDirty();
534
+ if (previous !== this.shared) {
535
+ this.idleChangeSequence = undefined;
536
+ this.configureDirty();
537
+ }
505
538
  }
506
539
  private namespaceGrowth(plan: NamespacePlan): number {
507
540
  let units = plan.created.reduce((sum, node) => sum + this.nodeMetadataBytes(node), 0);
@@ -689,13 +722,18 @@ export class PersistentBackend extends MemoryBackend {
689
722
  void work.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
690
723
  });
691
724
  }
725
+ private cachedDirEntryBytes(node: DirNode): number {
726
+ let entryBytes = this.dirEntryBytes.get(node);
727
+ if (entryBytes !== undefined) return entryBytes;
728
+ entryBytes = 0;
729
+ for (const name of node.children.keys()) entryBytes += 64 + name.length * 2;
730
+ this.dirEntryBytes.set(node, entryBytes);
731
+ return entryBytes;
732
+ }
692
733
  private nodeMetadataBytes(node: Node): number {
693
- let bytes = 256;
694
- if (node.kind === "symlink")
695
- return bytes + node.target.length * 2 + utf8ByteLength(node.target);
696
- if (node.kind !== "dir") return bytes;
697
- for (const name of node.children.keys()) bytes += 64 + name.length * 2;
698
- return bytes;
734
+ if (node.kind === "symlink") return 256 + node.target.length * 2 + utf8ByteLength(node.target);
735
+ if (node.kind === "dir") return 256 + this.cachedDirEntryBytes(node);
736
+ return 256;
699
737
  }
700
738
  private pinMetadataBytes(): number {
701
739
  let bytes = 0;
@@ -754,11 +792,37 @@ export class PersistentBackend extends MemoryBackend {
754
792
  return true;
755
793
  }
756
794
  private invalidateCapturedState(): void {
795
+ this.idleChangeSequence = undefined;
757
796
  this.keys = new Map(this.committedKeys);
758
797
  // Cold baselines still identify retained durable bytes. Only resident captures need retry.
759
798
  for (const handle of this.revisions.keys())
760
799
  if (this.shared.isResident(handle)) this.revisions.delete(handle);
761
800
  }
801
+ private reconcileDirtyAfterCommit(revision: number): void {
802
+ if (!this.shared.dirtyAdmission.enabled || this.pendingCheckpoints > 0) return;
803
+ const namespace = this.namespaceUnits();
804
+ if (
805
+ this.shared.dirtyAdmission.revision === revision &&
806
+ !this.dirty.size &&
807
+ !this.removed.size
808
+ ) {
809
+ this.shared.reconcileDirty(this.registeredNodes.keys(), namespace, 0, () => false);
810
+ return;
811
+ }
812
+ let dirtyNamespace = this.removed.size * 256;
813
+ for (const node of this.dirty) dirtyNamespace += this.nodeMetadataBytes(node);
814
+ this.shared.reconcileDirty(
815
+ this.registeredNodes.keys(),
816
+ namespace,
817
+ dirtyNamespace * 4,
818
+ (handle, kind, currentRevision, dirtyMark) => {
819
+ if (kind === 1) return currentRevision !== this.revisions.get(handle);
820
+ if (dirtyMark !== 1) return false;
821
+ const node = this.registeredNodes.get(handle);
822
+ return node !== undefined && this.dirty.has(node);
823
+ },
824
+ );
825
+ }
762
826
  private reserveCheckpoint(request: CheckpointRequest): Promise<void> {
763
827
  const cost = { ...this.captureCost(request) };
764
828
  this.shared.dirtyAdmission.reserveCopy(cost, this.shared.resources().usedBytes);
@@ -772,13 +836,21 @@ export class PersistentBackend extends MemoryBackend {
772
836
  const revision = this.includesDetachedWriters(request)
773
837
  ? this.shared.dirtyAdmission.revision
774
838
  : undefined;
839
+ const capturedChangeSeq = this.shared.changeSequence;
775
840
  try {
776
841
  return this.captureReserved(request, reservation, cost)
777
842
  .then(() => {
778
- if (revision === undefined) return;
779
- this.shared.mutate(undefined, undefined, () =>
780
- this.shared.cleanDirty(revision, this.namespaceUnits()),
781
- );
843
+ if (this.stopped) return;
844
+ this.shared.mutate(undefined, undefined, () => {
845
+ if (
846
+ !this.pendingCheckpoints &&
847
+ !this.dirty.size &&
848
+ !this.removed.size &&
849
+ this.shared.changeSequence === capturedChangeSeq
850
+ )
851
+ this.idleChangeSequence = capturedChangeSeq;
852
+ if (revision !== undefined) this.reconcileDirtyAfterCommit(revision);
853
+ });
782
854
  })
783
855
  .finally(() => {
784
856
  this.pressure.release(reservation);
package/fs/protocol.ts CHANGED
@@ -87,6 +87,9 @@ export function normalizeSharedMaxBytes(maxBytes: number): number {
87
87
  }
88
88
  export const HEADER = REQUEST_HEADER;
89
89
  export const TRANSIENT_HANDLES = 256;
90
+ /** The `signal` word that changes only on revocation, reap or transport failure. */
91
+ export const SIGNAL_TRANSPORT = 1;
92
+ export const SIGNAL_BYTES = 8;
90
93
  export const CAPABILITY_SLOTS = 4096;
91
94
  // One candidate-count word, then reusable [handle, open-reference count, transfer count] records. A negative
92
95
  // reference count revokes an entry. Handles never recycle, but these per-session entries do.
@@ -113,6 +116,10 @@ export interface FilesystemConnection {
113
116
  requests: FilesystemRequestMemory;
114
117
  requestBudget: SharedArrayBuffer;
115
118
  epoch: SharedArrayBuffer;
119
+ /** Shared by the whole identity tree. Word 0 changes on every completion, release and
120
+ * revocation, and blocked guests wait on it. Word 1 (`SIGNAL_TRANSPORT`) changes only when an
121
+ * identity in the tree is revoked or reaped or loses its transport, so watchers that need only
122
+ * those events are not woken once per request. */
116
123
  signal: SharedArrayBuffer;
117
124
  /** This connection's revocation word, then its ancestors. Never reused. */
118
125
  revocations: SharedArrayBuffer[];
@@ -158,7 +165,9 @@ export function filesystemOwnerPlan(publication: PublicationConfiguration) {
158
165
  bytes:
159
166
  MAX_CONNECTION_OWNERS * 4 +
160
167
  CAPABILITY_LENGTH * 4 +
161
- 12 +
168
+ // Epoch and revocation words, then the signal.
169
+ 8 +
170
+ SIGNAL_BYTES +
162
171
  FILESYSTEM_SECTION_BYTES +
163
172
  arena.bytes +
164
173
  REQUEST_BUDGET_BYTES +
@@ -219,7 +228,7 @@ function constructFilesystemIdentity(
219
228
  epoch: parent?.epoch ?? allocate(4),
220
229
  requestBudget: parent?.requestBudget ?? createRequestBudget(construction),
221
230
  // Every descendant waits here too, so root revocation can wake blocked guests after a crash.
222
- signal: parent?.signal ?? allocate(4),
231
+ signal: parent?.signal ?? allocate(SIGNAL_BYTES),
223
232
  revocations: [allocate(4)].concat(parent?.revocations ?? []),
224
233
  shared,
225
234
  // An independent identity starts with no extra backing at all. A fork shares its parent's
@@ -410,13 +419,15 @@ export function createFilesystemConnection(
410
419
  export function revokeFilesystemService(connection: FilesystemIdentity): void {
411
420
  Atomics.store(new Int32Array(connection.ownerStates), 0, 1);
412
421
  wakeFilesystemWatch(connection.shared, true);
413
- wake(connection);
422
+ wakeTransport(connection);
414
423
  }
415
424
  export function revokeFilesystem(connection: FilesystemIdentity): void {
416
425
  Atomics.compareExchange(new Int32Array(connection.revocations[0]!), 0, 0, 1);
417
426
  Atomics.compareExchange(new Int32Array(connection.ownerStates), connection.owner, 0, 1);
418
- wakeFilesystemWatch(connection.shared);
419
- wake(connection);
427
+ // Revocation can make a watch readable, so it moves the observed watch generation: a waiter
428
+ // that registers after this notify still sees the change by value.
429
+ wakeFilesystemWatch(connection.shared, true);
430
+ wakeTransport(connection);
420
431
  }
421
432
  /** Revokes synchronously, then waits without blocking the supervisor's event loop. Resolving
422
433
  * proves this identity cannot touch filesystem storage again, even if its worker is still alive.
@@ -450,19 +461,27 @@ export async function waitForFilesystemQuiescence(connection: FilesystemIdentity
450
461
  export function reapFilesystem(connection: FilesystemIdentity): void {
451
462
  Atomics.store(new Int32Array(connection.revocations[0]!), 0, 2);
452
463
  Atomics.store(new Int32Array(connection.ownerStates), connection.owner, 2);
453
- wakeFilesystemWatch(connection.shared);
464
+ wakeFilesystemWatch(connection.shared, true);
454
465
  if (connection.publication)
455
466
  new PublicationDomain(connection.publication.buffers).retireSession(
456
467
  connection.publication.session,
457
468
  );
458
469
  Atomics.notify(new Int32Array(connection.sections), 0);
459
- wake(connection);
470
+ wakeTransport(connection);
460
471
  }
461
472
  export function wake(connection: FilesystemIdentity): void {
462
473
  const signal = new Int32ArrayConstructor(connection.signal);
463
474
  atomicsAdd(signal, 0, 1);
464
475
  atomicsNotify(signal, 0);
465
476
  }
477
+ /** For a revocation, reap or transport failure already stored: wakes the transport watchers on
478
+ * word 1, then everything waiting on word 0. */
479
+ export function wakeTransport(connection: FilesystemIdentity): void {
480
+ const signal = new Int32ArrayConstructor(connection.signal);
481
+ atomicsAdd(signal, SIGNAL_TRANSPORT, 1);
482
+ atomicsNotify(signal, SIGNAL_TRANSPORT);
483
+ wake(connection);
484
+ }
466
485
  const encoder = new TextEncoder();
467
486
  const decoder = new TextDecoder();
468
487
  export function pack(value: unknown): Uint8Array {
@@ -60,6 +60,8 @@ import {
60
60
  pack,
61
61
  unpack,
62
62
  wake,
63
+ wakeTransport,
64
+ SIGNAL_BYTES,
63
65
  type FilesystemIdentity,
64
66
  CONNECTION_SHARED_BYTES,
65
67
  MAX_CONNECTION_OWNERS,
@@ -863,7 +865,7 @@ function workspaceConnection(value: unknown, parent: FilesystemConnection): File
863
865
  requestBudget: workspaceBuffer(data.requestBudget, REQUEST_BUDGET_BYTES),
864
866
  port: data.port,
865
867
  epoch: workspaceBuffer(data.epoch, 4),
866
- signal: workspaceBuffer(data.signal, 4),
868
+ signal: workspaceBuffer(data.signal, SIGNAL_BYTES),
867
869
  revocations,
868
870
  shared: workspaceBuffer(data.shared, CONNECTION_SHARED_BYTES + 4),
869
871
  segments,
@@ -908,7 +910,7 @@ class WorkspaceBridge {
908
910
  connection.port.onmessage = ({ data }: MessageEvent<unknown>) => this.receive(data);
909
911
  connection.port.onmessageerror = () => {
910
912
  closeRequestMemory(connection.requests);
911
- wake(connection);
913
+ wakeTransport(connection);
912
914
  this.replyStopped();
913
915
  };
914
916
  connection.port.start();
@@ -1017,7 +1019,7 @@ class WorkspaceBridge {
1017
1019
  this.message(record(value));
1018
1020
  } catch {
1019
1021
  closeRequestMemory(this.connection.requests);
1020
- wake(this.connection);
1022
+ wakeTransport(this.connection);
1021
1023
  this.replyStopped();
1022
1024
  }
1023
1025
  }
@@ -1035,7 +1037,7 @@ class WorkspaceBridge {
1035
1037
  }
1036
1038
  if ("transportClosed" in data) {
1037
1039
  closeRequestMemory(this.connection.requests);
1038
- wake(this.connection);
1040
+ wakeTransport(this.connection);
1039
1041
  return this.replyStopped();
1040
1042
  }
1041
1043
  const id = integer(data.id);
@@ -1165,14 +1167,14 @@ class WorkspaceBridge {
1165
1167
  void this.stop().then(
1166
1168
  () => {
1167
1169
  retireRequestMemory(this.connection.requests);
1168
- wake(this.connection);
1170
+ wakeTransport(this.connection);
1169
1171
  },
1170
1172
  (error: unknown) => {
1171
1173
  retireRequestMemory(
1172
1174
  this.connection.requests,
1173
1175
  error instanceof FilesystemError ? error.errno : 29,
1174
1176
  );
1175
- wake(this.connection);
1177
+ wakeTransport(this.connection);
1176
1178
  },
1177
1179
  );
1178
1180
  }
@@ -1197,7 +1199,7 @@ class WorkspaceBridge {
1197
1199
  if (this.endpoint.kind === "live") this.endpoint.channel.close();
1198
1200
  this.connection.port.close();
1199
1201
  retireRequestMemory(this.connection.requests);
1200
- wake(this.connection);
1202
+ wakeTransport(this.connection);
1201
1203
  if (!this.bindingStarted) this.transfer.resolve();
1202
1204
  }
1203
1205
  private async execute(
package/fs/service.ts CHANGED
@@ -49,6 +49,7 @@ import {
49
49
  CAPABILITY_WORDS,
50
50
  PAGE,
51
51
  TRANSIENT_HANDLES,
52
+ SIGNAL_TRANSPORT,
52
53
  State,
53
54
  FilesystemError,
54
55
  errno,
@@ -59,6 +60,7 @@ import {
59
60
  waitForFilesystemQuiescence,
60
61
  unpack,
61
62
  wake,
63
+ wakeTransport,
62
64
  sameFilesystemIdentity,
63
65
  reserveIdentityCapability,
64
66
  releaseFilesystemReservation,
@@ -155,6 +157,9 @@ interface Session {
155
157
  privateInputs: Map<number, Uint8Array>;
156
158
  preparingHandles: Map<number, number>;
157
159
  preparations: Set<Promise<void>>;
160
+ /** The backend's unlink generation when a trim last proved no transient capability was
161
+ * unlinked. Undefined while one may still become detached, so every trim rescans. */
162
+ trimmedUnlinks?: number;
158
163
  quiescing?: Promise<void>;
159
164
  releaseState?: { kind: "running" } | { kind: "failed"; error: unknown };
160
165
  closed?: boolean;
@@ -397,18 +402,21 @@ export class FilesystemService {
397
402
  reason: "messageerror" | "protocol" = "messageerror",
398
403
  ): void {
399
404
  closeRequestMemory(session.requests, reason);
400
- wake(session.connection);
405
+ wakeTransport(session.connection);
401
406
  }
402
407
  private async watchTransport(session: Session): Promise<void> {
403
408
  const signal = new Int32Array(session.connection.signal);
409
+ // Revocation, reap and transport failure all wake SIGNAL_TRANSPORT. A publication domain's
410
+ // stop wakes nothing itself, so a publishing session keeps watching every change.
411
+ const word = session.connection.publication ? 0 : SIGNAL_TRANSPORT;
404
412
  while (!session.closed) {
405
- const observed = Atomics.load(signal, 0);
413
+ const observed = Atomics.load(signal, word);
406
414
  if (sessionRevoked(session)) {
407
415
  if (requestTransportError(session.requests)) session.transportFailed = true;
408
416
  this.close(session);
409
417
  return;
410
418
  }
411
- const waiting = atomicsWaitAsync(signal, 0, observed);
419
+ const waiting = atomicsWaitAsync(signal, word, observed);
412
420
  if (waiting.async) await waiting.value;
413
421
  }
414
422
  }
@@ -462,7 +470,7 @@ export class FilesystemService {
462
470
  .map((entry) => entry[0]);
463
471
  if (!pending.length) {
464
472
  retireRequestMemory(session.requests);
465
- wake(session.connection);
473
+ wakeTransport(session.connection);
466
474
  return;
467
475
  }
468
476
  session.transportRetirement = Promise.allSettled(pending).then(() => {
@@ -764,21 +772,38 @@ export class FilesystemService {
764
772
  }
765
773
  return responseHeld;
766
774
  }
775
+ /** NaN, which never equals a recorded value, when the backend cannot say. */
776
+ private unlinkGeneration(): number {
777
+ if (this.backend instanceof MemoryBackend) return this.backend.unlinkGeneration();
778
+ if (!this.backend.isUnlinked) return 0;
779
+ return this.backend.unlinkGeneration?.() ?? NaN;
780
+ }
767
781
  private trim(session: Session): void {
782
+ // Only an unlink makes a capability detachable, and idle capabilities exceed the bound only
783
+ // when the whole set does. Until either changes, a previous scan's answer still holds.
784
+ const unlinks = this.unlinkGeneration();
785
+ if (session.trimmedUnlinks === unlinks && session.transient.size <= TRANSIENT_HANDLES) return;
786
+ session.trimmedUnlinks = undefined;
768
787
  let idle = 0,
788
+ unlinked = 0,
769
789
  detached = false;
770
790
  const shared = this.backend instanceof MemoryBackend ? this.backend.shared : undefined;
771
791
  const isUnlinked = (handle: number) =>
772
792
  shared ? shared.isUnlinked(handle) : (this.backend.isUnlinked?.(handle) ?? false);
773
793
  const responseHeld = this.responseReferenceCounts(session);
774
794
  for (const handle of session.transient.keys()) {
795
+ const gone = isUnlinked(handle);
796
+ if (gone) unlinked++;
775
797
  const references = Atomics.load(session.capabilities, session.handles.get(handle)! + 1);
776
798
  if (session.preparingHandles.has(handle) || references !== (responseHeld.get(handle) ?? 0))
777
799
  continue;
778
800
  idle++;
779
- if (references === 0 && isUnlinked(handle)) detached = true;
801
+ if (references === 0 && gone) detached = true;
802
+ }
803
+ if (idle <= TRANSIENT_HANDLES && !detached) {
804
+ if (!unlinked) session.trimmedUnlinks = unlinks;
805
+ return;
780
806
  }
781
- if (idle <= TRANSIENT_HANDLES && !detached) return;
782
807
  // Over the bound, evict the least recently used down to half of it. Each eviction bumps the
783
808
  // namespace epoch and so drops every client's cached answers; one handle per new path
784
809
  // would do that on every resolve of a build that touches more paths than the bound.
@@ -802,9 +827,11 @@ export class FilesystemService {
802
827
  Atomics.store(session.capabilities, key + 1, 0);
803
828
  continue;
804
829
  }
830
+ if (isUnlinked(handle)) unlinked--;
805
831
  this.forget(session, handle, key);
806
832
  idle--;
807
833
  }
834
+ if (!unlinked) session.trimmedUnlinks = unlinks;
808
835
  } finally {
809
836
  if (invalidate) {
810
837
  if (shared) shared.endServiceMutation(epoch);
@@ -939,6 +966,7 @@ export class FilesystemService {
939
966
  "readdir",
940
967
  "readdirPage",
941
968
  "resolve",
969
+ "realpath",
942
970
  ].includes(operation)
943
971
  )
944
972
  this.check(session, a, held);
@@ -1037,6 +1065,33 @@ export class FilesystemService {
1037
1065
  else held.release();
1038
1066
  return held.batch;
1039
1067
  }
1068
+ if (operation === "watchDrain") {
1069
+ if (this.backend.watchDrain) {
1070
+ const register = (held: import("./watch-service.js").HeldWatchDrain) => {
1071
+ if (cancelled()) {
1072
+ held.rollback();
1073
+ throw new FilesystemError(11);
1074
+ }
1075
+ if (held.hasEvents)
1076
+ session.watchTransactions.set(requestId, {
1077
+ cancel: held.rollback,
1078
+ release: held.release,
1079
+ });
1080
+ else held.release();
1081
+ return { entries: held.entries, more: held.more };
1082
+ };
1083
+ const draining = this.backend.watchDrain(session.connection.owner, cancelled);
1084
+ return draining instanceof Promise
1085
+ ? this.trackRequestWork(session, draining).then(register)
1086
+ : register(draining);
1087
+ }
1088
+ if (!this.watchService) return { entries: [], more: false };
1089
+ const held = this.watchService.drainHeld(session.connection.owner);
1090
+ if (held.hasEvents)
1091
+ session.watchTransactions.set(requestId, { cancel: held.rollback, release: held.release });
1092
+ else held.release();
1093
+ return { entries: held.entries, more: held.more };
1094
+ }
1040
1095
  if (operation === "watchClose") {
1041
1096
  if (this.backend.watchClose) {
1042
1097
  this.backend.watchClose(session.connection.owner, a);
@@ -2220,7 +2275,7 @@ export class FilesystemService {
2220
2275
  const failure = requestTransportError(session.requests);
2221
2276
  if (failure?.reason !== "stale" && !requestMemoryRetired(session.requests))
2222
2277
  retireRequestMemory(session.requests);
2223
- wake(session.connection);
2278
+ wakeTransport(session.connection);
2224
2279
  }
2225
2280
  private async drainShutdown(owner: ShutdownOwner, fences: Promise<void>[]): Promise<void> {
2226
2281
  const failures: unknown[] = [];