@syncular/client 0.53.0 → 0.54.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.
- package/README.md +10 -0
- package/dist/client.d.ts +3 -0
- package/dist/client.js +1 -2
- package/dist/devtools.d.ts +7 -7
- package/dist/devtools.js +7 -1
- package/dist/worker-core.d.ts +77 -0
- package/dist/worker-core.js +505 -0
- package/dist/worker-entry.d.ts +3 -55
- package/dist/worker-entry.js +4 -553
- package/dist/worker-host.d.ts +4 -0
- package/dist/worker-host.js +5 -3
- package/dist/worker-local-authority.d.ts +3 -0
- package/dist/worker-local-authority.js +70 -0
- package/dist/worker-protocol.d.ts +2 -0
- package/dist/worker-protocol.js +2 -0
- package/dist/worker-remote.d.ts +5 -0
- package/dist/worker-remote.js +5 -0
- package/package.json +13 -4
- package/src/client.ts +4 -2
- package/src/devtools.ts +23 -12
- package/src/worker-core.ts +713 -0
- package/src/worker-entry.ts +5 -743
- package/src/worker-host.ts +10 -4
- package/src/worker-local-authority.ts +106 -0
- package/src/worker-protocol.ts +3 -0
- package/src/worker-remote.ts +14 -0
package/dist/worker-entry.js
CHANGED
|
@@ -1,555 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
import { classifySqliteFailure, ClientSyncError, STORAGE_BUSY_CODE, } from './errors.js';
|
|
5
|
-
import { httpBlobTransport, httpSegmentDownloader, httpSyncTransport, webSocketRealtimeConnector, } from './http.js';
|
|
6
|
-
import { openPersistentWasmDatabase } from './wasm-database.js';
|
|
7
|
-
import { LOCAL_AUTHORITY_UNCONFIGURED_CODE, WORKER_FAILED_CODE, } from './worker-protocol.js';
|
|
8
|
-
/** §12: the worker's sibling file for the local authority. */
|
|
9
|
-
const LOCAL_AUTHORITY_SIBLING = 'local-authority';
|
|
10
|
-
function toErrorShape(caught) {
|
|
11
|
-
const error = classifySqliteFailure(caught).error;
|
|
12
|
-
if (error instanceof ClientSyncError) {
|
|
13
|
-
return {
|
|
14
|
-
code: error.code,
|
|
15
|
-
message: error.message,
|
|
16
|
-
retryable: error.retryable,
|
|
17
|
-
...(error.details !== undefined ? { details: error.details } : {}),
|
|
18
|
-
};
|
|
19
|
-
}
|
|
20
|
-
return {
|
|
21
|
-
code: WORKER_FAILED_CODE,
|
|
22
|
-
message: error instanceof Error ? error.message : String(error),
|
|
23
|
-
retryable: false,
|
|
24
|
-
};
|
|
25
|
-
}
|
|
26
|
-
/**
|
|
27
|
-
* ArrayBuffers safe to transfer out of a query result: whole-buffer
|
|
28
|
-
* views only (a view into a larger/pooled buffer is cloned instead —
|
|
29
|
-
* transferring would detach unrelated data), deduplicated because a
|
|
30
|
-
* buffer may only appear once in a transfer list.
|
|
31
|
-
*/
|
|
32
|
-
function queryTransferables(rows) {
|
|
33
|
-
const buffers = new Set();
|
|
34
|
-
for (const row of rows) {
|
|
35
|
-
if (row === null || typeof row !== 'object')
|
|
36
|
-
continue;
|
|
37
|
-
for (const value of Object.values(row)) {
|
|
38
|
-
if (value instanceof Uint8Array &&
|
|
39
|
-
value.buffer instanceof ArrayBuffer &&
|
|
40
|
-
value.byteOffset === 0 &&
|
|
41
|
-
value.byteLength === value.buffer.byteLength) {
|
|
42
|
-
buffers.add(value.buffer);
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
return [...buffers];
|
|
47
|
-
}
|
|
48
|
-
/**
|
|
49
|
-
* Register the RPC server on the current worker scope. Call this once
|
|
50
|
-
* from a worker entry script; the main-thread handle drives everything
|
|
51
|
-
* else through `init`/`call` messages.
|
|
52
|
-
*/
|
|
1
|
+
import { startSyncWorkerCore } from './worker-core.js';
|
|
2
|
+
import { createWorkerLocalAuthority } from './worker-local-authority.js';
|
|
3
|
+
/** Start a worker that supports the optional local authority (§12). */
|
|
53
4
|
export function startSyncWorker(overrides = {}) {
|
|
54
|
-
|
|
55
|
-
const post = (message, transfer) => {
|
|
56
|
-
if (transfer !== undefined && transfer.length > 0) {
|
|
57
|
-
scope.postMessage(message, transfer);
|
|
58
|
-
}
|
|
59
|
-
else {
|
|
60
|
-
scope.postMessage(message);
|
|
61
|
-
}
|
|
62
|
-
};
|
|
63
|
-
let client;
|
|
64
|
-
let database;
|
|
65
|
-
let authority;
|
|
66
|
-
let authoritySibling;
|
|
67
|
-
let remoteTransport;
|
|
68
|
-
let offline = false;
|
|
69
|
-
let headers = {};
|
|
70
|
-
let closed = false;
|
|
71
|
-
// -- one sync loop: RPC-driven and auto-driven rounds serialize ----------
|
|
72
|
-
let syncChain = Promise.resolve();
|
|
73
|
-
function serializedSync(fn) {
|
|
74
|
-
const next = syncChain.then(fn, fn);
|
|
75
|
-
syncChain = next.then(() => undefined, () => undefined);
|
|
76
|
-
return next;
|
|
77
|
-
}
|
|
78
|
-
// -- SPEC §7.5 host loop: event-driven intents, no interactive polling --
|
|
79
|
-
let autoSync = true;
|
|
80
|
-
let autoSyncScheduled = false;
|
|
81
|
-
let backgroundTimer;
|
|
82
|
-
let backgroundDue = Number.POSITIVE_INFINITY;
|
|
83
|
-
function runAutoSync() {
|
|
84
|
-
if (closed ||
|
|
85
|
-
client === undefined ||
|
|
86
|
-
offline ||
|
|
87
|
-
client.securityLifecycle() === 'preflight') {
|
|
88
|
-
autoSyncScheduled = false;
|
|
89
|
-
return;
|
|
90
|
-
}
|
|
91
|
-
const running = client;
|
|
92
|
-
void serializedSync(() => {
|
|
93
|
-
// The queued round owns the flag from here. Clearing it at entry would
|
|
94
|
-
// let every wake-up that arrives while this round waits behind the
|
|
95
|
-
// running one queue its own full drive (§8.4 coalescing).
|
|
96
|
-
autoSyncScheduled = false;
|
|
97
|
-
return running.syncUntilIdle();
|
|
98
|
-
})
|
|
99
|
-
.then((summary) => {
|
|
100
|
-
if (!closed)
|
|
101
|
-
post({ t: 'event', event: { kind: 'synced', summary } });
|
|
102
|
-
if (summary.budgetExhausted)
|
|
103
|
-
consumeSyncIntent({ kind: 'interactive' });
|
|
104
|
-
})
|
|
105
|
-
.catch((error) => {
|
|
106
|
-
if (!closed) {
|
|
107
|
-
post({
|
|
108
|
-
t: 'event',
|
|
109
|
-
event: { kind: 'synced', error: toErrorShape(error) },
|
|
110
|
-
});
|
|
111
|
-
}
|
|
112
|
-
});
|
|
113
|
-
}
|
|
114
|
-
function consumeSyncIntent(intent) {
|
|
115
|
-
if (!autoSync ||
|
|
116
|
-
closed ||
|
|
117
|
-
client === undefined ||
|
|
118
|
-
offline ||
|
|
119
|
-
client.securityLifecycle() === 'preflight' ||
|
|
120
|
-
intent.kind === 'none') {
|
|
121
|
-
return;
|
|
122
|
-
}
|
|
123
|
-
if (intent.kind === 'background') {
|
|
124
|
-
if (autoSyncScheduled)
|
|
125
|
-
return;
|
|
126
|
-
const due = Date.now() + Math.max(0, intent.delayMs);
|
|
127
|
-
if (backgroundTimer !== undefined && due >= backgroundDue)
|
|
128
|
-
return;
|
|
129
|
-
if (backgroundTimer !== undefined)
|
|
130
|
-
clearTimeout(backgroundTimer);
|
|
131
|
-
backgroundDue = due;
|
|
132
|
-
backgroundTimer = setTimeout(() => {
|
|
133
|
-
backgroundTimer = undefined;
|
|
134
|
-
backgroundDue = Number.POSITIVE_INFINITY;
|
|
135
|
-
if (!autoSyncScheduled) {
|
|
136
|
-
autoSyncScheduled = true;
|
|
137
|
-
runAutoSync();
|
|
138
|
-
}
|
|
139
|
-
}, Math.max(0, due - Date.now()));
|
|
140
|
-
return;
|
|
141
|
-
}
|
|
142
|
-
if (backgroundTimer !== undefined) {
|
|
143
|
-
clearTimeout(backgroundTimer);
|
|
144
|
-
backgroundTimer = undefined;
|
|
145
|
-
backgroundDue = Number.POSITIVE_INFINITY;
|
|
146
|
-
}
|
|
147
|
-
if (!autoSync || autoSyncScheduled || closed || client === undefined) {
|
|
148
|
-
return;
|
|
149
|
-
}
|
|
150
|
-
autoSyncScheduled = true;
|
|
151
|
-
queueMicrotask(runAutoSync);
|
|
152
|
-
}
|
|
153
|
-
/**
|
|
154
|
-
* §12.3: attach or abandon with the client's rounds held, so no round
|
|
155
|
-
* reaches the authority while it uploads or rolls back.
|
|
156
|
-
*/
|
|
157
|
-
async function driveLocalAuthority(run) {
|
|
158
|
-
const running = requireClient();
|
|
159
|
-
const local = authority;
|
|
160
|
-
const remote = remoteTransport;
|
|
161
|
-
if (local === undefined || remote === undefined) {
|
|
162
|
-
throw new ClientSyncError(LOCAL_AUTHORITY_UNCONFIGURED_CODE, 'init did not enable the local authority');
|
|
163
|
-
}
|
|
164
|
-
running.setTransportEnabled(false);
|
|
165
|
-
try {
|
|
166
|
-
await serializedSync(() => run(local, remote));
|
|
167
|
-
}
|
|
168
|
-
catch (error) {
|
|
169
|
-
// `sync.attach_rejected` keeps its code and details across the RPC.
|
|
170
|
-
if (error instanceof Error &&
|
|
171
|
-
!(error instanceof ClientSyncError) &&
|
|
172
|
-
'code' in error &&
|
|
173
|
-
typeof error.code === 'string') {
|
|
174
|
-
throw new ClientSyncError(error.code, error.message, false, 'details' in error &&
|
|
175
|
-
typeof error.details === 'object' &&
|
|
176
|
-
error.details !== null
|
|
177
|
-
? { ...error.details }
|
|
178
|
-
: undefined);
|
|
179
|
-
}
|
|
180
|
-
throw error;
|
|
181
|
-
}
|
|
182
|
-
finally {
|
|
183
|
-
running.setTransportEnabled(!offline);
|
|
184
|
-
}
|
|
185
|
-
consumeSyncIntent({ kind: 'interactive' });
|
|
186
|
-
}
|
|
187
|
-
function requireClient() {
|
|
188
|
-
if (client === undefined) {
|
|
189
|
-
throw new ClientSyncError(WORKER_FAILED_CODE, 'the worker received a call before init completed');
|
|
190
|
-
}
|
|
191
|
-
return client;
|
|
192
|
-
}
|
|
193
|
-
async function init(config) {
|
|
194
|
-
if (config.authorityReads !== undefined && !overrides.createAuthorityReads)
|
|
195
|
-
throw new ClientSyncError('client.authority_read_forbidden', 'authorityReads requires startSyncWorker({ createAuthorityReads })');
|
|
196
|
-
if (client !== undefined) {
|
|
197
|
-
throw new ClientSyncError(WORKER_FAILED_CODE, 'the worker is already initialized');
|
|
198
|
-
}
|
|
199
|
-
autoSync = config.autoSync ?? true;
|
|
200
|
-
headers = config.headers ?? {};
|
|
201
|
-
const http = { headers: () => headers };
|
|
202
|
-
for (let attempt = 0;; attempt++) {
|
|
203
|
-
try {
|
|
204
|
-
database =
|
|
205
|
-
overrides.openDatabase !== undefined
|
|
206
|
-
? await overrides.openDatabase(config)
|
|
207
|
-
: await defaultOpenDatabase(config);
|
|
208
|
-
break;
|
|
209
|
-
}
|
|
210
|
-
catch (error) {
|
|
211
|
-
if (config.database.mode !== 'persistent' ||
|
|
212
|
-
!(error instanceof ClientSyncError) ||
|
|
213
|
-
error.code !== STORAGE_BUSY_CODE ||
|
|
214
|
-
!error.retryable ||
|
|
215
|
-
attempt === 6) {
|
|
216
|
-
throw error;
|
|
217
|
-
}
|
|
218
|
-
// Retain the leader lease while the previous worker's OPFS handles
|
|
219
|
-
// drain. Only opening is retried; core initialization has not started.
|
|
220
|
-
const delayMs = Math.min(50 * 2 ** attempt, 1000);
|
|
221
|
-
if (overrides.waitForStorageRetry !== undefined) {
|
|
222
|
-
await overrides.waitForStorageRetry(delayMs);
|
|
223
|
-
}
|
|
224
|
-
else {
|
|
225
|
-
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
const remote = overrides.createTransport !== undefined
|
|
230
|
-
? overrides.createTransport(config)
|
|
231
|
-
: httpSyncTransport(config.endpoints.syncUrl, http);
|
|
232
|
-
remoteTransport = remote;
|
|
233
|
-
const remoteSegments = overrides.createSegments !== undefined
|
|
234
|
-
? overrides.createSegments(config)
|
|
235
|
-
: config.endpoints.segmentsUrl !== undefined
|
|
236
|
-
? httpSegmentDownloader(config.endpoints.segmentsUrl, http)
|
|
237
|
-
: undefined;
|
|
238
|
-
if (config.localAuthority === true) {
|
|
239
|
-
if (overrides.openLocalAuthority === undefined) {
|
|
240
|
-
throw new ClientSyncError(LOCAL_AUTHORITY_UNCONFIGURED_CODE, 'localAuthority requires startSyncWorker({ openLocalAuthority })');
|
|
241
|
-
}
|
|
242
|
-
authoritySibling = database.openSibling?.(LOCAL_AUTHORITY_SIBLING);
|
|
243
|
-
if (authoritySibling === undefined) {
|
|
244
|
-
throw new ClientSyncError(LOCAL_AUTHORITY_UNCONFIGURED_CODE, 'localAuthority requires a database with sibling files');
|
|
245
|
-
}
|
|
246
|
-
authority = await overrides.openLocalAuthority(authoritySibling.database, config.schema);
|
|
247
|
-
}
|
|
248
|
-
// §12.4: rounds reach the local authority until attach completes, then
|
|
249
|
-
// the remote server; the replica rebinds through the §2.1 epoch reset.
|
|
250
|
-
const localActive = () => authority !== undefined && authority.state !== 'attached';
|
|
251
|
-
const transport = (request) => localActive() ? authority.sync(request) : remote(request);
|
|
252
|
-
const segments = authority === undefined
|
|
253
|
-
? remoteSegments
|
|
254
|
-
: (request) => {
|
|
255
|
-
if (localActive())
|
|
256
|
-
return authority.downloadSegment(request);
|
|
257
|
-
if (remoteSegments === undefined) {
|
|
258
|
-
throw new ClientSyncError('sync.invalid_request', 'no segment endpoint configured');
|
|
259
|
-
}
|
|
260
|
-
return remoteSegments(request);
|
|
261
|
-
};
|
|
262
|
-
// §5.9 blob transport: only when a blobs URL is configured.
|
|
263
|
-
const blobs = config.endpoints.blobsUrl !== undefined
|
|
264
|
-
? httpBlobTransport(config.endpoints.blobsUrl, http)
|
|
265
|
-
: undefined;
|
|
266
|
-
// Realtime needs the (possibly persisted) clientId for the
|
|
267
|
-
// `{clientId}` URL placeholder — start the client first, then attach
|
|
268
|
-
// the connector through a mutable slot read at connect time.
|
|
269
|
-
let realtimeConnector;
|
|
270
|
-
offline = config.transportEnabled === false;
|
|
271
|
-
const started = new SyncClient({
|
|
272
|
-
transportEnabled: !offline,
|
|
273
|
-
database,
|
|
274
|
-
schema: config.schema,
|
|
275
|
-
transport,
|
|
276
|
-
...(segments !== undefined ? { segments } : {}),
|
|
277
|
-
...(blobs !== undefined ? { blobs } : {}),
|
|
278
|
-
realtime: (handlers) => {
|
|
279
|
-
// §12.2: a local authority has no realtime channel.
|
|
280
|
-
if (realtimeConnector === undefined || localActive()) {
|
|
281
|
-
throw new ClientSyncError('sync.invalid_request', 'no realtime connector configured');
|
|
282
|
-
}
|
|
283
|
-
return realtimeConnector(handlers);
|
|
284
|
-
},
|
|
285
|
-
...(config.clientId !== undefined ? { clientId: config.clientId } : {}),
|
|
286
|
-
...(config.limits !== undefined ? { limits: config.limits } : {}),
|
|
287
|
-
...(config.retainFailedCommits !== undefined
|
|
288
|
-
? { retainFailedCommits: config.retainFailedCommits }
|
|
289
|
-
: {}),
|
|
290
|
-
...(config.realtimePolicy !== undefined
|
|
291
|
-
? { realtimePolicy: config.realtimePolicy }
|
|
292
|
-
: {}),
|
|
293
|
-
...(config.encryption !== undefined
|
|
294
|
-
? { encryption: encryptionConfigFromKeyring(config.encryption) }
|
|
295
|
-
: {}),
|
|
296
|
-
...(config.authorityReads !== undefined
|
|
297
|
-
? {
|
|
298
|
-
authorityReads: overrides.createAuthorityReads(config.authorityReads),
|
|
299
|
-
}
|
|
300
|
-
: {}),
|
|
301
|
-
...(config.securityPreflight !== undefined
|
|
302
|
-
? { securityPreflight: config.securityPreflight }
|
|
303
|
-
: {}),
|
|
304
|
-
...(config.previousVersionContext !== undefined
|
|
305
|
-
? { previousVersionContext: config.previousVersionContext }
|
|
306
|
-
: {}),
|
|
307
|
-
onSyncNeeded: (reason) => {
|
|
308
|
-
post({ t: 'event', event: { kind: 'sync-needed', reason } });
|
|
309
|
-
consumeSyncIntent({ kind: 'interactive' });
|
|
310
|
-
},
|
|
311
|
-
onSyncIntent: consumeSyncIntent,
|
|
312
|
-
onConflict: (conflict) => {
|
|
313
|
-
post({ t: 'event', event: { kind: 'conflict', conflict } });
|
|
314
|
-
},
|
|
315
|
-
onUpgrading: (upgrading) => {
|
|
316
|
-
// §7.4.5: surface the schema-bump reset + completion to the UI thread.
|
|
317
|
-
post({ t: 'event', event: { kind: 'upgrading', upgrading } });
|
|
318
|
-
},
|
|
319
|
-
onPresence: (scopeKey) => {
|
|
320
|
-
// §8.6: surface a presence change to the UI thread.
|
|
321
|
-
post({ t: 'event', event: { kind: 'presence', scopeKey } });
|
|
322
|
-
},
|
|
323
|
-
});
|
|
324
|
-
started.onProgress((progress) => {
|
|
325
|
-
if (!closed)
|
|
326
|
-
post({ t: 'event', event: { kind: 'progress', progress } });
|
|
327
|
-
});
|
|
328
|
-
started.onChange((batch) => {
|
|
329
|
-
if (!closed)
|
|
330
|
-
post({ t: 'event', event: { kind: 'change', batch } });
|
|
331
|
-
});
|
|
332
|
-
const postDiagnostics = (snapshot) => {
|
|
333
|
-
if (closed)
|
|
334
|
-
return;
|
|
335
|
-
post({
|
|
336
|
-
t: 'event',
|
|
337
|
-
event: {
|
|
338
|
-
kind: 'diagnostics',
|
|
339
|
-
snapshot: withClientDiagnosticsHost(snapshot, {
|
|
340
|
-
kind: 'worker',
|
|
341
|
-
role: 'leader',
|
|
342
|
-
connectivity: offline ? 'offline' : snapshot.host.connectivity,
|
|
343
|
-
realtime: snapshot.host.realtime,
|
|
344
|
-
}),
|
|
345
|
-
},
|
|
346
|
-
});
|
|
347
|
-
};
|
|
348
|
-
started.onDiagnostics(postDiagnostics);
|
|
349
|
-
await started.start();
|
|
350
|
-
realtimeConnector =
|
|
351
|
-
overrides.createRealtime !== undefined
|
|
352
|
-
? overrides.createRealtime(config, started.clientId, http.headers)
|
|
353
|
-
: config.endpoints.realtimeUrl !== undefined
|
|
354
|
-
? webSocketRealtimeConnector(config.endpoints.realtimeUrl.replace('{clientId}', encodeURIComponent(started.clientId)))
|
|
355
|
-
: undefined;
|
|
356
|
-
client = started;
|
|
357
|
-
// `start()` may discover persisted subscriptions/outbox work. Its callback
|
|
358
|
-
// fires before this worker publishes the initialized client, so consume
|
|
359
|
-
// the durable state once here as well; coalescing makes this a single task.
|
|
360
|
-
if (started.statusSnapshot().syncNeeded)
|
|
361
|
-
consumeSyncIntent({ kind: 'interactive' });
|
|
362
|
-
return { clientId: started.clientId };
|
|
363
|
-
}
|
|
364
|
-
// Forward every argument to core methods, including authority's zero-argument check.
|
|
365
|
-
const coreMethods = [
|
|
366
|
-
'securityLifecycle',
|
|
367
|
-
'subscribe',
|
|
368
|
-
'subscribeMany',
|
|
369
|
-
'unsubscribe',
|
|
370
|
-
'windowState',
|
|
371
|
-
'purgeLocalData',
|
|
372
|
-
'rebootstrapLocalData',
|
|
373
|
-
'previousVersionSnapshot',
|
|
374
|
-
'previousVersionAudit',
|
|
375
|
-
'previousVersionDiscard',
|
|
376
|
-
'query',
|
|
377
|
-
'authoritySnapshot',
|
|
378
|
-
'querySnapshot',
|
|
379
|
-
'snapshotRead',
|
|
380
|
-
'statusSnapshot',
|
|
381
|
-
'conflicts',
|
|
382
|
-
'rejections',
|
|
383
|
-
'commitOutcome',
|
|
384
|
-
'commitOutcomes',
|
|
385
|
-
'resolveCommitOutcome',
|
|
386
|
-
'pendingCommits',
|
|
387
|
-
'subscriptions',
|
|
388
|
-
'subscription',
|
|
389
|
-
'connectRealtime',
|
|
390
|
-
'disconnectRealtime',
|
|
391
|
-
'setPresence',
|
|
392
|
-
'presence',
|
|
393
|
-
'uploadBlob',
|
|
394
|
-
'fetchBlob',
|
|
395
|
-
];
|
|
396
|
-
const api = {
|
|
397
|
-
...Object.fromEntries(coreMethods.map((method) => [
|
|
398
|
-
method,
|
|
399
|
-
(...args) => {
|
|
400
|
-
const running = requireClient();
|
|
401
|
-
return Reflect.apply(running[method], running, args);
|
|
402
|
-
},
|
|
403
|
-
])),
|
|
404
|
-
beginSecurityPreflight: async () => {
|
|
405
|
-
if (backgroundTimer !== undefined)
|
|
406
|
-
clearTimeout(backgroundTimer);
|
|
407
|
-
backgroundTimer = undefined;
|
|
408
|
-
backgroundDue = Number.POSITIVE_INFINITY;
|
|
409
|
-
autoSyncScheduled = false;
|
|
410
|
-
await requireClient().beginSecurityPreflight();
|
|
411
|
-
},
|
|
412
|
-
activateSecurity: async (options = {}) => {
|
|
413
|
-
await requireClient().activateSecurity({
|
|
414
|
-
...(options.encryption !== undefined
|
|
415
|
-
? { encryption: encryptionConfigFromKeyring(options.encryption) }
|
|
416
|
-
: {}),
|
|
417
|
-
});
|
|
418
|
-
},
|
|
419
|
-
setWindow: async (base, units) => {
|
|
420
|
-
await requireClient().setWindowCommand(base, units);
|
|
421
|
-
},
|
|
422
|
-
mutate: (mutations) => {
|
|
423
|
-
return requireClient().mutateCommand(mutations).value;
|
|
424
|
-
},
|
|
425
|
-
patch: (table, rowId, partial, options) => {
|
|
426
|
-
// Same §8.4 rule as `mutate`: a local write must push without the app
|
|
427
|
-
// orchestrating sync, so consume the core's immediate intent.
|
|
428
|
-
const result = requireClient().patchCommand(table, rowId, partial, options);
|
|
429
|
-
return result.value;
|
|
430
|
-
},
|
|
431
|
-
sync: () => {
|
|
432
|
-
const running = requireClient();
|
|
433
|
-
return serializedSync(() => running.sync());
|
|
434
|
-
},
|
|
435
|
-
syncUntilIdle: (options) => {
|
|
436
|
-
const running = requireClient();
|
|
437
|
-
return serializedSync(() => running.syncUntilIdle(options));
|
|
438
|
-
},
|
|
439
|
-
proveCurrentBase: (outcome, options) => {
|
|
440
|
-
const running = requireClient();
|
|
441
|
-
return serializedSync(() => running.proveCurrentBase(outcome, options));
|
|
442
|
-
},
|
|
443
|
-
resetClientId: () => requireClient().resetClientId(),
|
|
444
|
-
localRevision: () => requireClient().localRevision,
|
|
445
|
-
diagnosticsSnapshot: (request) => {
|
|
446
|
-
const snapshot = requireClient().diagnosticsSnapshot(request);
|
|
447
|
-
return withClientDiagnosticsHost(snapshot, {
|
|
448
|
-
kind: 'worker',
|
|
449
|
-
role: 'leader',
|
|
450
|
-
connectivity: offline ? 'offline' : snapshot.host.connectivity,
|
|
451
|
-
realtime: snapshot.host.realtime,
|
|
452
|
-
});
|
|
453
|
-
},
|
|
454
|
-
setHeaders: (next) => {
|
|
455
|
-
headers = next;
|
|
456
|
-
},
|
|
457
|
-
setOffline: (value) => {
|
|
458
|
-
offline = value;
|
|
459
|
-
requireClient().setTransportEnabled(!value);
|
|
460
|
-
if (offline) {
|
|
461
|
-
if (backgroundTimer !== undefined)
|
|
462
|
-
clearTimeout(backgroundTimer);
|
|
463
|
-
backgroundTimer = undefined;
|
|
464
|
-
backgroundDue = Number.POSITIVE_INFINITY;
|
|
465
|
-
}
|
|
466
|
-
else if (client !== undefined) {
|
|
467
|
-
const snapshot = client.diagnosticsSnapshot();
|
|
468
|
-
post({
|
|
469
|
-
t: 'event',
|
|
470
|
-
event: {
|
|
471
|
-
kind: 'diagnostics',
|
|
472
|
-
snapshot: withClientDiagnosticsHost(snapshot, {
|
|
473
|
-
kind: 'worker',
|
|
474
|
-
role: 'leader',
|
|
475
|
-
connectivity: snapshot.host.connectivity,
|
|
476
|
-
realtime: snapshot.host.realtime,
|
|
477
|
-
}),
|
|
478
|
-
},
|
|
479
|
-
});
|
|
480
|
-
}
|
|
481
|
-
},
|
|
482
|
-
localAuthorityState: () => authority?.state,
|
|
483
|
-
attachLocalAuthority: () => driveLocalAuthority((local, remote) => local.attach(remote)),
|
|
484
|
-
abandonLocalAuthorityAttach: () => driveLocalAuthority((local, remote) => local.abandonAttach(remote)),
|
|
485
|
-
close: async () => {
|
|
486
|
-
closed = true;
|
|
487
|
-
if (backgroundTimer !== undefined)
|
|
488
|
-
clearTimeout(backgroundTimer);
|
|
489
|
-
await client?.close();
|
|
490
|
-
authoritySibling?.close();
|
|
491
|
-
database?.close();
|
|
492
|
-
client = undefined;
|
|
493
|
-
database = undefined;
|
|
494
|
-
},
|
|
495
|
-
};
|
|
496
|
-
// Local purge/rebootstrap/discard rewrite the same durable state an
|
|
497
|
-
// in-flight sync round captured at send time, and the RFC 0005 reads observe
|
|
498
|
-
// (and can themselves trigger the discard of) that same previous-version
|
|
499
|
-
// container. Running all of them on the sync chain orders them against RPC-
|
|
500
|
-
// and auto-driven rounds (the client core's reset fence covers hosts that
|
|
501
|
-
// call the core directly).
|
|
502
|
-
const syncChainMethods = new Set([
|
|
503
|
-
'purgeLocalData',
|
|
504
|
-
'rebootstrapLocalData',
|
|
505
|
-
'previousVersionSnapshot',
|
|
506
|
-
'previousVersionAudit',
|
|
507
|
-
'previousVersionDiscard',
|
|
508
|
-
]);
|
|
509
|
-
async function dispatch(message) {
|
|
510
|
-
const method = api[message.method];
|
|
511
|
-
const invoke = () => method.apply(api, message.args);
|
|
512
|
-
if (syncChainMethods.has(message.method)) {
|
|
513
|
-
return await serializedSync(async () => invoke());
|
|
514
|
-
}
|
|
515
|
-
return await invoke();
|
|
516
|
-
}
|
|
517
|
-
function run(id, fn, transfer) {
|
|
518
|
-
void (async () => {
|
|
519
|
-
try {
|
|
520
|
-
const value = await fn();
|
|
521
|
-
post({ t: 'result', id, value }, transfer !== undefined ? transfer(value) : undefined);
|
|
522
|
-
}
|
|
523
|
-
catch (error) {
|
|
524
|
-
post({ t: 'error', id, error: toErrorShape(error) });
|
|
525
|
-
}
|
|
526
|
-
})();
|
|
527
|
-
}
|
|
528
|
-
scope.addEventListener('message', (event) => {
|
|
529
|
-
const message = event.data;
|
|
530
|
-
if (message.t === 'init') {
|
|
531
|
-
run(message.id, () => init(message.config));
|
|
532
|
-
return;
|
|
533
|
-
}
|
|
534
|
-
if (message.t === 'call') {
|
|
535
|
-
run(message.id, () => dispatch(message), message.method === 'query'
|
|
536
|
-
? (value) => queryTransferables(value)
|
|
537
|
-
: message.method === 'querySnapshot'
|
|
538
|
-
? (value) => queryTransferables(value.rows)
|
|
539
|
-
: undefined);
|
|
540
|
-
}
|
|
541
|
-
});
|
|
542
|
-
post({ t: 'ready' });
|
|
543
|
-
}
|
|
544
|
-
async function defaultOpenDatabase(config) {
|
|
545
|
-
if (config.database.mode !== 'persistent') {
|
|
546
|
-
throw new ClientSyncError(WORKER_FAILED_CODE, "database mode 'custom' requires an openDatabase override in the " +
|
|
547
|
-
'worker bootstrap (startSyncWorker({ openDatabase }))');
|
|
548
|
-
}
|
|
549
|
-
return openPersistentWasmDatabase(config.database.name, {
|
|
550
|
-
...(config.database.directory !== undefined
|
|
551
|
-
? { directory: config.database.directory }
|
|
552
|
-
: {}),
|
|
553
|
-
...(config.takeOverStorage === true ? { takeOver: true } : {}),
|
|
554
|
-
});
|
|
5
|
+
startSyncWorkerCore(overrides, createWorkerLocalAuthority);
|
|
555
6
|
}
|
package/dist/worker-host.d.ts
CHANGED
|
@@ -27,6 +27,7 @@ import type { WakeReason } from '@syncular/core';
|
|
|
27
27
|
import type { BlobRef, CachedBlob } from './blob.js';
|
|
28
28
|
import type { ConflictRecord, CurrentBaseProof, MutationInput, PresencePeer, QueryReadSpec, QuerySnapshot, RejectionRecord, SecurityLifecycle, SnapshotRead, SnapshotReadRequest, SubscribeInput, SyncClientConfig, SyncClientLimits, SyncSummary, SyncIdleOptions, SyncIdleResult, WindowState } from './client.js';
|
|
29
29
|
import type { SqlRow, SqlValue } from './database.js';
|
|
30
|
+
import type { DevtoolsRegistrar } from './devtools.js';
|
|
30
31
|
import { ClientDiagnosticsEmitter, type ClientDiagnosticsListener, type ClientDiagnosticsRequest, type ClientDiagnosticsSnapshot, type RealtimePolicy } from './diagnostics.js';
|
|
31
32
|
import type { EncryptionKeyringConfig } from './encryption.js';
|
|
32
33
|
import { ClientSyncError } from './errors.js';
|
|
@@ -65,6 +66,8 @@ export declare function isolatedReplicaNames(options: {
|
|
|
65
66
|
readonly replicaId: string;
|
|
66
67
|
}): IsolatedReplicaNames;
|
|
67
68
|
export interface SyncClientHandleConfig {
|
|
69
|
+
/** Explicit development console registry for this page's handle. */
|
|
70
|
+
readonly devtools?: DevtoolsRegistrar;
|
|
68
71
|
/**
|
|
69
72
|
* Spawns the worker running `startSyncWorker()` (a factory so bundlers
|
|
70
73
|
* see `new Worker(new URL(...))` at the call site, and so no worker is
|
|
@@ -193,6 +196,7 @@ export declare class SyncClientHandle implements PromiseMethods<WorkerApi> {
|
|
|
193
196
|
leadershipListeners?: Set<(state: LeadershipState) => void>;
|
|
194
197
|
unreachableListeners?: Set<(event: LeaderUnreachableEvent) => void>;
|
|
195
198
|
leadership?: LeadershipState;
|
|
199
|
+
devtools?: DevtoolsRegistrar;
|
|
196
200
|
});
|
|
197
201
|
/**
|
|
198
202
|
* @internal — apply a leadership snapshot in place: a promotion flips the
|
package/dist/worker-host.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { ProgressEmitter, } from './progress.js';
|
|
2
|
-
import { registerDevtools } from './devtools.js';
|
|
3
2
|
import { ClientDiagnosticsEmitter, withClientDiagnosticsHost, } from './diagnostics.js';
|
|
4
3
|
import { ClientSyncError } from './errors.js';
|
|
5
4
|
import { ChangeEmitter, InvalidationEmitter, invalidationFromChange, } from './invalidation.js';
|
|
@@ -107,7 +106,7 @@ export class SyncClientHandle {
|
|
|
107
106
|
this.#leadershipListeners = internals.leadershipListeners ?? new Set();
|
|
108
107
|
this.#unreachableListeners = internals.unreachableListeners ?? new Set();
|
|
109
108
|
// Console introspection is a no-op outside a dev page.
|
|
110
|
-
this.#devtoolsUnregister =
|
|
109
|
+
this.#devtoolsUnregister = internals.devtools?.({
|
|
111
110
|
kind: 'handle',
|
|
112
111
|
ref: this,
|
|
113
112
|
clientId: () => this.#clientId,
|
|
@@ -442,7 +441,7 @@ export class SyncClientHandle {
|
|
|
442
441
|
return;
|
|
443
442
|
this.#closed = true;
|
|
444
443
|
this.#progress.clear();
|
|
445
|
-
this.#devtoolsUnregister();
|
|
444
|
+
this.#devtoolsUnregister?.();
|
|
446
445
|
await this.#tabs?.close();
|
|
447
446
|
if (this.#core !== undefined) {
|
|
448
447
|
const core = this.#core;
|
|
@@ -660,6 +659,9 @@ export async function createSyncClientHandle(config) {
|
|
|
660
659
|
roleListeners,
|
|
661
660
|
leadershipListeners,
|
|
662
661
|
unreachableListeners,
|
|
662
|
+
...(resolvedConfig.devtools !== undefined
|
|
663
|
+
? { devtools: resolvedConfig.devtools }
|
|
664
|
+
: {}),
|
|
663
665
|
};
|
|
664
666
|
if (resolvedConfig.multiTab === false) {
|
|
665
667
|
// Single-tab contract: the leader runs its core with no channel; a losing
|