@waffle-os/runtime 0.0.153 → 0.0.154

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/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 +4 -0
  9. package/core/wasi.ts +49 -0
  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 +40 -0
  17. package/dist/fs/backend.js +7 -0
  18. package/dist/fs/client.js +69 -15
  19. package/dist/fs/dirty-admission.js +15 -8
  20. package/dist/fs/indexeddb.js +288 -96
  21. package/dist/fs/memory.js +106 -20
  22. package/dist/fs/multitab-backend.js +121 -37
  23. package/dist/fs/multitab-protocol.js +1 -0
  24. package/dist/fs/persistent.js +70 -16
  25. package/dist/fs/protocol.js +15 -7
  26. package/dist/fs/publication-attachment.js +9 -7
  27. package/dist/fs/service.js +34 -9
  28. package/dist/fs/shared.js +96 -6
  29. package/dist/proc/command-stdio.js +1 -1
  30. package/dist/tooling/program/program-transformer.json +1 -1
  31. package/fs/backend.ts +11 -0
  32. package/fs/client.ts +93 -16
  33. package/fs/dirty-admission.ts +22 -7
  34. package/fs/guest-watch.ts +1 -1
  35. package/fs/indexeddb.ts +379 -110
  36. package/fs/memory.ts +120 -19
  37. package/fs/multitab-backend.ts +206 -61
  38. package/fs/multitab-protocol.ts +1 -0
  39. package/fs/persistent.ts +82 -16
  40. package/fs/protocol.ts +26 -7
  41. package/fs/publication-attachment.ts +9 -7
  42. package/fs/service.ts +35 -7
  43. package/fs/shared.ts +106 -8
  44. package/package.json +1 -1
  45. package/proc/command-stdio.ts +1 -1
  46. package/testing/idle-workspace-cancellation-browser.ts +22 -13
  47. package/testing/indexeddb-storage-browser.ts +435 -1
  48. package/tooling/program/program-transformer.json +1 -1
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);
@@ -2220,7 +2248,7 @@ export class FilesystemService {
2220
2248
  const failure = requestTransportError(session.requests);
2221
2249
  if (failure?.reason !== "stale" && !requestMemoryRetired(session.requests))
2222
2250
  retireRequestMemory(session.requests);
2223
- wake(session.connection);
2251
+ wakeTransport(session.connection);
2224
2252
  }
