@syncular/client 0.48.0 → 0.49.2

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.
@@ -81,16 +81,14 @@ import {
81
81
  type LocalDataRebootstrapResult,
82
82
  } from './local-rebootstrap';
83
83
  import {
84
- broadcastChannelFactory,
85
84
  type CrossTabChannel,
86
- FollowerLink,
87
- LEADER_INCOMPATIBLE_CODE,
88
- LeaderBridge,
85
+ createTabCoordinator,
86
+ type LeaderUnreachableEvent,
89
87
  type LeadershipState,
90
- MULTI_TAB_PROTOCOL_VERSION,
91
88
  multiTabChannelName,
92
- newTabId,
93
- type TabIdentity,
89
+ TAKEOVER_REFUSED_CODE,
90
+ type TabClock,
91
+ type TabCoordinator,
94
92
  } from './multi-tab';
95
93
  import type { OutboxCommit } from './outbox';
96
94
  import type {
@@ -110,6 +108,7 @@ import type { ClientSchema } from './schema';
110
108
  import type { SubscriptionRecord } from './state';
111
109
  import type { WindowBase } from './window';
112
110
  import {
111
+ type LocalAuthorityState,
113
112
  type MainToWorkerMessage,
114
113
  NOT_LEADER_CODE,
115
114
  type SyncWorkerEvent,
@@ -201,6 +200,8 @@ export interface SyncClientHandleConfig {
201
200
  /** Open the worker-owned replica behind the fail-closed security gate. */
202
201
  readonly securityPreflight?: boolean;
203
202
  readonly transportEnabled?: boolean;
203
+ /** SPEC §12: start against the worker's local authority (`WorkerInitConfig`). */
204
+ readonly localAuthority?: boolean;
204
205
  readonly clientId?: string;
205
206
  readonly limits?: SyncClientLimits;
206
207
  readonly retainFailedCommits?: boolean;
@@ -237,6 +238,15 @@ export interface SyncClientHandleConfig {
237
238
  * `blocked` when the probe stays unanswered for the rest. Default 10 s.
238
239
  */
239
240
  readonly followerCallTimeoutMs?: number;
241
+ /**
242
+ * How long a follower must have been `leader-unreachable` before
243
+ * `takeOver()` is allowed. Default twice `followerCallTimeoutMs`.
244
+ */
245
+ readonly takeOverAfterMs?: number;
246
+ /** Start and end of every `leader-unreachable` period, for host telemetry. */
247
+ readonly onLeaderUnreachable?: (event: LeaderUnreachableEvent) => void;
248
+ /** Time source for the follower timers; injectable for tests. */
249
+ readonly tabClock?: TabClock;
240
250
  /** Fires when this handle's role changes (follower → leader on promotion). */
241
251
  readonly onRoleChange?: (role: HandleRole) => void;
242
252
  /** Fires when reachability or ownership changes without replacing the handle. */
@@ -269,9 +279,8 @@ function defaultLeaderLock(): LeaderLock {
269
279
  }
270
280
 
271
281
  /**
272
- * A running worker core owned by THIS tab (the leader). Wraps the worker,
273
- * the RPC pending map, and (in multi-tab mode) the `LeaderBridge` relaying
274
- * follower requests. Torn down on `close()` or on a graceful demotion.
282
+ * A running worker core owned by THIS tab (the leader). Wraps the worker and
283
+ * the RPC pending map. Torn down on `close()` or on a graceful demotion.
275
284
  */
276
285
  interface LeaderCore {
277
286
  readonly clientId: string;
@@ -279,9 +288,8 @@ interface LeaderCore {
279
288
  method: string,
280
289
  args: readonly unknown[],
281
290
  ) => Promise<unknown>;
282
- readonly bridge: LeaderBridge | undefined;
283
- readonly lease: LeaderLease;
284
- close(terminate: boolean): Promise<void>;
291
+ /** Close the core, terminate the worker, and release the lease. */
292
+ close(): Promise<void>;
285
293
  }
286
294
 
287
295
  /**
@@ -316,8 +324,10 @@ export class SyncClientHandle implements PromiseMethods<WorkerApi> {
316
324
  #clientId: string;
317
325
  readonly #currentSchemaVersion: number;
318
326
  #leadership: LeadershipState;
327
+ /** The multi-tab route: this tab's core when it leads, the leader's otherwise. */
328
+ readonly #tabs: TabCoordinator | undefined;
329
+ /** The `multiTab: false` leader's own core. */
319
330
  #core: LeaderCore | undefined;
320
- #follower: FollowerLink | undefined;
321
331
  readonly #invalidation: InvalidationEmitter;
322
332
  readonly #progress = new ProgressEmitter();
323
333
  readonly #changes: ChangeEmitter;
@@ -325,6 +335,7 @@ export class SyncClientHandle implements PromiseMethods<WorkerApi> {
325
335
  readonly #diagnostics: ClientDiagnosticsEmitter;
326
336
  readonly #roleListeners: Set<(role: HandleRole) => void>;
327
337
  readonly #leadershipListeners: Set<(state: LeadershipState) => void>;
338
+ readonly #unreachableListeners: Set<(event: LeaderUnreachableEvent) => void>;
328
339
  readonly #devtoolsUnregister: () => void;
329
340
  #closed = false;
330
341
 
@@ -334,13 +345,14 @@ export class SyncClientHandle implements PromiseMethods<WorkerApi> {
334
345
  clientId: string;
335
346
  currentSchemaVersion: number;
336
347
  core?: LeaderCore;
337
- follower?: FollowerLink;
348
+ tabs?: TabCoordinator;
338
349
  invalidation: InvalidationEmitter;
339
350
  changes: ChangeEmitter;
340
351
  presence: Set<(scopeKey: string) => void>;
341
352
  diagnostics: ClientDiagnosticsEmitter;
342
353
  roleListeners?: Set<(role: HandleRole) => void>;
343
354
  leadershipListeners?: Set<(state: LeadershipState) => void>;
355
+ unreachableListeners?: Set<(event: LeaderUnreachableEvent) => void>;
344
356
  leadership?: LeadershipState;
345
357
  }) {
346
358
  this.#role = internals.role;
@@ -348,22 +360,24 @@ export class SyncClientHandle implements PromiseMethods<WorkerApi> {
348
360
  this.#currentSchemaVersion = internals.currentSchemaVersion;
349
361
  this.#leadership =
350
362
  internals.leadership ??
363
+ internals.tabs?.state ??
351
364
  (internals.role === 'leader'
352
365
  ? { state: 'leader', clientId: internals.clientId }
353
- : (internals.follower?.leadershipState ?? {
366
+ : {
354
367
  state: 'blocked',
355
368
  reason: 'leader-unreachable',
356
369
  code: 'client.follower_timeout',
357
370
  retryable: true,
358
- }));
371
+ });
359
372
  this.#core = internals.core;
360
- this.#follower = internals.follower;
373
+ this.#tabs = internals.tabs;
361
374
  this.#invalidation = internals.invalidation;
362
375
  this.#changes = internals.changes;
363
376
  this.#presence = internals.presence;
364
377
  this.#diagnostics = internals.diagnostics;
365
378
  this.#roleListeners = internals.roleListeners ?? new Set();
366
379
  this.#leadershipListeners = internals.leadershipListeners ?? new Set();
380
+ this.#unreachableListeners = internals.unreachableListeners ?? new Set();
367
381
  // Console introspection is a no-op outside a dev page.
368
382
  this.#devtoolsUnregister = registerDevtools({
369
383
  kind: 'handle',
@@ -381,64 +395,12 @@ export class SyncClientHandle implements PromiseMethods<WorkerApi> {
381
395
  }
382
396
 
383
397
  /**
384
- * @internal — whether `close()` has run.
385
- *
386
- * A follower keeps a blocking `acquire` outstanding for the whole time it is a
387
- * follower, so its promotion can fire long after the application has discarded
388
- * the handle. The promotion path consults this before opening anything.
389
- */
390
- get __isClosed(): boolean {
391
- return this.#closed;
392
- }
393
-
394
- /** @internal — swap this handle from follower to leader (promotion). */
395
- __becomeLeader(core: LeaderCore): void {
396
- // Calls queued for the next leader run on this tab's own core.
397
- this.#follower?.handOver(core.invoke);
398
- this.#follower = undefined;
399
- this.#core = core;
400
- this.#clientId = core.clientId;
401
- this.#role = 'leader';
402
- this.__setLeadership({ state: 'leader', clientId: core.clientId });
403
- for (const listener of this.#roleListeners) {
404
- try {
405
- listener('leader');
406
- } catch {
407
- /* a UI listener must never break promotion */
408
- }
409
- }
410
- }
411
-
412
- /**
413
- * @internal — a newer tab asked for the database: close the core and
414
- * release the lock so that tab promotes. This tab stays blocked until it
415
- * reloads with the newer build.
398
+ * @internal — apply a leadership snapshot in place: a promotion flips the
399
+ * role to `'leader'`, stepping down for a newer tab flips it back.
416
400
  */
417
- __yieldToNewerTab(): void {
418
- const core = this.#core;
419
- if (core === undefined) return;
420
- this.#core = undefined;
421
- this.#role = 'follower';
422
- this.__setLeadership({
423
- state: 'blocked',
424
- reason: 'leader-incompatible',
425
- code: LEADER_INCOMPATIBLE_CODE,
426
- leader: 'newer',
427
- retryable: true,
428
- });
429
- for (const listener of this.#roleListeners) {
430
- try {
431
- listener('follower');
432
- } catch {
433
- /* a UI listener must never break the handover */
434
- }
435
- }
436
- void core.close(true);
437
- }
438
-
439
- /** @internal — apply a follower reachability snapshot in place. */
440
401
  __setLeadership(state: LeadershipState): void {
441
402
  this.#leadership = state;
403
+ if (state.state === 'leader') this.#clientId = state.clientId;
442
404
  if (state.state === 'follower') this.#clientId = state.leaderClientId;
443
405
  for (const listener of this.#leadershipListeners) {
444
406
  try {
@@ -447,6 +409,16 @@ export class SyncClientHandle implements PromiseMethods<WorkerApi> {
447
409
  /* a UI listener must never break leadership transitions */
448
410
  }
449
411
  }
412
+ const role = state.state === 'leader' ? 'leader' : 'follower';
413
+ if (role === this.#role) return;
414
+ this.#role = role;
415
+ for (const listener of this.#roleListeners) {
416
+ try {
417
+ listener(role);
418
+ } catch {
419
+ /* a UI listener must never break a promotion or a handover */
420
+ }
421
+ }
450
422
  }
451
423
 
452
424
  /** @internal — dispatch a worker/relayed event to handle-local listeners. */
@@ -527,45 +499,66 @@ export class SyncClientHandle implements PromiseMethods<WorkerApi> {
527
499
  };
528
500
  }
529
501
 
530
- #call<M extends WorkerMethod>(
531
- method: M,
532
- args: Parameters<WorkerApi[M]>,
533
- ): Promise<Awaited<ReturnType<WorkerApi[M]>>> {
502
+ /** Start and end of every `leader-unreachable` period, with its duration. */
503
+ onLeaderUnreachable(
504
+ listener: (event: LeaderUnreachableEvent) => void,
505
+ ): () => void {
506
+ this.#unreachableListeners.add(listener);
507
+ return () => {
508
+ this.#unreachableListeners.delete(listener);
509
+ };
510
+ }
511
+
512
+ /**
513
+ * Take the database from a leader tab that has been `leader-unreachable`
514
+ * for `takeOverAfterMs`, and run the worker in this tab. Call it from an
515
+ * explicit user action. The old leader's worker refuses every statement
516
+ * from then on (`client.storage_fenced`) and its tab reports
517
+ * `leadership-taken`. Rejects with `client.takeover_refused` when the
518
+ * conditions do not hold, and with `client.storage_busy` when the old
519
+ * worker still holds the database files.
520
+ */
521
+ takeOver(): Promise<void> {
534
522
  if (this.#closed) {
535
523
  return Promise.reject(
536
524
  new ClientSyncError(WORKER_FAILED_CODE, 'the handle is closed'),
537
525
  );
538
526
  }
539
- if (
540
- this.#leadership.state === 'blocked' &&
541
- this.#leadership.reason === 'leader-incompatible'
542
- ) {
527
+ if (this.#tabs === undefined) {
543
528
  return Promise.reject(
544
529
  new ClientSyncError(
545
- LEADER_INCOMPATIBLE_CODE,
546
- 'the tab that owns the database runs a different protocol or schema version',
547
- true,
530
+ TAKEOVER_REFUSED_CODE,
531
+ 'takeOver() requires a multi-tab handle',
532
+ false,
533
+ { reason: 'unsupported' },
548
534
  ),
549
535
  );
550
536
  }
551
- if (this.#role === 'follower') {
552
- if (this.#follower === undefined) {
553
- return Promise.reject(
554
- new ClientSyncError(
555
- NOT_LEADER_CODE,
556
- 'this tab is not the leader — another tab owns the syncular ' +
557
- 'core for this origin (this handle opted out of follower ' +
558
- 'proxying with multiTab: false)',
559
- ),
560
- );
561
- }
562
- return this.#follower.call(method, args) as Promise<
537
+ return this.#tabs.takeOver();
538
+ }
539
+
540
+ #call<M extends WorkerMethod>(
541
+ method: M,
542
+ args: Parameters<WorkerApi[M]>,
543
+ ): Promise<Awaited<ReturnType<WorkerApi[M]>>> {
544
+ if (this.#closed) {
545
+ return Promise.reject(
546
+ new ClientSyncError(WORKER_FAILED_CODE, 'the handle is closed'),
547
+ );
548
+ }
549
+ if (this.#tabs !== undefined) {
550
+ return this.#tabs.call(method, args) as Promise<
563
551
  Awaited<ReturnType<WorkerApi[M]>>
564
552
  >;
565
553
  }
566
554
  if (this.#core === undefined) {
567
555
  return Promise.reject(
568
- new ClientSyncError(WORKER_FAILED_CODE, 'the handle is closed'),
556
+ new ClientSyncError(
557
+ NOT_LEADER_CODE,
558
+ 'this tab is not the leader — another tab owns the syncular ' +
559
+ 'core for this origin (this handle opted out of follower ' +
560
+ 'proxying with multiTab: false)',
561
+ ),
569
562
  );
570
563
  }
571
564
  return this.#core.invoke(method, args) as Promise<
@@ -804,38 +797,49 @@ export class SyncClientHandle implements PromiseMethods<WorkerApi> {
804
797
  return this.#call('setOffline', [offline]);
805
798
  }
806
799
 
807
- /** Close the core (leader) or unbind the link (follower), release leadership. */
800
+ /** SPEC §12.3 local-authority state; `undefined` without `localAuthority`. */
801
+ localAuthorityState(): Promise<LocalAuthorityState | undefined> {
802
+ return this.#call('localAuthorityState', []);
803
+ }
804
+
805
+ /**
806
+ * SPEC §12.3: upload the local authority's rows to `endpoints.syncUrl`,
807
+ * then sync with that server. Rejects with `sync.attach_rejected` when the
808
+ * server refuses an upload commit.
809
+ */
810
+ attachLocalAuthority(): Promise<void> {
811
+ return this.#call('attachLocalAuthority', []);
812
+ }
813
+
814
+ /** SPEC §12.3: delete the rows a stopped attach uploaded, then sync locally. */
815
+ abandonLocalAuthorityAttach(): Promise<void> {
816
+ return this.#call('abandonLocalAuthorityAttach', []);
817
+ }
818
+
819
+ /** Close the core (leader) or the link (follower), release leadership. */
808
820
  async close(): Promise<void> {
809
821
  if (this.#closed) return;
810
822
  this.#closed = true;
811
823
  this.#progress.clear();
812
824
  this.#devtoolsUnregister();
813
- if (this.#follower !== undefined) {
814
- this.#follower.close();
815
- this.#follower = undefined;
816
- }
825
+ await this.#tabs?.close();
817
826
  if (this.#core !== undefined) {
818
827
  const core = this.#core;
819
828
  this.#core = undefined;
820
- await core.close(true);
829
+ await core.close();
821
830
  }
822
831
  }
823
832
  }
824
833
 
825
834
  /**
826
835
  * Spawn the worker, run the init handshake, and return a running leader core.
827
- * `dispatchEvent` receives every worker event; `bridge` (when supplied) is
828
- * the follower relay whose lifetime is tied to this core.
836
+ * `dispatchEvent` receives every worker event.
829
837
  */
830
838
  async function startWorkerCore(options: {
831
839
  config: SyncClientHandleConfig;
832
840
  initConfig: WorkerInitConfig;
833
841
  lease: LeaderLease;
834
842
  dispatchEvent: (event: SyncWorkerEvent) => void;
835
- makeBridge?: (
836
- clientId: string,
837
- invoke: (method: string, args: readonly unknown[]) => Promise<unknown>,
838
- ) => LeaderBridge;
839
843
  }): Promise<LeaderCore> {
840
844
  const { config, initConfig, lease } = options;
841
845
  const worker = config.worker();
@@ -851,7 +855,6 @@ async function startWorkerCore(options: {
851
855
  if (terminated) return;
852
856
  terminated = true;
853
857
  globalThis.removeEventListener?.('pagehide', terminate);
854
- bridge?.close();
855
858
  worker.terminate();
856
859
  rejectReady?.(closedError);
857
860
  for (const entry of pending.values()) entry.reject(closedError);
@@ -880,8 +883,6 @@ async function startWorkerCore(options: {
880
883
  });
881
884
  };
882
885
 
883
- let bridge: LeaderBridge | undefined;
884
-
885
886
  const ready = new Promise<void>((resolve, reject) => {
886
887
  rejectReady = reject;
887
888
  const onMessage = (event: MessageEvent) => {
@@ -911,7 +912,6 @@ async function startWorkerCore(options: {
911
912
  }
912
913
  case 'event':
913
914
  options.dispatchEvent(message.event);
914
- bridge?.broadcastEvent(message.event);
915
915
  break;
916
916
  }
917
917
  };
@@ -941,29 +941,17 @@ async function startWorkerCore(options: {
941
941
  } as MainToWorkerMessage);
942
942
  },
943
943
  );
944
- if (options.makeBridge !== undefined) {
945
- bridge = options.makeBridge(initResult.clientId, invoke);
946
- }
947
944
  return {
948
945
  clientId: initResult.clientId,
949
946
  invoke,
950
- bridge,
951
- lease,
952
- close: async (terminateWorker) => {
947
+ close: async () => {
953
948
  if (terminated) return;
954
- bridge?.close();
955
949
  try {
956
950
  await invoke('close', []);
957
951
  } catch {
958
952
  // A terminated or failed worker has no further close RPC to service.
959
953
  }
960
- if (terminateWorker) terminate();
961
- else {
962
- globalThis.removeEventListener?.('pagehide', terminate);
963
- for (const entry of pending.values()) entry.reject(closedError);
964
- pending.clear();
965
- await lease.release();
966
- }
954
+ terminate();
967
955
  },
968
956
  };
969
957
  } catch (error) {
@@ -987,6 +975,9 @@ function buildInitConfig(
987
975
  ...(config.transportEnabled !== undefined
988
976
  ? { transportEnabled: config.transportEnabled }
989
977
  : {}),
978
+ ...(config.localAuthority !== undefined
979
+ ? { localAuthority: config.localAuthority }
980
+ : {}),
990
981
  ...(config.authorityReads !== undefined
991
982
  ? { authorityReads: config.authorityReads.declarations }
992
983
  : {}),
@@ -1055,281 +1046,130 @@ export async function createSyncClientHandle(
1055
1046
  if (resolvedConfig.onLeadershipChange !== undefined) {
1056
1047
  leadershipListeners.add(resolvedConfig.onLeadershipChange);
1057
1048
  }
1058
-
1059
- // Leadership BEFORE the worker exists: one core per origin, and a losing
1060
- // tab never boots a database it must not own.
1061
- const lease =
1062
- lock.tryAcquire !== undefined
1063
- ? await lock.tryAcquire(lockName)
1064
- : await lock.acquire(lockName);
1065
-
1066
- // ---- Won the election: leader. ----
1067
- if (lease !== undefined) {
1068
- // Epoch derivation for a fresh boot: epoch 0. A promoter (below) reads
1069
- // the highest epoch it has seen and adds one, so leaders monotonically
1070
- // increase it across handovers.
1071
- return await bootLeader(resolvedConfig, lockName, lease, {
1072
- epoch: 0,
1073
- invalidation,
1074
- changes,
1075
- presence,
1076
- diagnostics,
1077
- roleListeners,
1078
- leadershipListeners,
1079
- });
1049
+ const unreachableListeners = new Set<
1050
+ (event: LeaderUnreachableEvent) => void
1051
+ >();
1052
+ if (resolvedConfig.onLeaderUnreachable !== undefined) {
1053
+ unreachableListeners.add(resolvedConfig.onLeaderUnreachable);
1080
1054
  }
1081
1055
 
1082
- // ---- Lost the election. ----
1083
- if (resolvedConfig.multiTab === false) {
1084
- // Opted-out single-tab contract: a dead not-leader handle.
1085
- return new SyncClientHandle({
1086
- role: 'follower',
1087
- clientId: '',
1088
- currentSchemaVersion: resolvedConfig.schema.version,
1089
- invalidation,
1090
- changes,
1091
- presence,
1092
- diagnostics,
1093
- roleListeners,
1094
- leadershipListeners,
1095
- });
1096
- }
1097
-
1098
- // ---- Follower: proxy to the leader; contest + promote on its close. ----
1099
- return await bootFollower(resolvedConfig, lockName, lock, {
1056
+ const handleRef: { handle: SyncClientHandle | undefined } = {
1057
+ handle: undefined,
1058
+ };
1059
+ const parts = {
1060
+ currentSchemaVersion: resolvedConfig.schema.version,
1100
1061
  invalidation,
1101
1062
  changes,
1102
1063
  presence,
1103
1064
  diagnostics,
1104
1065
  roleListeners,
1105
1066
  leadershipListeners,
1106
- });
1107
- }
1108
-
1109
- interface HandleParts {
1110
- epoch?: number;
1111
- invalidation: InvalidationEmitter;
1112
- changes: ChangeEmitter;
1113
- presence: Set<(scopeKey: string) => void>;
1114
- diagnostics: ClientDiagnosticsEmitter;
1115
- roleListeners: Set<(role: HandleRole) => void>;
1116
- leadershipListeners: Set<(state: LeadershipState) => void>;
1117
- }
1118
-
1119
- /** Boot (or promote to) a leader: spawn the worker, wire the bridge. */
1120
- async function bootLeader(
1121
- config: SyncClientHandleConfig,
1122
- lockName: string,
1123
- lease: LeaderLease,
1124
- parts: HandleParts,
1125
- ): Promise<SyncClientHandle> {
1126
- const handleRef: { handle: SyncClientHandle | undefined } = {
1127
- handle: undefined,
1128
- };
1129
- const dispatchEvent = (event: SyncWorkerEvent): void => {
1130
- fireConfigCallbacks(config, event);
1131
- handleRef.handle?.__dispatchEvent(event);
1132
- };
1133
- // A newer tab may say hello before the handle exists; yield once it does.
1134
- let newerTab = false;
1135
- const makeBridge =
1136
- config.multiTab !== false
1137
- ? (
1138
- clientId: string,
1139
- invoke: (
1140
- method: string,
1141
- args: readonly unknown[],
1142
- ) => Promise<unknown>,
1143
- ): LeaderBridge => {
1144
- const factory = config.channelFactory ?? broadcastChannelFactory();
1145
- const channel = factory(multiTabChannelName(lockName));
1146
- return new LeaderBridge({
1147
- channel,
1148
- epoch: parts.epoch ?? 0,
1149
- clientId,
1150
- identity: tabIdentity(config),
1151
- invoke,
1152
- onNewerTab: () => {
1153
- newerTab = true;
1154
- handleRef.handle?.__yieldToNewerTab();
1155
- },
1156
- });
1157
- }
1158
- : undefined;
1159
-
1160
- const core = await startWorkerCore({
1161
- config,
1162
- initConfig: buildInitConfig(config),
1163
- lease,
1164
- dispatchEvent,
1165
- ...(makeBridge !== undefined ? { makeBridge } : {}),
1166
- });
1167
-
1168
- const handle = new SyncClientHandle({
1169
- role: 'leader',
1170
- clientId: core.clientId,
1171
- currentSchemaVersion: config.schema.version,
1172
- core,
1173
- invalidation: parts.invalidation,
1174
- changes: parts.changes,
1175
- presence: parts.presence,
1176
- diagnostics: parts.diagnostics,
1177
- roleListeners: parts.roleListeners,
1178
- leadershipListeners: parts.leadershipListeners,
1179
- });
1180
- handleRef.handle = handle;
1181
- if (newerTab) handle.__yieldToNewerTab();
1182
- return handle;
1183
- }
1184
-
1185
- function tabIdentity(config: SyncClientHandleConfig): TabIdentity {
1186
- return {
1187
- protocol: MULTI_TAB_PROTOCOL_VERSION,
1188
- schemaVersion: config.schema.version,
1189
- };
1190
- }
1191
-
1192
- /**
1193
- * Boot a follower: open the channel, bind to the leader, and race the lock in
1194
- * the background so this tab promotes itself the instant the leader closes.
1195
- */
1196
- async function bootFollower(
1197
- config: SyncClientHandleConfig,
1198
- lockName: string,
1199
- lock: LeaderLock,
1200
- parts: HandleParts,
1201
- ): Promise<SyncClientHandle> {
1202
- const factory = config.channelFactory ?? broadcastChannelFactory();
1203
- const channel = factory(multiTabChannelName(lockName));
1204
- const handleRef: { handle: SyncClientHandle | undefined } = {
1205
- handle: undefined,
1067
+ unreachableListeners,
1206
1068
  };
1207
1069
 
1208
- const follower = new FollowerLink({
1209
- channel,
1210
- fromId: newTabId(),
1211
- identity: tabIdentity(config),
1212
- onEvent: (event) => handleRef.handle?.__dispatchEvent(event),
1213
- onLeaderChange: (clientId) => {
1214
- // Learn the leader's shared client id (best-effort; the handle exposes
1215
- // it after binding). Nothing else to do — calls already flush.
1216
- void clientId;
1217
- },
1218
- onStateChange: (state) => handleRef.handle?.__setLeadership(state),
1219
- ...(config.followerCallTimeoutMs !== undefined
1220
- ? { callTimeoutMs: config.followerCallTimeoutMs }
1221
- : {}),
1222
- });
1223
-
1224
- // A follower waits (blocking) on the exclusive lock: it resolves ONLY when
1225
- // the current leader releases it (tab close). Winning it triggers promotion.
1226
- // We do NOT hold this promise — it settles asynchronously.
1227
- void lock.acquire(lockName).then(async (lease) => {
1228
- const handle = handleRef.handle;
1229
- if (handle === undefined) {
1230
- // Handle was never assembled (shouldn't happen); drop the lease.
1231
- await lease.release();
1232
- return;
1233
- }
1234
- if (handle.__isClosed) {
1235
- // The application discarded this handle while it was queued for
1236
- // leadership. Promoting now would open a database nobody is holding and
1237
- // then keep the lock forever, so no other tab could ever take over.
1238
- // Release instead, and let the next waiter have it.
1239
- await lease.release();
1240
- return;
1070
+ if (resolvedConfig.multiTab === false) {
1071
+ // Single-tab contract: the leader runs its core with no channel; a losing
1072
+ // tab is a dead not-leader handle that never boots a database.
1073
+ const lease =
1074
+ lock.tryAcquire !== undefined
1075
+ ? await lock.tryAcquire(lockName)
1076
+ : await lock.acquire(lockName);
1077
+ if (lease === undefined) {
1078
+ return new SyncClientHandle({ role: 'follower', clientId: '', ...parts });
1241
1079
  }
1242
- // The follower saw the departing leader's epoch; the new leader must
1243
- // strictly exceed it so stale replies/events are discarded everywhere.
1244
- const nextEpoch = follower.maxEpochSeen + 1;
1245
- // Unbind the link so any late leader traffic is ignored, then promote.
1246
- follower.unbind();
1247
- // A newer tab may say hello before this core is installed.
1248
- let newerTab = false;
1249
- try {
1080
+ const core = await startWorkerCore({
1081
+ config: resolvedConfig,
1082
+ initConfig: buildInitConfig(resolvedConfig),
1083
+ lease,
1084
+ dispatchEvent: (event) => {
1085
+ fireConfigCallbacks(resolvedConfig, event);
1086
+ handleRef.handle?.__dispatchEvent(event);
1087
+ },
1088
+ });
1089
+ const handle = new SyncClientHandle({
1090
+ role: 'leader',
1091
+ clientId: core.clientId,
1092
+ core,
1093
+ ...parts,
1094
+ });
1095
+ handleRef.handle = handle;
1096
+ return handle;
1097
+ }
1098
+
1099
+ // One core per origin: the tab that wins the lock runs the worker, every
1100
+ // other tab forwards to it and promotes when it closes.
1101
+ const tabs = await createTabCoordinator<SyncWorkerEvent>({
1102
+ name: lockName,
1103
+ version: resolvedConfig.schema.version,
1104
+ lock,
1105
+ ...(resolvedConfig.channelFactory !== undefined
1106
+ ? { channelFactory: resolvedConfig.channelFactory }
1107
+ : {}),
1108
+ ...(resolvedConfig.followerCallTimeoutMs !== undefined
1109
+ ? { callTimeoutMs: resolvedConfig.followerCallTimeoutMs }
1110
+ : {}),
1111
+ ...(resolvedConfig.takeOverAfterMs !== undefined
1112
+ ? { takeOverAfterMs: resolvedConfig.takeOverAfterMs }
1113
+ : {}),
1114
+ ...(resolvedConfig.tabClock !== undefined
1115
+ ? { clock: resolvedConfig.tabClock }
1116
+ : {}),
1117
+ onLeaderUnreachable: (event) => {
1118
+ for (const listener of unreachableListeners) {
1119
+ try {
1120
+ listener(event);
1121
+ } catch {
1122
+ /* a telemetry listener must never break cross-tab coordination */
1123
+ }
1124
+ }
1125
+ },
1126
+ lead: async (context) => {
1250
1127
  const core = await startWorkerCore({
1251
- config,
1252
- initConfig: buildInitConfig(config, handle.__headers ?? config.headers),
1253
- lease,
1128
+ config: resolvedConfig,
1129
+ // A promoted tab carries the latest `setHeaders` set.
1130
+ initConfig: {
1131
+ ...buildInitConfig(
1132
+ resolvedConfig,
1133
+ handleRef.handle?.__headers ?? resolvedConfig.headers,
1134
+ ),
1135
+ ...(context.takeover ? { takeOverStorage: true } : {}),
1136
+ },
1137
+ lease: context.lease,
1254
1138
  dispatchEvent: (event) => {
1255
- fireConfigCallbacks(config, event);
1256
- handle.__dispatchEvent(event);
1139
+ fireConfigCallbacks(resolvedConfig, event);
1140
+ context.broadcast(event);
1257
1141
  },
1258
- ...(config.multiTab !== false
1259
- ? {
1260
- makeBridge: (
1261
- clientId: string,
1262
- invoke: (
1263
- method: string,
1264
- args: readonly unknown[],
1265
- ) => Promise<unknown>,
1266
- ): LeaderBridge => {
1267
- const promoteChannel = factory(multiTabChannelName(lockName));
1268
- return new LeaderBridge({
1269
- channel: promoteChannel,
1270
- epoch: nextEpoch,
1271
- clientId,
1272
- identity: tabIdentity(config),
1273
- invoke,
1274
- onNewerTab: () => {
1275
- newerTab = true;
1276
- handle.__yieldToNewerTab();
1277
- },
1278
- });
1279
- },
1280
- }
1281
- : {}),
1282
1142
  });
1283
- if (handle.__isClosed) {
1284
- // Closed while the worker was starting. `close()` already ran and found
1285
- // no core to shut down, so this one would leak: tear it down here rather
1286
- // than hand it to a discarded handle. `close(true)` releases the lease.
1287
- await core.close(true);
1288
- return;
1289
- }
1290
- handle.__becomeLeader(core);
1291
- if (newerTab) handle.__yieldToNewerTab();
1292
- } catch {
1293
- // Promotion failed to spawn a worker — release so the next tab tries.
1294
- await lease.release();
1295
- }
1143
+ return {
1144
+ clientId: core.clientId,
1145
+ call: (_tabId, method, args) => core.invoke(method, args),
1146
+ close: () => core.close(),
1147
+ };
1148
+ },
1149
+ onEvent: (event) => handleRef.handle?.__dispatchEvent(event),
1150
+ onStateChange: (state) => handleRef.handle?.__setLeadership(state),
1296
1151
  });
1297
-
1152
+ const leadership = tabs.state;
1298
1153
  const handle = new SyncClientHandle({
1299
- role: 'follower',
1300
- // The follower learns the leader's shared client id once bound; expose it
1301
- // lazily via `clientId` is not possible on a getter over the link, so we
1302
- // leave '' until promotion (the shared id is the leader's — hooks that
1303
- // need it read it after a round). Followers rarely need clientId directly.
1304
- clientId: '',
1305
- currentSchemaVersion: config.schema.version,
1306
- follower,
1307
- invalidation: parts.invalidation,
1308
- changes: parts.changes,
1309
- presence: parts.presence,
1310
- diagnostics: parts.diagnostics,
1311
- roleListeners: parts.roleListeners,
1312
- leadershipListeners: parts.leadershipListeners,
1154
+ role: leadership.state === 'leader' ? 'leader' : 'follower',
1155
+ clientId:
1156
+ leadership.state === 'leader'
1157
+ ? leadership.clientId
1158
+ : leadership.state === 'follower'
1159
+ ? leadership.leaderClientId
1160
+ : '',
1161
+ tabs,
1162
+ ...parts,
1313
1163
  });
1314
1164
  handleRef.handle = handle;
1315
- // Do not hand back a follower until its link has bound to the leader (the
1316
- // hello→announce round trip completed). Before binding, epoch is -1 and any
1317
- // event the leader fans out is dropped, so a caller that subscribes and then
1318
- // relies on push invalidation would silently miss events emitted in the
1319
- // binding window — a real multi-tab race, not just a test flake. Binding is
1320
- // fast (the leader answers every hello with an announce); on the off chance
1321
- // it times out we still return the handle (queued calls flush and events
1322
- // resume on the next announce) rather than failing handle construction.
1323
- try {
1324
- await follower.waitUntilBound();
1325
- } catch {
1326
- /* bind timed out — return the (degraded but functional) handle anyway */
1327
- }
1328
1165
  // Init configuration belongs to the one leader worker. A newly opened
1329
1166
  // follower that explicitly requests security preflight must therefore put
1330
1167
  // the shared origin replica behind the same barrier before it is returned;
1331
1168
  // otherwise an already-running leader would silently ignore the request.
1332
- if (config.securityPreflight === true) {
1169
+ if (
1170
+ leadership.state !== 'leader' &&
1171
+ resolvedConfig.securityPreflight === true
1172
+ ) {
1333
1173
  try {
1334
1174
  await handle.beginSecurityPreflight();
1335
1175
  } catch (error) {