@waffle-os/runtime 0.0.154 → 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.
@@ -23,22 +23,45 @@ export function parseChunk(value, size, key) {
23
23
  export function chunkLength(manifest, index) {
24
24
  return Math.min(CHUNK_SIZE, manifest.size - index * CHUNK_SIZE);
25
25
  }
26
+ const HEX = Array.from({ length: 256 }, (_, byte) => byte.toString(16).padStart(2, "0"));
27
+ const PREPARE_CONCURRENCY = 32;
26
28
  export async function chunkChecksum(bytes) {
27
29
  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
28
- return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
30
+ let hex = "";
31
+ for (let i = 0;i < digest.length; i++)
32
+ hex += HEX[digest[i]];
33
+ return hex;
29
34
  }
30
- export async function preparePayload(bytes, signal) {
31
- const chunks = [];
32
- for (let offset = 0;offset < bytes.length; offset += CHUNK_SIZE) {
35
+ async function prepareOwnedPayload(bytes, signal) {
36
+ if (!bytes.length) {
33
37
  signal?.throwIfAborted();
34
- const part = bytes.slice(offset, offset + CHUNK_SIZE);
35
- chunks.push({ bytes: part, checksum: await chunkChecksum(part) });
38
+ return {
39
+ manifest: { version: 2, size: 0, chunkSize: CHUNK_SIZE, count: 0 },
40
+ chunks: []
41
+ };
36
42
  }
43
+ const count = Math.ceil(bytes.length / CHUNK_SIZE);
44
+ const chunks = Array.from({ length: count });
45
+ let next = 0;
46
+ const workers = Math.min(PREPARE_CONCURRENCY, count);
47
+ await Promise.all(Array.from({ length: workers }, async () => {
48
+ while (next < count) {
49
+ signal?.throwIfAborted();
50
+ const index = next++;
51
+ const offset = index * CHUNK_SIZE;
52
+ const part = bytes.slice(offset, offset + CHUNK_SIZE);
53
+ chunks[index] = { bytes: part, checksum: await chunkChecksum(part) };
54
+ }
55
+ }));
56
+ signal?.throwIfAborted();
37
57
  return {
38
- manifest: { version: 2, size: bytes.length, chunkSize: CHUNK_SIZE, count: chunks.length },
58
+ manifest: { version: 2, size: bytes.length, chunkSize: CHUNK_SIZE, count },
39
59
  chunks
40
60
  };
41
61
  }
62
+ export function preparePayload(bytes, signal) {
63
+ return prepareOwnedPayload(bytes, signal);
64
+ }
42
65
  export function validateRange(range) {
43
66
  if (!validInteger(range.offset) || !validInteger(range.length) || !Number.isSafeInteger(range.offset + range.length))
44
67
  throw new RangeError("Invalid filesystem byte range");
@@ -48,7 +71,7 @@ export function deletePayload(store, key) {
48
71
  store.delete(key);
49
72
  store.delete(IDBKeyRange.bound([key, 0], [key, Number.MAX_SAFE_INTEGER]));
50
73
  }
51
- function putPayload(store, key, payload) {
74
+ export function putPayload(store, key, payload) {
52
75
  for (const [index, chunk] of payload.chunks.entries())
53
76
  store.put(chunk, [key, index]);
54
77
  store.put(payload.manifest, key);
@@ -96,10 +119,64 @@ function compareChunk(value, chunk, key, finish, abort) {
96
119
  abort(error);
97
120
  }
98
121
  }
99
- export async function preparePayloads(data) {
122
+ export async function preparePayloads(data, owned = false, checkAbort) {
100
123
  const prepared = new Map;
101
- for (const [key, bytes] of data)
102
- prepared.set(key, await preparePayload(bytes));
124
+ checkAbort?.();
125
+ if (!data.size)
126
+ return prepared;
127
+ const tasks = [];
128
+ for (const [key, bytes] of data) {
129
+ if (!bytes.length) {
130
+ prepared.set(key, {
131
+ manifest: { version: 2, size: 0, chunkSize: CHUNK_SIZE, count: 0 },
132
+ chunks: []
133
+ });
134
+ continue;
135
+ }
136
+ const count = Math.ceil(bytes.length / CHUNK_SIZE);
137
+ const chunks = Array.from({ length: count });
138
+ prepared.set(key, {
139
+ manifest: { version: 2, size: bytes.length, chunkSize: CHUNK_SIZE, count },
140
+ chunks
141
+ });
142
+ const direct = owned && count === 1 && bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength && bytes.buffer instanceof ArrayBuffer;
143
+ for (let index = 0;index < count; index++)
144
+ tasks.push({ chunks, index, bytes, offset: index * CHUNK_SIZE, direct });
145
+ }
146
+ if (!tasks.length)
147
+ return prepared;
148
+ let next = 0;
149
+ let failed = false;
150
+ let failure;
151
+ const fail = (error) => {
152
+ if (!failed) {
153
+ failed = true;
154
+ failure = error;
155
+ }
156
+ };
157
+ const workers = Math.min(PREPARE_CONCURRENCY, tasks.length);
158
+ await Promise.allSettled(Array.from({ length: workers }, async () => {
159
+ while (!failed && next < tasks.length) {
160
+ try {
161
+ checkAbort?.();
162
+ } catch (error) {
163
+ fail(error);
164
+ return;
165
+ }
166
+ const task = tasks[next++];
167
+ const part = task.direct ? task.bytes : task.bytes.slice(task.offset, task.offset + CHUNK_SIZE);
168
+ try {
169
+ const checksum = await chunkChecksum(part);
170
+ task.chunks[task.index] = { bytes: part, checksum };
171
+ } catch (error) {
172
+ fail(error);
173
+ return;
174
+ }
175
+ }
176
+ }));
177
+ if (failed)
178
+ throw failure;
179
+ checkAbort?.();
103
180
  return prepared;
104
181
  }
105
182
  export function copyLegacyChunks(data, key, prepared) {
@@ -23,6 +23,7 @@ import {
23
23
  parseManifest,
24
24
  preparePayload,
25
25
  preparePayloads,
26
+ putPayload,
26
27
  copyLegacyChunks,
27
28
  validateRange
28
29
  } from "./indexeddb-chunks.js";
@@ -347,6 +348,9 @@ class PayloadSizes {
347
348
  size(key) {
348
349
  return this.entries.get(key)?.size;
349
350
  }
351
+ has(key) {
352
+ return this.entries.has(key);
353
+ }
350
354
  }
351
355
  function validateDatabaseLayout(committed, format, keys, journalKeys, dataKeys) {
352
356
  const empty = committed && !keys.includes("format") && keys.every((key) => key === "epoch" || key === "lastExclusiveEpoch") && !journalKeys.length && !dataKeys.length;
@@ -454,6 +458,16 @@ function placeManifestReads(data, format, resolve, reject) {
454
458
  }
455
459
  };
456
460
  }
461
+ function raceAbort(promise, signal) {
462
+ if (!signal)
463
+ return promise;
464
+ signal.throwIfAborted();
465
+ return new Promise((resolve, reject) => {
466
+ const onAbort = () => reject(signal.reason);
467
+ signal.addEventListener("abort", onAbort, { once: true });
468
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
469
+ });
470
+ }
457
471
  function completed(tx) {
458
472
  return new Promise((resolve, reject) => {
459
473
  tx.oncomplete = () => resolve();
@@ -829,6 +843,7 @@ export class IndexedDBStorage {
829
843
  ownershipError;
830
844
  ownershipRetirement;
831
845
  transactions = new Set;
846
+ epochWitnesses = new Set;
832
847
  committedEnvelope;
833
848
  committedRecord;
834
849
  committedPending = false;
@@ -859,6 +874,32 @@ export class IndexedDBStorage {
859
874
  if (this.closed || this.ownershipError)
860
875
  return false;
861
876
  signal?.throwIfAborted();
877
+ const witnessed = await this.witnessedEpoch(signal);
878
+ if (witnessed !== undefined)
879
+ return witnessed && !this.closed && !this.ownershipError;
880
+ return this.readEpoch(signal);
881
+ }
882
+ async witnessedEpoch(signal) {
883
+ for (const witness of Array.from(this.epochWitnesses)) {
884
+ const result = await raceAbort(witness, signal);
885
+ if (result !== undefined)
886
+ return result;
887
+ }
888
+ return;
889
+ }
890
+ witnessEpoch(tx, read) {
891
+ const { promise: witness, resolve } = Promise.withResolvers();
892
+ const end = () => {
893
+ this.epochWitnesses.delete(witness);
894
+ resolve(undefined);
895
+ };
896
+ read.addEventListener("success", () => resolve(read.result === this.epoch));
897
+ read.addEventListener("error", () => resolve(undefined));
898
+ tx.addEventListener("complete", end);
899
+ tx.addEventListener("abort", end);
900
+ this.epochWitnesses.add(witness);
901
+ }
902
+ async readEpoch(signal) {
862
903
  let tx;
863
904
  const onAbort = () => {
864
905
  try {
@@ -1582,14 +1623,14 @@ export class IndexedDBStorage {
1582
1623
  this.committedRecord = await encodeCommit(envelope);
1583
1624
  }
1584
1625
  recordRecovery(state, extra) {
1585
- const retained = new Set(extra);
1586
- payloads(state.nodes.values(), retained);
1587
- for (const base of state.bases)
1588
- if (base)
1589
- payloads(base.nodes, retained);
1590
- for (const journal of state.journals.values())
1591
- payloads(journal.upserts, retained);
1592
- this.readers.recovery(retained);
1626
+ if (!extra?.length) {
1627
+ this.readers.recovery(state.payloadSizes);
1628
+ return;
1629
+ }
1630
+ const extraRoots = new Set(extra);
1631
+ this.readers.recovery({
1632
+ has: (key) => extraRoots.has(key) || state.payloadSizes.has(key)
1633
+ });
1593
1634
  }
1594
1635
  matchSizes(nodes, manifests) {
1595
1636
  return !manifests || nodes.every((node) => node.data === undefined || manifests.get(node.data)?.size === node.size);
@@ -1609,6 +1650,7 @@ export class IndexedDBStorage {
1609
1650
  const done = completed(tx);
1610
1651
  const metadata = tx.objectStore("metadata");
1611
1652
  const epoch = metadata.get("epoch");
1653
+ this.witnessEpoch(tx, epoch);
1612
1654
  epoch.onsuccess = () => {
1613
1655
  try {
1614
1656
  if (epoch.result !== this.epoch)
@@ -1669,7 +1711,12 @@ export class IndexedDBStorage {
1669
1711
  async commit(batch, committed) {
1670
1712
  if (this.committedMode !== !!committed)
1671
1713
  throw new Error("Committed storage requires a complete durable group");
1672
- const prepared = await preparePayloads(batch.data);
1714
+ const checkActive = () => {
1715
+ committed?.control.checkAbort();
1716
+ this.assertOwner();
1717
+ };
1718
+ const prepared = await preparePayloads(batch.data, true, checkActive);
1719
+ checkActive();
1673
1720
  const staged = stageChanges(this.state, batch), old = this.state;
1674
1721
  const discarded = new Set(old?.journalKeys.filter((key) => typeof key !== "number" || key > old.generation));
1675
1722
  const compact = !old || old.sinceCompaction + 1 >= this.compactEvery;
@@ -1782,26 +1829,43 @@ export class IndexedDBStorage {
1782
1829
  abort(error);
1783
1830
  }
1784
1831
  };
1785
- let remaining = checking.size + pinChecks.size + (committed ? 2 : 0);
1832
+ const newKeys = [];
1833
+ const verifyKeys = [];
1834
+ for (const key of checking) {
1835
+ if (prepared.has(key) && !old?.payloadKeys.has(key))
1836
+ newKeys.push(key);
1837
+ else
1838
+ verifyKeys.push(key);
1839
+ }
1840
+ let remaining = 1 + verifyKeys.length + pinChecks.size + (committed ? 1 : 0);
1786
1841
  const checked = () => {
1787
1842
  if (--remaining === 0)
1788
1843
  finish();
1789
1844
  };
1790
1845
  const checkEpoch = tx.objectStore("metadata").get("epoch");
1846
+ this.witnessEpoch(tx, checkEpoch);
1791
1847
  checkEpoch.onsuccess = () => {
1792
1848
  if (checkEpoch.result !== this.epoch) {
1793
1849
  abort(this.loseOwnership());
1794
1850
  return;
1795
1851
  }
1796
- if (committed)
1852
+ try {
1853
+ for (const key of newKeys) {
1854
+ const supplied = prepared.get(key);
1855
+ const size = expected.get(key);
1856
+ if (size !== undefined && supplied.manifest.size !== size)
1857
+ throw new Error(`Invalid filesystem payload size: ${key}`);
1858
+ putPayload(data, key, supplied);
1859
+ }
1797
1860
  checked();
1861
+ } catch (error) {
1862
+ abort(error);
1863
+ }
1798
1864
  };
1799
1865
  if (committed)
1800
1866
  checkCommitHead(tx, committed, checked, abort);
1801
1867
  try {
1802
- if (!remaining)
1803
- finish();
1804
- for (const key of checking) {
1868
+ for (const key of verifyKeys) {
1805
1869
  const get = data.get(key);
1806
1870
  get.onsuccess = () => {
1807
1871
  try {
@@ -9,7 +9,12 @@ import {
9
9
  pack,
10
10
  unpack
11
11
  } from "./protocol.js";
12
- import { CLIENT_MODE, CLIENT_MODE_NO_CLIENT_CACHE, CLIENT_MODE_NO_DIRECT_IO } from "./shared.js";
12
+ import {
13
+ CLIENT_MODE,
14
+ CLIENT_MODE_NO_CLIENT_CACHE,
15
+ CLIENT_MODE_NO_DIRECT_IO,
16
+ CLIENT_MODE_NO_WATCH_DRAIN
17
+ } from "./shared.js";
13
18
  import { HEADER_WORDS, WATCH_OFFSET } from "./storage-geometry.js";
14
19
  import { WatchRing } from "./watch-ring.js";
15
20
  import { WatchService } from "./watch-service.js";
@@ -323,7 +328,14 @@ export class MultiTabBackend {
323
328
  sharedMaxBytes;
324
329
  retainedSegments = [];
325
330
  watchCells;
326
- role = "init";
331
+ roleState = "init";
332
+ get role() {
333
+ return this.roleState;
334
+ }
335
+ set role(next) {
336
+ this.roleState = next;
337
+ this.syncClientMode();
338
+ }
327
339
  phase = "opening";
328
340
  steppingDown = false;
329
341
  disposing = false;
@@ -409,6 +421,7 @@ export class MultiTabBackend {
409
421
  byFileId = new Map;
410
422
  nextLocalWatchId = 1;
411
423
  localWatches = new Map;
424
+ hostWatchToLocal = new Map;
412
425
  constructor(options) {
413
426
  this.options = options;
414
427
  this.scope = multitabScope(options.implementation, options.name);
@@ -509,14 +522,22 @@ export class MultiTabBackend {
509
522
  this.configureSharedBuffer(buffer);
510
523
  if (this.persistent) {
511
524
  this.persistent.attachShared(buffer, this.sharedMaxBytes, this.retainedSegments);
512
- this.persistent.shared.setClientMode(CLIENT_MODE_NO_DIRECT_IO | CLIENT_MODE_NO_CLIENT_CACHE);
513
525
  }
526
+ this.syncClientMode();
514
527
  }
515
528
  configureSharedBuffer(buffer) {
516
- const header = new Int32Array(buffer, 0, HEADER_WORDS);
517
- Atomics.store(header, CLIENT_MODE, CLIENT_MODE_NO_DIRECT_IO | CLIENT_MODE_NO_CLIENT_CACHE);
518
529
  const ring = new WatchRing(buffer, WATCH_OFFSET);
519
530
  this.watchCells = ring.cells;
531
+ this.syncClientMode();
532
+ }
533
+ syncClientMode() {
534
+ const mode = CLIENT_MODE_NO_DIRECT_IO | CLIENT_MODE_NO_CLIENT_CACHE | (this.roleState === "host" ? 0 : CLIENT_MODE_NO_WATCH_DRAIN);
535
+ if (this.persistent) {
536
+ this.persistent.shared.setClientMode(mode);
537
+ } else if (this.sharedBuffer) {
538
+ const header = new Int32Array(this.sharedBuffer, 0, HEADER_WORDS);
539
+ Atomics.store(header, CLIENT_MODE, mode);
540
+ }
520
541
  }
521
542
  wakeWatchWord() {
522
543
  if (!this.watchCells)
@@ -777,16 +798,15 @@ export class MultiTabBackend {
777
798
  throw new FilesystemError(8);
778
799
  if (this.role === "host") {
779
800
  const admittedTerm = this.hostTerm;
780
- if (this.leaseOnlyLapsed(admittedTerm)) {
801
+ if (!this.hostReadyForLocal(admittedTerm)) {
781
802
  return this.watchOpenAfterRenewal(owner, handle, recursive, cancelled, admittedTerm);
782
803
  }
783
- this.assertHostReadyForLocal(admittedTerm);
784
804
  if (entry.remoteHandle === undefined)
785
805
  throw new FilesystemError(8);
786
806
  this.watchService ??= new WatchService(this.persistent);
787
807
  const hostWatchId = this.watchService.open(owner, entry.remoteHandle, recursive, cancelled);
788
808
  const localWatchId = this.nextLocalWatchId++;
789
- this.localWatches.set(localWatchId, {
809
+ const localEntry = {
790
810
  localWatchId,
791
811
  localOwner: owner,
792
812
  fileId: entry.fileId,
@@ -795,7 +815,9 @@ export class MultiTabBackend {
795
815
  hostWatchId,
796
816
  overflowed: false,
797
817
  closed: false
798
- });
818
+ };
819
+ this.localWatches.set(localWatchId, localEntry);
820
+ this.hostWatchToLocal.set(hostWatchId, localEntry);
799
821
  return localWatchId;
800
822
  }
801
823
  if (this.needsFailoverWait()) {
@@ -858,28 +880,119 @@ export class MultiTabBackend {
858
880
  return this.watchOpen(owner, handle, recursive, cancelled);
859
881
  }
860
882
  async watchReadHostAfterRenew(owner, watch, cancelled) {
861
- if (this.disposing || cancelled())
862
- throw new FilesystemError(11);
863
- if (this.leaseOnlyLapsed(watch.hostTerm)) {
864
- await this.renewLapsedLease(watch.hostTerm, cancelled).catch(() => {});
865
- } else {
866
- await raceWithAbort(this.renewLeaseNow(), this.disposeAbort.signal, cancelled);
867
- }
868
- if (this.disposing || cancelled())
869
- throw new FilesystemError(11);
870
883
  const overflow = {
871
884
  batch: { kind: "overflow", events: [] },
872
885
  release() {},
873
886
  rollback() {}
874
887
  };
875
- const termEnded = watch.hostTerm !== this.hostTerm || this.role !== "host" || this.ownershipLost || this.leaseClosed;
876
- if (watch.overflowed || termEnded || !this.watchService) {
877
- watch.overflowed = true;
878
- return overflow;
888
+ const budget = {};
889
+ await this.renewWatchLeaseOnce(watch.hostTerm, cancelled);
890
+ for (;; ) {
891
+ if (this.disposing || cancelled())
892
+ throw new FilesystemError(11);
893
+ const termEnded = watch.hostTerm !== this.hostTerm || this.role !== "host" || this.ownershipLost || this.leaseClosed;
894
+ if (watch.overflowed || termEnded || !this.watchService) {
895
+ watch.overflowed = true;
896
+ return overflow;
897
+ }
898
+ if (this.isLeaseValid())
899
+ return this.watchService.readHeld(owner, watch.hostWatchId);
900
+ if (!await this.renewWatchLease(watch.hostTerm, cancelled, budget))
901
+ return overflow;
902
+ }
903
+ }
904
+ async renewWatchLeaseOnce(admittedTerm, cancelled) {
905
+ if (this.disposing || cancelled())
906
+ throw new FilesystemError(11);
907
+ if (this.leaseOnlyLapsed(admittedTerm))
908
+ return;
909
+ await raceWithAbort(this.renewLeaseNow(), this.disposeAbort.signal, cancelled);
910
+ }
911
+ async renewWatchLease(admittedTerm, cancelled, budget) {
912
+ if (!this.leaseOnlyLapsed(admittedTerm))
913
+ return false;
914
+ try {
915
+ await this.renewLapsedLease(admittedTerm, cancelled, budget);
916
+ return true;
917
+ } catch {
918
+ if (this.disposing || cancelled())
919
+ throw new FilesystemError(11);
920
+ return false;
921
+ }
922
+ }
923
+ watchDrain(owner, cancelled) {
924
+ if (this.role === "host") {
925
+ const admittedTerm = this.hostTerm;
926
+ if (!this.isLeaseValid()) {
927
+ return this.watchDrainHostAfterRenew(owner, admittedTerm, cancelled);
928
+ }
929
+ return this.drainHostWatches(owner);
930
+ }
931
+ throw new FilesystemError(58);
932
+ }
933
+ overflowOwnerWatches(owner, permanent) {
934
+ const entries = [];
935
+ for (const watch of this.localWatches.values()) {
936
+ if (watch.closed || watch.localOwner !== owner)
937
+ continue;
938
+ if (permanent || watch.hostTerm !== this.hostTerm)
939
+ watch.overflowed = true;
940
+ entries.push({ id: watch.localWatchId, batch: { kind: "overflow", events: [] } });
941
+ }
942
+ return { entries, more: false, hasEvents: false, release() {}, rollback() {} };
943
+ }
944
+ async watchDrainHostAfterRenew(owner, admittedTerm, cancelled) {
945
+ const budget = {};
946
+ await this.renewWatchLeaseOnce(admittedTerm, cancelled);
947
+ for (;; ) {
948
+ if (this.disposing || cancelled())
949
+ throw new FilesystemError(11);
950
+ const termEnded = admittedTerm !== this.hostTerm || this.role !== "host" || this.ownershipLost || this.leaseClosed || !!this.terminalFailure || !this.watchService;
951
+ if (termEnded)
952
+ return this.overflowOwnerWatches(owner, true);
953
+ if (this.isLeaseValid())
954
+ return this.drainHostWatches(owner);
955
+ if (!await this.renewWatchLease(admittedTerm, cancelled, budget))
956
+ return this.overflowOwnerWatches(owner, false);
957
+ }
958
+ }
959
+ drainHostWatches(owner) {
960
+ if (this.terminalFailure || !this.watchService) {
961
+ return this.overflowOwnerWatches(owner, true);
962
+ }
963
+ const entries = [];
964
+ const seen = new Set;
965
+ const held = this.watchService.drainHeld(owner);
966
+ for (const entry of held.entries) {
967
+ const local = this.hostWatchToLocal.get(entry.id);
968
+ if (!local || local.closed || local.localOwner !== owner)
969
+ continue;
970
+ if (local.overflowed || local.hostTerm !== this.hostTerm) {
971
+ local.overflowed = true;
972
+ seen.add(local.localWatchId);
973
+ entries.push({ id: local.localWatchId, batch: { kind: "overflow", events: [] } });
974
+ continue;
975
+ }
976
+ seen.add(local.localWatchId);
977
+ entries.push("batch" in entry ? { id: local.localWatchId, batch: entry.batch } : { id: local.localWatchId, errno: entry.errno });
879
978
  }
880
- if (!this.isLeaseValid())
881
- return overflow;
882
- return this.watchService.readHeld(owner, watch.hostWatchId);
979
+ if (this.hostWatchToLocal.size !== this.localWatches.size) {
980
+ for (const watch of this.localWatches.values()) {
981
+ if (watch.closed || watch.localOwner !== owner || seen.has(watch.localWatchId))
982
+ continue;
983
+ if (watch.overflowed || watch.hostTerm !== this.hostTerm || watch.hostWatchId === undefined) {
984
+ watch.overflowed = true;
985
+ entries.push({ id: watch.localWatchId, batch: { kind: "overflow", events: [] } });
986
+ }
987
+ }
988
+ }
989
+ return {
990
+ entries,
991
+ more: held.more,
992
+ hasEvents: held.hasEvents,
993
+ release: held.release,
994
+ rollback: held.rollback
995
+ };
883
996
  }
884
997
  watchClose(owner, localWatchId) {
885
998
  const watch = this.localWatches.get(localWatchId);
@@ -887,6 +1000,9 @@ export class MultiTabBackend {
887
1000
  return;
888
1001
  watch.closed = true;
889
1002
  this.localWatches.delete(localWatchId);
1003
+ if (watch.hostWatchId !== undefined && this.hostWatchToLocal.get(watch.hostWatchId) === watch) {
1004
+ this.hostWatchToLocal.delete(watch.hostWatchId);
1005
+ }
890
1006
  if (this.role === "host" && watch.hostTerm === this.hostTerm && watch.hostWatchId !== undefined) {
891
1007
  this.watchService?.close(owner, watch.hostWatchId);
892
1008
  } else if (this.role === "peer" && watch.hostTerm === this.peerHostTerm && watch.hostWatchId !== undefined && this.peerSessionId) {
@@ -1188,7 +1304,7 @@ export class MultiTabBackend {
1188
1304
  }
1189
1305
  });
1190
1306
  if (this.sharedBuffer) {
1191
- backend.shared.setClientMode(CLIENT_MODE_NO_DIRECT_IO | CLIENT_MODE_NO_CLIENT_CACHE);
1307
+ backend.shared.setClientMode(CLIENT_MODE_NO_DIRECT_IO | CLIENT_MODE_NO_CLIENT_CACHE | CLIENT_MODE_NO_WATCH_DRAIN);
1192
1308
  }
1193
1309
  if (!backend.hasLoadedIndex) {
1194
1310
  await backend.flush();
@@ -4027,7 +4143,7 @@ export class MultiTabBackend {
4027
4143
  this.hostAdmittedZeroWaiters.push(resolve);
4028
4144
  });
4029
4145
  }
4030
- assertHostReadyForLocal(admittedTerm) {
4146
+ hostReadyForLocal(admittedTerm) {
4031
4147
  if (this.terminalFailure || this.persistent?.isTerminallyFailed()) {
4032
4148
  throw new FilesystemError(29, describeReason(this.terminalFailure?.reason));
4033
4149
  }
@@ -4037,19 +4153,23 @@ export class MultiTabBackend {
4037
4153
  if (this.steppingDown && (!this.disposing || this.disposeHostTerm !== admittedTerm)) {
4038
4154
  throw new FilesystemError(11, "host is stepping down");
4039
4155
  }
4040
- if (!this.isLeaseValid()) {
4041
- throw new FilesystemError(11, "host lease expired");
4042
- }
4156
+ if (this.isLeaseValid())
4157
+ return true;
4158
+ if (this.lapseIsRenewable(admittedTerm))
4159
+ return false;
4160
+ throw new FilesystemError(11, "host lease expired");
4043
4161
  }
4044
4162
  leaseOnlyLapsed(admittedTerm) {
4045
- return !this.isLeaseValid() && !this.leaseClosed && !this.ownershipLost && !this.terminalFailure && !this.persistent?.isTerminallyFailed() && !!this.persistent && this.role === "host" && this.hostTerm === admittedTerm && !this.steppingDown && !this.disposing;
4163
+ return !this.isLeaseValid() && this.lapseIsRenewable(admittedTerm);
4164
+ }
4165
+ lapseIsRenewable(admittedTerm) {
4166
+ return !this.leaseClosed && !this.ownershipLost && !this.terminalFailure && !this.persistent?.isTerminallyFailed() && !!this.persistent && this.role === "host" && this.hostTerm === admittedTerm && !this.steppingDown && !this.disposing;
4046
4167
  }
4047
4168
  assertLocalAttempt(admittedTerm, cancelled) {
4048
4169
  if (cancelled?.())
4049
4170
  throw new FilesystemError(11, "operation cancelled");
4050
- if (this.leaseOnlyLapsed(admittedTerm))
4171
+ if (!this.hostReadyForLocal(admittedTerm))
4051
4172
  throw LEASE_LAPSED;
4052
- this.assertHostReadyForLocal(admittedTerm);
4053
4173
  }
4054
4174
  localAttemptStale(admittedTerm, cancelled) {
4055
4175
  if (cancelled?.() || this.hostTerm !== admittedTerm)
@@ -4068,9 +4188,9 @@ export class MultiTabBackend {
4068
4188
  }
4069
4189
  }
4070
4190
  async assertHostAfterRenewal(admittedTerm, cancelled, budget) {
4071
- if (this.leaseOnlyLapsed(admittedTerm))
4191
+ while (!this.hostReadyForLocal(admittedTerm)) {
4072
4192
  await this.renewLapsedLease(admittedTerm, cancelled, budget);
4073
- this.assertHostReadyForLocal(admittedTerm);
4193
+ }
4074
4194
  }
4075
4195
  async renewLapsedLease(admittedTerm, cancelled, budget = {}) {
4076
4196
  const fresh = budget.deadline === undefined;
@@ -4091,44 +4211,56 @@ export class MultiTabBackend {
4091
4211
  if (cancelled?.())
4092
4212
  throw new FilesystemError(11, "operation cancelled");
4093
4213
  }
4094
- async executeLocalOnHost(operation, args, data, responseCookieTag, cancelled) {
4214
+ async renewBeforeLocalHostCall(admittedTerm, budget, operation, args, data, responseCookieTag, cancelled) {
4215
+ if (this.disposing)
4216
+ throw new FilesystemError(11, "host lease expired during dispose");
4217
+ if (this.leaseOnlyLapsed(admittedTerm)) {
4218
+ await this.renewLapsedLease(admittedTerm, cancelled, budget);
4219
+ } else {
4220
+ await raceWithAbort(this.renewLeaseNow(this.currentAttemptId), this.disposeAbort.signal, cancelled);
4221
+ }
4095
4222
  if (cancelled?.())
4096
4223
  throw new FilesystemError(11, "operation cancelled");
4097
- const admittedTerm = this.hostTerm;
4098
- const budget = {};
4099
- if (!this.isLeaseValid()) {
4100
- if (this.disposing)
4101
- throw new FilesystemError(11, "host lease expired during dispose");
4102
- if (this.leaseOnlyLapsed(admittedTerm)) {
4103
- await this.renewLapsedLease(admittedTerm, cancelled, budget);
4104
- } else {
4105
- await raceWithAbort(this.renewLeaseNow(this.currentAttemptId), this.disposeAbort.signal, cancelled);
4106
- }
4224
+ if (this.disposing)
4225
+ throw new FilesystemError(11, "filesystem is disposing");
4226
+ if (!this.isLeaseValid() && !this.leaseOnlyLapsed(admittedTerm)) {
4227
+ await this.awaitPendingFenceLoss(cancelled);
4107
4228
  if (cancelled?.())
4108
4229
  throw new FilesystemError(11, "operation cancelled");
4109
4230
  if (this.disposing)
4110
4231
  throw new FilesystemError(11, "filesystem is disposing");
4111
- if (!this.isLeaseValid()) {
4112
- await this.awaitPendingFenceLoss(cancelled);
4113
- if (cancelled?.())
4114
- throw new FilesystemError(11, "operation cancelled");
4115
- if (this.disposing)
4116
- throw new FilesystemError(11, "filesystem is disposing");
4117
- if (this.terminalFailure) {
4118
- throw new FilesystemError(29, describeReason(this.terminalFailure.reason));
4119
- }
4120
- if (this.ownershipLost)
4121
- throw new FilesystemError(11, "filesystem ownership lost");
4122
- if (this.role === "peer" || this.role === "failover" || this.role === "waiting") {
4123
- const nextCookieTag = this.revalidateCookieForPeerForward(operation, args, responseCookieTag);
4124
- return this.executeOnPeer(operation, args, data, nextCookieTag, cancelled);
4125
- }
4126
- throw new FilesystemError(11, "host lease expired");
4232
+ if (this.terminalFailure) {
4233
+ throw new FilesystemError(29, describeReason(this.terminalFailure.reason));
4234
+ }
4235
+ if (this.ownershipLost)
4236
+ throw new FilesystemError(11, "filesystem ownership lost");
4237
+ if (this.role === "peer" || this.role === "failover" || this.role === "waiting") {
4238
+ const nextCookieTag = this.revalidateCookieForPeerForward(operation, args, responseCookieTag);
4239
+ return {
4240
+ result: await this.executeOnPeer(operation, args, data, nextCookieTag, cancelled)
4241
+ };
4127
4242
  }
4243
+ throw new FilesystemError(11, "host lease expired");
4128
4244
  }
4245
+ return;
4246
+ }
4247
+ async executeLocalOnHost(operation, args, data, responseCookieTag, cancelled) {
4129
4248
  if (cancelled?.())
4130
4249
  throw new FilesystemError(11, "operation cancelled");
4131
- this.assertHostReadyForLocal(admittedTerm);
4250
+ const admittedTerm = this.hostTerm;
4251
+ const budget = {};
4252
+ if (!this.isLeaseValid()) {
4253
+ const forwarded = await this.renewBeforeLocalHostCall(admittedTerm, budget, operation, args, data, responseCookieTag, cancelled);
4254
+ if (forwarded)
4255
+ return forwarded.result;
4256
+ }
4257
+ if (cancelled?.())
4258
+ throw new FilesystemError(11, "operation cancelled");
4259
+ if (!this.hostReadyForLocal(admittedTerm)) {
4260
+ await this.assertHostAfterRenewal(admittedTerm, cancelled, budget);
4261
+ if (cancelled?.())
4262
+ throw new FilesystemError(11, "operation cancelled");
4263
+ }
4132
4264
  const persistent = this.persistent;
4133
4265
  const translated = this.translateArgsToHost(operation, args);
4134
4266
  if (!translated)
@@ -5241,6 +5373,7 @@ export class MultiTabBackend {
5241
5373
  this.dirEpoch++;
5242
5374
  }
5243
5375
  markLocalWatchesOverflow() {
5376
+ this.hostWatchToLocal.clear();
5244
5377
  for (const watch of this.localWatches.values()) {
5245
5378
  watch.overflowed = true;
5246
5379
  }