@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
@@ -8,7 +8,10 @@ import {
8
8
  } from "./checkpoint-pressure.js";
9
9
  import { FilesystemError, PAGE } from "./protocol.js";
10
10
  import { MemoryBackend } from "./backend.js";
11
- import { MemFS, adoptInodes } from "./memory.js";
11
+ import {
12
+ MemFS,
13
+ adoptInodes
14
+ } from "./memory.js";
12
15
  import {
13
16
  storeTime,
14
17
  validatePersistedIndex
@@ -25,6 +28,9 @@ export class PersistentBackend extends MemoryBackend {
25
28
  pressure;
26
29
  nodes = new Map;
27
30
  byFileId = new Map;
31
+ dirEntryBytes = new WeakMap;
32
+ namespaceBytes = 0;
33
+ idleChangeSequence;
28
34
  initialWorkspaceId;
29
35
  initialEra;
30
36
  loadedIndex;
@@ -64,6 +70,7 @@ export class PersistentBackend extends MemoryBackend {
64
70
  if (this.nodes.has(node.ino))
65
71
  return;
66
72
  this.nodes.set(node.ino, node);
73
+ this.namespaceBytes += this.nodeMetadataBytes(node);
67
74
  if (node.identity)
68
75
  this.byFileId.set(node.identity.id, node);
69
76
  if (node.kind === "dir")
@@ -83,6 +90,13 @@ export class PersistentBackend extends MemoryBackend {
83
90
  this.committedKeys = new Map(this.keys);
84
91
  } else
85
92
  this.dirty.add(fs.root);
93
+ fs.onDirEntryDelta = (dir, delta) => {
94
+ const existing = this.dirEntryBytes.get(dir);
95
+ if (existing !== undefined)
96
+ this.dirEntryBytes.set(dir, existing + delta);
97
+ if (this.nodes.has(dir.ino))
98
+ this.namespaceBytes += delta;
99
+ };
86
100
  fs.onLinkChange = (node, delta) => this.changeLinks(node, delta);
87
101
  fs.onChange = (node) => {
88
102
  if (!this.detached.has(node)) {
@@ -127,10 +141,15 @@ export class PersistentBackend extends MemoryBackend {
127
141
  setTerminalFailureListener(listener) {
128
142
  this.storage.setTerminalFailureListener?.(listener);
129
143
  }
144
+ hasPendingChanges() {
145
+ if (this.dirty.size > 0 || this.removed.size > 0 || this.shared.publication)
146
+ return true;
147
+ return this.idleChangeSequence === undefined || this.shared.changeSequence !== this.idleChangeSequence;
148
+ }
130
149
  startTimer(intervalMs) {
131
150
  if (intervalMs > 0)
132
151
  this.timer = setInterval(() => {
133
- if (!this.stopped && !this.pendingCheckpoints)
152
+ if (!this.stopped && !this.pendingCheckpoints && this.hasPendingChanges())
134
153
  this.checkpoint().catch(() => {});
135
154
  }, intervalMs);
136
155
  }
@@ -174,6 +193,7 @@ export class PersistentBackend extends MemoryBackend {
174
193
  this.links.delete(node.ino);
175
194
  if (delta === 1 && previous === 0) {
176
195
  this.nodes.set(node.ino, node);
196
+ this.namespaceBytes += this.nodeMetadataBytes(node);
177
197
  if (node.identity)
178
198
  this.byFileId.set(node.identity.id, node);
179
199
  this.detached.delete(node);
@@ -192,6 +212,7 @@ export class PersistentBackend extends MemoryBackend {
192
212
  this.changeLinks(child, 1);
193
213
  } else if (delta === -1 && count === 0) {
194
214
  this.nodes.delete(node.ino);
215
+ this.namespaceBytes -= this.nodeMetadataBytes(node);
195
216
  this.dirty.delete(node);
196
217
  this.detached.add(node);
197
218
  this.removed.add(node.ino);
@@ -392,10 +413,7 @@ export class PersistentBackend extends MemoryBackend {
392
413
  return this.ownWork(load);
393
414
  }
394
415
  namespaceUnits() {
395
- let units = 0;
396
- for (const node of this.nodes.values())
397
- units += this.nodeMetadataBytes(node) * 4;
398
- return units;
416
+ return this.namespaceBytes * 4;
399
417
  }
400
418
  configureDirty() {
401
419
  if (this.dirtyLimits === false)
@@ -405,8 +423,10 @@ export class PersistentBackend extends MemoryBackend {
405
423
  attachShared(...args) {
406
424
  const previous = this.shared;
407
425
  super.attachShared(...args);
408
- if (previous !== this.shared)
426
+ if (previous !== this.shared) {
427
+ this.idleChangeSequence = undefined;
409
428
  this.configureDirty();
429
+ }
410
430
  }
411
431
  namespaceGrowth(plan) {
412
432
  let units = plan.created.reduce((sum, node) => sum + this.nodeMetadataBytes(node), 0);
@@ -587,15 +607,22 @@ export class PersistentBackend extends MemoryBackend {
587
607
  work.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
588
608
  });
589
609
  }
610
+ cachedDirEntryBytes(node) {
611
+ let entryBytes = this.dirEntryBytes.get(node);
612
+ if (entryBytes !== undefined)
613
+ return entryBytes;
614
+ entryBytes = 0;
615
+ for (const name of node.children.keys())
616
+ entryBytes += 64 + name.length * 2;
617
+ this.dirEntryBytes.set(node, entryBytes);
618
+ return entryBytes;
619
+ }
590
620
  nodeMetadataBytes(node) {
591
- let bytes = 256;
592
621
  if (node.kind === "symlink")
593
- return bytes + node.target.length * 2 + utf8ByteLength(node.target);
594
- if (node.kind !== "dir")
595
- return bytes;
596
- for (const name of node.children.keys())
597
- bytes += 64 + name.length * 2;
598
- return bytes;
622
+ return 256 + node.target.length * 2 + utf8ByteLength(node.target);
623
+ if (node.kind === "dir")
624
+ return 256 + this.cachedDirEntryBytes(node);
625
+ return 256;
599
626
  }
600
627
  pinMetadataBytes() {
601
628
  let bytes = 0;
@@ -652,11 +679,32 @@ export class PersistentBackend extends MemoryBackend {
652
679
  return true;
653
680
  }
654
681
  invalidateCapturedState() {
682
+ this.idleChangeSequence = undefined;
655
683
  this.keys = new Map(this.committedKeys);
656
684
  for (const handle of this.revisions.keys())
657
685
  if (this.shared.isResident(handle))
658
686
  this.revisions.delete(handle);
659
687
  }
688
+ reconcileDirtyAfterCommit(revision) {
689
+ if (!this.shared.dirtyAdmission.enabled || this.pendingCheckpoints > 0)
690
+ return;
691
+ const namespace = this.namespaceUnits();
692
+ if (this.shared.dirtyAdmission.revision === revision && !this.dirty.size && !this.removed.size) {
693
+ this.shared.reconcileDirty(this.registeredNodes.keys(), namespace, 0, () => false);
694
+ return;
695
+ }
696
+ let dirtyNamespace = this.removed.size * 256;
697
+ for (const node of this.dirty)
698
+ dirtyNamespace += this.nodeMetadataBytes(node);
699
+ this.shared.reconcileDirty(this.registeredNodes.keys(), namespace, dirtyNamespace * 4, (handle, kind, currentRevision, dirtyMark) => {
700
+ if (kind === 1)
701
+ return currentRevision !== this.revisions.get(handle);
702
+ if (dirtyMark !== 1)
703
+ return false;
704
+ const node = this.registeredNodes.get(handle);
705
+ return node !== undefined && this.dirty.has(node);
706
+ });
707
+ }
660
708
  reserveCheckpoint(request) {
661
709
  const cost = { ...this.captureCost(request) };
662
710
  this.shared.dirtyAdmission.reserveCopy(cost, this.shared.resources().usedBytes);
@@ -668,11 +716,17 @@ export class PersistentBackend extends MemoryBackend {
668
716
  throw error;
669
717
  }
670
718
  const revision = this.includesDetachedWriters(request) ? this.shared.dirtyAdmission.revision : undefined;
719
+ const capturedChangeSeq = this.shared.changeSequence;
671
720
  try {
672
721
  return this.captureReserved(request, reservation, cost).then(() => {
673
- if (revision === undefined)
722
+ if (this.stopped)
674
723
  return;
675
- this.shared.mutate(undefined, undefined, () => this.shared.cleanDirty(revision, this.namespaceUnits()));
724
+ this.shared.mutate(undefined, undefined, () => {
725
+ if (!this.pendingCheckpoints && !this.dirty.size && !this.removed.size && this.shared.changeSequence === capturedChangeSeq)
726
+ this.idleChangeSequence = capturedChangeSeq;
727
+ if (revision !== undefined)
728
+ this.reconcileDirtyAfterCommit(revision);
729
+ });
676
730
  }).finally(() => {
677
731
  this.pressure.release(reservation);
678
732
  this.shared.mutate(undefined, undefined, () => this.shared.dirtyAdmission.releaseCopy(cost));
@@ -68,6 +68,8 @@ export function normalizeSharedMaxBytes(maxBytes) {
68
68
  }
69
69
  export const HEADER = REQUEST_HEADER;
70
70
  export const TRANSIENT_HANDLES = 256;
71
+ export const SIGNAL_TRANSPORT = 1;
72
+ export const SIGNAL_BYTES = 8;
71
73
  export const CAPABILITY_SLOTS = 4096;
72
74
  export const CAPABILITY_HEADER = 1;
73
75
  export const FILESYSTEM_SECTION_BYTES = 8;
@@ -89,7 +91,7 @@ export function filesystemOwnerPlan(publication) {
89
91
  const arena = publicationBufferPlan(publication.limits, publication.observe);
90
92
  const allocations = 9 + arena.allocations;
91
93
  return {
92
- bytes: MAX_CONNECTION_OWNERS * 4 + CAPABILITY_LENGTH * 4 + 12 + FILESYSTEM_SECTION_BYTES + arena.bytes + REQUEST_BUDGET_BYTES + REQUEST_CONTROL_BYTES,
94
+ bytes: MAX_CONNECTION_OWNERS * 4 + CAPABILITY_LENGTH * 4 + 8 + SIGNAL_BYTES + FILESYSTEM_SECTION_BYTES + arena.bytes + REQUEST_BUDGET_BYTES + REQUEST_CONTROL_BYTES,
93
95
  allocations,
94
96
  references: allocations,
95
97
  leases: 0
@@ -130,7 +132,7 @@ function constructFilesystemIdentity(parent, maxBytes, publication, construction
130
132
  ...parent?.residentPublication ? { residentPublication: parent.residentPublication } : {},
131
133
  epoch: parent?.epoch ?? allocate(4),
132
134
  requestBudget: parent?.requestBudget ?? createRequestBudget(construction),
133
- signal: parent?.signal ?? allocate(4),
135
+ signal: parent?.signal ?? allocate(SIGNAL_BYTES),
134
136
  revocations: [allocate(4)].concat(parent?.revocations ?? []),
135
137
  shared,
136
138
  segments: parent?.segments ?? [],
@@ -270,13 +272,13 @@ export function createFilesystemConnection(parent, publication, construction) {
270
272
  export function revokeFilesystemService(connection) {
271
273
  Atomics.store(new Int32Array(connection.ownerStates), 0, 1);
272
274
  wakeFilesystemWatch(connection.shared, true);
273
- wake(connection);
275
+ wakeTransport(connection);
274
276
  }
275
277
  export function revokeFilesystem(connection) {
276
278
  Atomics.compareExchange(new Int32Array(connection.revocations[0]), 0, 0, 1);
277
279
  Atomics.compareExchange(new Int32Array(connection.ownerStates), connection.owner, 0, 1);
278
- wakeFilesystemWatch(connection.shared);
279
- wake(connection);
280
+ wakeFilesystemWatch(connection.shared, true);
281
+ wakeTransport(connection);
280
282
  }
281
283
  export async function waitForFilesystemQuiescence(connection) {
282
284
  revokeFilesystem(connection);
@@ -299,17 +301,23 @@ export async function waitForFilesystemQuiescence(connection) {
299
301
  export function reapFilesystem(connection) {
300
302
  Atomics.store(new Int32Array(connection.revocations[0]), 0, 2);
301
303
  Atomics.store(new Int32Array(connection.ownerStates), connection.owner, 2);
302
- wakeFilesystemWatch(connection.shared);
304
+ wakeFilesystemWatch(connection.shared, true);
303
305
  if (connection.publication)
304
306
  new PublicationDomain(connection.publication.buffers).retireSession(connection.publication.session);
305
307
  Atomics.notify(new Int32Array(connection.sections), 0);
306
- wake(connection);
308
+ wakeTransport(connection);
307
309
  }
308
310
  export function wake(connection) {
309
311
  const signal = new Int32ArrayConstructor(connection.signal);
310
312
  atomicsAdd(signal, 0, 1);
311
313
  atomicsNotify(signal, 0);
312
314
  }
315
+ export function wakeTransport(connection) {
316
+ const signal = new Int32ArrayConstructor(connection.signal);
317
+ atomicsAdd(signal, SIGNAL_TRANSPORT, 1);
318
+ atomicsNotify(signal, SIGNAL_TRANSPORT);
319
+ wake(connection);
320
+ }
313
321
  const encoder = new TextEncoder;
314
322
  const decoder = new TextDecoder;
315
323
  export function pack(value) {
@@ -50,6 +50,8 @@ import {
50
50
  pack,
51
51
  unpack,
52
52
  wake,
53
+ wakeTransport,
54
+ SIGNAL_BYTES,
53
55
  CONNECTION_SHARED_BYTES,
54
56
  MAX_CONNECTION_OWNERS,
55
57
  connectFilesystemIdentity,
@@ -761,7 +763,7 @@ function workspaceConnection(value, parent) {
761
763
  requestBudget: workspaceBuffer(data.requestBudget, REQUEST_BUDGET_BYTES),
762
764
  port: data.port,
763
765
  epoch: workspaceBuffer(data.epoch, 4),
764
- signal: workspaceBuffer(data.signal, 4),
766
+ signal: workspaceBuffer(data.signal, SIGNAL_BYTES),
765
767
  revocations,
766
768
  shared: workspaceBuffer(data.shared, CONNECTION_SHARED_BYTES + 4),
767
769
  segments,
@@ -795,7 +797,7 @@ class WorkspaceBridge {
795
797
  connection.port.onmessage = ({ data }) => this.receive(data);
796
798
  connection.port.onmessageerror = () => {
797
799
  closeRequestMemory(connection.requests);
798
- wake(connection);
800
+ wakeTransport(connection);
799
801
  this.replyStopped();
800
802
  };
801
803
  connection.port.start();
@@ -876,7 +878,7 @@ class WorkspaceBridge {
876
878
  this.message(record(value));
877
879
  } catch {
878
880
  closeRequestMemory(this.connection.requests);
879
- wake(this.connection);
881
+ wakeTransport(this.connection);
880
882
  this.replyStopped();
881
883
  }
882
884
  }
@@ -896,7 +898,7 @@ class WorkspaceBridge {
896
898
  }
897
899
  if ("transportClosed" in data) {
898
900
  closeRequestMemory(this.connection.requests);
899
- wake(this.connection);
901
+ wakeTransport(this.connection);
900
902
  return this.replyStopped();
901
903
  }
902
904
  const id = integer(data.id);
@@ -1012,10 +1014,10 @@ class WorkspaceBridge {
1012
1014
  replyStopped() {
1013
1015
  this.stop().then(() => {
1014
1016
  retireRequestMemory(this.connection.requests);
1015
- wake(this.connection);
1017
+ wakeTransport(this.connection);
1016
1018
  }, (error) => {
1017
1019
  retireRequestMemory(this.connection.requests, error instanceof FilesystemError ? error.errno : 29);
1018
- wake(this.connection);
1020
+ wakeTransport(this.connection);
1019
1021
  });
1020
1022
  }
1021
1023
  stop() {
@@ -1044,7 +1046,7 @@ class WorkspaceBridge {
1044
1046
  this.endpoint.channel.close();
1045
1047
  this.connection.port.close();
1046
1048
  retireRequestMemory(this.connection.requests);
1047
- wake(this.connection);
1049
+ wakeTransport(this.connection);
1048
1050
  if (!this.bindingStarted)
1049
1051
  this.transfer.resolve();
1050
1052
  }
@@ -43,6 +43,7 @@ import {
43
43
  CAPABILITY_WORDS,
44
44
  PAGE,
45
45
  TRANSIENT_HANDLES,
46
+ SIGNAL_TRANSPORT,
46
47
  State,
47
48
  FilesystemError,
48
49
  errno,
@@ -53,6 +54,7 @@ import {
53
54
  waitForFilesystemQuiescence,
54
55
  unpack,
55
56
  wake,
57
+ wakeTransport,
56
58
  sameFilesystemIdentity,
57
59
  reserveIdentityCapability,
58
60
  releaseFilesystemReservation
@@ -282,19 +284,20 @@ export class FilesystemService {
282
284
  }
283
285
  signalTransportFailure(session, reason = "messageerror") {
284
286
  closeRequestMemory(session.requests, reason);
285
- wake(session.connection);
287
+ wakeTransport(session.connection);
286
288
  }
287
289
  async watchTransport(session) {
288
290
  const signal = new Int32Array(session.connection.signal);
291
+ const word = session.connection.publication ? 0 : SIGNAL_TRANSPORT;
289
292
  while (!session.closed) {
290
- const observed = Atomics.load(signal, 0);
293
+ const observed = Atomics.load(signal, word);
291
294
  if (sessionRevoked(session)) {
292
295
  if (requestTransportError(session.requests))
293
296
  session.transportFailed = true;
294
297
  this.close(session);
295
298
  return;
296
299
  }
297
- const waiting = atomicsWaitAsync(signal, 0, observed);
300
+ const waiting = atomicsWaitAsync(signal, word, observed);
298
301
  if (waiting.async)
299
302
  await waiting.value;
300
303
  }
@@ -345,7 +348,7 @@ export class FilesystemService {
345
348
  const pending = Array.from(this.work).filter((entry) => entry[1] === session && !joined.has(entry[0])).map((entry) => entry[0]);
346
349
  if (!pending.length) {
347
350
  retireRequestMemory(session.requests);
348
- wake(session.connection);
351
+ wakeTransport(session.connection);
349
352
  return;
350
353
  }
351
354
  session.transportRetirement = Promise.allSettled(pending).then(() => {
@@ -592,21 +595,38 @@ export class FilesystemService {
592
595
  }
593
596
  return responseHeld;
594
597
  }
598
+ unlinkGeneration() {
599
+ if (this.backend instanceof MemoryBackend)
600
+ return this.backend.unlinkGeneration();
601
+ if (!this.backend.isUnlinked)
602
+ return 0;
603
+ return this.backend.unlinkGeneration?.() ?? NaN;
604
+ }
595
605
  trim(session) {
596
- let idle = 0, detached = false;
606
+ const unlinks = this.unlinkGeneration();
607
+ if (session.trimmedUnlinks === unlinks && session.transient.size <= TRANSIENT_HANDLES)
608
+ return;
609
+ session.trimmedUnlinks = undefined;
610
+ let idle = 0, unlinked = 0, detached = false;
597
611
  const shared = this.backend instanceof MemoryBackend ? this.backend.shared : undefined;
598
612
  const isUnlinked = (handle) => shared ? shared.isUnlinked(handle) : this.backend.isUnlinked?.(handle) ?? false;
599
613
  const responseHeld = this.responseReferenceCounts(session);
600
614
  for (const handle of session.transient.keys()) {
615
+ const gone = isUnlinked(handle);
616
+ if (gone)
617
+ unlinked++;
601
618
  const references = Atomics.load(session.capabilities, session.handles.get(handle) + 1);
602
619
  if (session.preparingHandles.has(handle) || references !== (responseHeld.get(handle) ?? 0))
603
620
  continue;
604
621
  idle++;
605
- if (references === 0 && isUnlinked(handle))
622
+ if (references === 0 && gone)
606
623
  detached = true;
607
624
  }
608
- if (idle <= TRANSIENT_HANDLES && !detached)
625
+ if (idle <= TRANSIENT_HANDLES && !detached) {
626
+ if (!unlinked)
627
+ session.trimmedUnlinks = unlinks;
609
628
  return;
629
+ }
610
630
  const keep = idle > TRANSIENT_HANDLES ? TRANSIENT_HANDLES / 2 : TRANSIENT_HANDLES;
611
631
  const epoch = session.epoch;
612
632
  const invalidate = !shared?.ownsServiceMutation;
@@ -630,9 +650,13 @@ export class FilesystemService {
630
650
  Atomics.store(session.capabilities, key + 1, 0);
631
651
  continue;
632
652
  }
653
+ if (isUnlinked(handle))
654
+ unlinked--;
633
655
  this.forget(session, handle, key);
634
656
  idle--;
635
657
  }
658
+ if (!unlinked)
659
+ session.trimmedUnlinks = unlinks;
636
660
  } finally {
637
661
  if (invalidate) {
638
662
  if (shared)
@@ -751,7 +775,8 @@ export class FilesystemService {
751
775
  "setTimes",
752
776
  "readdir",
753
777
  "readdirPage",
754
- "resolve"
778
+ "resolve",
779
+ "realpath"
755
780
  ].includes(operation))
756
781
  this.check(session, a, held);
757
782
  if (["create", "symlink", "link", "removePath", "rename"].includes(operation)) {
@@ -1789,7 +1814,7 @@ export class FilesystemService {
1789
1814
  const failure = requestTransportError(session.requests);
1790
1815
  if (failure?.reason !== "stale" && !requestMemoryRetired(session.requests))
1791
1816
  retireRequestMemory(session.requests);
1792
- wake(session.connection);
1817
+ wakeTransport(session.connection);
1793
1818
  }
1794
1819
  async drainShutdown(owner, fences) {
1795
1820
  const failures = [];
package/dist/fs/shared.js CHANGED
@@ -60,6 +60,8 @@ const RETIRED_PAGE = -1;
60
60
  const FREED_REVISION_LOW = 7;
61
61
  const FREED_REVISION_HIGH = 8;
62
62
  const REGISTERED_SLOTS = 11;
63
+ const CHANGE_SEQUENCE = 12;
64
+ const UNLINK_GENERATION = 31;
63
65
  const PHYSICAL_HINT = 27;
64
66
  const TABLE_HINT = 28;
65
67
  const PINNED_PAGES = 29;
@@ -131,6 +133,8 @@ export class SharedFilesystemState {
131
133
  publication;
132
134
  watch;
133
135
  pageReaders;
136
+ registeredIndex;
137
+ registeredOrder;
134
138
  onContention;
135
139
  constructor(buffer, maxBytes = DEFAULT_SHARED_MAX_BYTES, lockOwner = SERVICE_OWNER, segments = [], section, publication, startupMemoryBudget) {
136
140
  this.lockOwner = lockOwner;
@@ -730,11 +734,15 @@ export class SharedFilesystemState {
730
734
  const base = slot * SLOT_WORDS;
731
735
  return (this.slots[base + REVISION_STATE] >>> 1) * 4294967296 + (this.slots[base + REVISION] >>> 0);
732
736
  }
737
+ get changeSequence() {
738
+ return Atomics.load(this.cells, CHANGE_SEQUENCE);
739
+ }
733
740
  changed(slot) {
734
741
  const base = slot * SLOT_WORDS, low = this.slots[base + REVISION];
735
742
  this.slots[base + REVISION] = low + 1;
736
743
  if (low === -1)
737
744
  this.slots[base + REVISION_STATE] = this.slots[base + REVISION_STATE] + 2;
745
+ Atomics.add(this.cells, CHANGE_SEQUENCE, 1);
738
746
  }
739
747
  residentBytes() {
740
748
  return Atomics.load(this.cells, USED_PAGES) * DATA_PAGE_BYTES;
@@ -769,13 +777,41 @@ export class SharedFilesystemState {
769
777
  this.slots[this.at(slot, DIRTY_MARK)] = 1;
770
778
  }
771
779
  }
772
- cleanDirty(revision, namespace) {
773
- if (!this.dirtyAdmission.clean(revision, namespace))
780
+ reconcileDirty(handles, namespace, dirtyNamespace, isDirty) {
781
+ if (!this.dirtyAdmission.enabled)
774
782
  return;
775
- for (let slot = 1;slot < MAX_FILES; slot++) {
776
- this.slots[this.at(slot, DIRTY_SIZE)] = 0;
777
- this.slots[this.at(slot, DIRTY_MARK)] = 0;
783
+ let dirtyBytes = 0;
784
+ let dirtyMetadata = 0;
785
+ for (const handle of handles) {
786
+ const slot = this.findSlot(handle);
787
+ if (!slot)
788
+ continue;
789
+ if (this.staged.size && this.staged.has(slot))
790
+ this.settleUnderLock(slot);
791
+ const base = slot * SLOT_WORDS;
792
+ const kind = this.slots[base];
793
+ if (!kind || this.slots[base + HANDLE] !== handle + 1)
794
+ continue;
795
+ const revision = this.getRevision(slot);
796
+ const dirtyMark = this.slots[base + DIRTY_MARK];
797
+ if (!isDirty(handle, kind, revision, dirtyMark)) {
798
+ this.slots[base + DIRTY_SIZE] = 0;
799
+ this.slots[base + DIRTY_MARK] = 0;
800
+ continue;
801
+ }
802
+ if (kind === 1) {
803
+ const resident = (this.slots[base + REVISION_STATE] & RESIDENT) !== 0;
804
+ const size = resident ? this.slots[base + FILE_SIZE] : 0;
805
+ this.slots[base + DIRTY_SIZE] = size;
806
+ this.slots[base + DIRTY_MARK] = 1;
807
+ dirtyBytes += size * 2;
808
+ } else {
809
+ this.slots[base + DIRTY_SIZE] = 0;
810
+ this.slots[base + DIRTY_MARK] = 1;
811
+ }
812
+ dirtyMetadata += DIRTY_NODE_UNITS;
778
813
  }
814
+ this.dirtyAdmission.reconcile(namespace, dirtyNamespace, dirtyBytes, dirtyMetadata);
779
815
  }
780
816
  checkFile(slot, handle) {
781
817
  if (this.slots[this.at(slot, HANDLE)] !== handle + 1)
@@ -892,7 +928,7 @@ export class SharedFilesystemState {
892
928
  this.slots[this.at(slot, REVISION_STATE)] = Math.floor(revision / 4294967296) * 2 + (loaded ? RESIDENT : 0);
893
929
  if (identity)
894
930
  this.installIdentity(slot, identity);
895
- Atomics.store(this.slots, this.at(slot, HANDLE), handle + 1);
931
+ this.publishHandle(slot, handle);
896
932
  } catch (error) {
897
933
  if (pinned)
898
934
  this.dirtyAdmission.pin(-1, this.residentBytes());
@@ -989,12 +1025,45 @@ export class SharedFilesystemState {
989
1025
  this.unlock(this.at(slot, FILE_LOCK));
990
1026
  }
991
1027
  }
1028
+ publishHandle(slot, handle) {
1029
+ Atomics.store(this.slots, this.at(slot, HANDLE), handle + 1);
1030
+ if (!this.registeredIndex || this.registeredIndex.has(slot))
1031
+ return;
1032
+ this.registeredIndex.add(slot);
1033
+ this.registeredOrder = undefined;
1034
+ }
992
1035
  registeredHandles() {
1036
+ const expected = Atomics.load(this.cells, REGISTERED_SLOTS);
1037
+ const indexed = this.indexedHandles();
1038
+ if (indexed?.length === expected)
1039
+ return indexed;
993
1040
  const handles = [];
1041
+ const index = new Set;
994
1042
  for (let slot = 1;slot < MAX_FILES; slot++) {
1043
+ const handle = Atomics.load(this.slots, this.at(slot, HANDLE)) - 1;
1044
+ if (handle < 0)
1045
+ continue;
1046
+ handles.push(handle);
1047
+ index.add(slot);
1048
+ }
1049
+ this.registeredIndex = index;
1050
+ this.registeredOrder = undefined;
1051
+ return handles;
1052
+ }
1053
+ indexedHandles() {
1054
+ const index = this.registeredIndex;
1055
+ if (!index)
1056
+ return;
1057
+ const order = this.registeredOrder ??= Array.from(index).sort((a, b) => a - b);
1058
+ const handles = [];
1059
+ for (const slot of order) {
995
1060
  const handle = Atomics.load(this.slots, this.at(slot, HANDLE)) - 1;
996
1061
  if (handle >= 0)
997
1062
  handles.push(handle);
1063
+ else {
1064
+ index.delete(slot);
1065
+ this.registeredOrder = undefined;
1066
+ }
998
1067
  }
999
1068
  return handles;
1000
1069
  }
@@ -1608,6 +1677,7 @@ export class SharedFilesystemState {
1608
1677
  this.changed(stage.slot);
1609
1678
  }
1610
1679
  slots[base + REVISION_STATE] = slots[base + REVISION_STATE] | RESIDENT;
1680
+ Atomics.add(this.cells, CHANGE_SEQUENCE, 1);
1611
1681
  }
1612
1682
  tryWrite(handle, chunks, offset, total, revoked, owner = this.lockOwner) {
1613
1683
  const slot = this.slot(handle);
@@ -1866,7 +1936,21 @@ export class SharedFilesystemState {
1866
1936
  this.section?.exit();
1867
1937
  }
1868
1938
  }
1939
+ unlinkGeneration() {
1940
+ return Atomics.load(this.cells, UNLINK_GENERATION);
1941
+ }
1942
+ continueUnlinks(previous) {
1943
+ const floor = previous.unlinkGeneration() + 1;
1944
+ for (;; ) {
1945
+ const current = Atomics.load(this.cells, UNLINK_GENERATION);
1946
+ if (current >= floor)
1947
+ return;
1948
+ if (Atomics.compareExchange(this.cells, UNLINK_GENERATION, current, floor) === current)
1949
+ return;
1950
+ }
1951
+ }
1869
1952
  unlink(handle) {
1953
+ Atomics.add(this.cells, UNLINK_GENERATION, 1);
1870
1954
  this.section?.enter();
1871
1955
  try {
1872
1956
  const slot = this.findSlot(handle);
@@ -1904,9 +1988,15 @@ export class SharedFilesystemState {
1904
1988
  if (this.slots[this.at(slot, UNLINKED)])
1905
1989
  this.publication?.forgetContent(this.slots[this.at(slot, INO)]);
1906
1990
  this.freePagesLocked(slot);
1991
+ const dirtySize = this.slots[this.at(slot, DIRTY_SIZE)];
1992
+ const dirtyMark = this.slots[this.at(slot, DIRTY_MARK)];
1907
1993
  this.dirtyAdmission.pin(-1, this.residentBytes());
1908
1994
  this.slots[this.at(slot, DIRTY_SIZE)] = 0;
1909
1995
  this.slots[this.at(slot, DIRTY_MARK)] = 0;
1996
+ if (dirtySize || dirtyMark) {
1997
+ this.dirtyAdmission.releaseSlot(dirtySize * 2, dirtyMark ? DIRTY_NODE_UNITS : 0);
1998
+ Atomics.add(this.cells, CHANGE_SEQUENCE, 1);
1999
+ }
1910
2000
  const revision = this.getRevision(slot);
1911
2001
  const floor = (this.cells[FREED_REVISION_HIGH] >>> 0) * 4294967296 + (this.cells[FREED_REVISION_LOW] >>> 0);
1912
2002
  if (revision > floor) {
@@ -211,7 +211,7 @@ export class CommandStdio {
211
211
  if (!filesystem)
212
212
  throw new CommandStdioError("EBADF", "File descriptor has no filesystem connection");
213
213
  const offset = shareFileResource(resource, filesystem.connection);
214
- return [new Int32Array(filesystem.connection.signal), new Int32Array(offset, 0, 1)];
214
+ return [new Int32Array(filesystem.connection.signal, 0, 1), new Int32Array(offset, 0, 1)];
215
215
  }
216
216
  file(resource, bytes, writing) {
217
217
  const filesystem = this.filesystem;
@@ -1 +1 @@
1
- {"commit":"5dcc58a08c0c1b3044dc6d47b4c13b688d70fa6d","buildToolsSha256":"b617652c1601f8722bb85c3a688a1fca4985b53f2c2066c10c76c2e693081137","optimizerSourceSha256":"34c4a040f3cf639f039823880822c6541c384c9b4eaa116d27dda8d9cb5c9f9e"}
1
+ {"commit":"d5c6dc5f37fb4cbbf8b40f3d82741cb9e00cdfff","buildToolsSha256":"b617652c1601f8722bb85c3a688a1fca4985b53f2c2066c10c76c2e693081137","optimizerSourceSha256":"34c4a040f3cf639f039823880822c6541c384c9b4eaa116d27dda8d9cb5c9f9e"}
package/fs/backend.ts CHANGED
@@ -71,6 +71,9 @@ export interface FilesystemBackend {
71
71
  isPreparedReadValid?(): boolean;
72
72
  /** Whether a handle is unlinked (used by service capability trimming when not MemoryBackend). */
73
73
  isUnlinked?(handle: FileHandle): boolean;
74
+ /** Changes whenever `isUnlinked` may have become true for some handle, so capability trimming
75
+ * can skip rescanning while nothing was unlinked. Without it every trim rescans. */
76
+ unlinkGeneration?(): number;
74
77
  /** Select a bounded cold descriptor range before asynchronous storage work. */
75
78
  prepareDescriptorRead?(
76
79
  handle: FileHandle,
@@ -162,6 +165,10 @@ export type MemoryBackendSharedRoot = Pick<FilesystemIdentity, "shared" | "maxBy
162
165
 
163
166
  export class MemoryBackend implements FilesystemBackend {
164
167
  private readonly watchOwner: { observer?: WatchMutationObserver };
168
+ /** The shared slot table's unlink count, so wrappers over the same table share it. */
169
+ unlinkGeneration(): number {
170
+ return this.shared.unlinkGeneration();
171
+ }
165
172
  installWatchObserver(observer: WatchMutationObserver): void {
166
173
  if (this.watchOwner.observer && this.watchOwner.observer !== observer)
167
174
  throw new Error("filesystem root already has a watch owner");
@@ -270,6 +277,7 @@ export class MemoryBackend implements FilesystemBackend {
270
277
  publication,
271
278
  );
272
279
  if (this.sharedPhase !== "imported") this.shared.identities.copyFrom(previous.identities);
280
+ this.shared.continueUnlinks(previous);
273
281
  this.sharedPhase = "attached";
274
282
  }
275
283
  /** revoked ends a wait for another owner's shared lock when the caller's request is cancelled. */
@@ -448,6 +456,9 @@ export class MemoryBackend implements FilesystemBackend {
448
456
  case "resolve":
449
457
  this.check(a, "directory");
450
458
  return this.fs.resolve(a, b, c === true, args[3] === true);
459
+ case "realpath":
460
+ this.check(a, "directory");
461
+ return this.fs.realpath(a, b, c === true);
451
462
  case "readlink":
452
463
  this.check(a);
453
464
  return this.fs.readlink(a);