@syncular/client 0.48.0 → 0.49.1
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.
- package/README.md +32 -0
- package/dist/client.js +18 -3
- package/dist/multi-tab.d.ts +96 -22
- package/dist/multi-tab.js +242 -10
- package/dist/outbox.d.ts +5 -0
- package/dist/outbox.js +11 -3
- package/dist/outcomes.js +6 -2
- package/dist/previous-version.d.ts +3 -1
- package/dist/previous-version.js +24 -5
- package/dist/worker-entry.d.ts +17 -1
- package/dist/worker-entry.js +73 -4
- package/dist/worker-host.d.ts +23 -26
- package/dist/worker-host.js +122 -311
- package/dist/worker-protocol.d.ts +16 -0
- package/dist/worker-protocol.js +2 -0
- package/package.json +3 -3
- package/src/client.ts +26 -3
- package/src/multi-tab.ts +366 -34
- package/src/outbox.ts +16 -2
- package/src/outcomes.ts +6 -2
- package/src/previous-version.ts +32 -5
- package/src/worker-entry.ts +123 -4
- package/src/worker-host.ts +143 -381
- package/src/worker-protocol.ts +18 -0
package/src/worker-host.ts
CHANGED
|
@@ -81,16 +81,11 @@ import {
|
|
|
81
81
|
type LocalDataRebootstrapResult,
|
|
82
82
|
} from './local-rebootstrap';
|
|
83
83
|
import {
|
|
84
|
-
broadcastChannelFactory,
|
|
85
84
|
type CrossTabChannel,
|
|
86
|
-
|
|
87
|
-
LEADER_INCOMPATIBLE_CODE,
|
|
88
|
-
LeaderBridge,
|
|
85
|
+
createTabCoordinator,
|
|
89
86
|
type LeadershipState,
|
|
90
|
-
MULTI_TAB_PROTOCOL_VERSION,
|
|
91
87
|
multiTabChannelName,
|
|
92
|
-
|
|
93
|
-
type TabIdentity,
|
|
88
|
+
type TabCoordinator,
|
|
94
89
|
} from './multi-tab';
|
|
95
90
|
import type { OutboxCommit } from './outbox';
|
|
96
91
|
import type {
|
|
@@ -110,6 +105,7 @@ import type { ClientSchema } from './schema';
|
|
|
110
105
|
import type { SubscriptionRecord } from './state';
|
|
111
106
|
import type { WindowBase } from './window';
|
|
112
107
|
import {
|
|
108
|
+
type LocalAuthorityState,
|
|
113
109
|
type MainToWorkerMessage,
|
|
114
110
|
NOT_LEADER_CODE,
|
|
115
111
|
type SyncWorkerEvent,
|
|
@@ -201,6 +197,8 @@ export interface SyncClientHandleConfig {
|
|
|
201
197
|
/** Open the worker-owned replica behind the fail-closed security gate. */
|
|
202
198
|
readonly securityPreflight?: boolean;
|
|
203
199
|
readonly transportEnabled?: boolean;
|
|
200
|
+
/** SPEC §12: start against the worker's local authority (`WorkerInitConfig`). */
|
|
201
|
+
readonly localAuthority?: boolean;
|
|
204
202
|
readonly clientId?: string;
|
|
205
203
|
readonly limits?: SyncClientLimits;
|
|
206
204
|
readonly retainFailedCommits?: boolean;
|
|
@@ -269,9 +267,8 @@ function defaultLeaderLock(): LeaderLock {
|
|
|
269
267
|
}
|
|
270
268
|
|
|
271
269
|
/**
|
|
272
|
-
* A running worker core owned by THIS tab (the leader). Wraps the worker
|
|
273
|
-
* the RPC pending map
|
|
274
|
-
* follower requests. Torn down on `close()` or on a graceful demotion.
|
|
270
|
+
* A running worker core owned by THIS tab (the leader). Wraps the worker and
|
|
271
|
+
* the RPC pending map. Torn down on `close()` or on a graceful demotion.
|
|
275
272
|
*/
|
|
276
273
|
interface LeaderCore {
|
|
277
274
|
readonly clientId: string;
|
|
@@ -279,9 +276,8 @@ interface LeaderCore {
|
|
|
279
276
|
method: string,
|
|
280
277
|
args: readonly unknown[],
|
|
281
278
|
) => Promise<unknown>;
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
close(terminate: boolean): Promise<void>;
|
|
279
|
+
/** Close the core, terminate the worker, and release the lease. */
|
|
280
|
+
close(): Promise<void>;
|
|
285
281
|
}
|
|
286
282
|
|
|
287
283
|
/**
|
|
@@ -316,8 +312,10 @@ export class SyncClientHandle implements PromiseMethods<WorkerApi> {
|
|
|
316
312
|
#clientId: string;
|
|
317
313
|
readonly #currentSchemaVersion: number;
|
|
318
314
|
#leadership: LeadershipState;
|
|
315
|
+
/** The multi-tab route: this tab's core when it leads, the leader's otherwise. */
|
|
316
|
+
readonly #tabs: TabCoordinator | undefined;
|
|
317
|
+
/** The `multiTab: false` leader's own core. */
|
|
319
318
|
#core: LeaderCore | undefined;
|
|
320
|
-
#follower: FollowerLink | undefined;
|
|
321
319
|
readonly #invalidation: InvalidationEmitter;
|
|
322
320
|
readonly #progress = new ProgressEmitter();
|
|
323
321
|
readonly #changes: ChangeEmitter;
|
|
@@ -334,7 +332,7 @@ export class SyncClientHandle implements PromiseMethods<WorkerApi> {
|
|
|
334
332
|
clientId: string;
|
|
335
333
|
currentSchemaVersion: number;
|
|
336
334
|
core?: LeaderCore;
|
|
337
|
-
|
|
335
|
+
tabs?: TabCoordinator;
|
|
338
336
|
invalidation: InvalidationEmitter;
|
|
339
337
|
changes: ChangeEmitter;
|
|
340
338
|
presence: Set<(scopeKey: string) => void>;
|
|
@@ -348,16 +346,17 @@ export class SyncClientHandle implements PromiseMethods<WorkerApi> {
|
|
|
348
346
|
this.#currentSchemaVersion = internals.currentSchemaVersion;
|
|
349
347
|
this.#leadership =
|
|
350
348
|
internals.leadership ??
|
|
349
|
+
internals.tabs?.state ??
|
|
351
350
|
(internals.role === 'leader'
|
|
352
351
|
? { state: 'leader', clientId: internals.clientId }
|
|
353
|
-
:
|
|
352
|
+
: {
|
|
354
353
|
state: 'blocked',
|
|
355
354
|
reason: 'leader-unreachable',
|
|
356
355
|
code: 'client.follower_timeout',
|
|
357
356
|
retryable: true,
|
|
358
|
-
})
|
|
357
|
+
});
|
|
359
358
|
this.#core = internals.core;
|
|
360
|
-
this.#
|
|
359
|
+
this.#tabs = internals.tabs;
|
|
361
360
|
this.#invalidation = internals.invalidation;
|
|
362
361
|
this.#changes = internals.changes;
|
|
363
362
|
this.#presence = internals.presence;
|
|
@@ -381,64 +380,12 @@ export class SyncClientHandle implements PromiseMethods<WorkerApi> {
|
|
|
381
380
|
}
|
|
382
381
|
|
|
383
382
|
/**
|
|
384
|
-
* @internal —
|
|
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.
|
|
383
|
+
* @internal — apply a leadership snapshot in place: a promotion flips the
|
|
384
|
+
* role to `'leader'`, stepping down for a newer tab flips it back.
|
|
416
385
|
*/
|
|
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
386
|
__setLeadership(state: LeadershipState): void {
|
|
441
387
|
this.#leadership = state;
|
|
388
|
+
if (state.state === 'leader') this.#clientId = state.clientId;
|
|
442
389
|
if (state.state === 'follower') this.#clientId = state.leaderClientId;
|
|
443
390
|
for (const listener of this.#leadershipListeners) {
|
|
444
391
|
try {
|
|
@@ -447,6 +394,16 @@ export class SyncClientHandle implements PromiseMethods<WorkerApi> {
|
|
|
447
394
|
/* a UI listener must never break leadership transitions */
|
|
448
395
|
}
|
|
449
396
|
}
|
|
397
|
+
const role = state.state === 'leader' ? 'leader' : 'follower';
|
|
398
|
+
if (role === this.#role) return;
|
|
399
|
+
this.#role = role;
|
|
400
|
+
for (const listener of this.#roleListeners) {
|
|
401
|
+
try {
|
|
402
|
+
listener(role);
|
|
403
|
+
} catch {
|
|
404
|
+
/* a UI listener must never break a promotion or a handover */
|
|
405
|
+
}
|
|
406
|
+
}
|
|
450
407
|
}
|
|
451
408
|
|
|
452
409
|
/** @internal — dispatch a worker/relayed event to handle-local listeners. */
|
|
@@ -536,36 +493,19 @@ export class SyncClientHandle implements PromiseMethods<WorkerApi> {
|
|
|
536
493
|
new ClientSyncError(WORKER_FAILED_CODE, 'the handle is closed'),
|
|
537
494
|
);
|
|
538
495
|
}
|
|
539
|
-
if (
|
|
540
|
-
this.#
|
|
541
|
-
this.#leadership.reason === 'leader-incompatible'
|
|
542
|
-
) {
|
|
543
|
-
return Promise.reject(
|
|
544
|
-
new ClientSyncError(
|
|
545
|
-
LEADER_INCOMPATIBLE_CODE,
|
|
546
|
-
'the tab that owns the database runs a different protocol or schema version',
|
|
547
|
-
true,
|
|
548
|
-
),
|
|
549
|
-
);
|
|
550
|
-
}
|
|
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<
|
|
496
|
+
if (this.#tabs !== undefined) {
|
|
497
|
+
return this.#tabs.call(method, args) as Promise<
|
|
563
498
|
Awaited<ReturnType<WorkerApi[M]>>
|
|
564
499
|
>;
|
|
565
500
|
}
|
|
566
501
|
if (this.#core === undefined) {
|
|
567
502
|
return Promise.reject(
|
|
568
|
-
new ClientSyncError(
|
|
503
|
+
new ClientSyncError(
|
|
504
|
+
NOT_LEADER_CODE,
|
|
505
|
+
'this tab is not the leader — another tab owns the syncular ' +
|
|
506
|
+
'core for this origin (this handle opted out of follower ' +
|
|
507
|
+
'proxying with multiTab: false)',
|
|
508
|
+
),
|
|
569
509
|
);
|
|
570
510
|
}
|
|
571
511
|
return this.#core.invoke(method, args) as Promise<
|
|
@@ -804,38 +744,49 @@ export class SyncClientHandle implements PromiseMethods<WorkerApi> {
|
|
|
804
744
|
return this.#call('setOffline', [offline]);
|
|
805
745
|
}
|
|
806
746
|
|
|
807
|
-
/**
|
|
747
|
+
/** SPEC §12.3 local-authority state; `undefined` without `localAuthority`. */
|
|
748
|
+
localAuthorityState(): Promise<LocalAuthorityState | undefined> {
|
|
749
|
+
return this.#call('localAuthorityState', []);
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* SPEC §12.3: upload the local authority's rows to `endpoints.syncUrl`,
|
|
754
|
+
* then sync with that server. Rejects with `sync.attach_rejected` when the
|
|
755
|
+
* server refuses an upload commit.
|
|
756
|
+
*/
|
|
757
|
+
attachLocalAuthority(): Promise<void> {
|
|
758
|
+
return this.#call('attachLocalAuthority', []);
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/** SPEC §12.3: delete the rows a stopped attach uploaded, then sync locally. */
|
|
762
|
+
abandonLocalAuthorityAttach(): Promise<void> {
|
|
763
|
+
return this.#call('abandonLocalAuthorityAttach', []);
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/** Close the core (leader) or the link (follower), release leadership. */
|
|
808
767
|
async close(): Promise<void> {
|
|
809
768
|
if (this.#closed) return;
|
|
810
769
|
this.#closed = true;
|
|
811
770
|
this.#progress.clear();
|
|
812
771
|
this.#devtoolsUnregister();
|
|
813
|
-
|
|
814
|
-
this.#follower.close();
|
|
815
|
-
this.#follower = undefined;
|
|
816
|
-
}
|
|
772
|
+
await this.#tabs?.close();
|
|
817
773
|
if (this.#core !== undefined) {
|
|
818
774
|
const core = this.#core;
|
|
819
775
|
this.#core = undefined;
|
|
820
|
-
await core.close(
|
|
776
|
+
await core.close();
|
|
821
777
|
}
|
|
822
778
|
}
|
|
823
779
|
}
|
|
824
780
|
|
|
825
781
|
/**
|
|
826
782
|
* Spawn the worker, run the init handshake, and return a running leader core.
|
|
827
|
-
* `dispatchEvent` receives every worker event
|
|
828
|
-
* the follower relay whose lifetime is tied to this core.
|
|
783
|
+
* `dispatchEvent` receives every worker event.
|
|
829
784
|
*/
|
|
830
785
|
async function startWorkerCore(options: {
|
|
831
786
|
config: SyncClientHandleConfig;
|
|
832
787
|
initConfig: WorkerInitConfig;
|
|
833
788
|
lease: LeaderLease;
|
|
834
789
|
dispatchEvent: (event: SyncWorkerEvent) => void;
|
|
835
|
-
makeBridge?: (
|
|
836
|
-
clientId: string,
|
|
837
|
-
invoke: (method: string, args: readonly unknown[]) => Promise<unknown>,
|
|
838
|
-
) => LeaderBridge;
|
|
839
790
|
}): Promise<LeaderCore> {
|
|
840
791
|
const { config, initConfig, lease } = options;
|
|
841
792
|
const worker = config.worker();
|
|
@@ -851,7 +802,6 @@ async function startWorkerCore(options: {
|
|
|
851
802
|
if (terminated) return;
|
|
852
803
|
terminated = true;
|
|
853
804
|
globalThis.removeEventListener?.('pagehide', terminate);
|
|
854
|
-
bridge?.close();
|
|
855
805
|
worker.terminate();
|
|
856
806
|
rejectReady?.(closedError);
|
|
857
807
|
for (const entry of pending.values()) entry.reject(closedError);
|
|
@@ -880,8 +830,6 @@ async function startWorkerCore(options: {
|
|
|
880
830
|
});
|
|
881
831
|
};
|
|
882
832
|
|
|
883
|
-
let bridge: LeaderBridge | undefined;
|
|
884
|
-
|
|
885
833
|
const ready = new Promise<void>((resolve, reject) => {
|
|
886
834
|
rejectReady = reject;
|
|
887
835
|
const onMessage = (event: MessageEvent) => {
|
|
@@ -911,7 +859,6 @@ async function startWorkerCore(options: {
|
|
|
911
859
|
}
|
|
912
860
|
case 'event':
|
|
913
861
|
options.dispatchEvent(message.event);
|
|
914
|
-
bridge?.broadcastEvent(message.event);
|
|
915
862
|
break;
|
|
916
863
|
}
|
|
917
864
|
};
|
|
@@ -941,29 +888,17 @@ async function startWorkerCore(options: {
|
|
|
941
888
|
} as MainToWorkerMessage);
|
|
942
889
|
},
|
|
943
890
|
);
|
|
944
|
-
if (options.makeBridge !== undefined) {
|
|
945
|
-
bridge = options.makeBridge(initResult.clientId, invoke);
|
|
946
|
-
}
|
|
947
891
|
return {
|
|
948
892
|
clientId: initResult.clientId,
|
|
949
893
|
invoke,
|
|
950
|
-
|
|
951
|
-
lease,
|
|
952
|
-
close: async (terminateWorker) => {
|
|
894
|
+
close: async () => {
|
|
953
895
|
if (terminated) return;
|
|
954
|
-
bridge?.close();
|
|
955
896
|
try {
|
|
956
897
|
await invoke('close', []);
|
|
957
898
|
} catch {
|
|
958
899
|
// A terminated or failed worker has no further close RPC to service.
|
|
959
900
|
}
|
|
960
|
-
|
|
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
|
-
}
|
|
901
|
+
terminate();
|
|
967
902
|
},
|
|
968
903
|
};
|
|
969
904
|
} catch (error) {
|
|
@@ -987,6 +922,9 @@ function buildInitConfig(
|
|
|
987
922
|
...(config.transportEnabled !== undefined
|
|
988
923
|
? { transportEnabled: config.transportEnabled }
|
|
989
924
|
: {}),
|
|
925
|
+
...(config.localAuthority !== undefined
|
|
926
|
+
? { localAuthority: config.localAuthority }
|
|
927
|
+
: {}),
|
|
990
928
|
...(config.authorityReads !== undefined
|
|
991
929
|
? { authorityReads: config.authorityReads.declarations }
|
|
992
930
|
: {}),
|
|
@@ -1056,280 +994,104 @@ export async function createSyncClientHandle(
|
|
|
1056
994
|
leadershipListeners.add(resolvedConfig.onLeadershipChange);
|
|
1057
995
|
}
|
|
1058
996
|
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
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
|
-
});
|
|
1080
|
-
}
|
|
1081
|
-
|
|
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, {
|
|
997
|
+
const handleRef: { handle: SyncClientHandle | undefined } = {
|
|
998
|
+
handle: undefined,
|
|
999
|
+
};
|
|
1000
|
+
const parts = {
|
|
1001
|
+
currentSchemaVersion: resolvedConfig.schema.version,
|
|
1100
1002
|
invalidation,
|
|
1101
1003
|
changes,
|
|
1102
1004
|
presence,
|
|
1103
1005
|
diagnostics,
|
|
1104
1006
|
roleListeners,
|
|
1105
1007
|
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
1008
|
};
|
|
1190
|
-
}
|
|
1191
1009
|
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
): Promise<SyncClientHandle> {
|
|
1202
|
-
const factory = config.channelFactory ?? broadcastChannelFactory();
|
|
1203
|
-
const channel = factory(multiTabChannelName(lockName));
|
|
1204
|
-
const handleRef: { handle: SyncClientHandle | undefined } = {
|
|
1205
|
-
handle: undefined,
|
|
1206
|
-
};
|
|
1207
|
-
|
|
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;
|
|
1010
|
+
if (resolvedConfig.multiTab === false) {
|
|
1011
|
+
// Single-tab contract: the leader runs its core with no channel; a losing
|
|
1012
|
+
// tab is a dead not-leader handle that never boots a database.
|
|
1013
|
+
const lease =
|
|
1014
|
+
lock.tryAcquire !== undefined
|
|
1015
|
+
? await lock.tryAcquire(lockName)
|
|
1016
|
+
: await lock.acquire(lockName);
|
|
1017
|
+
if (lease === undefined) {
|
|
1018
|
+
return new SyncClientHandle({ role: 'follower', clientId: '', ...parts });
|
|
1241
1019
|
}
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1020
|
+
const core = await startWorkerCore({
|
|
1021
|
+
config: resolvedConfig,
|
|
1022
|
+
initConfig: buildInitConfig(resolvedConfig),
|
|
1023
|
+
lease,
|
|
1024
|
+
dispatchEvent: (event) => {
|
|
1025
|
+
fireConfigCallbacks(resolvedConfig, event);
|
|
1026
|
+
handleRef.handle?.__dispatchEvent(event);
|
|
1027
|
+
},
|
|
1028
|
+
});
|
|
1029
|
+
const handle = new SyncClientHandle({
|
|
1030
|
+
role: 'leader',
|
|
1031
|
+
clientId: core.clientId,
|
|
1032
|
+
core,
|
|
1033
|
+
...parts,
|
|
1034
|
+
});
|
|
1035
|
+
handleRef.handle = handle;
|
|
1036
|
+
return handle;
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
// One core per origin: the tab that wins the lock runs the worker, every
|
|
1040
|
+
// other tab forwards to it and promotes when it closes.
|
|
1041
|
+
const tabs = await createTabCoordinator<SyncWorkerEvent>({
|
|
1042
|
+
name: lockName,
|
|
1043
|
+
version: resolvedConfig.schema.version,
|
|
1044
|
+
lock,
|
|
1045
|
+
...(resolvedConfig.channelFactory !== undefined
|
|
1046
|
+
? { channelFactory: resolvedConfig.channelFactory }
|
|
1047
|
+
: {}),
|
|
1048
|
+
...(resolvedConfig.followerCallTimeoutMs !== undefined
|
|
1049
|
+
? { callTimeoutMs: resolvedConfig.followerCallTimeoutMs }
|
|
1050
|
+
: {}),
|
|
1051
|
+
lead: async (context) => {
|
|
1250
1052
|
const core = await startWorkerCore({
|
|
1251
|
-
config,
|
|
1252
|
-
|
|
1253
|
-
|
|
1053
|
+
config: resolvedConfig,
|
|
1054
|
+
// A promoted tab carries the latest `setHeaders` set.
|
|
1055
|
+
initConfig: buildInitConfig(
|
|
1056
|
+
resolvedConfig,
|
|
1057
|
+
handleRef.handle?.__headers ?? resolvedConfig.headers,
|
|
1058
|
+
),
|
|
1059
|
+
lease: context.lease,
|
|
1254
1060
|
dispatchEvent: (event) => {
|
|
1255
|
-
fireConfigCallbacks(
|
|
1256
|
-
|
|
1061
|
+
fireConfigCallbacks(resolvedConfig, event);
|
|
1062
|
+
context.broadcast(event);
|
|
1257
1063
|
},
|
|
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
1064
|
});
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
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
|
-
}
|
|
1065
|
+
return {
|
|
1066
|
+
clientId: core.clientId,
|
|
1067
|
+
call: (_tabId, method, args) => core.invoke(method, args),
|
|
1068
|
+
close: () => core.close(),
|
|
1069
|
+
};
|
|
1070
|
+
},
|
|
1071
|
+
onEvent: (event) => handleRef.handle?.__dispatchEvent(event),
|
|
1072
|
+
onStateChange: (state) => handleRef.handle?.__setLeadership(state),
|
|
1296
1073
|
});
|
|
1297
|
-
|
|
1074
|
+
const leadership = tabs.state;
|
|
1298
1075
|
const handle = new SyncClientHandle({
|
|
1299
|
-
role: 'follower',
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
changes: parts.changes,
|
|
1309
|
-
presence: parts.presence,
|
|
1310
|
-
diagnostics: parts.diagnostics,
|
|
1311
|
-
roleListeners: parts.roleListeners,
|
|
1312
|
-
leadershipListeners: parts.leadershipListeners,
|
|
1076
|
+
role: leadership.state === 'leader' ? 'leader' : 'follower',
|
|
1077
|
+
clientId:
|
|
1078
|
+
leadership.state === 'leader'
|
|
1079
|
+
? leadership.clientId
|
|
1080
|
+
: leadership.state === 'follower'
|
|
1081
|
+
? leadership.leaderClientId
|
|
1082
|
+
: '',
|
|
1083
|
+
tabs,
|
|
1084
|
+
...parts,
|
|
1313
1085
|
});
|
|
1314
1086
|
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
1087
|
// Init configuration belongs to the one leader worker. A newly opened
|
|
1329
1088
|
// follower that explicitly requests security preflight must therefore put
|
|
1330
1089
|
// the shared origin replica behind the same barrier before it is returned;
|
|
1331
1090
|
// otherwise an already-running leader would silently ignore the request.
|
|
1332
|
-
if (
|
|
1091
|
+
if (
|
|
1092
|
+
leadership.state !== 'leader' &&
|
|
1093
|
+
resolvedConfig.securityPreflight === true
|
|
1094
|
+
) {
|
|
1333
1095
|
try {
|
|
1334
1096
|
await handle.beginSecurityPreflight();
|
|
1335
1097
|
} catch (error) {
|