@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
@@ -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)) {
@@ -839,6 +864,34 @@ export class FilesystemService {
839
864
  held.release();
840
865
  return held.batch;
841
866
  }
867
+ if (operation === "watchDrain") {
868
+ if (this.backend.watchDrain) {
869
+ const register = (held) => {
870
+ if (cancelled()) {
871
+ held.rollback();
872
+ throw new FilesystemError(11);
873
+ }
874
+ if (held.hasEvents)
875
+ session.watchTransactions.set(requestId, {
876
+ cancel: held.rollback,
877
+ release: held.release
878
+ });
879
+ else
880
+ held.release();
881
+ return { entries: held.entries, more: held.more };
882
+ };
883
+ const draining = this.backend.watchDrain(session.connection.owner, cancelled);
884
+ return draining instanceof Promise ? this.trackRequestWork(session, draining).then(register) : register(draining);
885
+ }
886
+ if (!this.watchService)
887
+ return { entries: [], more: false };
888
+ const held = this.watchService.drainHeld(session.connection.owner);
889
+ if (held.hasEvents)
890
+ session.watchTransactions.set(requestId, { cancel: held.rollback, release: held.release });
891
+ else
892
+ held.release();
893
+ return { entries: held.entries, more: held.more };
894
+ }
842
895
  if (operation === "watchClose") {
843
896
  if (this.backend.watchClose) {
844
897
  this.backend.watchClose(session.connection.owner, a);
@@ -1789,7 +1842,7 @@ export class FilesystemService {
1789
1842
  const failure = requestTransportError(session.requests);
1790
1843
  if (failure?.reason !== "stale" && !requestMemoryRetired(session.requests))
1791
1844
  retireRequestMemory(session.requests);
1792
- wake(session.connection);
1845
+ wakeTransport(session.connection);
1793
1846
  }
1794
1847
  async drainShutdown(owner, fences) {
1795
1848
  const failures = [];
package/dist/fs/shared.js CHANGED
@@ -60,12 +60,15 @@ 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;
66
68
  export const CLIENT_MODE = 30;
67
69
  export const CLIENT_MODE_NO_DIRECT_IO = 1;
68
70
  export const CLIENT_MODE_NO_CLIENT_CACHE = 2;
71
+ export const CLIENT_MODE_NO_WATCH_DRAIN = 4;
69
72
  const MODE = 12;
70
73
  const FILE_SIZE = 1;
71
74
  const MTIME = 2;
@@ -131,6 +134,8 @@ export class SharedFilesystemState {
131
134
  publication;
132
135
  watch;
133
136
  pageReaders;
137
+ registeredIndex;
138
+ registeredOrder;
134
139
  onContention;
135
140
  constructor(buffer, maxBytes = DEFAULT_SHARED_MAX_BYTES, lockOwner = SERVICE_OWNER, segments = [], section, publication, startupMemoryBudget) {
136
141
  this.lockOwner = lockOwner;
@@ -218,6 +223,9 @@ export class SharedFilesystemState {
218
223
  isClientCacheDisabled() {
219
224
  return (atomicsLoad(this.cells, CLIENT_MODE) & CLIENT_MODE_NO_CLIENT_CACHE) !== 0;
220
225
  }
226
+ isWatchDrainDisabled() {
227
+ return (atomicsLoad(this.cells, CLIENT_MODE) & CLIENT_MODE_NO_WATCH_DRAIN) !== 0;
228
+ }
221
229
  resetForRemount(retainedSegments = []) {
222
230
  Atomics.store(this.cells, GLOBAL_LOCK, 0);
223
231
  Atomics.store(this.cells, USED_PAGES, 0);
@@ -730,11 +738,15 @@ export class SharedFilesystemState {
730
738
  const base = slot * SLOT_WORDS;
731
739
  return (this.slots[base + REVISION_STATE] >>> 1) * 4294967296 + (this.slots[base + REVISION] >>> 0);
732
740
  }
741
+ get changeSequence() {
742
+ return Atomics.load(this.cells, CHANGE_SEQUENCE);
743
+ }
733
744
  changed(slot) {
734
745
  const base = slot * SLOT_WORDS, low = this.slots[base + REVISION];
735
746
  this.slots[base + REVISION] = low + 1;
736
747
  if (low === -1)
737
748
  this.slots[base + REVISION_STATE] = this.slots[base + REVISION_STATE] + 2;
749
+ Atomics.add(this.cells, CHANGE_SEQUENCE, 1);
738
750
  }
739
751
  residentBytes() {
740
752
  return Atomics.load(this.cells, USED_PAGES) * DATA_PAGE_BYTES;
@@ -769,13 +781,41 @@ export class SharedFilesystemState {
769
781
  this.slots[this.at(slot, DIRTY_MARK)] = 1;
770
782
  }
771
783
  }
772
- cleanDirty(revision, namespace) {
773
- if (!this.dirtyAdmission.clean(revision, namespace))
784
+ reconcileDirty(handles, namespace, dirtyNamespace, isDirty) {
785
+ if (!this.dirtyAdmission.enabled)
774
786
  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;
787
+ let dirtyBytes = 0;
788
+ let dirtyMetadata = 0;
789
+ for (const handle of handles) {
790
+ const slot = this.findSlot(handle);
791
+ if (!slot)
792
+ continue;
793
+ if (this.staged.size && this.staged.has(slot))
794
+ this.settleUnderLock(slot);
795
+ const base = slot * SLOT_WORDS;
796
+ const kind = this.slots[base];
797
+ if (!kind || this.slots[base + HANDLE] !== handle + 1)
798
+ continue;
799
+ const revision = this.getRevision(slot);
800
+ const dirtyMark = this.slots[base + DIRTY_MARK];
801
+ if (!isDirty(handle, kind, revision, dirtyMark)) {
802
+ this.slots[base + DIRTY_SIZE] = 0;
803
+ this.slots[base + DIRTY_MARK] = 0;
804
+ continue;
805
+ }
806
+ if (kind === 1) {
807
+ const resident = (this.slots[base + REVISION_STATE] & RESIDENT) !== 0;
808
+ const size = resident ? this.slots[base + FILE_SIZE] : 0;
809
+ this.slots[base + DIRTY_SIZE] = size;
810
+ this.slots[base + DIRTY_MARK] = 1;
811
+ dirtyBytes += size * 2;
812
+ } else {
813
+ this.slots[base + DIRTY_SIZE] = 0;
814
+ this.slots[base + DIRTY_MARK] = 1;
815
+ }
816
+ dirtyMetadata += DIRTY_NODE_UNITS;
778
817
  }
818
+ this.dirtyAdmission.reconcile(namespace, dirtyNamespace, dirtyBytes, dirtyMetadata);
779
819
  }
780
820
  checkFile(slot, handle) {
781
821
  if (this.slots[this.at(slot, HANDLE)] !== handle + 1)
@@ -892,7 +932,7 @@ export class SharedFilesystemState {
892
932
  this.slots[this.at(slot, REVISION_STATE)] = Math.floor(revision / 4294967296) * 2 + (loaded ? RESIDENT : 0);
893
933
  if (identity)
894
934
  this.installIdentity(slot, identity);
895
- Atomics.store(this.slots, this.at(slot, HANDLE), handle + 1);
935
+ this.publishHandle(slot, handle);
896
936
  } catch (error) {
897
937
  if (pinned)
898
938
  this.dirtyAdmission.pin(-1, this.residentBytes());
@@ -989,12 +1029,45 @@ export class SharedFilesystemState {
989
1029
  this.unlock(this.at(slot, FILE_LOCK));
990
1030
  }
991
1031
  }
1032
+ publishHandle(slot, handle) {
1033
+ Atomics.store(this.slots, this.at(slot, HANDLE), handle + 1);
1034
+ if (!this.registeredIndex || this.registeredIndex.has(slot))
1035
+ return;
1036
+ this.registeredIndex.add(slot);
1037
+ this.registeredOrder = undefined;
1038
+ }
992
1039
  registeredHandles() {
1040
+ const expected = Atomics.load(this.cells, REGISTERED_SLOTS);
1041
+ const indexed = this.indexedHandles();
1042
+ if (indexed?.length === expected)
1043
+ return indexed;
993
1044
  const handles = [];
1045
+ const index = new Set;
994
1046
  for (let slot = 1;slot < MAX_FILES; slot++) {
1047
+ const handle = Atomics.load(this.slots, this.at(slot, HANDLE)) - 1;
1048
+ if (handle < 0)
1049
+ continue;
1050
+ handles.push(handle);
1051
+ index.add(slot);
1052
+ }
1053
+ this.registeredIndex = index;
1054
+ this.registeredOrder = undefined;
1055
+ return handles;
1056
+ }
1057
+ indexedHandles() {
1058
+ const index = this.registeredIndex;
1059
+ if (!index)
1060
+ return;
1061
+ const order = this.registeredOrder ??= Array.from(index).sort((a, b) => a - b);
1062
+ const handles = [];
1063
+ for (const slot of order) {
995
1064
  const handle = Atomics.load(this.slots, this.at(slot, HANDLE)) - 1;
996
1065
  if (handle >= 0)
997
1066
  handles.push(handle);
1067
+ else {
1068
+ index.delete(slot);
1069
+ this.registeredOrder = undefined;
1070
+ }
998
1071
  }
999
1072
  return handles;
1000
1073
  }
@@ -1608,6 +1681,7 @@ export class SharedFilesystemState {
1608
1681
  this.changed(stage.slot);
1609
1682
  }
1610
1683
  slots[base + REVISION_STATE] = slots[base + REVISION_STATE] | RESIDENT;
1684
+ Atomics.add(this.cells, CHANGE_SEQUENCE, 1);
1611
1685
  }
1612
1686
  tryWrite(handle, chunks, offset, total, revoked, owner = this.lockOwner) {
1613
1687
  const slot = this.slot(handle);
@@ -1866,7 +1940,21 @@ export class SharedFilesystemState {
1866
1940
  this.section?.exit();
1867
1941
  }
1868
1942
  }
1943
+ unlinkGeneration() {
1944
+ return Atomics.load(this.cells, UNLINK_GENERATION);
1945
+ }
1946
+ continueUnlinks(previous) {
1947
+ const floor = previous.unlinkGeneration() + 1;
1948
+ for (;; ) {
1949
+ const current = Atomics.load(this.cells, UNLINK_GENERATION);
1950
+ if (current >= floor)
1951
+ return;
1952
+ if (Atomics.compareExchange(this.cells, UNLINK_GENERATION, current, floor) === current)
1953
+ return;
1954
+ }
1955
+ }
1869
1956
  unlink(handle) {
1957
+ Atomics.add(this.cells, UNLINK_GENERATION, 1);
1870
1958
  this.section?.enter();
1871
1959
  try {
1872
1960
  const slot = this.findSlot(handle);
@@ -1904,9 +1992,15 @@ export class SharedFilesystemState {
1904
1992
  if (this.slots[this.at(slot, UNLINKED)])
1905
1993
  this.publication?.forgetContent(this.slots[this.at(slot, INO)]);
1906
1994
  this.freePagesLocked(slot);
1995
+ const dirtySize = this.slots[this.at(slot, DIRTY_SIZE)];
1996
+ const dirtyMark = this.slots[this.at(slot, DIRTY_MARK)];
1907
1997
  this.dirtyAdmission.pin(-1, this.residentBytes());
1908
1998
  this.slots[this.at(slot, DIRTY_SIZE)] = 0;
1909
1999
  this.slots[this.at(slot, DIRTY_MARK)] = 0;
2000
+ if (dirtySize || dirtyMark) {
2001
+ this.dirtyAdmission.releaseSlot(dirtySize * 2, dirtyMark ? DIRTY_NODE_UNITS : 0);
2002
+ Atomics.add(this.cells, CHANGE_SEQUENCE, 1);
2003
+ }
1910
2004
  const revision = this.getRevision(slot);
1911
2005
  const floor = (this.cells[FREED_REVISION_HIGH] >>> 0) * 4294967296 + (this.cells[FREED_REVISION_LOW] >>> 0);
1912
2006
  if (revision > floor) {