2225
2253
  private async drainShutdown(owner: ShutdownOwner, fences: Promise<void>[]): Promise<void> {
2226
2254
  const failures: unknown[] = [];
package/fs/shared.ts CHANGED
@@ -76,6 +76,9 @@ const FREED_REVISION_HIGH = 8;
76
76
  // not scan the whole identity table. Other header words: 9 and 10 are DirtyAdmission's
77
77
  // signals, 16 to 24 the identity allocator, and 32 onward the dirty-admission ledger.
78
78
  const REGISTERED_SLOTS = 11;
79
+ const CHANGE_SEQUENCE = 12;
80
+ // Unlinks of this table, for capability trimming. Kept across remount, so it never repeats.
81
+ const UNLINK_GENERATION = 31;
79
82
  // Global-lock accelerators. Nothing below a hint is free; ownership stays authoritative.
80
83
  const PHYSICAL_HINT = 27;
81
84
  const TABLE_HINT = 28;
@@ -184,6 +187,11 @@ export class SharedFilesystemState {
184
187
  readonly publication?: PublicationDomain;
185
188
  readonly watch: WatchRing;
186
189
  private readonly pageReaders?: Int32Array;
190
+ /** Slots this state has registered or seen registered, so listing them need not walk the
191
+ * whole identity table. Entries whose slot was freed since are dropped as they are found. */
192
+ private registeredIndex?: Set<number>;
193
+ /** The index in ascending slot order, rebuilt only after the index changes. */
194
+ private registeredOrder?: number[];
187
195
  onContention?: () => void;
188
196
  constructor(
189
197
  buffer?: SharedArrayBuffer,
@@ -296,7 +304,7 @@ export class SharedFilesystemState {
296
304
  }
297
305
  /** Reset all per-mount filesystem state in place across Host remount/demotion while preserving
298
306
  * tab-lifetime header invariants (`MAGIC`, `maxSegments`, owner/probe words, `WATCH_OFFSET`,
299
- * `watch.cells[3]`, `CLIENT_MODE`) and reusing tab-lifetime segments at their exact indexes. */
307
+ * `watch.cells[3]`, `CLIENT_MODE`, `UNLINK_GENERATION`) and reusing tab-lifetime segments at their exact indexes. */
300
308
  resetForRemount(retainedSegments: readonly (SharedArrayBuffer | undefined)[] = []): void {
301
309
  Atomics.store(this.cells, GLOBAL_LOCK, 0);
302
310
  Atomics.store(this.cells, USED_PAGES, 0);
@@ -834,11 +842,15 @@ export class SharedFilesystemState {
834
842
  (this.slots[base + REVISION]! >>> 0)
835
843
  );
836
844
  }
845
+ get changeSequence(): number {
846
+ return Atomics.load(this.cells, CHANGE_SEQUENCE);
847
+ }
837
848
  private changed(slot: number): void {
838
849
  const base = slot * SLOT_WORDS,
839
850
  low = this.slots[base + REVISION]!;
840
851
  this.slots[base + REVISION] = low + 1;
841
852
  if (low === -1) this.slots[base + REVISION_STATE] = this.slots[base + REVISION_STATE]! + 2;
853
+ Atomics.add(this.cells, CHANGE_SEQUENCE, 1);
842
854
  }
843
855
  private residentBytes(): number {
844
856
  return Atomics.load(this.cells, USED_PAGES) * DATA_PAGE_BYTES;
@@ -885,12 +897,42 @@ export class SharedFilesystemState {
885
897
  this.slots[this.at(slot, DIRTY_MARK)] = 1;
886
898
  }
887
899
  }
888
- cleanDirty(revision: number, namespace: number): void {
889
- if (!this.dirtyAdmission.clean(revision, namespace)) return;
890
- for (let slot = 1; slot < MAX_FILES; slot++) {
891
- this.slots[this.at(slot, DIRTY_SIZE)] = 0;
892
- this.slots[this.at(slot, DIRTY_MARK)] = 0;
900
+ reconcileDirty(
901
+ handles: Iterable<FileHandle>,
902
+ namespace: number,
903
+ dirtyNamespace: number,
904
+ isDirty: (handle: FileHandle, kind: number, revision: number, dirtyMark: number) => boolean,
905
+ ): void {
906
+ if (!this.dirtyAdmission.enabled) return;
907
+ let dirtyBytes = 0;
908
+ let dirtyMetadata = 0;
909
+ for (const handle of handles) {
910
+ const slot = this.findSlot(handle);
911
+ if (!slot) continue;
912
+ if (this.staged.size && this.staged.has(slot)) this.settleUnderLock(slot);
913
+ const base = slot * SLOT_WORDS;
914
+ const kind = this.slots[base]!;
915
+ if (!kind || this.slots[base + HANDLE] !== handle + 1) continue;
916
+ const revision = this.getRevision(slot);
917
+ const dirtyMark = this.slots[base + DIRTY_MARK]!;
918
+ if (!isDirty(handle, kind, revision, dirtyMark)) {
919
+ this.slots[base + DIRTY_SIZE] = 0;
920
+ this.slots[base + DIRTY_MARK] = 0;
921
+ continue;
922
+ }
923
+ if (kind === 1) {
924
+ const resident = (this.slots[base + REVISION_STATE]! & RESIDENT) !== 0;
925
+ const size = resident ? this.slots[base + FILE_SIZE]! : 0;
926
+ this.slots[base + DIRTY_SIZE] = size;
927
+ this.slots[base + DIRTY_MARK] = 1;
928
+ dirtyBytes += size * 2;
929
+ } else {
930
+ this.slots[base + DIRTY_SIZE] = 0;
931
+ this.slots[base + DIRTY_MARK] = 1;
932
+ }
933
+ dirtyMetadata += DIRTY_NODE_UNITS;
893
934
  }
935
+ this.dirtyAdmission.reconcile(namespace, dirtyNamespace, dirtyBytes, dirtyMetadata);
894
936
  }
895
937
  private checkFile(slot: number, handle: FileHandle): void {
896
938
  if (this.slots[this.at(slot, HANDLE)] !== handle + 1) throw new FilesystemError(8);
@@ -1013,7 +1055,7 @@ export class SharedFilesystemState {
1013
1055
  this.slots[this.at(slot, REVISION_STATE)] =
1014
1056
  Math.floor(revision / 0x100000000) * 2 + (loaded ? RESIDENT : 0);
1015
1057
  if (identity) this.installIdentity(slot, identity);
1016
- Atomics.store(this.slots, this.at(slot, HANDLE), handle + 1);
1058
+ this.publishHandle(slot, handle);
1017
1059
  } catch (error) {
1018
1060
  if (pinned) this.dirtyAdmission.pin(-1, this.residentBytes());
1019
1061
  throw error;
@@ -1113,12 +1155,44 @@ export class SharedFilesystemState {
1113
1155
  this.unlock(this.at(slot, FILE_LOCK));
1114
1156
  }
1115
1157
  }
1116
- /** Bounded by the resident identity table, not the size of the persisted namespace. */
1158
+ /** Publishes a registered slot's handle, then adds the slot to this state's index. */
1159
+ private publishHandle(slot: number, handle: FileHandle): void {
1160
+ Atomics.store(this.slots, this.at(slot, HANDLE), handle + 1);
1161
+ if (!this.registeredIndex || this.registeredIndex.has(slot)) return;
1162
+ this.registeredIndex.add(slot);
1163
+ this.registeredOrder = undefined;
1164
+ }
1165
+ /** Bounded by the resident identity table, not the size of the persisted namespace. In slot
1166
+ * order. Another agent's registration, or one racing this read, makes the indexed count differ
1167
+ * from the header's, and then the whole table is walked and the index rebuilt. */
1117
1168
  registeredHandles(): FileHandle[] {
1169
+ const expected = Atomics.load(this.cells, REGISTERED_SLOTS);
1170
+ const indexed = this.indexedHandles();
1171
+ if (indexed?.length === expected) return indexed;
1118
1172
  const handles: FileHandle[] = [];
1173
+ const index = new Set<number>();
1119
1174
  for (let slot = 1; slot < MAX_FILES; slot++) {
1175
+ const handle = Atomics.load(this.slots, this.at(slot, HANDLE)) - 1;
1176
+ if (handle < 0) continue;
1177
+ handles.push(handle);
1178
+ index.add(slot);
1179
+ }
1180
+ this.registeredIndex = index;
1181
+ this.registeredOrder = undefined;
1182
+ return handles;
1183
+ }
1184
+ private indexedHandles(): FileHandle[] | undefined {
1185
+ const index = this.registeredIndex;
1186
+ if (!index) return undefined;
1187
+ const order = (this.registeredOrder ??= Array.from(index).sort((a, b) => a - b));
1188
+ const handles: FileHandle[] = [];
1189
+ for (const slot of order) {
1120
1190
  const handle = Atomics.load(this.slots, this.at(slot, HANDLE)) - 1;
1121
1191
  if (handle >= 0) handles.push(handle);
1192
+ else {
1193
+ index.delete(slot);
1194
+ this.registeredOrder = undefined;
1195
+ }
1122
1196
  }
1123
1197
  return handles;
1124
1198
  }
@@ -2006,6 +2080,7 @@ export class SharedFilesystemState {
2006
2080
  if (slots[base + REVISION_STATE]! & RESIDENT) this.changed(stage.slot);
2007
2081
  }
2008
2082
  slots[base + REVISION_STATE] = slots[base + REVISION_STATE]! | RESIDENT;
2083
+ Atomics.add(this.cells, CHANGE_SEQUENCE, 1);
2009
2084
  }
2010
2085
  /** Caller owns the global mutation lock. Undefined asks for service growth after unlock. */
2011
2086
  tryWrite(
@@ -2356,7 +2431,24 @@ export class SharedFilesystemState {
2356
2431
  this.section?.exit();
2357
2432
  }
2358
2433
  }
2434
+ /** Moves on every unlink() of this table, the only place a slot becomes unlinked. It lives in
2435
+ * the table's header, so every state attached to the same backing reads one count.
2436
+ * Capability trimming compares it to skip rescans while nothing was unlinked. */
2437
+ unlinkGeneration(): number {
2438
+ return Atomics.load(this.cells, UNLINK_GENERATION);
2439
+ }
2440
+ /** A table that replaces another starts past its count, so the generation never repeats. */
2441
+ continueUnlinks(previous: SharedFilesystemState): void {
2442
+ const floor = previous.unlinkGeneration() + 1;
2443
+ for (;;) {
2444
+ const current = Atomics.load(this.cells, UNLINK_GENERATION);
2445
+ if (current >= floor) return;
2446
+ if (Atomics.compareExchange(this.cells, UNLINK_GENERATION, current, floor) === current)
2447
+ return;
2448
+ }
2449
+ }
2359
2450
  unlink(handle: FileHandle): void {
2451
+ Atomics.add(this.cells, UNLINK_GENERATION, 1);
2360
2452
  this.section?.enter();
2361
2453
  try {
2362
2454
  const slot = this.findSlot(handle);
@@ -2397,9 +2489,15 @@ export class SharedFilesystemState {
2397
2489
  if (this.slots[this.at(slot, UNLINKED)])
2398
2490
  this.publication?.forgetContent(this.slots[this.at(slot, INO)]!);
2399
2491
  this.freePagesLocked(slot);
2492
+ const dirtySize = this.slots[this.at(slot, DIRTY_SIZE)]!;
2493
+ const dirtyMark = this.slots[this.at(slot, DIRTY_MARK)]!;
2400
2494
  this.dirtyAdmission.pin(-1, this.residentBytes());
2401
2495
  this.slots[this.at(slot, DIRTY_SIZE)] = 0;
2402
2496
  this.slots[this.at(slot, DIRTY_MARK)] = 0;
2497
+ if (dirtySize || dirtyMark) {
2498
+ this.dirtyAdmission.releaseSlot(dirtySize * 2, dirtyMark ? DIRTY_NODE_UNITS : 0);
2499
+ Atomics.add(this.cells, CHANGE_SEQUENCE, 1);
2500
+ }
2403
2501
  const revision = this.getRevision(slot);
2404
2502
  const floor =
2405
2503
  (this.cells[FREED_REVISION_HIGH]! >>> 0) * 0x100000000 +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@waffle-os/runtime",
3
- "version": "0.0.153",
3
+ "version": "0.0.154",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/ShaulLavo/waffle.git",
@@ -250,7 +250,7 @@ export class CommandStdio {
250
250
  if (!filesystem)
251
251
  throw new CommandStdioError("EBADF", "File descriptor has no filesystem connection");
252
252
  const offset = shareFileResource(resource, filesystem.connection);
253
- return [new Int32Array(filesystem.connection.signal), new Int32Array(offset, 0, 1)];
253
+ return [new Int32Array(filesystem.connection.signal, 0, 1), new Int32Array(offset, 0, 1)];
254
254
  }
255
255
 
256
256
  private file(
@@ -40,6 +40,7 @@ async function cancelledLoad(name: string, phase: "metadata" | "manifest"): Prom
40
40
  const controller = new AbortController();
41
41
  const reason = new Error(`cancel idle ${phase} validation`);
42
42
  const nativeGet = IDBObjectStore.prototype.get;
43
+ const nativeGetAll = IDBObjectStore.prototype.getAll;
43
44
  const nativeClose = IDBDatabase.prototype.close;
44
45
  const nativeOpen = IDBFactory.prototype.open;
45
46
  let settled = false,
@@ -54,27 +55,34 @@ async function cancelledLoad(name: string, phase: "metadata" | "manifest"): Prom
54
55
  event.preventDefault();
55
56
  };
56
57
  globalThis.addEventListener("unhandledrejection", observeRejection);
57
- IDBObjectStore.prototype.get = function (key) {
58
- if (this.name === "data" && typeof key === "string" && controller.signal.aborted)
59
- manifestsAfterAbort++;
60
- const result = nativeGet.call(this, key);
61
- const selected =
62
- phase === "metadata"
63
- ? this.name === "metadata" && key === 0
64
- : this.name === "data" && typeof key === "string";
65
- if (!selected || controller.signal.aborted) return result;
66
- const aborted = this.transaction.onabort;
67
- const completed = this.transaction.oncomplete;
68
- this.transaction.onabort = function (event) {
58
+ /** Cancels once, right after the selected native request was placed. */
59
+ const cancelAfter = (store: IDBObjectStore, selected: boolean) => {
60
+ if (!selected || controller.signal.aborted) return;
61
+ const aborted = store.transaction.onabort;
62
+ const completed = store.transaction.oncomplete;
63
+ store.transaction.onabort = function (event) {
69
64
  settled = true;
70
65
  aborted?.call(this, event);
71
66
  };
72
- this.transaction.oncomplete = function (event) {
67
+ store.transaction.oncomplete = function (event) {
73
68
  settled = true;
74
69
  completed?.call(this, event);
75
70
  };
76
71
  successor = IndexedDBStorage.open(name);
77
72
  controller.abort(reason);
73
+ };
74
+ IDBObjectStore.prototype.get = function (key) {
75
+ if (this.name === "data" && typeof key === "string" && controller.signal.aborted)
76
+ manifestsAfterAbort++;
77
+ const result = nativeGet.call(this, key);
78
+ cancelAfter(this, phase === "metadata" && this.name === "metadata" && key === 0);
79
+ return result;
80
+ };
81
+ // Manifests are validated from one bulk read of the data store's string keys.
82
+ IDBObjectStore.prototype.getAll = function (...args: Parameters<IDBObjectStore["getAll"]>) {
83
+ if (this.name === "data" && controller.signal.aborted) manifestsAfterAbort++;
84
+ const result = nativeGetAll.apply(this, args);
85
+ cancelAfter(this, phase === "manifest" && this.name === "data");
78
86
  return result;
79
87
  };
80
88
  IDBDatabase.prototype.close = function () {
@@ -114,6 +122,7 @@ async function cancelledLoad(name: string, phase: "metadata" | "manifest"): Prom
114
122
  assert(unhandled.length === 0, "cancelled native requests have rejection observers");
115
123
  } finally {
116
124
  IDBObjectStore.prototype.get = nativeGet;
125
+ IDBObjectStore.prototype.getAll = nativeGetAll;
117
126
  IDBDatabase.prototype.close = nativeClose;
118
127
  IDBFactory.prototype.open = nativeOpen;
119
128
  globalThis.removeEventListener("unhandledrejection", observeRejection);