@syncular/client 0.58.0 → 0.60.0

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 (99) hide show
  1. package/README.md +34 -34
  2. package/dist/apply.d.ts +24 -14
  3. package/dist/apply.js +119 -70
  4. package/dist/authority.js +21 -16
  5. package/dist/blob.d.ts +17 -9
  6. package/dist/blob.js +5 -6
  7. package/dist/bun-database.d.ts +1 -0
  8. package/dist/bun-database.js +15 -0
  9. package/dist/client.d.ts +83 -75
  10. package/dist/client.js +982 -910
  11. package/dist/database.d.ts +5 -0
  12. package/dist/devtools.d.ts +2 -2
  13. package/dist/devtools.js +3 -3
  14. package/dist/diagnostics.d.ts +17 -28
  15. package/dist/diagnostics.js +1 -2
  16. package/dist/encryption.d.ts +2 -2
  17. package/dist/encryption.js +8 -2
  18. package/dist/errors.d.ts +3 -1
  19. package/dist/errors.js +5 -1
  20. package/dist/failed-overlay.d.ts +0 -1
  21. package/dist/failed-overlay.js +6 -6
  22. package/dist/http.d.ts +4 -1
  23. package/dist/http.js +67 -39
  24. package/dist/index.d.ts +1 -1
  25. package/dist/index.js +1 -1
  26. package/dist/invalidation.d.ts +14 -14
  27. package/dist/invalidation.js +24 -48
  28. package/dist/local-purge.js +9 -12
  29. package/dist/local-rebootstrap.js +2 -2
  30. package/dist/multi-tab.d.ts +89 -1
  31. package/dist/multi-tab.js +70 -31
  32. package/dist/native-bridge.d.ts +226 -0
  33. package/dist/native-bridge.js +764 -0
  34. package/dist/node-database.d.ts +1 -0
  35. package/dist/node-database.js +21 -1
  36. package/dist/outbox.d.ts +9 -12
  37. package/dist/outbox.js +20 -36
  38. package/dist/outcomes.js +3 -3
  39. package/dist/previous-version.js +96 -114
  40. package/dist/progress.d.ts +2 -2
  41. package/dist/query-guard.d.ts +34 -24
  42. package/dist/query-guard.js +61 -186
  43. package/dist/reactive-store.js +55 -13
  44. package/dist/realtime-supervisor.d.ts +9 -2
  45. package/dist/realtime-supervisor.js +31 -7
  46. package/dist/remote.js +19 -23
  47. package/dist/schema.d.ts +3 -2
  48. package/dist/schema.js +43 -22
  49. package/dist/state.d.ts +69 -36
  50. package/dist/state.js +178 -89
  51. package/dist/sync-scheduler.js +28 -2
  52. package/dist/transport.d.ts +19 -4
  53. package/dist/wasm-database.js +58 -21
  54. package/dist/window.d.ts +30 -52
  55. package/dist/window.js +33 -77
  56. package/dist/worker-core.d.ts +5 -0
  57. package/dist/worker-core.js +83 -75
  58. package/dist/worker-host.d.ts +19 -13
  59. package/dist/worker-host.js +75 -18
  60. package/dist/worker-local-authority.js +2 -2
  61. package/dist/worker-protocol.d.ts +15 -10
  62. package/package.json +11 -3
  63. package/src/apply.ts +176 -86
  64. package/src/authority.ts +31 -17
  65. package/src/blob.ts +28 -15
  66. package/src/bun-database.ts +24 -0
  67. package/src/client.ts +1282 -1217
  68. package/src/database.ts +5 -0
  69. package/src/devtools.ts +5 -5
  70. package/src/diagnostics.ts +17 -37
  71. package/src/encryption.ts +10 -5
  72. package/src/errors.ts +9 -1
  73. package/src/failed-overlay.ts +8 -7
  74. package/src/http.ts +95 -79
  75. package/src/index.ts +1 -1
  76. package/src/invalidation.ts +26 -61
  77. package/src/local-purge.ts +11 -13
  78. package/src/local-rebootstrap.ts +2 -3
  79. package/src/multi-tab.ts +88 -30
  80. package/src/native-bridge.ts +1153 -0
  81. package/src/node-database.ts +32 -1
  82. package/src/outbox.ts +20 -41
  83. package/src/outcomes.ts +3 -5
  84. package/src/previous-version.ts +103 -114
  85. package/src/progress.ts +2 -2
  86. package/src/query-guard.ts +77 -177
  87. package/src/reactive-store.ts +52 -12
  88. package/src/realtime-supervisor.ts +37 -12
  89. package/src/remote.ts +23 -31
  90. package/src/schema.ts +67 -25
  91. package/src/state.ts +246 -125
  92. package/src/sync-scheduler.ts +31 -1
  93. package/src/transport.ts +21 -2
  94. package/src/wasm-database.ts +76 -27
  95. package/src/window.ts +55 -134
  96. package/src/worker-core.ts +97 -77
  97. package/src/worker-host.ts +76 -32
  98. package/src/worker-local-authority.ts +2 -5
  99. package/src/worker-protocol.ts +14 -10
