@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
@@ -34,17 +34,13 @@ export class ChangeAccumulator {
34
34
  }
35
35
  current.scopeKeys?.add(key);
36
36
  }
37
- /** Record registration/completeness change for one window unit. */
38
- window(baseKey, table, unit) {
37
+ /** Record registration/completeness change for one window value. */
38
+ window(baseKey, value) {
39
39
  const current = this.#windows.get(baseKey);
40
- if (current === undefined) {
41
- this.#windows.set(baseKey, { table, units: new Set([unit]) });
42
- return;
43
- }
44
- if (current.table !== table) {
45
- throw new Error(`window base ${JSON.stringify(baseKey)} changed tables`);
46
- }
47
- current.units.add(unit);
40
+ if (current === undefined)
41
+ this.#windows.set(baseKey, new Set([value]));
42
+ else
43
+ current.add(value);
48
44
  }
49
45
  status() {
50
46
  this.#status = true;
@@ -58,8 +54,16 @@ export class ChangeAccumulator {
58
54
  outcomes() {
59
55
  this.#outcomes = true;
60
56
  }
61
- /** Add precise keys for a requested/effective scope map. */
57
+ /**
58
+ * Add precise keys for a bulk scoped delete. A map that leaves a declared
59
+ * scope variable unnamed cannot list the deleted rows' keys for that
60
+ * variable, so the change is table-wide.
61
+ */
62
62
  scopeMap(table, scopes) {
63
+ for (const variable of table.scopePrefixByVariable.keys()) {
64
+ if (!Object.hasOwn(scopes, variable))
65
+ return this.table(table.name);
66
+ }
63
67
  for (const [variable, values] of Object.entries(scopes)) {
64
68
  const prefix = table.scopePrefixByVariable.get(variable);
65
69
  if (prefix === undefined)
@@ -102,13 +106,8 @@ export class ChangeAccumulator {
102
106
  : { table, scopeKeys: change.scopeKeys });
103
107
  }
104
108
  const windows = [];
105
- for (const [baseKey, change] of this.#windows) {
106
- windows.push({
107
- baseKey,
108
- table: change.table,
109
- units: change.units,
110
- });
111
- }
109
+ for (const [baseKey, units] of this.#windows)
110
+ windows.push({ baseKey, units });
112
111
  return {
113
112
  revision,
114
113
  tables,
@@ -123,7 +122,8 @@ export class ChangeAccumulator {
123
122
  };
124
123
  }
125
124
  }
126
- /** Exception-isolated synchronous change listener set. */
125
+ /** Exception-isolated synchronous listener set; observer code must never
126
+ * corrupt the committed core path. */
127
127
  export class ChangeEmitter {
128
128
  #listeners = new Set();
129
129
  on(listener) {
@@ -132,13 +132,13 @@ export class ChangeEmitter {
132
132
  this.#listeners.delete(listener);
133
133
  };
134
134
  }
135
- emit(batch) {
135
+ emit(value) {
136
136
  for (const listener of this.#listeners) {
137
137
  try {
138
- listener(batch);
138
+ listener(value);
139
139
  }
140
140
  catch {
141
- // Observer code must never corrupt the committed core path.
141
+ // Isolated: a throwing observer does not stop the others.
142
142
  }
143
143
  }
144
144
  }
@@ -147,7 +147,7 @@ export class ChangeEmitter {
147
147
  }
148
148
  }
149
149
  export function invalidationFromChange(batch) {
150
- if (batch.tables.length === 0 && batch.windows.length === 0)
150
+ if (batch.tables.length === 0)
151
151
  return undefined;
152
152
  const tables = new Set();
153
153
  const scopeKeys = new Set();
@@ -156,33 +156,9 @@ export function invalidationFromChange(batch) {
156
156
  for (const key of change.scopeKeys ?? [])
157
157
  scopeKeys.add(key);
158
158
  }
159
- // Window-only changes project the table for old completeness consumers.
160
- // The exact API still keeps this distinct, so new table-only reads do not run.
161
- for (const change of batch.windows)
162
- tables.add(change.table);
163
159
  return { tables, scopeKeys };
164
160
  }
165
- export class InvalidationEmitter {
166
- #listeners = new Set();
167
- on(listener) {
168
- this.#listeners.add(listener);
169
- return () => {
170
- this.#listeners.delete(listener);
171
- };
172
- }
173
- emit(event) {
174
- for (const listener of this.#listeners) {
175
- try {
176
- listener(event);
177
- }
178
- catch {
179
- // Compatibility observers are isolated like exact observers.
180
- }
181
- }
182
- }
183
- get size() {
184
- return this.#listeners.size;
185
- }
161
+ export class InvalidationEmitter extends ChangeEmitter {
186
162
  }
187
163
  /** @deprecated Use {@link ChangeAccumulator}. */
188
164
  export { ChangeAccumulator as Invalidation };
@@ -7,7 +7,7 @@
7
7
  * local engine. The engine owns the atomic SQLite consequences: synced rows,
8
8
  * generated FTS projections, doomed optimistic commits, and blob references.
9
9
  */
10
- import { ClientSyncError } from './errors.js';
10
+ import { invalidRequest } from './errors.js';
11
11
  const MAX_TARGETS = 64;
12
12
  const MAX_SELECTORS_PER_TARGET = 8;
13
13
  const MAX_VALUES_PER_SELECTOR = 128;
@@ -16,41 +16,38 @@ const CODE_LIKE_VALUE = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
16
16
  function compareCodeLike(left, right) {
17
17
  return left < right ? -1 : left > right ? 1 : 0;
18
18
  }
19
- function invalid(message) {
20
- throw new ClientSyncError('sync.invalid_request', message);
21
- }
22
19
  /** Validate and canonicalize before any transaction is entered. */
23
20
  export function compileLocalDataPurge(schema, input) {
24
21
  if (input.purgeId.length === 0 ||
25
22
  input.purgeId.length > 128 ||
26
23
  !CODE_LIKE_VALUE.test(input.purgeId)) {
27
- invalid('local purge purgeId must be a 1–128 character code-like identifier');
24
+ throw invalidRequest('local purge purgeId must be a 1–128 character code-like identifier');
28
25
  }
29
26
  if (input.targets.length === 0 || input.targets.length > MAX_TARGETS) {
30
- invalid(`local purge needs between 1 and ${MAX_TARGETS} targets`);
27
+ throw invalidRequest(`local purge needs between 1 and ${MAX_TARGETS} targets`);
31
28
  }
32
29
  const deduplicated = new Map();
33
30
  for (const target of input.targets) {
34
31
  const table = schema.tables.get(target.table);
35
32
  if (table === undefined) {
36
- invalid(`local purge names unknown table ${JSON.stringify(target.table)}`);
33
+ throw invalidRequest(`local purge names unknown table ${JSON.stringify(target.table)}`);
37
34
  }
38
35
  const entries = Object.entries(target.selectors);
39
36
  if (entries.length === 0 || entries.length > MAX_SELECTORS_PER_TARGET) {
40
- invalid(`local purge target ${JSON.stringify(target.table)} needs between 1 and ${MAX_SELECTORS_PER_TARGET} selectors`);
37
+ throw invalidRequest(`local purge target ${JSON.stringify(target.table)} needs between 1 and ${MAX_SELECTORS_PER_TARGET} selectors`);
41
38
  }
42
39
  const selectors = entries
43
40
  .map(([columnName, rawValues]) => {
44
41
  const column = table.columns.find((candidate) => candidate.name === columnName);
45
42
  if (column === undefined) {
46
- invalid(`local purge target ${JSON.stringify(target.table)} names unknown column ${JSON.stringify(columnName)}`);
43
+ throw invalidRequest(`local purge target ${JSON.stringify(target.table)} names unknown column ${JSON.stringify(columnName)}`);
47
44
  }
48
45
  if (column.type !== 'string' || column.encrypted === true) {
49
- invalid(`local purge selector ${JSON.stringify(target.table)}.${JSON.stringify(columnName)} must be a plaintext string column`);
46
+ throw invalidRequest(`local purge selector ${JSON.stringify(target.table)}.${JSON.stringify(columnName)} must be a plaintext string column`);
50
47
  }
51
48
  if (rawValues.length === 0 ||
52
49
  rawValues.length > MAX_VALUES_PER_SELECTOR) {
53
- invalid(`local purge selector ${JSON.stringify(target.table)}.${JSON.stringify(columnName)} needs between 1 and ${MAX_VALUES_PER_SELECTOR} values`);
50
+ throw invalidRequest(`local purge selector ${JSON.stringify(target.table)}.${JSON.stringify(columnName)} needs between 1 and ${MAX_VALUES_PER_SELECTOR} values`);
54
51
  }
55
52
  const values = [...new Set(rawValues)];
56
53
  for (const value of values) {
@@ -58,7 +55,7 @@ export function compileLocalDataPurge(schema, input) {
58
55
  value.length === 0 ||
59
56
  value.length > MAX_ROUTING_VALUE_LENGTH ||
60
57
  !CODE_LIKE_VALUE.test(value)) {
61
- invalid(`local purge selector values must be 1–${MAX_ROUTING_VALUE_LENGTH} character code-like identifiers`);
58
+ throw invalidRequest(`local purge selector values must be 1–${MAX_ROUTING_VALUE_LENGTH} character code-like identifiers`);
62
59
  }
63
60
  }
64
61
  values.sort();
@@ -6,7 +6,7 @@
6
6
  * lease state, and protected bookkeeping. It only discards server-derived
7
7
  * projection state so the registered subscriptions can bootstrap it again.
8
8
  */
9
- import { ClientSyncError } from './errors.js';
9
+ import { ClientSyncError, invalidRequest } from './errors.js';
10
10
  const CODE_LIKE_VALUE = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
11
11
  const RESULT_KEYS = [
12
12
  'alreadyApplied',
@@ -51,7 +51,7 @@ export function compileLocalDataRebootstrap(input) {
51
51
  if (input.rebootstrapId.length === 0 ||
52
52
  input.rebootstrapId.length > 128 ||
53
53
  !CODE_LIKE_VALUE.test(input.rebootstrapId)) {
54
- throw new ClientSyncError('sync.invalid_request', 'local rebootstrap rebootstrapId must be a 1–128 character code-like identifier');
54
+ throw invalidRequest('local rebootstrap rebootstrapId must be a 1–128 character code-like identifier');
55
55
  }
56
56
  return input.rebootstrapId;
57
57
  }
@@ -1,3 +1,76 @@
1
+ /**
2
+ * Multi-tab followers: one core per origin, N tabs.
3
+ *
4
+ * The leader tab holds the Web Locks lease and runs the worker core (the
5
+ * existing worker-host path, unchanged). Every OTHER tab is a FOLLOWER: it
6
+ * loses the lock election and, instead of a dead not-leader handle, opens a
7
+ * BroadcastChannel to the leader and proxies the whole logical API over it —
8
+ * one sync loop, one WebSocket, one DB, N tabs.
9
+ *
10
+ * Wire (all messages structured-clone-safe; `Set`/`Uint8Array`/`ArrayBuffer`
11
+ * survive `postMessage` on a BroadcastChannel):
12
+ *
13
+ * follower → leader
14
+ * hello {t,epoch?,fromId,protocol,schemaVersion}
15
+ * — "who's the leader?" on join,
16
+ * and the follower's liveness probe
17
+ * req {t,epoch,fromId,reqId,method,args,protocol,schemaVersion}
18
+ * leader → all
19
+ * announce {t,epoch,clientId,protocol,schemaVersion}
20
+ * — "I am the leader, this epoch";
21
+ * the answer to every hello
22
+ * res {t,epoch,to,reqId,ok,value|error}
23
+ * — reply to one req, for the
24
+ * follower `to` that sent it
25
+ * event {t,epoch,event,to?} — fan-out (invalidate/presence/…),
26
+ * or one tab's event when `to` is set
27
+ *
28
+ * Epoch (leader generation token): a monotonic counter carried in a shared
29
+ * BroadcastChannel and bumped by every promotion. Followers stamp requests
30
+ * with the epoch they last heard in an `announce`; a leader ignores requests
31
+ * from a stale epoch, and a follower discards any `res`/`event` that does not
32
+ * match its current epoch — so a late reply from a tab that has since died
33
+ * (or a duplicate from a previous leader) can never be mistaken for a live
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.
39
+ *
40
+ * Identity: every hello, req, and announce carries the sender's
41
+ * {@link MULTI_TAB_PROTOCOL_VERSION} and application schema version. A leader
42
+ * serves only requests with its own identity. A follower whose leader has a
43
+ * different identity goes `blocked` with `leader-incompatible` and sends it
44
+ * nothing. A leader that hears a hello from a newer tab closes its core and
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.
49
+ *
50
+ * Liveness is follower-driven: the leader runs no timer. Browsers throttle
51
+ * the timers of a hidden tab (Chrome's intensive throttling wakes them about
52
+ * once a minute) but still dispatch its BroadcastChannel messages, so a leader
53
+ * heartbeat misses its schedule in a background leader tab while that tab is
54
+ * alive. Instead, a bound follower that has heard no `announce` for a third of
55
+ * its call timeout posts a `hello`, and goes `blocked` only when that probe
56
+ * stays unanswered for the rest of the timeout. A leader tab whose main thread
57
+ * processes no messages (hung or frozen) therefore still blocks its followers
58
+ * within `callTimeoutMs`, and a closed leader hands over through the lock.
59
+ * A forwarded call has no deadline of its own: a live leader may run it behind
60
+ * a long sync round, exactly as it runs its own tab's calls. It rejects when
61
+ * the link blocks, when another leader announces, or when the link closes.
62
+ *
63
+ * Presence identity: all tabs share the leader's one connection, so a device
64
+ * is exactly ONE presence peer collectively — `(actorId, leaderClientId)`.
65
+ * A follower's `setPresence` forwards to the leader's single publisher; there
66
+ * is no per-tab presence peer (documented in the web-client README).
67
+ *
68
+ * Tab lifetime: every tab of a {@link TabCoordinator} holds an exclusive Web
69
+ * Lock named for its tab id until it closes. A leader whose core keeps per-tab
70
+ * state waits on that lock for each tab that called it; the grant means the
71
+ * tab is gone.
72
+ */
73
+ import { ClientSyncError } from './errors.js';
1
74
  import { type LeaderLease, type LeaderLock } from './leader-lock.js';
2
75
  import type { SyncWorkerEvent } from './worker-protocol.js';
3
76
  /** Client-local: a follower call could not reach a leader before its deadline. */
@@ -15,7 +88,7 @@ export declare const TAKEOVER_REFUSED_CODE = "client.takeover_refused";
15
88
  * with every change to a message shape or to a forwarded method's arguments
16
89
  * or result, so tabs of different builds never serve each other.
17
90
  */
18
- export declare const MULTI_TAB_PROTOCOL_VERSION = 2;
91
+ export declare const MULTI_TAB_PROTOCOL_VERSION = 3;
19
92
  /** What a tab must share with its leader to be served by it. */
20
93
  export interface TabIdentity {
21
94
  readonly protocol: number;
@@ -43,6 +116,19 @@ export type LeadershipState = {
43
116
  } | {
44
117
  readonly state: 'waiting';
45
118
  readonly reason: 'handover' | 'leader-announcement';
119
+ } | {
120
+ /**
121
+ * This tab won the lock after the leader left and its core failed to
122
+ * start. It released the lock and, while `retrying`, asks for it again
123
+ * behind every other waiting tab; after the third failed start it stops
124
+ * contesting and binds to whichever tab leads next.
125
+ */
126
+ readonly state: 'waiting';
127
+ readonly reason: 'leader-start-failed';
128
+ readonly error: ClientSyncError;
129
+ /** Failed starts of this tab's core so far. */
130
+ readonly attempt: number;
131
+ readonly retrying: boolean;
46
132
  } | {
47
133
  readonly state: 'blocked';
48
134
  readonly reason: 'leader-unreachable';
@@ -89,6 +175,8 @@ interface AnnounceMessage extends IdentityFields {
89
175
  interface ResMessage {
90
176
  readonly t: 'res';
91
177
  readonly epoch: number;
178
+ /** The follower that sent the request. */
179
+ readonly to: string;
92
180
  readonly reqId: number;
93
181
  readonly ok: boolean;
94
182
  readonly value?: unknown;
package/dist/multi-tab.js 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
@@ -82,7 +88,7 @@ export const TAKEOVER_REFUSED_CODE = 'client.takeover_refused';
82
88
  * with every change to a message shape or to a forwarded method's arguments
83
89
  * or result, so tabs of different builds never serve each other.
84
90
  */
85
- export const MULTI_TAB_PROTOCOL_VERSION = 2;
91
+ export const MULTI_TAB_PROTOCOL_VERSION = 3;
86
92
  /**
87
93
  * Order a peer's identity against our own: -1 older, 0 same, 1 newer. A peer
88
94
  * from before protocol 1 sends no identity and is older.
@@ -202,6 +208,7 @@ export class LeaderBridge {
202
208
  this.#channel.postMessage({
203
209
  t: 'res',
204
210
  epoch: this.#epoch,
211
+ to: fromId,
205
212
  reqId,
206
213
  ok: false,
207
214
  error: {
@@ -223,6 +230,7 @@ export class LeaderBridge {
223
230
  this.#channel.postMessage({
224
231
  t: 'res',
225
232
  epoch: this.#epoch,
233
+ to: fromId,
226
234
  reqId,
227
235
  ok: true,
228
236
  value,
@@ -247,6 +255,7 @@ export class LeaderBridge {
247
255
  this.#channel.postMessage({
248
256
  t: 'res',
249
257
  epoch: this.#epoch,
258
+ to: fromId,
250
259
  reqId,
251
260
  ok: false,
252
261
  error: shape,
@@ -292,6 +301,8 @@ export class FollowerLink {
292
301
  #nextReqId = 1;
293
302
  #inFlight = new Map();
294
303
  #replayOnHandover;
304
+ /** `epoch:clientId` of every older leader this tab asked to step down. */
305
+ #deposed = new Set();
295
306
  #queue = [];
296
307
  #closed = false;
297
308
  #state = {
@@ -481,6 +492,13 @@ export class FollowerLink {
481
492
  return;
482
493
  const relation = compareTabIdentity(message, this.#identity);
483
494
  if (relation !== 0) {
495
+ // An older leader steps down for this tab's hello. Each one hears it
496
+ // once: an older tab that promotes later is another leader.
497
+ const leader = `${message.epoch}:${message.clientId}`;
498
+ if (relation < 0 && !this.#deposed.has(leader)) {
499
+ this.#deposed.add(leader);
500
+ this.#probe();
501
+ }
484
502
  this.#setIncompatible(relation < 0 ? 'older' : 'newer');
485
503
  return;
486
504
  }
@@ -509,8 +527,9 @@ export class FollowerLink {
509
527
  }
510
528
  if (message.t === 'res') {
511
529
  // Discard a reply for a stale epoch — the leader that produced it is
512
- // gone; the request (if still pending) is being retried elsewhere.
513
- if (message.epoch !== this.#epoch)
530
+ // gone; the request (if still pending) is being retried elsewhere. A
531
+ // reply for another follower carries a `reqId` of that tab's counter.
532
+ if (message.epoch !== this.#epoch || message.to !== this.#fromId)
514
533
  return;
515
534
  const inflight = this.#inFlight.get(message.reqId);
516
535
  if (inflight === undefined)
@@ -631,9 +650,9 @@ export class FollowerLink {
631
650
  });
632
651
  }
633
652
  /**
634
- * The leader runs another build. Send it nothing and stay unbound until a
635
- * leader with this tab's identity announces (a newer leader's own hello
636
- * already asked an older one to step down; see the module comment).
653
+ * The leader runs another build. Send it nothing but the one step-down
654
+ * hello for an older leader, and stay unbound until a leader with this
655
+ * tab's identity announces (see the module comment).
637
656
  */
638
657
  #setIncompatible(leader) {
639
658
  this.#clearReachabilityTimers();
@@ -996,27 +1015,47 @@ export async function createTabCoordinator(config) {
996
1015
  : {}),
997
1016
  });
998
1017
  follower = link;
1018
+ let failedStarts = 0;
999
1019
  // Granted only when the lock is released: the leader's tab closed, or this
1000
1020
  // tab's own failed takeover let go of it.
1001
- void lock.acquire(config.name).then(async (promoted) => {
1002
- if (closed || follower !== link) {
1003
- // Closed, or this tab already leads through takeOver(): promoting would
1004
- // hold the lock forever.
1005
- await promoted.release();
1006
- return;
1007
- }
1008
- // The new leader must exceed every epoch this tab saw, so stale replies
1009
- // and events are discarded everywhere.
1010
- const epoch = link.maxEpochSeen + 1;
1011
- link.unbind();
1012
- try {
1013
- await lead(promoted, epoch, false);
1014
- }
1015
- catch {
1016
- // The core failed to start: release so the next tab tries.
1017
- await promoted.release();
1018
- }
1019
- });
1021
+ const contest = () => {
1022
+ void lock.acquire(config.name).then(async (promoted) => {
1023
+ if (closed || follower !== link) {
1024
+ // Closed, or this tab already leads through takeOver(): promoting
1025
+ // would hold the lock forever.
1026
+ await promoted.release();
1027
+ return;
1028
+ }
1029
+ // The new leader must exceed every epoch this tab saw, so stale replies
1030
+ // and events are discarded everywhere.
1031
+ const epoch = link.maxEpochSeen + 1;
1032
+ link.unbind();
1033
+ try {
1034
+ await lead(promoted, epoch, false);
1035
+ }
1036
+ catch (error) {
1037
+ // Release so the next waiting tab tries, then queue behind it. Three
1038
+ // failed starts stop the contest: a core that fails the same way each
1039
+ // time (a changed worker bundle, an unreadable database) would
1040
+ // otherwise take and drop the lock in a loop while this tab is alone.
1041
+ await promoted.release();
1042
+ failedStarts += 1;
1043
+ const retrying = failedStarts < 3 && !closed;
1044
+ setState({
1045
+ state: 'waiting',
1046
+ reason: 'leader-start-failed',
1047
+ error: error instanceof ClientSyncError
1048
+ ? error
1049
+ : new ClientSyncError(WORKER_FAILED_CODE, 'the core failed to start'),
1050
+ attempt: failedStarts,
1051
+ retrying,
1052
+ });
1053
+ if (retrying)
1054
+ contest();
1055
+ }
1056
+ });
1057
+ };
1058
+ contest();
1020
1059
  // Return bound: an event the leader fans out before binding is dropped.
1021
1060
  try {
1022
1061
  await link.waitUntilBound();