@pgxsinkit/client 0.2.0 → 0.2.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/dist/index.d.ts +20 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +460 -165
- package/dist/index.js.map +8 -8
- package/dist/mutation.d.ts +6 -0
- package/dist/mutation.d.ts.map +1 -1
- package/dist/worker/attach-sync-client.d.ts +81 -20
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +33 -8
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/engine-control.d.ts +2 -1
- package/dist/worker/engine-control.d.ts.map +1 -1
- package/dist/worker/protocol.d.ts +32 -21
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +3 -3
- package/skills/core/SKILL.md +1 -1
- package/skills/operating/SKILL.md +47 -8
- package/src/index.ts +55 -7
- package/src/mutation.ts +48 -4
- package/src/worker/attach-sync-client.ts +322 -130
- package/src/worker/define-sync-worker.ts +445 -132
- package/src/worker/engine-control.ts +2 -2
- package/src/worker/protocol.ts +33 -6
package/dist/index.js
CHANGED
|
@@ -2838,6 +2838,17 @@ function createMutationRuntime(options) {
|
|
|
2838
2838
|
const flushBatchSize = options.flushBatchSize ?? DEFAULT_FLUSH_BATCH_SIZE;
|
|
2839
2839
|
const registryVersion = options.registryVersion ?? fingerprintRegistry(options.registry);
|
|
2840
2840
|
let flushQueue = Promise.resolve();
|
|
2841
|
+
const disposeController = new AbortController;
|
|
2842
|
+
const untilAborted = (work) => {
|
|
2843
|
+
if (disposeController.signal.aborted) {
|
|
2844
|
+
return Promise.reject(new DOMException("Mutation runtime disposed", "AbortError"));
|
|
2845
|
+
}
|
|
2846
|
+
return new Promise((resolve, reject) => {
|
|
2847
|
+
const onAbort = () => reject(new DOMException("Mutation runtime disposed", "AbortError"));
|
|
2848
|
+
disposeController.signal.addEventListener("abort", onAbort, { once: true });
|
|
2849
|
+
work.then(resolve, reject).finally(() => disposeController.signal.removeEventListener("abort", onAbort));
|
|
2850
|
+
});
|
|
2851
|
+
};
|
|
2841
2852
|
const ownsMetaTable = options.ownsMetaTable ?? true;
|
|
2842
2853
|
let recoveryMarkerDirty = false;
|
|
2843
2854
|
let markSendingInFlight = 0;
|
|
@@ -3152,7 +3163,7 @@ function createMutationRuntime(options) {
|
|
|
3152
3163
|
const conflictedMutationIds = new Set;
|
|
3153
3164
|
let processedCount = 0;
|
|
3154
3165
|
do {
|
|
3155
|
-
const batchResult = await flushBatch(options.db, tableContexts, mutationUrls.batch, maxMutationAttempts, flushBatchSize, table, resolveAuthToken, options.requestHeaders, ensureRecoveryMarker, markSendingScope);
|
|
3166
|
+
const batchResult = await flushBatch(options.db, tableContexts, mutationUrls.batch, maxMutationAttempts, flushBatchSize, table, resolveAuthToken, options.requestHeaders, ensureRecoveryMarker, markSendingScope, disposeController.signal);
|
|
3156
3167
|
processedCount = batchResult.processedCount;
|
|
3157
3168
|
for (const context of batchResult.affectedContexts) {
|
|
3158
3169
|
affectedContexts.set(context.key, context);
|
|
@@ -3240,6 +3251,7 @@ function createMutationRuntime(options) {
|
|
|
3240
3251
|
});
|
|
3241
3252
|
await nextFlush;
|
|
3242
3253
|
},
|
|
3254
|
+
abortInFlight: () => disposeController.abort(),
|
|
3243
3255
|
flushUnit: async (unitId) => {
|
|
3244
3256
|
const contexts = Object.values(tableContexts).filter((context) => context != null);
|
|
3245
3257
|
const unitRows = await readUnitPendingRows(options.db, contexts, unitId);
|
|
@@ -3300,17 +3312,20 @@ function createMutationRuntime(options) {
|
|
|
3300
3312
|
const url = mutationUrls.authoritative;
|
|
3301
3313
|
let acksByMutationId;
|
|
3302
3314
|
try {
|
|
3303
|
-
const authToken = await options.getAuthToken?.();
|
|
3315
|
+
const authToken = await untilAborted(Promise.resolve(options.getAuthToken?.()));
|
|
3304
3316
|
let response = await fetch(url, {
|
|
3305
3317
|
method: "POST",
|
|
3306
3318
|
headers: buildRequestHeaders(authToken, options.requestHeaders),
|
|
3307
|
-
body: jsonStringifyPayload({ writeUnit: unitId, mutations })
|
|
3319
|
+
body: jsonStringifyPayload({ writeUnit: unitId, mutations }),
|
|
3320
|
+
signal: disposeController.signal
|
|
3308
3321
|
});
|
|
3309
3322
|
if ([401, 403].includes(response.status) && options.getAuthToken) {
|
|
3323
|
+
const retryToken = await untilAborted(Promise.resolve(options.getAuthToken()));
|
|
3310
3324
|
response = await fetch(url, {
|
|
3311
3325
|
method: "POST",
|
|
3312
|
-
headers: buildRequestHeaders(
|
|
3313
|
-
body: jsonStringifyPayload({ writeUnit: unitId, mutations })
|
|
3326
|
+
headers: buildRequestHeaders(retryToken, options.requestHeaders),
|
|
3327
|
+
body: jsonStringifyPayload({ writeUnit: unitId, mutations }),
|
|
3328
|
+
signal: disposeController.signal
|
|
3314
3329
|
});
|
|
3315
3330
|
}
|
|
3316
3331
|
if (!response.ok) {
|
|
@@ -4000,7 +4015,18 @@ async function readUnitPendingRows(db, contexts, unitId) {
|
|
|
4000
4015
|
const result = await db.query(query.sql, query.params);
|
|
4001
4016
|
return result.rows;
|
|
4002
4017
|
}
|
|
4003
|
-
|
|
4018
|
+
function raceAbort(work, signal) {
|
|
4019
|
+
if (!signal)
|
|
4020
|
+
return work;
|
|
4021
|
+
if (signal.aborted)
|
|
4022
|
+
return Promise.reject(new DOMException("Mutation runtime disposed", "AbortError"));
|
|
4023
|
+
return new Promise((resolve, reject) => {
|
|
4024
|
+
const onAbort = () => reject(new DOMException("Mutation runtime disposed", "AbortError"));
|
|
4025
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
4026
|
+
work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
4027
|
+
});
|
|
4028
|
+
}
|
|
4029
|
+
async function flushBatch(db, tableContexts, batchMutationUrl, maxAttempts, batchSize, tableFilter, getAuthToken, requestHeaders, ensureRecoveryMarker, markSendingScope, signal) {
|
|
4004
4030
|
const contexts = filterContexts(tableContexts, tableFilter);
|
|
4005
4031
|
const nowUs = nowMicroseconds();
|
|
4006
4032
|
const quarantinedMutationIds = [];
|
|
@@ -4073,19 +4099,21 @@ async function flushBatch(db, tableContexts, batchMutationUrl, maxAttempts, batc
|
|
|
4073
4099
|
let acksByMutationId = new Map;
|
|
4074
4100
|
try {
|
|
4075
4101
|
const authStart = typeof performance !== "undefined" ? performance.now() : Date.now();
|
|
4076
|
-
const authToken = await getAuthToken?.();
|
|
4102
|
+
const authToken = await raceAbort(getAuthToken?.() ?? Promise.resolve(undefined), signal);
|
|
4077
4103
|
const fetchStart = typeof performance !== "undefined" ? performance.now() : Date.now();
|
|
4078
4104
|
syncDebug("board-write auth token resolved", { ms: Math.round(fetchStart - authStart) });
|
|
4079
4105
|
let response = await fetch(batchMutationUrl, {
|
|
4080
4106
|
method: "POST",
|
|
4081
4107
|
headers: buildRequestHeaders(authToken, requestHeaders),
|
|
4082
|
-
body: jsonStringifyPayload({ mutations })
|
|
4108
|
+
body: jsonStringifyPayload({ mutations }),
|
|
4109
|
+
signal: signal ?? null
|
|
4083
4110
|
});
|
|
4084
4111
|
if ([401, 403].includes(response.status) && getAuthToken) {
|
|
4085
4112
|
response = await fetch(batchMutationUrl, {
|
|
4086
4113
|
method: "POST",
|
|
4087
|
-
headers: buildRequestHeaders(await getAuthToken(), requestHeaders),
|
|
4088
|
-
body: jsonStringifyPayload({ mutations })
|
|
4114
|
+
headers: buildRequestHeaders(await raceAbort(getAuthToken(), signal), requestHeaders),
|
|
4115
|
+
body: jsonStringifyPayload({ mutations }),
|
|
4116
|
+
signal: signal ?? null
|
|
4089
4117
|
});
|
|
4090
4118
|
}
|
|
4091
4119
|
const fetchEnd = typeof performance !== "undefined" ? performance.now() : Date.now();
|
|
@@ -7310,7 +7338,14 @@ function createWorkerTokenCache(options) {
|
|
|
7310
7338
|
|
|
7311
7339
|
// packages/client/src/worker/define-sync-worker.ts
|
|
7312
7340
|
import { types as types2 } from "@electric-sql/pglite";
|
|
7313
|
-
import {
|
|
7341
|
+
import {
|
|
7342
|
+
assertStorageDeclarationCompatible,
|
|
7343
|
+
getSyncRegistryStorage,
|
|
7344
|
+
isStorageBackend,
|
|
7345
|
+
isStorageDurability,
|
|
7346
|
+
resolveStorageDeclaration,
|
|
7347
|
+
StorageDeclarationRefusedError
|
|
7348
|
+
} from "@pgxsinkit/contracts";
|
|
7314
7349
|
function defineSyncWorker(options) {
|
|
7315
7350
|
validateLiveQueryPolicy(options.liveQueries);
|
|
7316
7351
|
const codec = options.codec ?? identityCodec;
|
|
@@ -7323,10 +7358,18 @@ function defineSyncWorker(options) {
|
|
|
7323
7358
|
const placementGate = new Promise((resolve) => {
|
|
7324
7359
|
openPlacementGate = resolve;
|
|
7325
7360
|
});
|
|
7326
|
-
|
|
7361
|
+
let engineStorage;
|
|
7362
|
+
const bindEngineStorage = (wire) => {
|
|
7363
|
+
if (engineStorage === undefined) {
|
|
7364
|
+
engineStorage = resolveStorageDeclaration(getSyncRegistryStorage(options.registry), wire);
|
|
7365
|
+
} else {
|
|
7366
|
+
assertStorageDeclarationCompatible(engineStorage, wire);
|
|
7367
|
+
}
|
|
7368
|
+
};
|
|
7369
|
+
const currentDurability = () => engineStorage?.durability ?? getSyncRegistryStorage(options.registry)?.durability ?? "relaxed";
|
|
7327
7370
|
const createPglite = options.createPglite ?? ((storePath, backendOverride) => createClientPGlite(storePath, {
|
|
7328
7371
|
...backendOverride ? { backendOverride } : {},
|
|
7329
|
-
durability:
|
|
7372
|
+
durability: currentDurability(),
|
|
7330
7373
|
...placementOpfsAccess ? { hasOpfsSyncAccess: true } : {}
|
|
7331
7374
|
}));
|
|
7332
7375
|
const workerTestMarker = readTestStoreMarker(options);
|
|
@@ -7463,6 +7506,9 @@ function defineSyncWorker(options) {
|
|
|
7463
7506
|
tokenCache.push(attach.token);
|
|
7464
7507
|
bootedRole = attach.config?.role;
|
|
7465
7508
|
const registry = options.resolveRegistry?.(attach.config?.role) ?? options.registry;
|
|
7509
|
+
if (registry !== options.registry) {
|
|
7510
|
+
assertStorageDeclarationCompatible(engineStorage ?? resolveStorageDeclaration(getSyncRegistryStorage(options.registry), undefined), getSyncRegistryStorage(registry) ?? {});
|
|
7511
|
+
}
|
|
7466
7512
|
const storePath = attach.storePath ?? attach.storeId ?? options.storePath ?? "pgxsinkit-overlay-v1";
|
|
7467
7513
|
const backendOverride = attach.testStoreBackend;
|
|
7468
7514
|
const testMarker = backendOverride === "memory" ? "memory" : workerTestMarker;
|
|
@@ -7490,6 +7536,7 @@ function defineSyncWorker(options) {
|
|
|
7490
7536
|
...options.pgliteInstance && restoreFrom == null ? { pgliteInstance: options.pgliteInstance } : {},
|
|
7491
7537
|
...options.prepareLocalDbBeforeSchema ? { prepareLocalDbBeforeSchema: options.prepareLocalDbBeforeSchema } : {},
|
|
7492
7538
|
...options.prepareLocalDbAfterSchema ? { prepareLocalDbAfterSchema: options.prepareLocalDbAfterSchema } : {},
|
|
7539
|
+
...engineStorage ? { storage: engineStorage } : {},
|
|
7493
7540
|
...placementOpfsAccess ? { hasOpfsSyncAccess: true } : {},
|
|
7494
7541
|
...placementFallbackReason ? { storageFallbackReason: placementFallbackReason } : {},
|
|
7495
7542
|
...options.adoption ? { adoption: options.adoption } : {},
|
|
@@ -7673,6 +7720,16 @@ function defineSyncWorker(options) {
|
|
|
7673
7720
|
const provision = payload;
|
|
7674
7721
|
const storePath = provision.storePath ?? provision.storeId ?? options.storePath ?? "pgxsinkit-overlay-v1";
|
|
7675
7722
|
const backendOverride = provision.testStoreBackend;
|
|
7723
|
+
try {
|
|
7724
|
+
bindEngineStorage(provision.storage);
|
|
7725
|
+
} catch (error) {
|
|
7726
|
+
postBridgeMessage(port, codec, "provision-ack", {
|
|
7727
|
+
ok: false,
|
|
7728
|
+
error: serializeError(error),
|
|
7729
|
+
...provision.storeId ? { storeId: provision.storeId } : {}
|
|
7730
|
+
});
|
|
7731
|
+
break;
|
|
7732
|
+
}
|
|
7676
7733
|
if (bootPromise != null || provisioned != null || provisionAttempt != null) {
|
|
7677
7734
|
postBridgeMessage(port, codec, "provision-ack", {
|
|
7678
7735
|
ok: true,
|
|
@@ -7736,10 +7793,17 @@ function defineSyncWorker(options) {
|
|
|
7736
7793
|
const attach = payload;
|
|
7737
7794
|
replayRailBufferTo(port);
|
|
7738
7795
|
const alreadyBooted = bootPromise !== null;
|
|
7796
|
+
try {
|
|
7797
|
+
bindEngineStorage(attach.storage);
|
|
7798
|
+
} catch (error) {
|
|
7799
|
+
postBridgeMessage(port, codec, "attach-ack", { alreadyBooted, error: serializeError(error) });
|
|
7800
|
+
break;
|
|
7801
|
+
}
|
|
7739
7802
|
if (alreadyBooted && attach.restore != null) {
|
|
7740
7803
|
postBridgeMessage(port, codec, "attach-ack", {
|
|
7741
7804
|
alreadyBooted,
|
|
7742
7805
|
error: {
|
|
7806
|
+
name: "RestoreIntoRunningStoreError",
|
|
7743
7807
|
message: "[pgxsinkit] cannot restore into a running store: the worker engine has already booted, and a store backup can only seed a brand-new store on the FIRST attach (ADR-0035 decision 6). Restore into a fresh worker instead."
|
|
7744
7808
|
}
|
|
7745
7809
|
});
|
|
@@ -7855,9 +7919,22 @@ function defineSyncWorker(options) {
|
|
|
7855
7919
|
pending.cancelled = true;
|
|
7856
7920
|
}
|
|
7857
7921
|
};
|
|
7858
|
-
const
|
|
7922
|
+
const hostInstanceId = crypto.randomUUID();
|
|
7923
|
+
const connect = (port, connection) => {
|
|
7859
7924
|
ports.add(port);
|
|
7860
7925
|
const listener = (event) => {
|
|
7926
|
+
if (isPlacementQuery(event.data)) {
|
|
7927
|
+
if (connection?.placementQueriesHandled !== true) {
|
|
7928
|
+
port.postMessage({
|
|
7929
|
+
[PLACEMENT_RESULT_KEY]: {
|
|
7930
|
+
engineHome: "shared-worker",
|
|
7931
|
+
electionRequired: false,
|
|
7932
|
+
swInstanceId: hostInstanceId
|
|
7933
|
+
}
|
|
7934
|
+
});
|
|
7935
|
+
}
|
|
7936
|
+
return;
|
|
7937
|
+
}
|
|
7861
7938
|
if (isBridgeEnvelope(event.data) && event.data.type === "detach") {
|
|
7862
7939
|
detachPort(port);
|
|
7863
7940
|
port.removeEventListener("message", listener);
|
|
@@ -7869,18 +7946,47 @@ function defineSyncWorker(options) {
|
|
|
7869
7946
|
port.start?.();
|
|
7870
7947
|
};
|
|
7871
7948
|
const closeHost = async () => {
|
|
7872
|
-
|
|
7873
|
-
|
|
7874
|
-
|
|
7875
|
-
|
|
7876
|
-
|
|
7877
|
-
|
|
7878
|
-
|
|
7879
|
-
|
|
7880
|
-
|
|
7881
|
-
|
|
7882
|
-
|
|
7883
|
-
|
|
7949
|
+
const closeStartedAt = nowStamp();
|
|
7950
|
+
const retirementPhase = (phase, data) => syncDebug("worker retirement phase", {
|
|
7951
|
+
phase,
|
|
7952
|
+
workerElapsedMs: Math.max(0, nowStamp() - closeStartedAt),
|
|
7953
|
+
...data ?? {}
|
|
7954
|
+
});
|
|
7955
|
+
retirementPhase("host-close-started", {
|
|
7956
|
+
pendingSubscribes: inFlightSubscribes.size,
|
|
7957
|
+
liveSubscriptions: liveSubs.size,
|
|
7958
|
+
hasBoot: bootPromise !== null,
|
|
7959
|
+
hasProvisionedStore: provisioned !== null
|
|
7960
|
+
});
|
|
7961
|
+
try {
|
|
7962
|
+
const active = client ?? (bootPromise ? await bootPromise.catch(() => null) : null);
|
|
7963
|
+
active?.haltActivity();
|
|
7964
|
+
retirementPhase("activity-halted", { activeClient: active !== null });
|
|
7965
|
+
closing = true;
|
|
7966
|
+
for (const pending of pendingSubscribes.values())
|
|
7967
|
+
pending.cancelled = true;
|
|
7968
|
+
retirementPhase("pending-subscriptions-wait-started", { count: inFlightSubscribes.size });
|
|
7969
|
+
await Promise.allSettled([...inFlightSubscribes]);
|
|
7970
|
+
retirementPhase("pending-subscriptions-wait-completed");
|
|
7971
|
+
liveSubs.clear();
|
|
7972
|
+
retirementPhase("live-query-disposal-started");
|
|
7973
|
+
await liveManager?.dispose();
|
|
7974
|
+
retirementPhase("live-query-disposal-completed");
|
|
7975
|
+
retirementPhase("active-client-stop-started", { activeClient: active !== null });
|
|
7976
|
+
await active?.stop();
|
|
7977
|
+
retirementPhase("active-client-stop-completed");
|
|
7978
|
+
retirementPhase("host-close-completed");
|
|
7979
|
+
} catch (error) {
|
|
7980
|
+
retirementPhase("host-close-failed", {
|
|
7981
|
+
message: error instanceof Error ? error.message : String(error)
|
|
7982
|
+
});
|
|
7983
|
+
throw error;
|
|
7984
|
+
} finally {
|
|
7985
|
+
ports.clear();
|
|
7986
|
+
setSyncDebugSink(undefined);
|
|
7987
|
+
}
|
|
7988
|
+
};
|
|
7989
|
+
const staticStorage = getSyncRegistryStorage(options.registry);
|
|
7884
7990
|
if (options.installGlobal === false) {
|
|
7885
7991
|
openPlacementGate();
|
|
7886
7992
|
} else {
|
|
@@ -7888,7 +7994,7 @@ function defineSyncWorker(options) {
|
|
|
7888
7994
|
connect,
|
|
7889
7995
|
closeHost,
|
|
7890
7996
|
peerCount: () => ports.size,
|
|
7891
|
-
|
|
7997
|
+
...staticStorage ? { staticStorage } : {},
|
|
7892
7998
|
...options.executionLimit ? { executionLimit: options.executionLimit } : {},
|
|
7893
7999
|
onPlacement: (outcome) => {
|
|
7894
8000
|
placementOpfsAccess = outcome.opfsGranted;
|
|
@@ -7910,7 +8016,11 @@ function serializeError(error) {
|
|
|
7910
8016
|
}
|
|
7911
8017
|
if (error instanceof Error) {
|
|
7912
8018
|
const detail = error.detail;
|
|
7913
|
-
return {
|
|
8019
|
+
return {
|
|
8020
|
+
message: error.message,
|
|
8021
|
+
...error.name && error.name !== "Error" ? { name: error.name } : {},
|
|
8022
|
+
...detail !== undefined ? { detail } : {}
|
|
8023
|
+
};
|
|
7914
8024
|
}
|
|
7915
8025
|
return { message: String(error) };
|
|
7916
8026
|
}
|
|
@@ -8003,18 +8113,28 @@ function isPlacementQuery(data) {
|
|
|
8003
8113
|
function isDestroyQuery(data) {
|
|
8004
8114
|
return typeof data === "object" && data !== null && data[DESTROY_QUERY_KEY] === true;
|
|
8005
8115
|
}
|
|
8116
|
+
function readDeclarationMessage(data) {
|
|
8117
|
+
if (typeof data !== "object" || data === null)
|
|
8118
|
+
return;
|
|
8119
|
+
const raw = data[DECLARATION_KEY];
|
|
8120
|
+
if (typeof raw !== "object" || raw === null)
|
|
8121
|
+
return;
|
|
8122
|
+
return raw;
|
|
8123
|
+
}
|
|
8124
|
+
function invalidDeclarationField(declaration) {
|
|
8125
|
+
if (declaration.backend !== undefined && !isStorageBackend(declaration.backend)) {
|
|
8126
|
+
return `backend "${String(declaration.backend)}"`;
|
|
8127
|
+
}
|
|
8128
|
+
if (declaration.durability !== undefined && !isStorageDurability(declaration.durability)) {
|
|
8129
|
+
return `durability "${String(declaration.durability)}"`;
|
|
8130
|
+
}
|
|
8131
|
+
return;
|
|
8132
|
+
}
|
|
8006
8133
|
function bootstrapWorkerScope(deps) {
|
|
8007
8134
|
const globalScope = deps.globalScope ?? globalThis;
|
|
8008
8135
|
const hasSharedWorkerScope = typeof globalScope.SharedWorkerGlobalScope !== "undefined";
|
|
8009
8136
|
if (hasSharedWorkerScope) {
|
|
8010
|
-
|
|
8011
|
-
wireSharedWorkerPlacement({
|
|
8012
|
-
...deps,
|
|
8013
|
-
decidePlacement: () => Promise.resolve({ engineHome: "shared-worker", swInstanceId: crypto.randomUUID() })
|
|
8014
|
-
}, globalScope, false);
|
|
8015
|
-
} else {
|
|
8016
|
-
wireSharedWorkerPlacement(deps, globalScope, true);
|
|
8017
|
-
}
|
|
8137
|
+
wireSharedWorkerPlacement(deps, globalScope);
|
|
8018
8138
|
return;
|
|
8019
8139
|
}
|
|
8020
8140
|
const hasDedicatedWorkerScope = typeof globalScope.DedicatedWorkerGlobalScope !== "undefined";
|
|
@@ -8035,43 +8155,113 @@ function bootstrapWorkerScope(deps) {
|
|
|
8035
8155
|
bindGlobalScope(deps.connect, globalScope);
|
|
8036
8156
|
deps.onPlacement?.({ engineHome: undefined, opfsGranted: false });
|
|
8037
8157
|
}
|
|
8038
|
-
function wireSharedWorkerPlacement(deps, globalScope
|
|
8158
|
+
function wireSharedWorkerPlacement(deps, globalScope) {
|
|
8039
8159
|
const scope = globalScope;
|
|
8040
8160
|
const decide = deps.decidePlacement ?? (() => decideSwPlacement());
|
|
8041
8161
|
const swScriptUrl = globalScope.location?.href;
|
|
8042
8162
|
let placement;
|
|
8043
8163
|
let router;
|
|
8044
|
-
|
|
8164
|
+
let opfsGrantedForSharedHome = false;
|
|
8165
|
+
let boundDeclaration;
|
|
8166
|
+
let decisionStarted = false;
|
|
8167
|
+
const portStates = new Map;
|
|
8045
8168
|
let sharedHostTeardown;
|
|
8046
8169
|
const currentPeerCount = () => placement?.engineHome === "elected-worker" ? router?.tabCount() ?? 0 : deps.peerCount();
|
|
8047
|
-
const
|
|
8048
|
-
const
|
|
8170
|
+
const refuseDeclaration = (port, error) => {
|
|
8171
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
8172
|
+
port.postMessage({
|
|
8173
|
+
[DECLARATION_REFUSED_KEY]: { message, name: "StorageDeclarationRefusedError" }
|
|
8174
|
+
});
|
|
8175
|
+
};
|
|
8176
|
+
const answerPlacementQuery = (port) => {
|
|
8177
|
+
const live = placement;
|
|
8178
|
+
port.postMessage({
|
|
8179
|
+
[PLACEMENT_RESULT_KEY]: {
|
|
8180
|
+
engineHome: live.engineHome,
|
|
8181
|
+
electionRequired: live.engineHome === "elected-worker",
|
|
8182
|
+
swInstanceId: live.swInstanceId,
|
|
8183
|
+
...swScriptUrl !== undefined ? { swScriptUrl } : {}
|
|
8184
|
+
}
|
|
8185
|
+
});
|
|
8186
|
+
};
|
|
8187
|
+
const redeliver = (port, entry) => {
|
|
8188
|
+
const target = port;
|
|
8189
|
+
if (typeof target.dispatchEvent !== "function" || typeof MessageEvent === "undefined")
|
|
8190
|
+
return;
|
|
8191
|
+
target.dispatchEvent(new MessageEvent("message", {
|
|
8192
|
+
data: entry.data,
|
|
8193
|
+
...entry.ports ? { ports: entry.ports } : {}
|
|
8194
|
+
}));
|
|
8195
|
+
};
|
|
8196
|
+
const routePort = (port, state) => {
|
|
8197
|
+
if (state.routed)
|
|
8198
|
+
return;
|
|
8199
|
+
state.routed = true;
|
|
8200
|
+
if (placement.engineHome === "shared-worker") {
|
|
8201
|
+
deps.connect(port, { placementQueriesHandled: true });
|
|
8202
|
+
} else {
|
|
8203
|
+
router.attachTab(port);
|
|
8204
|
+
}
|
|
8205
|
+
};
|
|
8206
|
+
const handleDeclaration = (port, state, wire) => {
|
|
8207
|
+
const invalid = invalidDeclarationField(wire);
|
|
8208
|
+
if (invalid !== undefined) {
|
|
8209
|
+
refuseDeclaration(port, new StorageDeclarationRefusedError(`storage declaration carries an unknown ${invalid}`));
|
|
8210
|
+
return;
|
|
8211
|
+
}
|
|
8212
|
+
if (boundDeclaration === undefined) {
|
|
8213
|
+
boundDeclaration = resolveStorageDeclaration(deps.staticStorage, wire);
|
|
8214
|
+
state.declared = true;
|
|
8215
|
+
startDecision(boundDeclaration.backend);
|
|
8216
|
+
} else {
|
|
8217
|
+
try {
|
|
8218
|
+
assertStorageDeclarationCompatible(boundDeclaration, wire);
|
|
8219
|
+
} catch (error) {
|
|
8220
|
+
refuseDeclaration(port, error);
|
|
8221
|
+
return;
|
|
8222
|
+
}
|
|
8223
|
+
state.declared = true;
|
|
8224
|
+
}
|
|
8225
|
+
if (placement !== undefined)
|
|
8226
|
+
routePort(port, state);
|
|
8227
|
+
};
|
|
8228
|
+
const installPortListener = (port, state) => {
|
|
8049
8229
|
const metaListener = (event) => {
|
|
8050
8230
|
const data = event.data;
|
|
8051
|
-
|
|
8052
|
-
|
|
8053
|
-
port
|
|
8054
|
-
[PLACEMENT_RESULT_KEY]: {
|
|
8055
|
-
engineHome: live.engineHome,
|
|
8056
|
-
electionRequired: live.engineHome === "elected-worker",
|
|
8057
|
-
swInstanceId: live.swInstanceId,
|
|
8058
|
-
...swScriptUrl !== undefined ? { swScriptUrl } : {}
|
|
8059
|
-
}
|
|
8060
|
-
});
|
|
8231
|
+
const declaration = readDeclarationMessage(data);
|
|
8232
|
+
if (declaration !== undefined) {
|
|
8233
|
+
handleDeclaration(port, state, declaration);
|
|
8061
8234
|
return;
|
|
8062
8235
|
}
|
|
8063
|
-
if (isDestroyQuery(data)) {
|
|
8064
|
-
|
|
8236
|
+
if (isPlacementQuery(data) || isDestroyQuery(data)) {
|
|
8237
|
+
if (placement === undefined) {
|
|
8238
|
+
state.queuedQueries.push(data);
|
|
8239
|
+
return;
|
|
8240
|
+
}
|
|
8241
|
+
if (isPlacementQuery(data))
|
|
8242
|
+
answerPlacementQuery(port);
|
|
8243
|
+
else
|
|
8244
|
+
port.postMessage({ [DESTROY_VERDICT_KEY]: { peers: currentPeerCount() } });
|
|
8245
|
+
return;
|
|
8246
|
+
}
|
|
8247
|
+
if (!state.declared && isBridgeEnvelope(data)) {
|
|
8248
|
+
refuseDeclaration(port, new StorageDeclarationRefusedError("engine-bound message received before the port's storage declaration \u2014 the declaration message " + "must precede provision/attach on every worker port (ADR-0050)"));
|
|
8249
|
+
return;
|
|
8250
|
+
}
|
|
8251
|
+
if (placement === undefined) {
|
|
8252
|
+
if (state.declared && (isBridgeEnvelope(data) || readControlEnvelope(data) !== undefined)) {
|
|
8253
|
+
state.queuedTraffic.push({ data, ...event.ports?.length ? { ports: event.ports } : {} });
|
|
8254
|
+
}
|
|
8065
8255
|
return;
|
|
8066
8256
|
}
|
|
8067
8257
|
const control = readControlEnvelope(data);
|
|
8068
|
-
if (
|
|
8258
|
+
if (placement.engineHome === "shared-worker") {
|
|
8069
8259
|
if (control?.type === "control-ping") {
|
|
8070
8260
|
port.postMessage(wrapControlEnvelope({ type: "control-ack", identity: control.identity, pingId: control.pingId }));
|
|
8071
8261
|
return;
|
|
8072
8262
|
}
|
|
8073
8263
|
if (control?.type === "engine-teardown") {
|
|
8074
|
-
const sharedIdentity = { swInstanceId:
|
|
8264
|
+
const sharedIdentity = { swInstanceId: placement.swInstanceId, generation: 0 };
|
|
8075
8265
|
if (!shouldApplyControlMessage(sharedIdentity, control))
|
|
8076
8266
|
return;
|
|
8077
8267
|
sharedHostTeardown ??= Promise.resolve().then(() => deps.closeHost?.()).then(() => ({}), (error) => ({ error: serializeError(error) }));
|
|
@@ -8103,11 +8293,6 @@ function wireSharedWorkerPlacement(deps, globalScope, opfsGrantedForSharedHome)
|
|
|
8103
8293
|
};
|
|
8104
8294
|
port.addEventListener("message", metaListener);
|
|
8105
8295
|
port.start?.();
|
|
8106
|
-
if (current.engineHome === "shared-worker") {
|
|
8107
|
-
deps.connect(port);
|
|
8108
|
-
} else {
|
|
8109
|
-
router.attachTab(port);
|
|
8110
|
-
}
|
|
8111
8296
|
};
|
|
8112
8297
|
let fellBack = false;
|
|
8113
8298
|
const fallBackToIdbfs = (reason, reportingPort) => {
|
|
@@ -8116,37 +8301,63 @@ function wireSharedWorkerPlacement(deps, globalScope, opfsGrantedForSharedHome)
|
|
|
8116
8301
|
fellBack = true;
|
|
8117
8302
|
placement = { engineHome: "shared-worker", swInstanceId: placement?.swInstanceId ?? crypto.randomUUID() };
|
|
8118
8303
|
deps.onPlacement?.({ engineHome: "shared-worker", opfsGranted: false, storageFallbackReason: reason });
|
|
8119
|
-
deps.connect(reportingPort);
|
|
8120
|
-
};
|
|
8121
|
-
|
|
8122
|
-
|
|
8123
|
-
|
|
8124
|
-
|
|
8125
|
-
|
|
8126
|
-
|
|
8127
|
-
|
|
8128
|
-
}
|
|
8129
|
-
|
|
8130
|
-
|
|
8131
|
-
|
|
8132
|
-
|
|
8304
|
+
deps.connect(reportingPort, { placementQueriesHandled: true });
|
|
8305
|
+
};
|
|
8306
|
+
function startDecision(backend) {
|
|
8307
|
+
if (decisionStarted)
|
|
8308
|
+
return;
|
|
8309
|
+
decisionStarted = true;
|
|
8310
|
+
let decision;
|
|
8311
|
+
if (backend === "idbfs") {
|
|
8312
|
+
decision = Promise.resolve({ engineHome: "shared-worker", swInstanceId: crypto.randomUUID() });
|
|
8313
|
+
} else {
|
|
8314
|
+
opfsGrantedForSharedHome = true;
|
|
8315
|
+
decision = decide();
|
|
8316
|
+
}
|
|
8317
|
+
decision.then((result) => {
|
|
8318
|
+
placement = result;
|
|
8319
|
+
const isSharedFallback = result.engineHome === "shared-worker" && result.storageFallbackReason !== undefined;
|
|
8320
|
+
deps.onPlacement?.({
|
|
8321
|
+
engineHome: result.engineHome,
|
|
8322
|
+
opfsGranted: result.engineHome === "shared-worker" && opfsGrantedForSharedHome && !isSharedFallback,
|
|
8323
|
+
...isSharedFallback ? { storageFallbackReason: result.storageFallbackReason } : {}
|
|
8133
8324
|
});
|
|
8134
|
-
|
|
8135
|
-
|
|
8136
|
-
|
|
8137
|
-
|
|
8138
|
-
|
|
8325
|
+
if (result.engineHome === "elected-worker") {
|
|
8326
|
+
router = createEngineRouter({
|
|
8327
|
+
swInstanceId: result.swInstanceId,
|
|
8328
|
+
...deps.executionLimit ? { executionLimit: deps.executionLimit } : {}
|
|
8329
|
+
});
|
|
8330
|
+
}
|
|
8331
|
+
for (const [port, state] of portStates) {
|
|
8332
|
+
if (state.declared)
|
|
8333
|
+
routePort(port, state);
|
|
8334
|
+
for (const queued of state.queuedQueries) {
|
|
8335
|
+
if (isPlacementQuery(queued))
|
|
8336
|
+
answerPlacementQuery(port);
|
|
8337
|
+
else
|
|
8338
|
+
port.postMessage({ [DESTROY_VERDICT_KEY]: { peers: currentPeerCount() } });
|
|
8339
|
+
}
|
|
8340
|
+
state.queuedQueries.length = 0;
|
|
8341
|
+
const traffic = state.queuedTraffic.splice(0);
|
|
8342
|
+
for (const entry of traffic)
|
|
8343
|
+
redeliver(port, entry);
|
|
8344
|
+
}
|
|
8345
|
+
});
|
|
8346
|
+
}
|
|
8347
|
+
if (deps.staticStorage !== undefined) {
|
|
8348
|
+
boundDeclaration = resolveStorageDeclaration(deps.staticStorage, undefined);
|
|
8349
|
+
startDecision(boundDeclaration.backend);
|
|
8350
|
+
}
|
|
8139
8351
|
scope.onconnect = (event) => {
|
|
8140
8352
|
const port = event.ports[0];
|
|
8141
8353
|
if (!port)
|
|
8142
8354
|
return;
|
|
8143
|
-
|
|
8144
|
-
|
|
8145
|
-
|
|
8146
|
-
attachPort(port);
|
|
8355
|
+
const state = { declared: false, routed: false, queuedQueries: [], queuedTraffic: [] };
|
|
8356
|
+
portStates.set(port, state);
|
|
8357
|
+
installPortListener(port, state);
|
|
8147
8358
|
};
|
|
8148
8359
|
}
|
|
8149
|
-
var identityParser = (value) => value, DRIZZLE_PGLITE_IDENTITY_PARSERS, CONTROL_PORT_DELIVERY_KEY = "pgx0049ControlPort", PLACEMENT_QUERY_KEY = "pgx0049Placement", PLACEMENT_RESULT_KEY = "pgx0049PlacementResult", DESTROY_QUERY_KEY = "pgx0049DestroyQuery", DESTROY_VERDICT_KEY = "pgx0049DestroyVerdict";
|
|
8360
|
+
var identityParser = (value) => value, DRIZZLE_PGLITE_IDENTITY_PARSERS, CONTROL_PORT_DELIVERY_KEY = "pgx0049ControlPort", PLACEMENT_QUERY_KEY = "pgx0049Placement", PLACEMENT_RESULT_KEY = "pgx0049PlacementResult", DESTROY_QUERY_KEY = "pgx0049DestroyQuery", DESTROY_VERDICT_KEY = "pgx0049DestroyVerdict", DECLARATION_KEY = "pgx0050Declaration", DECLARATION_REFUSED_KEY = "pgx0050DeclarationRefused";
|
|
8150
8361
|
var init_define_sync_worker = __esm(() => {
|
|
8151
8362
|
init_convergence();
|
|
8152
8363
|
init_src();
|
|
@@ -8446,14 +8657,16 @@ var exports_attach_sync_client = {};
|
|
|
8446
8657
|
__export(exports_attach_sync_client, {
|
|
8447
8658
|
wrapEngineWorker: () => wrapEngineWorker,
|
|
8448
8659
|
runStoreDestruction: () => runStoreDestruction,
|
|
8449
|
-
retireSyncWorkerHost: () => retireSyncWorkerHost,
|
|
8450
8660
|
resolvedOwnershipRelease: () => resolvedOwnershipRelease,
|
|
8661
|
+
quiesceStoreWorker: () => quiesceStoreWorker,
|
|
8451
8662
|
provisionSyncWorker: () => provisionSyncWorker,
|
|
8663
|
+
destroyStoreArtifacts: () => destroyStoreArtifacts,
|
|
8452
8664
|
createStoreDestructionEffects: () => createStoreDestructionEffects,
|
|
8453
8665
|
attachSyncClient: () => attachSyncClient,
|
|
8454
8666
|
StoreDestroyRefusedError: () => StoreDestroyRefusedError,
|
|
8455
8667
|
ElectedEngineUnconstructibleError: () => ElectedEngineUnconstructibleError
|
|
8456
8668
|
});
|
|
8669
|
+
import { StorageDeclarationRefusedError as StorageDeclarationRefusedError2 } from "@pgxsinkit/contracts";
|
|
8457
8670
|
function resolvedOwnershipRelease() {
|
|
8458
8671
|
return Promise.resolve();
|
|
8459
8672
|
}
|
|
@@ -8527,6 +8740,59 @@ function createStoreDestructionEffects(storePath, deps) {
|
|
|
8527
8740
|
deleteMetaRecord: () => deleteStoreMetaRecord(storePath, meta)
|
|
8528
8741
|
};
|
|
8529
8742
|
}
|
|
8743
|
+
function destroyStoreArtifacts(storePath, opts) {
|
|
8744
|
+
return runStoreDestruction(createStoreDestructionEffects(storePath), opts);
|
|
8745
|
+
}
|
|
8746
|
+
function quiesceStoreWorker(worker, opts) {
|
|
8747
|
+
const timers = opts?.timers ?? {
|
|
8748
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
8749
|
+
clearTimeout: (handle) => clearTimeout(handle)
|
|
8750
|
+
};
|
|
8751
|
+
const timeoutMs = opts?.timeoutMs ?? 6000;
|
|
8752
|
+
const port = resolvePort({ worker });
|
|
8753
|
+
return new Promise((resolve, reject) => {
|
|
8754
|
+
let settled = false;
|
|
8755
|
+
let teardownIdentity;
|
|
8756
|
+
const finish = (run) => {
|
|
8757
|
+
if (settled)
|
|
8758
|
+
return;
|
|
8759
|
+
settled = true;
|
|
8760
|
+
timers.clearTimeout(timeout);
|
|
8761
|
+
port.removeEventListener("message", listener);
|
|
8762
|
+
run();
|
|
8763
|
+
};
|
|
8764
|
+
const timeout = timers.setTimeout(() => finish(() => reject(new Error(`[pgxsinkit] quiesceStoreWorker timed out after ${timeoutMs}ms`))), timeoutMs);
|
|
8765
|
+
const listener = (event) => {
|
|
8766
|
+
const placement = readPlacementResult(event.data);
|
|
8767
|
+
if (placement !== undefined) {
|
|
8768
|
+
if (placement.engineHome !== "shared-worker") {
|
|
8769
|
+
finish(() => resolve({ engineHome: placement.engineHome, toreDown: false }));
|
|
8770
|
+
return;
|
|
8771
|
+
}
|
|
8772
|
+
teardownIdentity = { swInstanceId: placement.swInstanceId, generation: 0 };
|
|
8773
|
+
port.postMessage(wrapControlEnvelope({ type: "engine-teardown", identity: teardownIdentity }));
|
|
8774
|
+
return;
|
|
8775
|
+
}
|
|
8776
|
+
const refusal = readDeclarationRefusal(event.data);
|
|
8777
|
+
if (refusal !== undefined) {
|
|
8778
|
+
finish(() => reject(new StorageDeclarationRefusedError2(refusal.message)));
|
|
8779
|
+
return;
|
|
8780
|
+
}
|
|
8781
|
+
const control = readControlEnvelope(event.data);
|
|
8782
|
+
if (control?.type === "control-ack" && control.pingId === -1 && teardownIdentity !== undefined && control.identity?.swInstanceId === teardownIdentity.swInstanceId) {
|
|
8783
|
+
if (control.error) {
|
|
8784
|
+
finish(() => reject(new Error(`[pgxsinkit] store-worker teardown failed: ${control.error?.message}`)));
|
|
8785
|
+
} else {
|
|
8786
|
+
finish(() => resolve({ engineHome: "shared-worker", toreDown: true }));
|
|
8787
|
+
}
|
|
8788
|
+
}
|
|
8789
|
+
};
|
|
8790
|
+
port.addEventListener("message", listener);
|
|
8791
|
+
port.start?.();
|
|
8792
|
+
port.postMessage({ [DECLARATION_KEY]: opts?.storage ?? {} });
|
|
8793
|
+
port.postMessage({ [PLACEMENT_QUERY_KEY]: true });
|
|
8794
|
+
});
|
|
8795
|
+
}
|
|
8530
8796
|
function defaultIsOwnershipError(error) {
|
|
8531
8797
|
const name = error?.name;
|
|
8532
8798
|
if (name === "NoModificationAllowedError" || name === "InvalidStateError")
|
|
@@ -8576,6 +8842,15 @@ function readDestroyVerdict(data) {
|
|
|
8576
8842
|
const peers = verdict.peers;
|
|
8577
8843
|
return typeof peers === "number" ? peers : undefined;
|
|
8578
8844
|
}
|
|
8845
|
+
function readDeclarationRefusal(data) {
|
|
8846
|
+
if (typeof data !== "object" || data === null)
|
|
8847
|
+
return;
|
|
8848
|
+
const refusal = data[DECLARATION_REFUSED_KEY];
|
|
8849
|
+
if (typeof refusal !== "object" || refusal === null)
|
|
8850
|
+
return;
|
|
8851
|
+
const message = refusal.message;
|
|
8852
|
+
return typeof message === "string" ? refusal : undefined;
|
|
8853
|
+
}
|
|
8579
8854
|
function buildElectedCoordinator(params) {
|
|
8580
8855
|
const factory = params.createEngineWorker;
|
|
8581
8856
|
let pendingChannel;
|
|
@@ -8604,7 +8879,13 @@ function buildElectedCoordinator(params) {
|
|
|
8604
8879
|
return { port1: channel.port1, port2: channel.port2 };
|
|
8605
8880
|
},
|
|
8606
8881
|
swPort: params.controlPort,
|
|
8607
|
-
...params.swFactory ? {
|
|
8882
|
+
...params.swFactory ? {
|
|
8883
|
+
reconstructSw: () => {
|
|
8884
|
+
const port = resolvePort({ worker: params.swFactory });
|
|
8885
|
+
port.postMessage({ [DECLARATION_KEY]: params.storage ?? {} });
|
|
8886
|
+
return port;
|
|
8887
|
+
}
|
|
8888
|
+
} : {},
|
|
8608
8889
|
awaitOwnershipRelease: params.awaitOwnershipRelease ?? resolvedOwnershipRelease,
|
|
8609
8890
|
timers: params.timers,
|
|
8610
8891
|
...params.pageLifecycle ? { pageLifecycle: params.pageLifecycle } : {}
|
|
@@ -8654,6 +8935,11 @@ function takeProvisionPipe(storePath) {
|
|
|
8654
8935
|
delete entry.provisionPipe;
|
|
8655
8936
|
return stashed;
|
|
8656
8937
|
}
|
|
8938
|
+
function setProvisionRelease(storePath, release) {
|
|
8939
|
+
const entry = sharedCoordinators.get(storePath);
|
|
8940
|
+
if (entry !== undefined)
|
|
8941
|
+
entry.releaseProvision = release;
|
|
8942
|
+
}
|
|
8657
8943
|
async function attachSyncClient(options) {
|
|
8658
8944
|
const codec = options.codec ?? identityCodec;
|
|
8659
8945
|
const port = resolvePort(options);
|
|
@@ -8683,6 +8969,16 @@ async function attachSyncClient(options) {
|
|
|
8683
8969
|
let swTeardownIdentity;
|
|
8684
8970
|
let adoptedSharedCoordinatorStore;
|
|
8685
8971
|
let placementDecided = false;
|
|
8972
|
+
let resolvePlacementKnown;
|
|
8973
|
+
let rejectPlacementKnown;
|
|
8974
|
+
const placementKnown = new Promise((resolve, reject) => {
|
|
8975
|
+
resolvePlacementKnown = resolve;
|
|
8976
|
+
rejectPlacementKnown = reject;
|
|
8977
|
+
});
|
|
8978
|
+
placementKnown.catch(() => {
|
|
8979
|
+
return;
|
|
8980
|
+
});
|
|
8981
|
+
let restoreConsumed = false;
|
|
8686
8982
|
let firstAttachSettled = false;
|
|
8687
8983
|
let resolveFirstAttach;
|
|
8688
8984
|
let rejectFirstAttach;
|
|
@@ -8910,6 +9206,13 @@ async function attachSyncClient(options) {
|
|
|
8910
9206
|
onPlacementResult(placementResult2);
|
|
8911
9207
|
return;
|
|
8912
9208
|
}
|
|
9209
|
+
const declarationRefusal = readDeclarationRefusal(event.data);
|
|
9210
|
+
if (declarationRefusal !== undefined) {
|
|
9211
|
+
const refusal = new StorageDeclarationRefusedError2(declarationRefusal.message);
|
|
9212
|
+
rejectPlacementKnown?.(refusal);
|
|
9213
|
+
failFirstAttach(refusal);
|
|
9214
|
+
return;
|
|
9215
|
+
}
|
|
8913
9216
|
const destroyPeers = readDestroyVerdict(event.data);
|
|
8914
9217
|
if (destroyPeers !== undefined) {
|
|
8915
9218
|
destroyVerdictResolver?.(destroyPeers);
|
|
@@ -9023,7 +9326,7 @@ async function attachSyncClient(options) {
|
|
|
9023
9326
|
swapDataPort(pipe, replacing);
|
|
9024
9327
|
hasPipe = true;
|
|
9025
9328
|
try {
|
|
9026
|
-
await runAttachHandshake(pipe,
|
|
9329
|
+
await runAttachHandshake(pipe, true);
|
|
9027
9330
|
} catch {
|
|
9028
9331
|
return;
|
|
9029
9332
|
}
|
|
@@ -9069,6 +9372,7 @@ async function attachSyncClient(options) {
|
|
|
9069
9372
|
newPort.addEventListener("message", listener);
|
|
9070
9373
|
newPort.addEventListener("message", controlListener);
|
|
9071
9374
|
newPort.start?.();
|
|
9375
|
+
newPort.postMessage({ [DECLARATION_KEY]: options.storage ?? {} });
|
|
9072
9376
|
try {
|
|
9073
9377
|
await runAttachHandshake(newPort, false);
|
|
9074
9378
|
} catch {
|
|
@@ -9087,6 +9391,7 @@ async function attachSyncClient(options) {
|
|
|
9087
9391
|
return;
|
|
9088
9392
|
placementDecided = true;
|
|
9089
9393
|
placementResult = result;
|
|
9394
|
+
resolvePlacementKnown?.();
|
|
9090
9395
|
if (!result.electionRequired)
|
|
9091
9396
|
return;
|
|
9092
9397
|
electedEngineFactory = options.createEngineWorker ?? deriveEngineWorkerFactory(result.swScriptUrl);
|
|
@@ -9147,6 +9452,7 @@ async function attachSyncClient(options) {
|
|
|
9147
9452
|
controlPort,
|
|
9148
9453
|
createEngineWorker: electedEngineFactory,
|
|
9149
9454
|
...workerFactory ? { swFactory: workerFactory } : {},
|
|
9455
|
+
...options.storage ? { storage: options.storage } : {},
|
|
9150
9456
|
...options.electionIo ? { electionIo: options.electionIo } : {},
|
|
9151
9457
|
...options.awaitOwnershipRelease ? { awaitOwnershipRelease: options.awaitOwnershipRelease } : {},
|
|
9152
9458
|
timers,
|
|
@@ -9215,8 +9521,11 @@ async function attachSyncClient(options) {
|
|
|
9215
9521
|
};
|
|
9216
9522
|
let pendingAttachAck = null;
|
|
9217
9523
|
const runAttachHandshake = (target, includeRestore) => new Promise((resolve, reject) => {
|
|
9524
|
+
const carryRestore = includeRestore && restoreWire !== undefined && !restoreConsumed;
|
|
9525
|
+
if (carryRestore)
|
|
9526
|
+
restoreConsumed = true;
|
|
9218
9527
|
pendingAttachAck = { resolve, reject };
|
|
9219
|
-
postBridgeMessage(target, codec, "attach", buildAttachPayload(
|
|
9528
|
+
postBridgeMessage(target, codec, "attach", buildAttachPayload(carryRestore), undefined, carryRestore && restoreWire ? [restoreWire.buffer] : undefined);
|
|
9220
9529
|
});
|
|
9221
9530
|
let resolveLocalReadReady;
|
|
9222
9531
|
const localReadReady = new Promise((resolve) => {
|
|
@@ -9350,6 +9659,7 @@ async function attachSyncClient(options) {
|
|
|
9350
9659
|
token: initialToken,
|
|
9351
9660
|
...options.storeId ? { storeId: options.storeId } : {},
|
|
9352
9661
|
...options.storePath ? { storePath: options.storePath } : {},
|
|
9662
|
+
...options.storage ? { storage: options.storage } : {},
|
|
9353
9663
|
...memoryOverride ? { testStoreBackend: "memory" } : {},
|
|
9354
9664
|
...options.executionLimit ? { executionLimit: options.executionLimit } : {},
|
|
9355
9665
|
...includeRestore && restoreWire ? { restore: restoreWire } : {},
|
|
@@ -9362,10 +9672,20 @@ async function attachSyncClient(options) {
|
|
|
9362
9672
|
} : {}
|
|
9363
9673
|
};
|
|
9364
9674
|
}
|
|
9675
|
+
controlPort.postMessage({ [DECLARATION_KEY]: options.storage ?? {} });
|
|
9365
9676
|
controlPort.postMessage({ [PLACEMENT_QUERY_KEY]: true });
|
|
9366
|
-
|
|
9367
|
-
|
|
9368
|
-
})
|
|
9677
|
+
try {
|
|
9678
|
+
await placementKnown;
|
|
9679
|
+
} catch (error) {
|
|
9680
|
+
detachFromWorker();
|
|
9681
|
+
throw error;
|
|
9682
|
+
}
|
|
9683
|
+
const handshakePort = currentDataPort();
|
|
9684
|
+
if (placementResult?.electionRequired !== true || handshakePort === controlPort) {
|
|
9685
|
+
runAttachHandshake(handshakePort, placementResult?.electionRequired !== true).catch(() => {
|
|
9686
|
+
return;
|
|
9687
|
+
});
|
|
9688
|
+
}
|
|
9369
9689
|
try {
|
|
9370
9690
|
await firstAttachReady;
|
|
9371
9691
|
} catch (error) {
|
|
@@ -9484,6 +9804,9 @@ async function attachSyncClient(options) {
|
|
|
9484
9804
|
start: async () => {
|
|
9485
9805
|
await ready;
|
|
9486
9806
|
},
|
|
9807
|
+
haltActivity: () => {
|
|
9808
|
+
detachFromWorker();
|
|
9809
|
+
},
|
|
9487
9810
|
stop: async () => {
|
|
9488
9811
|
detachFromWorker();
|
|
9489
9812
|
},
|
|
@@ -9630,73 +9953,6 @@ async function attachSyncClient(options) {
|
|
|
9630
9953
|
});
|
|
9631
9954
|
return client;
|
|
9632
9955
|
}
|
|
9633
|
-
function retireSyncWorkerHost(options) {
|
|
9634
|
-
const port = resolvePort(options);
|
|
9635
|
-
const timers = options.timers ?? {
|
|
9636
|
-
setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
|
|
9637
|
-
clearTimeout: (handle) => globalThis.clearTimeout(handle)
|
|
9638
|
-
};
|
|
9639
|
-
return new Promise((resolve, reject) => {
|
|
9640
|
-
let identity;
|
|
9641
|
-
let settled = false;
|
|
9642
|
-
const finish = (result) => {
|
|
9643
|
-
if (settled)
|
|
9644
|
-
return;
|
|
9645
|
-
settled = true;
|
|
9646
|
-
timers.clearTimeout(timeout);
|
|
9647
|
-
port.removeEventListener("message", listener);
|
|
9648
|
-
if (result.ok)
|
|
9649
|
-
resolve();
|
|
9650
|
-
else
|
|
9651
|
-
reject(result.error);
|
|
9652
|
-
};
|
|
9653
|
-
const listener = (event) => {
|
|
9654
|
-
const placement = readPlacementResult(event.data);
|
|
9655
|
-
if (placement !== undefined) {
|
|
9656
|
-
if (placement.electionRequired) {
|
|
9657
|
-
finish({
|
|
9658
|
-
ok: false,
|
|
9659
|
-
error: new Error("[pgxsinkit] retireSyncWorkerHost only applies to a SW-direct host; elected placement retires " + "through its election coordinator.")
|
|
9660
|
-
});
|
|
9661
|
-
return;
|
|
9662
|
-
}
|
|
9663
|
-
identity = { swInstanceId: placement.swInstanceId, generation: 0 };
|
|
9664
|
-
port.postMessage({ [DESTROY_QUERY_KEY]: true });
|
|
9665
|
-
return;
|
|
9666
|
-
}
|
|
9667
|
-
const peers = readDestroyVerdict(event.data);
|
|
9668
|
-
if (peers !== undefined && identity !== undefined) {
|
|
9669
|
-
if (peers > 1) {
|
|
9670
|
-
finish({
|
|
9671
|
-
ok: false,
|
|
9672
|
-
error: new Error(`[pgxsinkit] SW-direct host retirement refused: ${peers} attached tabs still use this store. ` + "Close the peer tabs before changing the worker construction preference.")
|
|
9673
|
-
});
|
|
9674
|
-
return;
|
|
9675
|
-
}
|
|
9676
|
-
port.postMessage(wrapControlEnvelope({ type: "engine-teardown", identity }));
|
|
9677
|
-
return;
|
|
9678
|
-
}
|
|
9679
|
-
const control = readControlEnvelope(event.data);
|
|
9680
|
-
if (identity !== undefined && control?.type === "control-ack" && control.pingId === -1 && engineIdentityEquals(control.identity, identity)) {
|
|
9681
|
-
if (control.error) {
|
|
9682
|
-
finish({
|
|
9683
|
-
ok: false,
|
|
9684
|
-
error: new Error(`[pgxsinkit] SW-direct host teardown failed: ${control.error.message}`)
|
|
9685
|
-
});
|
|
9686
|
-
} else {
|
|
9687
|
-
finish({ ok: true });
|
|
9688
|
-
}
|
|
9689
|
-
}
|
|
9690
|
-
};
|
|
9691
|
-
const timeout = timers.setTimeout(() => finish({
|
|
9692
|
-
ok: false,
|
|
9693
|
-
error: new Error("[pgxsinkit] timed out while retiring the SW-direct sync host.")
|
|
9694
|
-
}), options.timeoutMs ?? 5000);
|
|
9695
|
-
port.addEventListener("message", listener);
|
|
9696
|
-
port.start?.();
|
|
9697
|
-
port.postMessage({ [PLACEMENT_QUERY_KEY]: true });
|
|
9698
|
-
});
|
|
9699
|
-
}
|
|
9700
9956
|
function provisionSyncWorker(options) {
|
|
9701
9957
|
const codec = options.codec ?? identityCodec;
|
|
9702
9958
|
const port = resolvePort(options);
|
|
@@ -9709,10 +9965,11 @@ function provisionSyncWorker(options) {
|
|
|
9709
9965
|
const provisionPayload = {
|
|
9710
9966
|
...options.storeId ? { storeId: options.storeId } : {},
|
|
9711
9967
|
...options.storePath ? { storePath: options.storePath } : {},
|
|
9968
|
+
...options.storage ? { storage: options.storage } : {},
|
|
9712
9969
|
...memoryOverride ? { testStoreBackend: "memory" } : {}
|
|
9713
9970
|
};
|
|
9714
9971
|
const pageLifecycle = readDefaultPageLifecycle();
|
|
9715
|
-
|
|
9972
|
+
const provision = new Promise((resolve, reject) => {
|
|
9716
9973
|
let settled = false;
|
|
9717
9974
|
const ackRemovers = [];
|
|
9718
9975
|
const controlListener = (event) => {
|
|
@@ -9721,6 +9978,11 @@ function provisionSyncWorker(options) {
|
|
|
9721
9978
|
onPlacement(placement);
|
|
9722
9979
|
return;
|
|
9723
9980
|
}
|
|
9981
|
+
const declarationRefusal = readDeclarationRefusal(event.data);
|
|
9982
|
+
if (declarationRefusal !== undefined) {
|
|
9983
|
+
settle(() => reject(new StorageDeclarationRefusedError2(declarationRefusal.message)));
|
|
9984
|
+
return;
|
|
9985
|
+
}
|
|
9724
9986
|
const control = readControlEnvelope(event.data);
|
|
9725
9987
|
if (control?.type === "connect-port")
|
|
9726
9988
|
onProvisionPipe(event.ports?.[0], control.identity);
|
|
@@ -9762,8 +10024,10 @@ function provisionSyncWorker(options) {
|
|
|
9762
10024
|
if (placementDecided)
|
|
9763
10025
|
return;
|
|
9764
10026
|
placementDecided = true;
|
|
9765
|
-
if (!result.electionRequired)
|
|
10027
|
+
if (!result.electionRequired) {
|
|
10028
|
+
postProvisionOn(port);
|
|
9766
10029
|
return;
|
|
10030
|
+
}
|
|
9767
10031
|
const engineFactory = options.createEngineWorker ?? deriveEngineWorkerFactory(result.swScriptUrl);
|
|
9768
10032
|
if (engineFactory === undefined) {
|
|
9769
10033
|
settle(() => reject(new ElectedEngineUnconstructibleError(result.swScriptUrl === undefined ? "provisionSyncWorker: the SharedWorker reported no derivable script URL and no `createEngineWorker` override was supplied" : "provisionSyncWorker: no `Worker` constructor is available in this scope to derive the module engine and no override was supplied")));
|
|
@@ -9775,6 +10039,7 @@ function provisionSyncWorker(options) {
|
|
|
9775
10039
|
controlPort: port,
|
|
9776
10040
|
createEngineWorker: engineFactory,
|
|
9777
10041
|
...provisionSwFactory ? { swFactory: provisionSwFactory } : {},
|
|
10042
|
+
...options.storage ? { storage: options.storage } : {},
|
|
9778
10043
|
...options.electionIo ? { electionIo: options.electionIo } : {},
|
|
9779
10044
|
...options.awaitOwnershipRelease ? { awaitOwnershipRelease: options.awaitOwnershipRelease } : {},
|
|
9780
10045
|
timers,
|
|
@@ -9782,16 +10047,32 @@ function provisionSyncWorker(options) {
|
|
|
9782
10047
|
}));
|
|
9783
10048
|
const releaseProvisionClaim = coordinator.claimForProvision();
|
|
9784
10049
|
const expiryMs = options.provisionExpiryMs ?? 60000;
|
|
9785
|
-
|
|
10050
|
+
let released = false;
|
|
10051
|
+
const expiryHandle = timers.setTimeout(() => {
|
|
10052
|
+
if (released)
|
|
10053
|
+
return;
|
|
10054
|
+
released = true;
|
|
10055
|
+
const entry = sharedCoordinators.get(storePath);
|
|
10056
|
+
if (entry?.releaseProvision === releaseProvision)
|
|
10057
|
+
delete entry.releaseProvision;
|
|
9786
10058
|
releaseProvisionClaim();
|
|
9787
10059
|
releaseSharedCoordinator(storePath);
|
|
9788
10060
|
}, expiryMs);
|
|
10061
|
+
const releaseProvision = () => {
|
|
10062
|
+
if (released)
|
|
10063
|
+
return;
|
|
10064
|
+
released = true;
|
|
10065
|
+
timers.clearTimeout(expiryHandle);
|
|
10066
|
+
releaseProvisionClaim();
|
|
10067
|
+
};
|
|
10068
|
+
setProvisionRelease(storePath, releaseProvision);
|
|
9789
10069
|
};
|
|
9790
10070
|
port.addEventListener("message", controlListener);
|
|
9791
10071
|
port.start?.();
|
|
10072
|
+
port.postMessage({ [DECLARATION_KEY]: options.storage ?? {} });
|
|
9792
10073
|
port.postMessage({ [PLACEMENT_QUERY_KEY]: true });
|
|
9793
|
-
postProvisionOn(port);
|
|
9794
10074
|
});
|
|
10075
|
+
return provision;
|
|
9795
10076
|
}
|
|
9796
10077
|
function readDefaultPageLifecycle() {
|
|
9797
10078
|
const pageWindow = globalThis.window;
|
|
@@ -9833,6 +10114,9 @@ function rebuildError(error) {
|
|
|
9833
10114
|
return mismatch;
|
|
9834
10115
|
}
|
|
9835
10116
|
const rebuilt = new Error(error?.message ?? "worker rpc failed");
|
|
10117
|
+
if (error?.name !== undefined) {
|
|
10118
|
+
rebuilt.name = error.name;
|
|
10119
|
+
}
|
|
9836
10120
|
if (error && "detail" in error && error.detail !== undefined) {
|
|
9837
10121
|
rebuilt.detail = error.detail;
|
|
9838
10122
|
}
|
|
@@ -9900,7 +10184,8 @@ import {
|
|
|
9900
10184
|
fingerprintRegistry as fingerprintRegistry2,
|
|
9901
10185
|
getSyncRegistrySchema as getSyncRegistrySchema4,
|
|
9902
10186
|
getSyncRegistryStorage as getSyncRegistryStorage2,
|
|
9903
|
-
isClaimsDependentRowFilter
|
|
10187
|
+
isClaimsDependentRowFilter,
|
|
10188
|
+
resolveStorageDeclaration as resolveStorageDeclaration2
|
|
9904
10189
|
} from "@pgxsinkit/contracts";
|
|
9905
10190
|
async function openWithBoundedRetries(open, backoffMs) {
|
|
9906
10191
|
let lastError;
|
|
@@ -10280,7 +10565,7 @@ async function createSyncClient(options) {
|
|
|
10280
10565
|
let commitmentBarrierPending = false;
|
|
10281
10566
|
const probeGranted = options.hasOpfsSyncAccess === true;
|
|
10282
10567
|
let storageFallbackReason;
|
|
10283
|
-
const resolvedDurability = getSyncRegistryStorage2(options.registry)
|
|
10568
|
+
const resolvedDurability = resolveStorageDeclaration2(getSyncRegistryStorage2(options.registry), options.storage).durability;
|
|
10284
10569
|
const createClientOptions = {
|
|
10285
10570
|
...options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : {},
|
|
10286
10571
|
...backendOverride ? { backendOverride } : {},
|
|
@@ -10586,6 +10871,12 @@ async function createSyncClient(options) {
|
|
|
10586
10871
|
return;
|
|
10587
10872
|
});
|
|
10588
10873
|
};
|
|
10874
|
+
const haltActivity = () => {
|
|
10875
|
+
disposed = true;
|
|
10876
|
+
mutationRuntime.abortInFlight();
|
|
10877
|
+
engine.close();
|
|
10878
|
+
convergenceDriver?.stop();
|
|
10879
|
+
};
|
|
10589
10880
|
const runWriteAndSyncTail = async () => {
|
|
10590
10881
|
if (disposed)
|
|
10591
10882
|
return;
|
|
@@ -10936,7 +11227,9 @@ async function createSyncClient(options) {
|
|
|
10936
11227
|
start: async () => {
|
|
10937
11228
|
await ready;
|
|
10938
11229
|
},
|
|
11230
|
+
haltActivity,
|
|
10939
11231
|
stop: async () => {
|
|
11232
|
+
haltActivity();
|
|
10940
11233
|
await quiesceTailForTeardown();
|
|
10941
11234
|
await convergenceDriver?.stop();
|
|
10942
11235
|
sync?.unsubscribe();
|
|
@@ -10947,6 +11240,7 @@ async function createSyncClient(options) {
|
|
|
10947
11240
|
await pglite.close();
|
|
10948
11241
|
},
|
|
10949
11242
|
destroy: (destroyOptions) => lifecycleSlot.run("destroy", async () => {
|
|
11243
|
+
haltActivity();
|
|
10950
11244
|
await quiesceTailForTeardown();
|
|
10951
11245
|
if (!destroyOptions?.force) {
|
|
10952
11246
|
const stats = await mutationRuntime.readMutationStats();
|
|
@@ -11285,11 +11579,11 @@ export {
|
|
|
11285
11579
|
runBootAdoption,
|
|
11286
11580
|
runAdoptionTransition,
|
|
11287
11581
|
rowKey,
|
|
11288
|
-
retireSyncWorkerHost,
|
|
11289
11582
|
resolveStoreDataDir,
|
|
11290
11583
|
resolveStoreBoot,
|
|
11291
11584
|
resolveFreshBoot,
|
|
11292
11585
|
replAdapter,
|
|
11586
|
+
quiesceStoreWorker,
|
|
11293
11587
|
provisionSyncWorker,
|
|
11294
11588
|
postBridgeMessage,
|
|
11295
11589
|
performStoreExport,
|
|
@@ -11311,6 +11605,7 @@ export {
|
|
|
11311
11605
|
findReferencedLazyKeysInSql,
|
|
11312
11606
|
fallbackVirginCandidateToIdb,
|
|
11313
11607
|
encodeEnvelope,
|
|
11608
|
+
destroyStoreArtifacts,
|
|
11314
11609
|
deriveStoreId,
|
|
11315
11610
|
defineSyncWorker,
|
|
11316
11611
|
createWorkerTokenCache,
|
|
@@ -11349,4 +11644,4 @@ export {
|
|
|
11349
11644
|
BRIDGE_CHANNEL
|
|
11350
11645
|
};
|
|
11351
11646
|
|
|
11352
|
-
//# debugId=
|
|
11647
|
+
//# debugId=62F3E6980D885DE664756E2164756E21
|