@@ -19,7 +19,7 @@ export interface TableChange {
19
19
 
20
20
  export interface WindowChange {
21
21
  readonly baseKey: string;
22
- readonly table: string;
22
+ /** Changed values of the base. */
23
23
  readonly units: ReadonlySet<string>;
24
24
  }
25
25
 
@@ -51,7 +51,6 @@ export interface ClientChangeBatch {
51
51
  readonly outcomesChanged: boolean;
52
52
  /** Server COMMIT frames applied by this transaction, when present. */
53
53
  readonly appliedCommits?: readonly {
54
- readonly subscriptionId: string;
55
54
  readonly table: string;
56
55
  readonly commitSeq: number;
57
56
  readonly source: 'delta' | 'pull';
@@ -84,18 +83,13 @@ interface MutableTableChange {
84
83
  scopeKeys: Set<string> | undefined;
85
84
  }
86
85
 
87
- interface MutableWindowChange {
88
- table: string;
89
- units: Set<string>;
90
- }
91
-
92
86
  /**
93
87
  * Per-observer-transaction accumulator. It contains no revision itself: the
94
88
  * transaction wrapper assigns the revision only after all writes succeeded.
95
89
  */
96
90
  export class ChangeAccumulator {
97
91
  readonly #tables = new Map<string, MutableTableChange>();
98
- readonly #windows = new Map<string, MutableWindowChange>();
92
+ readonly #windows = new Map<string, Set<string>>();
99
93
  #status = false;
100
94
  #conflicts = false;
101
95
  #rejections = false;
@@ -129,17 +123,11 @@ export class ChangeAccumulator {
129
123
  current.scopeKeys?.add(key);
130
124
  }
131
125
 
132
- /** Record registration/completeness change for one window unit. */
133
- window(baseKey: string, table: string, unit: string): void {
126
+ /** Record registration/completeness change for one window value. */
127
+ window(baseKey: string, value: string): void {
134
128
  const current = this.#windows.get(baseKey);
135
- if (current === undefined) {
136
- this.#windows.set(baseKey, { table, units: new Set([unit]) });
137
- return;
138
- }
139
- if (current.table !== table) {
140
- throw new Error(`window base ${JSON.stringify(baseKey)} changed tables`);
141
- }
142
- current.units.add(unit);
129
+ if (current === undefined) this.#windows.set(baseKey, new Set([value]));
130
+ else current.add(value);
143
131
  }
144
132
 
145
133
  status(): void {
@@ -158,8 +146,15 @@ export class ChangeAccumulator {
158
146
  this.#outcomes = true;
159
147
  }
160
148
 
161
- /** Add precise keys for a requested/effective scope map. */
149
+ /**
150
+ * Add precise keys for a bulk scoped delete. A map that leaves a declared
151
+ * scope variable unnamed cannot list the deleted rows' keys for that
152
+ * variable, so the change is table-wide.
153
+ */
162
154
  scopeMap(table: CompiledClientTable, scopes: ScopeMap): void {
155
+ for (const variable of table.scopePrefixByVariable.keys()) {
156
+ if (!Object.hasOwn(scopes, variable)) return this.table(table.name);
157
+ }
163
158
  for (const [variable, values] of Object.entries(scopes)) {
164
159
  const prefix = table.scopePrefixByVariable.get(variable);
165
160
  if (prefix === undefined) continue;
@@ -215,13 +210,8 @@ export class ChangeAccumulator {
215
210
  );
216
211
  }
217
212
  const windows: WindowChange[] = [];
218
- for (const [baseKey, change] of this.#windows) {
219
- windows.push({
220
- baseKey,
221
- table: change.table,
222
- units: change.units,
223
- });
224
- }
213
+ for (const [baseKey, units] of this.#windows)
214
+ windows.push({ baseKey, units });
225
215
  return {
226
216
  revision,
227
217
  tables,
@@ -237,23 +227,24 @@ export class ChangeAccumulator {
237
227
  }
238
228
  }
239
229
 
240
- /** Exception-isolated synchronous change listener set. */
241
- export class ChangeEmitter {
242
- readonly #listeners = new Set<ClientChangeListener>();
230
+ /** Exception-isolated synchronous listener set; observer code must never
231
+ * corrupt the committed core path. */
232
+ export class ChangeEmitter<T = ClientChangeBatch> {
233
+ readonly #listeners = new Set<(value: T) => void>();
243
234
 
244
- on(listener: ClientChangeListener): () => void {
235
+ on(listener: (value: T) => void): () => void {
245
236
  this.#listeners.add(listener);
246
237
  return () => {
247
238
  this.#listeners.delete(listener);
248
239
  };
249
240
  }
250
241
 
251
- emit(batch: ClientChangeBatch): void {
242
+ emit(value: T): void {
252
243
  for (const listener of this.#listeners) {
253
244
  try {
254
- listener(batch);
245
+ listener(value);
255
246
  } catch {
256
- // Observer code must never corrupt the committed core path.
247
+ // Isolated: a throwing observer does not stop the others.
257
248
  }
258
249
  }
259
250
  }
@@ -281,43 +272,17 @@ export type InvalidationListener = (event: InvalidationEvent) => void;
281
272
  export function invalidationFromChange(
282
273
  batch: ClientChangeBatch,
283
274
  ): InvalidationEvent | undefined {
284
- if (batch.tables.length === 0 && batch.windows.length === 0) return undefined;
275
+ if (batch.tables.length === 0) return undefined;
285
276
  const tables = new Set<string>();
286
277
  const scopeKeys = new Set<string>();
287
278
  for (const change of batch.tables) {
288
279
  tables.add(change.table);
289
280
  for (const key of change.scopeKeys ?? []) scopeKeys.add(key);
290
281
  }
291
- // Window-only changes project the table for old completeness consumers.
292
- // The exact API still keeps this distinct, so new table-only reads do not run.
293
- for (const change of batch.windows) tables.add(change.table);
294
282
  return { tables, scopeKeys };
295
283
  }
296
284
 
297
- export class InvalidationEmitter {
298
- readonly #listeners = new Set<InvalidationListener>();
299
-
300
- on(listener: InvalidationListener): () => void {
301
- this.#listeners.add(listener);
302
- return () => {
303
- this.#listeners.delete(listener);
304
- };
305
- }
306
-
307
- emit(event: InvalidationEvent): void {
308
- for (const listener of this.#listeners) {
309
- try {
310
- listener(event);
311
- } catch {
312
- // Compatibility observers are isolated like exact observers.
313
- }
314
- }
315
- }
316
-
317
- get size(): number {
318
- return this.#listeners.size;
319
- }
320
- }
285
+ export class InvalidationEmitter extends ChangeEmitter<InvalidationEvent> {}
321
286
 
322
287
  /** @deprecated Use {@link ChangeAccumulator}. */
323
288
  export { ChangeAccumulator as Invalidation };
@@ -8,7 +8,7 @@
8
8
  * generated FTS projections, doomed optimistic commits, and blob references.
9
9
  */
10
10
 
11
- import { ClientSyncError } from './errors';
11
+ import { invalidRequest } from './errors';
12
12
  import type { CompiledClientSchema, CompiledClientTable } from './schema';
13
13
 
14
14
  const MAX_TARGETS = 64;
@@ -57,10 +57,6 @@ export interface CompiledLocalDataPurge {
57
57
  readonly canonicalPlan: string;
58
58
  }
59
59
 
60
- function invalid(message: string): never {
61
- throw new ClientSyncError('sync.invalid_request', message);
62
- }
63
-
64
60
  /** Validate and canonicalize before any transaction is entered. */
65
61
  export function compileLocalDataPurge(
66
62
  schema: CompiledClientSchema,
@@ -71,25 +67,27 @@ export function compileLocalDataPurge(
71
67
  input.purgeId.length > 128 ||
72
68
  !CODE_LIKE_VALUE.test(input.purgeId)
73
69
  ) {
74
- invalid(
70
+ throw invalidRequest(
75
71
  'local purge purgeId must be a 1–128 character code-like identifier',
76
72
  );
77
73
  }
78
74
  if (input.targets.length === 0 || input.targets.length > MAX_TARGETS) {
79
- invalid(`local purge needs between 1 and ${MAX_TARGETS} targets`);
75
+ throw invalidRequest(
76
+ `local purge needs between 1 and ${MAX_TARGETS} targets`,
77
+ );
80
78
  }
81
79
 
82
80
  const deduplicated = new Map<string, CompiledLocalDataPurgeTarget>();
83
81
  for (const target of input.targets) {
84
82
  const table = schema.tables.get(target.table);
85
83
  if (table === undefined) {
86
- invalid(
84
+ throw invalidRequest(
87
85
  `local purge names unknown table ${JSON.stringify(target.table)}`,
88
86
  );
89
87
  }
90
88
  const entries = Object.entries(target.selectors);
91
89
  if (entries.length === 0 || entries.length > MAX_SELECTORS_PER_TARGET) {
92
- invalid(
90
+ throw invalidRequest(
93
91
  `local purge target ${JSON.stringify(target.table)} needs between 1 and ${MAX_SELECTORS_PER_TARGET} selectors`,
94
92
  );
95
93
  }
@@ -99,12 +97,12 @@ export function compileLocalDataPurge(
99
97
  (candidate) => candidate.name === columnName,
100
98
  );
101
99
  if (column === undefined) {
102
- invalid(
100
+ throw invalidRequest(
103
101
  `local purge target ${JSON.stringify(target.table)} names unknown column ${JSON.stringify(columnName)}`,
104
102
  );
105
103
  }
106
104
  if (column.type !== 'string' || column.encrypted === true) {
107
- invalid(
105
+ throw invalidRequest(
108
106
  `local purge selector ${JSON.stringify(target.table)}.${JSON.stringify(columnName)} must be a plaintext string column`,
109
107
  );
110
108
  }
@@ -112,7 +110,7 @@ export function compileLocalDataPurge(
112
110
  rawValues.length === 0 ||
113
111
  rawValues.length > MAX_VALUES_PER_SELECTOR
114
112
  ) {
115
- invalid(
113
+ throw invalidRequest(
116
114
  `local purge selector ${JSON.stringify(target.table)}.${JSON.stringify(columnName)} needs between 1 and ${MAX_VALUES_PER_SELECTOR} values`,
117
115
  );
118
116
  }
@@ -124,7 +122,7 @@ export function compileLocalDataPurge(
124
122
  value.length > MAX_ROUTING_VALUE_LENGTH ||
125
123
  !CODE_LIKE_VALUE.test(value)
126
124
  ) {
127
- invalid(
125
+ throw invalidRequest(
128
126
  `local purge selector values must be 1–${MAX_ROUTING_VALUE_LENGTH} character code-like identifiers`,
129
127
  );
130
128
  }
@@ -7,7 +7,7 @@
7
7
  * projection state so the registered subscriptions can bootstrap it again.
8
8
  */
9
9
 
10
- import { ClientSyncError } from './errors';
10
+ import { ClientSyncError, invalidRequest } from './errors';
11
11
 
12
12
  const CODE_LIKE_VALUE = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
13
13
  const RESULT_KEYS = [
@@ -85,8 +85,7 @@ export function compileLocalDataRebootstrap(
85
85
  input.rebootstrapId.length > 128 ||
86
86
  !CODE_LIKE_VALUE.test(input.rebootstrapId)
87
87
  ) {
88
- throw new ClientSyncError(
89
- 'sync.invalid_request',
88
+ throw invalidRequest(
90
89
  'local rebootstrap rebootstrapId must be a 1–128 character code-like identifier',
91
90
  );
92
91
  }
package/src/multi-tab.ts CHANGED
@@ -19,7 +19,9 @@
19
19
  * announce {t,epoch,clientId,protocol,schemaVersion}
20
20
  * — "I am the leader, this epoch";
21
21
  * the answer to every hello
22
- * res {t,epoch,reqId,ok,value|error} — reply to one req
22
+ * res {t,epoch,to,reqId,ok,value|error}
23
+ * — reply to one req, for the
24
+ * follower `to` that sent it
23
25
  * event {t,epoch,event,to?} — fan-out (invalidate/presence/…),
24
26
  * or one tab's event when `to` is set
25
27
  *
@@ -29,17 +31,21 @@
29
31
  * from a stale epoch, and a follower discards any `res`/`event` that does not
30
32
  * match its current epoch — so a late reply from a tab that has since died
31
33
  * (or a duplicate from a previous leader) can never be mistaken for a live
32
- * one. Epoch is derived deterministically from a per-origin clock: each
33
- * promoter reads the highest epoch it has seen and adds one, so successive
34
- * leaders always strictly increase it even across the lock-handover gap.
34
+ * one. Every follower counts its `reqId`s from 1, so a follower also discards
35
+ * a `res` whose `to` names another tab. Epoch is derived deterministically
36
+ * from a per-origin clock: each promoter reads the highest epoch it has seen
37
+ * and adds one, so successive leaders always strictly increase it even across
38
+ * the lock-handover gap.
35
39
  *
36
40
  * Identity: every hello, req, and announce carries the sender's
37
41
  * {@link MULTI_TAB_PROTOCOL_VERSION} and application schema version. A leader
38
42
  * serves only requests with its own identity. A follower whose leader has a
39
43
  * different identity goes `blocked` with `leader-incompatible` and sends it
40
44
  * nothing. A leader that hears a hello from a newer tab closes its core and
41
- * releases the lock, so the newer tab takes over. Tabs from before protocol 1
42
- * send no identity and count as older.
45
+ * releases the lock, so the newer tab takes over. A newer follower sends one
46
+ * hello to every older leader it hears announce, so an older tab that promotes
47
+ * after the first one stepped down steps down as well. Tabs from before
48
+ * protocol 1 send no identity and count as older.
43
49
  *
44
50
  * Liveness is follower-driven: the leader runs no timer. Browsers throttle
45
51
  * the timers of a hidden tab (Chrome's intensive throttling wakes them about
@@ -93,7 +99,7 @@ export const TAKEOVER_REFUSED_CODE = 'client.takeover_refused';
93
99
  * with every change to a message shape or to a forwarded method's arguments
94
100
  * or result, so tabs of different builds never serve each other.
95
101
  */
96
- export const MULTI_TAB_PROTOCOL_VERSION = 2;
102
+ export const MULTI_TAB_PROTOCOL_VERSION = 3;
97
103
 
98
104
  /** What a tab must share with its leader to be served by it. */
99
105
  export interface TabIdentity {
@@ -134,6 +140,20 @@ export type LeadershipState =
134
140
  readonly state: 'waiting';
135
141
  readonly reason: 'handover' | 'leader-announcement';
136
142
  }
143
+ | {
144
+ /**
145
+ * This tab won the lock after the leader left and its core failed to
146
+ * start. It released the lock and, while `retrying`, asks for it again
147
+ * behind every other waiting tab; after the third failed start it stops
148
+ * contesting and binds to whichever tab leads next.
149
+ */
150
+ readonly state: 'waiting';
151
+ readonly reason: 'leader-start-failed';
152
+ readonly error: ClientSyncError;
153
+ /** Failed starts of this tab's core so far. */
154
+ readonly attempt: number;
155
+ readonly retrying: boolean;
156
+ }
137
157
  | {
138
158
  readonly state: 'blocked';
139
159
  readonly reason: 'leader-unreachable';
@@ -191,6 +211,8 @@ interface AnnounceMessage extends IdentityFields {
191
211
  interface ResMessage {
192
212
  readonly t: 'res';
193
213
  readonly epoch: number;
214
+ /** The follower that sent the request. */
215
+ readonly to: string;
194
216
  readonly reqId: number;
195
217
  readonly ok: boolean;
196
218
  readonly value?: unknown;
@@ -358,6 +380,7 @@ export class LeaderBridge<E = SyncWorkerEvent> {
358
380
  this.#channel.postMessage({
359
381
  t: 'res',
360
382
  epoch: this.#epoch,
383
+ to: fromId,
361
384
  reqId,
362
385
  ok: false,
363
386
  error: {
@@ -379,6 +402,7 @@ export class LeaderBridge<E = SyncWorkerEvent> {
379
402
  this.#channel.postMessage({
380
403
  t: 'res',
381
404
  epoch: this.#epoch,
405
+ to: fromId,
382
406
  reqId,
383
407
  ok: true,
384
408
  value,
@@ -405,6 +429,7 @@ export class LeaderBridge<E = SyncWorkerEvent> {
405
429
  this.#channel.postMessage({
406
430
  t: 'res',
407
431
  epoch: this.#epoch,
432
+ to: fromId,
408
433
  reqId,
409
434
  ok: false,
410
435
  error: shape,
@@ -471,6 +496,8 @@ export class FollowerLink<E = SyncWorkerEvent> {
471
496
  #nextReqId = 1;
472
497
  readonly #inFlight = new Map<number, QueuedCall>();
473
498
  readonly #replayOnHandover: ReadonlySet<string>;
499
+ /** `epoch:clientId` of every older leader this tab asked to step down. */
500
+ readonly #deposed = new Set<string>();
474
501
  #queue: QueuedCall[] = [];
475
502
  #closed = false;
476
503
  #state: LeadershipState = {
@@ -707,6 +734,13 @@ export class FollowerLink<E = SyncWorkerEvent> {
707
734
  if (message.epoch < this.#epoch) return;
708
735
  const relation = compareTabIdentity(message, this.#identity);
709
736
  if (relation !== 0) {
737
+ // An older leader steps down for this tab's hello. Each one hears it
738
+ // once: an older tab that promotes later is another leader.
739
+ const leader = `${message.epoch}:${message.clientId}`;
740
+ if (relation < 0 && !this.#deposed.has(leader)) {
741
+ this.#deposed.add(leader);
742
+ this.#probe();
743
+ }
710
744
  this.#setIncompatible(relation < 0 ? 'older' : 'newer');
711
745
  return;
712
746
  }
@@ -742,8 +776,9 @@ export class FollowerLink<E = SyncWorkerEvent> {
742
776
  }
743
777
  if (message.t === 'res') {
744
778
  // Discard a reply for a stale epoch — the leader that produced it is
745
- // gone; the request (if still pending) is being retried elsewhere.
746
- if (message.epoch !== this.#epoch) return;
779
+ // gone; the request (if still pending) is being retried elsewhere. A
780
+ // reply for another follower carries a `reqId` of that tab's counter.
781
+ if (message.epoch !== this.#epoch || message.to !== this.#fromId) return;
747
782
  const inflight = this.#inFlight.get(message.reqId);
748
783
  if (inflight === undefined) return;
749
784
  this.#inFlight.delete(message.reqId);
@@ -883,9 +918,9 @@ export class FollowerLink<E = SyncWorkerEvent> {
883
918
  }
884
919
 
885
920
  /**
886
- * The leader runs another build. Send it nothing and stay unbound until a
887
- * leader with this tab's identity announces (a newer leader's own hello
888
- * already asked an older one to step down; see the module comment).
921
+ * The leader runs another build. Send it nothing but the one step-down
922
+ * hello for an older leader, and stay unbound until a leader with this
923
+ * tab's identity announces (see the module comment).
889
924
  */
890
925
  #setIncompatible(leader: 'older' | 'newer'): void {
891
926
  this.#clearReachabilityTimers();
@@ -1438,26 +1473,49 @@ export async function createTabCoordinator<E>(
1438
1473
  : {}),
1439
1474
  });
1440
1475
  follower = link;
1476
+ let failedStarts = 0;
1441
1477
  // Granted only when the lock is released: the leader's tab closed, or this
1442
1478
  // tab's own failed takeover let go of it.
1443
- void lock.acquire(config.name).then(async (promoted) => {
1444
- if (closed || follower !== link) {
1445
- // Closed, or this tab already leads through takeOver(): promoting would
1446
- // hold the lock forever.
1447
- await promoted.release();
1448
- return;
1449
- }
1450
- // The new leader must exceed every epoch this tab saw, so stale replies
1451
- // and events are discarded everywhere.
1452
- const epoch = link.maxEpochSeen + 1;
1453
- link.unbind();
1454
- try {
1455
- await lead(promoted, epoch, false);
1456
- } catch {
1457
- // The core failed to start: release so the next tab tries.
1458
- await promoted.release();
1459
- }
1460
- });
1479
+ const contest = (): void => {
1480
+ void lock.acquire(config.name).then(async (promoted) => {
1481
+ if (closed || follower !== link) {
1482
+ // Closed, or this tab already leads through takeOver(): promoting
1483
+ // would hold the lock forever.
1484
+ await promoted.release();
1485
+ return;
1486
+ }
1487
+ // The new leader must exceed every epoch this tab saw, so stale replies
1488
+ // and events are discarded everywhere.
1489
+ const epoch = link.maxEpochSeen + 1;
1490
+ link.unbind();
1491
+ try {
1492
+ await lead(promoted, epoch, false);
1493
+ } catch (error) {
1494
+ // Release so the next waiting tab tries, then queue behind it. Three
1495
+ // failed starts stop the contest: a core that fails the same way each
1496
+ // time (a changed worker bundle, an unreadable database) would
1497
+ // otherwise take and drop the lock in a loop while this tab is alone.
1498
+ await promoted.release();
1499
+ failedStarts += 1;
1500
+ const retrying = failedStarts < 3 && !closed;
1501
+ setState({
1502
+ state: 'waiting',
1503
+ reason: 'leader-start-failed',
1504
+ error:
1505
+ error instanceof ClientSyncError
1506
+ ? error
1507
+ : new ClientSyncError(
1508
+ WORKER_FAILED_CODE,
1509
+ 'the core failed to start',
1510
+ ),
1511
+ attempt: failedStarts,
1512
+ retrying,
1513
+ });
1514
+ if (retrying) contest();
1515
+ }
1516
+ });
1517
+ };
1518
+ contest();
1461
1519
  // Return bound: an event the leader fans out before binding is dropped.
1462
1520
  try {
1463
1521
  await link.waitUntilBound();